file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
_request.ts | import axios, { AxiosRequestConfig } from "axios";
import { IDHeaderName, RoomNumberHeaderName, SERVER_BASE_URL } from "../../shared/constants";
import { HttpRes } from "../../shared/httpMsg/_httpResTemplate";
import { showDialog } from "../reactivity/dialog";
import { getToken } from "../utils/token";
export default function request<T = {}>(
config: AxiosRequestConfig
) {
const instance = axios.create({
baseURL: SERVER_BASE_URL,
timeout: 60000,
withCredentials: true,
});
instance.interceptors.request.use(
(config) => {
const token = getToken();
config.headers[IDHeaderName] = token && token.ID;
config.headers[RoomNumberHeaderName] =
token && token.roomNumber;
return config;
},
(err) => {
console.error(err);
}
);
instance.interceptors.response.use(
(response) => {
const data = response.data || {};
if (data.status === 200) {
return data;
} else {
if (data.msg) {
showDialog(data.msg);
} else {
console.error("# e", { response });
showDialog("不知道发生了什么呢QwQ");
} | },
(err) => {
console.error(err);
}
);
return new Promise<HttpRes<T>>(async (resolve) => {
const res = await instance(config);
resolve((res as unknown) as HttpRes<T>);
});
} | return null;
} |
dfp-helpers.min.js | /* v5.3.0 */
"use strict";function hasClass(n,e){var t=n.className;return!!t&&t.match(new RegExp("(\\s|^)"+e+"(\\s|$)"))}function addClass(n,e){hasClass(n,e)||(n.className+=" "+e)}function removeClass(n,e){var t;hasClass(n,e)&&(t=new RegExp("(\\s|^)"+e+"(\\s|$)"),n.className=n.className.replace(t," "))}function addEvent(n,e,t){n.addEventListener?n.addEventListener(e,t,!1):n.attachEvent&&n.attachEvent("on"+e,t)}window.lazyload=function(){var t,a,n,e,i=window.lazyloadthreshold?window.lazyloadthreshold:200,o=[];function l(){for(var n,e=o.length-1;0<=e;e--)c((n=o[e]).element)&&(n.callback.call(),o.splice(e,1))}function | (){t=window.innerHeight||document.documentElement.clientHeight,a=window.innerWidth||document.documentElement.clientWidth}function c(n){var e;return!(!(n&&n instanceof Element)||function(n){var e;for(e=n;e;e=e.parentElement)if("none"===getComputedStyle(e).display)return!0;return!1}(n))&&(0<=(e=n.getBoundingClientRect()).bottom&&0<=e.right&&e.top-i<=t&&e.left<=a)}function r(e,t){var a;return function(){var n=arguments;a||(e.apply(this,n),a=!0,setTimeout(function(){a=!1},t))}}return e=r(function(){l()},100),n=r(function(){s()},100),window.addEventListener("scroll",e),window.addEventListener("resize",n),s(),function(n,e){o.push({element:n,callback:e}),l()}}(); | s |
localMutationTypes.ts | import { Mutation } from 'react-apollo';
import { ModalType } from 'constants/enums';
interface ModalData {}
interface ModalVariables {
type: ModalType;
}
export class ModalMutation extends Mutation<ModalData, ModalVariables> {} | ||
main.go | /*******************************************************************************
* IBM Confidential
* OCO Source Materials
* IBM Cloud Container Service, 5737-D43
* (C) Copyright IBM Corp. 2017, 2018 All Rights Reserved.
* The source code for this program is not published or otherwise divested of
* its trade secrets, irrespective of what has been deposited with
* the U.S. Copyright Office.
******************************************************************************/
package main
import (
"encoding/json"
"fmt"
"github.com/IBM/ibmcloud-object-storage-plugin/driver"
"github.com/IBM/ibmcloud-object-storage-plugin/driver/interfaces"
"github.com/IBM/ibmcloud-object-storage-plugin/utils/backend"
optParser "github.com/IBM/ibmcloud-object-storage-plugin/utils/parser"
flags "github.com/jessevdk/go-flags"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
"io/ioutil"
"log"
"os"
"strings"
)
const (
logConfig = "/var/log/ibmc-s3fs.log"
)
// Version and Build time will be set during the "make driver"
// go build -ldflags "-X main.Version=${VERSION} -X main.Build=${BUILD}" -o ${BINARY_NAME}
// go build -ldflags "-X main.Version=0.0.1 -X main.Build=2017-08-06T00:33:58+0530" cmd/driver/main.go
// VERSION=`git describe --tags`
// BUILD=`date +%FT%T%z`
// Version holds the driver version string
var Version string
// Build holds the driver build string
var Build string
var filelogger = getZapLogger()
// Save the io streams, before we divert them to File.
// this will be used used while printing the response
var stdout = os.Stdout
// NewS3fsPlugin returns a new instance of the driver that supports mount & unmount operations of s3fs volumes
func NewS3fsPlugin(logger *zap.Logger) *driver.S3fsPlugin {
return &driver.S3fsPlugin{
Backend: &backend.COSSessionFactory{},
Logger: logger,
}
}
type versionCommand struct{}
func (v *versionCommand) Execute(args []string) error {
fmt.Fprintf(stdout, "Version:%s, Build:%s\n", Version, Build)
return nil
}
type initCommand struct{}
func (i *initCommand) Execute(args []string) error {
response := NewS3fsPlugin(filelogger).Init()
filelogger.Info(":S3FS Driver info:", zap.String("Version", Version), zap.String("Build", Build))
return printResponse(response)
}
type PodDetail struct {
PodUid string `json:"kubernetes.io/pod.uid,omitempty"`
PodName string `json:"kubernetes.io/pod.name,omitempty"`
PodNS string `json:"kubernetes.io/pod.namespace,omitempty"`
}
type mountCommand struct{}
func maskSecrets(m map[string]string) (map[string]string, []byte, error) {
mountOptsLogs := make(map[string]string)
for k, v := range m {
mountOptsLogs[k] = v
}
mountOptsLogs["kubernetes.io/secret/access-key"] = "XXX"
mountOptsLogs["kubernetes.io/secret/secret-key"] = "YYY"
mountOptsLogs["kubernetes.io/secret/api-key"] = "KKK"
mountOptsLogs["kubernetes.io/secret/service-instance-id"] = "MMM"
mountOptsLogs["kubernetes.io/secret/ca-bundle-crt"] = "ZZZ"
newString, err := json.Marshal(mountOptsLogs)
return mountOptsLogs, newString, err
}
func (m *mountCommand) Execute(args []string) error {
var err error
var podDetail PodDetail
var podUID = ""
var hostname, anyerror = os.Hostname()
if anyerror != nil {
hostname = ""
}
filelogger.Info(":MountCommand start:" + hostname)
mountOpts := make(map[string]string)
mountOptsLogs := make(map[string]string)
switch len(args) {
case 2:
// Kubernetes 1.6+
err = json.Unmarshal([]byte(args[1]), &mountOpts)
case 3:
// Kubernetes 1.5-
err = json.Unmarshal([]byte(args[2]), &mountOpts)
default:
return printResponse(interfaces.FlexVolumeResponse{
Status: interfaces.StatusFailure,
Message: fmt.Sprintf("Unexpected number of arguments to 'mount' command: %d", len(args)),
})
}
err = optParser.UnmarshalMap(&mountOpts, &podDetail)
if err == nil {
podUID = podDetail.PodUid
filelogger.Info(podDetail.PodUid + ":" + podDetail.PodName + ":" +
podDetail.PodNS + ":" + hostname)
}
mountOptsLogs, newString, err := maskSecrets(mountOpts)
filelogger.Info(podUID+":MountCommand args", zap.ByteString("input args", newString))
targetMountDir := args[0]
if err != nil {
return printResponse(interfaces.FlexVolumeResponse{
Status: interfaces.StatusFailure,
Message: fmt.Sprintf("Failed to mount volume to %s due to: %#v", targetMountDir, err),
})
}
filelogger.Info(podUID+":cmd-MountCommand ", zap.Any("mountOpts", mountOptsLogs))
// For logs
mountRequestLog := interfaces.FlexVolumeMountRequest{
MountDir: targetMountDir,
Opts: mountOptsLogs,
}
mountRequest := interfaces.FlexVolumeMountRequest{
MountDir: targetMountDir,
Opts: mountOpts,
}
filelogger.Info(podUID+":cmd-MountCommand ", zap.Any("mountRequest", mountRequestLog))
//response := NewS3fsPlugin(filelogger).Mount(mountRequest)
s3fsPlugin := NewS3fsPlugin(filelogger)
driver.SetBuildVersion(Version)
driver.SetPodUID(podUID)
response := (*s3fsPlugin).Mount(mountRequest)
filelogger.Info(podUID+":MountCommand End", zap.Any("response", response))
return printResponse(response)
}
type unmountCommand struct{}
func (u *unmountCommand) Execute(args []string) error {
var hostname, anyerror = os.Hostname()
if anyerror != nil {
hostname = ""
}
filelogger.Info(":UnmountCommand start:" + hostname)
filelogger.Info(":UnmountCommand args", zap.Strings("input args", args))
if len(args) != 1 {
return printResponse(interfaces.FlexVolumeResponse{
Status: interfaces.StatusFailure,
Message: fmt.Sprintf("Unexpected number of arguments to 'unmount' command: %d", len(args)),
})
}
mountDir := args[0]
unmountRequest := interfaces.FlexVolumeUnmountRequest{
MountDir: mountDir,
}
response := NewS3fsPlugin(filelogger).Unmount(unmountRequest)
filelogger.Info(":UnmountCommand end", zap.Reflect("response", response))
return printResponse(response)
}
type flagsOptions struct{}
func main() {
var err error
var versionCommand versionCommand
var initCommand initCommand
var mountCommand mountCommand
var unmountCommand unmountCommand
var options flagsOptions
var parser = flags.NewParser(&options, flags.Default&^flags.PrintErrors)
// disable the console logging (if anywhere else being done by softlayer or any other pkg)
// presently softlayer logs few warning message, which makes the flexdriver unmarshall failure
log.SetFlags(0)
log.SetOutput(ioutil.Discard)
// Divert all loggers outputs and fmt.printf loggings (this will create issues with flex response)
NullDevice, _ := os.Open(os.DevNull)
os.Stdout = NullDevice
os.Stderr = NullDevice
/* #nosec */
parser.AddCommand("version",
"Prints version",
"Prints version and build information",
&versionCommand)
/* #nosec */
parser.AddCommand("init",
"Init the plugin",
"The info command print the driver name and version.",
&initCommand)
/* #nosec */
parser.AddCommand("mount",
"Mount Volume",
"Mount a volume Id to a path - returning the path.",
&mountCommand)
/* #nosec */
parser.AddCommand("unmount",
"Unmount Volume",
"UnMount given a mount dir",
&unmountCommand)
_, err = parser.Parse()
if err != nil {
var status string
if strings.Contains(strings.ToLower(err.Error()), "unknown command") {
status = interfaces.StatusNotSupported
} else {
status = interfaces.StatusFailure
}
/* #nosec */
printResponse(interfaces.FlexVolumeResponse{
Status: status,
Message: fmt.Sprintf("Error parsing arguments: %v", err),
})
}
}
func getZapLogger() *zap.Logger |
func printResponse(f interfaces.FlexVolumeResponse) error {
responseBytes, err := json.Marshal(f)
if err != nil {
return err
}
output := string(responseBytes[:])
// log output being returned to flex driver
filelogger.Info(":FlexVolumeResponse", zap.String("output", output))
// write it to stdout, so that flexdriver will read it
fmt.Fprintf(stdout, "%s", output)
return nil
}
func getFromEnv(key string, defaultVal string) string {
value := os.Getenv(key)
if value == "" {
value = defaultVal
}
return value
}
| {
logfilepath := getFromEnv("LOGCONFIG", logConfig)
// Configure log rotate
lumberjackLogger := &lumberjack.Logger{
Filename: logfilepath,
MaxSize: 100, //MB
MaxBackups: 10, //Maximum number of backup
MaxAge: 60, //Days
}
//defer lumberjackLogger.Close()
//Create json encoder
prodConf := zap.NewProductionEncoderConfig()
prodConf.EncodeTime = zapcore.ISO8601TimeEncoder
encoder := zapcore.NewJSONEncoder(prodConf)
//create sync, where zap writes the output
zapsync := zapcore.AddSync(lumberjackLogger)
//Default Log level
loglevel := zap.NewAtomicLevelAt(zapcore.InfoLevel)
//zapcore
loggercore := zapcore.NewCore(encoder, zapsync, loglevel)
//Zap Logger with Log rotation
logger := zap.New(loggercore)
logger.Named("S3FSDriver")
return logger
} |
visibility_relation.rs | use super::{Parent, ParentHierarchy, TuiChannel, TuiEvent, Visible};
use crate::specs_ext::{ComponentEventReader, SpecsExt};
use amethyst::ecs::{prelude::*, SystemData as _};
use hibitset::BitSetLike;
#[derive(Default, Debug, Copy, Clone, PartialEq)]
pub struct VisibleIfChildIs;
impl Component for VisibleIfChildIs {
type Storage = DenseVecStorage<Self>;
}
#[derive(Default)]
pub struct VisibilityRelationSystem {
visibility_reader: ComponentEventReader<Visible>,
}
#[derive(SystemData)]
pub struct | <'s> {
visible: WriteStorage<'s, Visible>,
visible_if_child: ReadStorage<'s, VisibleIfChildIs>,
parent: ReadStorage<'s, Parent>,
parent_hierarchy: ReadExpect<'s, ParentHierarchy>,
}
impl<'s> System<'s> for VisibilityRelationSystem {
type SystemData = SystemData<'s>;
fn run(&mut self, mut data: Self::SystemData) {
let mut dirty = BitSet::new();
self.visibility_reader
.read_to_bitset(&data.visible, &mut dirty);
if dirty.is_empty() {
return;
}
for (parent, _) in (&data.parent, &dirty).join() {
if data.visible_if_child.contains(parent.entity) {
let vis = data
.parent_hierarchy
.children(parent.entity)
.iter()
.find(|x| data.visible.get(**x).map(|x| x.0).unwrap_or(true))
.is_some();
data.visible.get_mut_or_default(parent.entity).0 = vis;
}
}
}
fn setup(&mut self, res: &mut Resources) {
Self::SystemData::setup(res);
self.visibility_reader.setup(&res);
}
}
| SystemData |
barchart.js | (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else {
var a = factory();
for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
}
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 9);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */,
/* 1 */,
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "splineCurve", function() { return splineCurve; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bezierCurveTo", function() { return bezierCurveTo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPointInArea", function() { return isPointInArea; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateBezierControlPoints", function() { return updateBezierControlPoints; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "none", function() { return none; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isType", function() { return isType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deepCopy", function() { return deepCopy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPlainObject", function() { return isPlainObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "extend", function() { return extend; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDataRangeAndStep", function() { return getDataRangeAndStep; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changeUnit", function() { return changeUnit; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "formatX", function() { return formatX; });
/* eslint no-param-reassign: ["error", { "props": false }]*/
/*
* @author: zimyuan
*/
/*
* 判断JavaScript对象类型的函数
* @param {}
*/
function is(obj, type) {
const { toString } = Object.prototype;
let undefined;
return (type === 'Null' && obj === null) ||
(type === 'Undefined' && obj === undefined) ||
toString.call(obj).slice(8, -1) === type;
}
/*
* 深拷贝函数
* @param {Object} oldObj: 被拷贝的对象
* @param {Object} newObj: 需要拷贝的对象
* @ return {Object} newObj: 拷贝之后的对象
*/
function deepCopy(oldObj = {}, newObj = {}) {
/* eslint-disable */
for (const key in oldObj) {
const copy = oldObj[key];
if (oldObj === copy) continue; // 如window.window === window,会陷入死循环,需要处理一下
if (is(copy, 'Object')) {
newObj[key] = deepCopy(copy, newObj[key] || {});
} else if (is(copy, 'Array')) {
newObj[key] = [];
newObj[key] = deepCopy(copy, newObj[key] || []);
} else {
newObj[key] = copy;
}
}
/* eslint-disable */
return newObj;
}
function isType(type, value) {
return Object.prototype.toString.call(value).match(/\s(\w+)/)[1].toLowerCase() === type;
}
function isPlainObject(value) {
return (!!value && isType('object', value));
}
function extend(destination, source) {
if (!isPlainObject(destination) || !isPlainObject(source)) throw 'destination and source must be type of object';
for (const property in source) destination[property] = source[property];
return destination;
}
/**
* 数字取整逻辑
* 在计算坐标轴的最大最小值和区间的时候,预期的效果是最大最小值都是“整数”
* 这里根据数字的大小定义取整逻辑
*/
function getRoundForNumber(number) {
let round;
// 计算出当前数组位数减一的最小数字
if (number >= 100) round = String(number).split('')
.reduce(sum => sum * 10, 0.01);
// 数字介于10-100之间,逢5为整
else if (number >= 10) round = 5;
else if (number > 1) round = 1;
else round = 0.1;
return round;
}
function roundForNumber(number, direction) {
let result;
const round = getRoundForNumber(number);
if (number === 0) return 0;
if (direction === 'up') result = number + (round - (number % round));
else if (direction === 'down') result = number - (number % round);
return result;
}
/**
* 给定最大值最小值和区间个数,给出优化后的最大最小值和单step值
*/
function getDataRangeAndStep(maxSource, minSource, step) {
let max = maxSource;
let min = minSource;
if (max === 0) {
return {
max: 4,
min: 0,
divider: 1,
multiple: 1,
};
}
if (max === min) {
return {
max: max + 2,
min: (min - 2 >= 0 ? min - 2 : 0),
divider: 1,
multiple: 1,
};
}
// console.log(1, max, min, step);
let multiple = 1;
// 每一步的值小于1的情况,先放大100倍方便计算
if ((max - min) / step < 1) {
multiple = 10000;
max *= multiple;
min *= multiple;
}
const originMax = max;
// console.log(2, max, min, step);
let divider = Math.round((max - min) / step);
// 如果divider为0,说明值放大后,最大值和最小值差值过小;后续过程没有意义,直接返回
if (divider === 0) {
return {
max: 4,
min: 0,
divider: 1,
multiple: 1,
};
}
// console.log(3, divider);
// 先将divider降低一点,后面慢慢增加逼近满意值
divider = roundForNumber(divider, 'down');
// console.log(4, divider);
// 尽量保证整个图是居中而不是贴边的
max = max + (max % divider);
min = min - (min % divider);
// console.log(5, max, min);
// 最小值取整,因为divider也是取整的,所以最后max也是取整的
min = roundForNumber(min, 'down');
// console.log(6, min);
// 逼近求理想值
const round = getRoundForNumber(divider);
// console.log(8, round)
let flag = true;
while (flag) {
// console.log( min + divider * step , originMax, max, );
const temp = min + divider * step;
if (temp >= max || temp - originMax >= round * 10) flag = false;
divider += round;
}
// console.log(9, max, min, divider);
return {
max: (min + divider * step) / multiple,
min: min / multiple,
divider: divider / multiple,
multiple,
};
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function isFloat(n) {
return Number(n) === n && n % 1 !== 0;
}
function changeUnit(value, fixedParam = 1) {
let fixed = fixedParam;
// value是非数字的情况,直接返回value
if (!isNumeric(value)) return value;
const number = parseFloat(value);
let unit = '';
let divider = 1;
// 小于1000的值,保留小数点
if (isFloat(value) && number < 1000) return number.toFixed(fixed);
if (number < 1e3) {
unit = '';
divider = 1;
} else if (number >= 1e3 && number < 1e4) {
unit = 'k';
divider = 1e3;
} else if (number < 1e7) {
unit = 'w';
divider = 1e4 | lse {
unit = 'kw';
divider = 1e7;
}
const temp = number / divider;
// 如果达不到保留小数的基本要求,取整
if (temp - Math.floor(temp) < 0.5 * (0.1 ** fixed)) {
fixed = 0;
}
return temp.toFixed(fixed) + unit;
}
function none() {}
function formatX(length, maxXPoint) {
let step = Math.ceil(length / maxXPoint);
let start = 0;
// 记录原始的step长度
const origin = step;
while (step * (maxXPoint - 1) >= length) {
step -= 1;
}
if (step < origin) {
start = Math.floor((length - step * (maxXPoint - 1)) / 2);
}
return { step, start: start > 1 ? start - 1 : start };
}
function splineCurve(firstPoint, middlePoint, afterPoint, t) {
// Props to Rob Spencer at scaled innovation for his post on splining between points
// http://scaledinnovation.com/analytics/splines/aboutSplines.html
// This function must also respect "skipped" points
const previous = firstPoint.skip ? middlePoint : firstPoint;
const current = middlePoint;
const next = afterPoint.skip ? middlePoint : afterPoint;
const d01 = Math.sqrt((current.x - previous.x) ** 2 + (current.y - previous.y) ** 2);
const d12 = Math.sqrt((next.x - current.x) ** 2 + (next.y - current.y) ** 2);
let s01 = d01 / (d01 + d12);
let s12 = d12 / (d01 + d12);
// If all points are the same, s01 & s02 will be inf
s01 = isNaN(s01) ? 0 : s01;
s12 = isNaN(s12) ? 0 : s12;
const fa = t * s01; // scaling factor for triangle Ta
const fb = t * s12;
return {
previous: {
x: current.x - fa * (next.x - previous.x),
y: current.y - fa * (next.y - previous.y),
},
next: {
x: current.x + fb * (next.x - previous.x),
y: current.y + fb * (next.y - previous.y),
},
};
}
/**
* @private
*/
function bezierCurveTo(ctx, previous, target, flip) {
if (!previous) {
return ctx.lineTo(target.x, target.y);
}
ctx.bezierCurveTo(
flip ? previous.controlPointPreviousX : previous.controlPointNextX,
flip ? previous.controlPointPreviousY : previous.controlPointNextY,
flip ? target.controlPointNextX : target.controlPointPreviousX,
flip ? target.controlPointNextY : target.controlPointPreviousY,
target.x,
target.y,
);
}
function capControlPoint(pt, min, max) {
return Math.max(Math.min(pt, max), min);
}
/**
* Returns true if the point is inside the rectangle
* @param {object} point - The point to test
* @param {object} area - The rectangle
* @returns {boolean}
* @private
*/
function isPointInArea(point, area) {
const epsilon = 0.5; // margin - to match rounded decimals
return point.x > area.left - epsilon && point.x < area.right + epsilon &&
point.y > area.top - epsilon && point.y < area.bottom + epsilon;
}
function capBezierPoints(points, area) {
let i;
let ilen;
let point;
for (i = 0, ilen = points.length; i < ilen; ++i) {
point = points[i];
if (!isPointInArea(point, area)) {
continue;
}
if (i > 0 && isPointInArea(points[i - 1], area)) {
point.controlPointPreviousX = capControlPoint(point.controlPointPreviousX, area.left, area.right);
point.controlPointPreviousY = capControlPoint(point.controlPointPreviousY, area.top, area.bottom);
}
if (i < points.length - 1 && isPointInArea(points[i + 1], area)) {
point.controlPointNextX = capControlPoint(point.controlPointNextX, area.left, area.right);
point.controlPointNextY = capControlPoint(point.controlPointNextY, area.top, area.bottom);
}
}
}
function updateBezierControlPoints(points, area) {
let i;
let ilen;
let point;
let controlPoints;
const loop = false;
let prev = loop ? points[points.length - 1] : points[0];
for (i = 0, ilen = points.length; i < ilen; ++i) {
point = points[i];
controlPoints = splineCurve(
prev,
point,
points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen],
/* options.tension*/
0.1,
);
point.controlPointPreviousX = controlPoints.previous.x;
point.controlPointPreviousY = controlPoints.previous.y;
point.controlPointNextX = controlPoints.next.x;
point.controlPointNextY = controlPoints.next.y;
prev = point;
}
capBezierPoints(points, area);
}
/***/ }),
/* 3 */,
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/**
* 所有组件通用配置
*/
/* harmony default export */ __webpack_exports__["default"] = ({
debug: false,
/**
* 默认的图表宽度
*/
width: 414,
/**
* 默认的图表高度
*/
height: 200,
// Y轴标签的单位
unit: '',
/**
* Y轴标签以及toolTip的单位换算函数
* 组件内置了changeUnit函数,可以自行设置
*/
changeUnit: _util_js__WEBPACK_IMPORTED_MODULE_0__["changeUnit"],
/**
* 图表内本身的padding
*/
padding: {
left: 10,
right: 10,
top: 10,
bottom: 5,
},
/**
* 无数据时的文案配置
* */
emptyData: {
content: '暂无数据',
color: 'rgb(200,200,200)',
fontSize: 16,
},
});
/***/ }),
/* 5 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Base; });
/* harmony import */ var _draw_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _easing_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7);
/* harmony import */ var _Native2H5CTX_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
// 太老的库,很多变量是下滑线开头的,暂时屏蔽先
/* eslint no-underscore-dangle: "off"*/
/* eslint no-param-reassign: ["error", { "props": false }] */
/* eslint no-restricted-syntax: "off"*/
const dpr = wx.getSystemInfoSync().pixelRatio;
class Base extends _draw_js__WEBPACK_IMPORTED_MODULE_0__["default"] {
constructor() {
super();
this._dpr = dpr;
// 用于性能数据打点
this._start = 0;
// 寄存最终用于渲染的数据
this._render = {};
// 为了方便调试,在调试模式下会打出性能信息
this._performance = {};
// 实际绘图区域边界点信息
this._boundary = {};
this.aniTimer = null;
}
/**
* 通用的CTX实例方法
* */
initCTX(canvasNode) {
if (canvasNode.node) { //以节点传入
this._renderType = 'h5';
this._canvas = canvasNode.node;
//清晰度调整
this._canvas.width = canvasNode.width * this._dpr;
this._canvas.height = canvasNode.height * this._dpr;
this._canvasNode = canvasNode;
this.ctx = this._canvas.getContext('2d');
this.ctx.scale(this._dpr, this._dpr);
} else { //以原生ctx传入
this._renderType = 'native';
this._canvas = {
width: 100,
height: 100,
}
this.ctx = Object(_Native2H5CTX_js__WEBPACK_IMPORTED_MODULE_3__["default"])(canvasNode);
}
}
/**
* 性能数据打点
*/
log(performancePointName) {
this._performance[performancePointName] = new Date() - this._start;
}
/**
* 获取本实例的配置
*/
getConfig(cfg, sourceConfig) {
if (!Object(_util_js__WEBPACK_IMPORTED_MODULE_1__["isPlainObject"])(cfg)) throw new Error('options must be type of Object');
for (const key in sourceConfig) {
if (cfg[key] !== undefined) {
if (typeof sourceConfig[key] !== typeof cfg[key]) throw new Error(`TypeMismatch:${key} must be type of ${typeof sourceConfig[key]}`);
// 对于对象类型的属性,递归调用来替换
if (Object(_util_js__WEBPACK_IMPORTED_MODULE_1__["isPlainObject"])(cfg[key])) this.getConfig(cfg[key], sourceConfig[key]);
else sourceConfig[key] = cfg[key];
}
}
return sourceConfig;
}
/**
* 因为可以设置padding样式,所以需要维护真实的边界点
* 才可以实现精确绘制
*/
calBoundaryPoint() {
const { _config } = this;
const { padding } = this._config;
// 实际绘图区域的左上角
this._boundary.leftTop = {
x: padding.left,
y: padding.top,
};
// 计算实际绘图区域的左下角信息
this._boundary.leftBottom = {
x: padding.left,
y: (_config.height -
padding.bottom),
};
if (_config.xAxis) {
this._boundary.leftBottom.y -= (_config.xAxis.fontSize + _config.xAxis.marginTop);
}
// 计算实际绘图区域的右上角信息
this._boundary.rightTop = {
x: _config.width - padding.right,
y: padding.top,
};
this._boundary.rightBottom = {
x: _config.width - padding.right,
y: this._boundary.leftBottom.y,
};
this._boundary.size = {
width: this._boundary.rightTop.x - this._boundary.leftTop.x,
height: this._boundary.leftBottom.y - this._boundary.leftTop.y,
};
this._area = {
...this._boundary.size,
left: this._boundary.leftTop.x,
top: this._boundary.leftTop.y,
right: this._boundary.rightBottom.x,
bottom: this._boundary.rightBottom.y,
};
this.log('calBoundaryPoint');
return this._boundary;
}
// 计算用于绘制的点的信息
requestAnimFrame(callback) {
if (typeof requestAnimationFrame !== 'undefined') {
requestAnimationFrame(callback);
} else {
setTimeout(callback, 1000 / 60);
}
}
animationLopp(config, draw) {
const animationCount = 1 / (config.animationStep || 1);
const easingFunction = _easing_js__WEBPACK_IMPORTED_MODULE_2__["default"][config.animationEasing];
// 动画完成的百分比
let percentComplete = (config.animation ?
0 :
1);
const animationFrame = () => {
let easeAdjustedAnimationPercent = (config.animation ?
easingFunction(percentComplete) :
1);
if (easeAdjustedAnimationPercent > 1) {
easeAdjustedAnimationPercent = 1;
}
draw.call(this, easeAdjustedAnimationPercent);
};
const animationLoop = () => {
percentComplete += animationCount;
animationFrame();
if (percentComplete <= 1) {
this.requestAnimFrame(animationLoop);
} else {
config.onAnimationComplete && config.onAnimationComplete();
}
};
this.requestAnimFrame(animationLoop);
}
}
/***/ }),
/* 6 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ChartBase; });
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* eslint no-param-reassign: ["error", { "props": false }] */
/**
* 图表组件基础类,封装一些canvas画图的基本方法
* 这里可用于兼容H5和小程序
* 因为小程序和H5的绘图API并不是完全一致的,通过基础类来兼容是最合适的
*/
class ChartBase {
wordWidth(words, fontSize) {
if (words === undefined || words === null) return 0;
let totLength = 0;
for (let i = 0; i < words.length; i++) {
const strCode = words.charCodeAt(i);
if (strCode > 128) totLength += fontSize;
else totLength += fontSize / 2;
}
return totLength;
}
measureText(ctx, word) {
// 低版本兼容处理
if (!ctx.measureText) {
return this.getWordWidth(word);
}
ctx.save();
if (typeof(word.text) === 'number') {
word.text = word.text.toString();
}
ctx.font = `${word.fontSize}px sans-serif`;
const metrics = ctx.measureText(word.text);
ctx.restore();
return metrics.width;
}
getWordWidth(word) {
if (typeof(word.text) === 'number') {
word.text = word.text.toString();
}
const w = this.wordWidth(word.text, word.fontSize);
return Math.ceil(w);
}
/**
* 根据给定样式绘制文字
*/
drawWord(ctx, word) {
if (typeof(word.text) === 'number') word.text = word.text.toString();
ctx.beginPath();
if (word.isbottom) {
// ctx.setTextBaseline('bottom');
ctx.textBaseline = 'bottom';
}
if (word.baseline) {
// ctx.setTextBaseline(word.baseline);
ctx.textBaseline = word.baseline;
}
// ctx.setFontSize(word.fontSize);
ctx.font = `${word.fontSize}px sans-serif`;
// ctx.setFillStyle(word.color);
ctx.fillStyle = word.color;
// ctx.setTextAlign(word.textAlign || 'left');
ctx.textAlign = word.textAlign || 'left';
ctx.fillText(word.text, word.x, word.y);
ctx.stroke();
ctx.closePath();
}
/**
* 绘制一个矩形 支持圆角矩形
* rect = {
* fillColor
* x
* y
* widht
* height
* r
* }
*/
drawRect(ctx, rect) {
if (rect.r && rect.r > 0) {
ctx.save();
ctx.beginPath();
// 左上弧线
ctx.arc(rect.x + rect.r, rect.y + rect.r, rect.r, 1 * Math.PI, 1.5 * Math.PI);
// 左直线
ctx.moveTo(rect.x, rect.y + rect.r);
ctx.lineTo(rect.x, rect.y + rect.height - rect.r);
// 左下弧线
ctx.arc(rect.x + rect.r, rect.y + rect.height - rect.r, rect.r, 0.5 * Math.PI, 1 * Math.PI);
// 下直线
ctx.lineTo(rect.x + rect.r, rect.y + rect.height);
ctx.lineTo(rect.x + rect.width - rect.r, rect.y + rect.height);
// 右下弧线
ctx.arc(rect.x + rect.width - rect.r, rect.y + rect.height - rect.r, rect.r, 0 * Math.PI, 0.5 * Math.PI);
// 右直线
ctx.lineTo(rect.x + rect.width, rect.y + rect.height - rect.r);
ctx.lineTo(rect.x + rect.width, rect.y + rect.r);
// 右上弧线
ctx.arc(rect.x + rect.width - rect.r, rect.y + rect.r, rect.r, 1.5 * Math.PI, 2 * Math.PI);
// 上直线
ctx.lineTo(rect.x + rect.width - rect.r, rect.y);
ctx.lineTo(rect.x + rect.r, rect.y);
// ctx.setFillStyle(rect.fillColor);
ctx.fillStyle = rect.fillColor;
ctx.fill();
} else {
ctx.beginPath();
// ctx.setStrokeStyle(rect.fillColor);
ctx.strokeStyle = rect.fillColor;
// ctx.setFillStyle(rect.fillColor);
ctx.fillStyle = rect.fillColor;
ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
ctx.closePath();
}
}
/**
* 根据给定样式绘制线条
*/
drawLine(ctx, line) {
ctx.beginPath();
// ctx.setLineWidth(line.width || 1);
ctx.lineWidth = line.width || 1;
ctx.strokeStyle = line.color;
if (line.isDash) ctx.setLineDash(line.dashPattern, line.dashOffset);
ctx.moveTo(line.start.x, line.start.y);
ctx.lineTo(line.end.x, line.end.y);
ctx.stroke();
ctx.closePath();
ctx.setLineDash([0], 0);
}
drawLongLine(ctx, line) {
ctx.beginPath();
// ctx.setLineWidth(line.width || 1);
// ctx.setStrokeStyle(line.color);
ctx.lineWidth = line.width || 1;
ctx.strokeStyle = line.color;
if (line.isDash) ctx.setLineDash(line.dashPattern, line.dashOffset);
const points = line.points || [];
for (let index = 0; index < points.length; index++) {
const point = points[index];
if (index === 0) ctx.moveTo(point.x, point.y);
else ctx.lineTo(point.x, point.y);
}
// 需要填充背景颜色要在stroke之前填充,否则边界线会发虚
if (line.fill) {
// ctx.setFillStyle(line.fillColor);
ctx.fillStyle = line.fillColor;
ctx.fill();
}
ctx.stroke();
ctx.closePath();
ctx.setLineDash([0], 0);
}
/**
* 绘制一条由线段连接在一起的长线
* 绘制多个线条时,效率更高的做法是,创建一个包含所有线条的路径,
* 然后通过单个绘制调用进行绘制。也就是说,无需分别绘制各个线条。
* 当这条线由很多线段组成的时候,可以非常显著提升性能!
*/
drawLongLineWithFill(ctx, points, opts = {
lineWidth: 1,
lineColor: '#7587db',
fillColor: 'rgba(117, 135, 219, 0.3)',
needFill: false,
}) {
ctx.save();
ctx.beginPath();
// ctx.setFillStyle(opts.fillColor);
ctx.fillStyle = opts.fillColor;
// ctx.setLineWidth(opts.lineWidth);
ctx.lineWidth = opts.lineWidth;
// ctx.setStrokeStyle(opts.lineColor);
ctx.strokeStyle = opts.lineColor;
const start = points[0];
const end = points[points.length - 1];
ctx.moveTo(start.x, start.y);
let prev;
for (let index = 1; index < points.length - 1; index++) {
const point = points[index];
// if ( index === 1 ) {
// ctx.moveTo(point.x, point.y);
// } else {
if (points[index - 1].show === false) {
ctx.moveTo(point.x, point.y);
} else {
if (point.show !== false) {
if (opts.curve) {
Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["bezierCurveTo"])(ctx, prev, point);
} else {
ctx.lineTo(point.x, point.y);
}
}
}
// }
prev = point;
}
ctx.stroke();
// 闭合区域
ctx.lineTo(end.x, end.y);
ctx.lineTo(start.x, start.y);
if (opts.needFill !== false) {
ctx.fill();
}
ctx.closePath();
ctx.restore();
}
/**
* 根据给定样式绘制一个圆
*/
drawCircle(ctx, circle) {
ctx.beginPath();
// ctx.setStrokeStyle(circle.strokeColor);
ctx.strokeStyle = circle.strokeColor;
if (circle.fillColor) {
// ctx.setFillStyle(circle.fillColor);
ctx.fillStyle = circle.fillColor;
}
// ctx.setLineWidth(circle.lineWidth || 1);
ctx.lineWidth = circle.lineWidth || 1;
ctx.arc(circle.x, circle.y, circle.r, 0, 2 * Math.PI);
ctx.stroke();
if (circle.fillColor) ctx.fill();
ctx.closePath();
}
/**
* 绘制无数据文案
* */
drawEmptyData() {
const config = this._config.emptyData;
//清空画布
this.ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
if (this._renderType == 'h5') {
this.drawWord(this.ctx, {
text: config.content,
fontSize: config.fontSize,
textAlign: 'center',
color: config.color,
x: this._canvasNode.width / 2,
y: this._canvasNode.height / 2,
});
} else {
this.drawWord(this.ctx, {
text: config.content,
fontSize: config.fontSize,
textAlign: 'center',
color: config.color,
x: this._config.width / 2,
y: this._config.height / 2,
});
this.ctx.draw();
}
}
clearCanvas(ctx, width, height) {
ctx.clearRect(0, 0, width, height);
// ctx.draw();
}
}
/***/ }),
/* 7 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
// Easing functions adapted from Robert Penner's easing equations
// http://www.robertpenner.com/easing/
/* eslint-disable */
/* harmony default export */ __webpack_exports__["default"] = ({
linear(t) {
return t;
},
easeInQuad(t) {
return t * t;
},
easeOutQuad(t) {
return -1 * t * (t - 2);
},
easeInOutQuad(t) {
if ((t /= 1 / 2) < 1) return 1 / 2 * t * t;
return -1 / 2 * ((--t) * (t - 2) - 1);
},
easeInCubic(t) {
return t * t * t;
},
easeOutCubic(t) {
return 1 * ((t = t / 1 - 1) * t * t + 1);
},
easeInOutCubic(t) {
if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t;
return 1 / 2 * ((t -= 2) * t * t + 2);
},
easeInQuart(t) {
return t * t * t * t;
},
easeOutQuart(t) {
return -1 * ((t = t / 1 - 1) * t * t * t - 1);
},
easeInOutQuart(t) {
if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t;
return -1 / 2 * ((t -= 2) * t * t * t - 2);
},
easeInQuint(t) {
return 1 * (t /= 1) * t * t * t * t;
},
easeOutQuint(t) {
return 1 * ((t = t / 1 - 1) * t * t * t * t + 1);
},
easeInOutQuint(t) {
if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t * t;
return 1 / 2 * ((t -= 2) * t * t * t * t + 2);
},
easeInSine(t) {
return -1 * Math.cos(t / 1 * (Math.PI / 2)) + 1;
},
easeOutSine(t) {
return 1 * Math.sin(t / 1 * (Math.PI / 2));
},
easeInOutSine(t) {
return -1 / 2 * (Math.cos(Math.PI * t / 1) - 1);
},
easeInExpo(t) {
return (t == 0) ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1));
},
easeOutExpo(t) {
return (t == 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1);
},
easeInOutExpo(t) {
if (t == 0) return 0;
if (t == 1) return 1;
if ((t /= 1 / 2) < 1) return 1 / 2 * Math.pow(2, 10 * (t - 1));
return 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
},
easeInCirc(t) {
if (t >= 1) return t;
return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1);
},
easeOutCirc(t) {
return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t);
},
easeInOutCirc(t) {
if ((t /= 1 / 2) < 1) return -1 / 2 * (Math.sqrt(1 - t * t) - 1);
return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
},
easeInElastic(t) {
let s = 1.70158;
let p = 0;
let a = 1;
if (t == 0) return 0;
if ((t /= 1) == 1) return 1;
if (!p) p = 1 * .3;
if (a < Math.abs(1)) {
a = 1;
s = p / 4;
} else s = p / (2 * Math.PI) * Math.asin(1 / a);
return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
},
easeOutElastic(t) {
let s = 1.70158;
let p = 0;
let a = 1;
if (t == 0) return 0;
if ((t /= 1) == 1) return 1;
if (!p) p = 1 * .3;
if (a < Math.abs(1)) {
a = 1;
s = p / 4;
} else s = p / (2 * Math.PI) * Math.asin(1 / a);
return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1;
},
easeInOutElastic(t) {
let s = 1.70158;
let p = 0;
let a = 1;
if (t == 0) return 0;
if ((t /= 1 / 2) == 2) return 1;
if (!p) p = 1 * (.3 * 1.5);
if (a < Math.abs(1)) {
a = 1;
s = p / 4;
} else s = p / (2 * Math.PI) * Math.asin(1 / a);
if (t < 1) return -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * .5 + 1;
},
easeInBack(t) {
const s = 1.70158;
return 1 * (t /= 1) * t * ((s + 1) * t - s);
},
easeOutBack(t) {
const s = 1.70158;
return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1);
},
easeInOutBack(t) {
let s = 1.70158;
if ((t /= 1 / 2) < 1) return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s));
return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
},
easeInBounce(t) {
return 1 - animationOptions.easeOutBounce(1 - t);
},
easeOutBounce(t) {
if ((t /= 1) < (1 / 2.75)) {
return 1 * (7.5625 * t * t);
}
if (t < (2 / 2.75)) {
return 1 * (7.5625 * (t -= (1.5 / 2.75)) * t + .75);
}
if (t < (2.5 / 2.75)) {
return 1 * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375);
}
return 1 * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375);
},
easeInOutBounce(t) {
if (t < 1 / 2) return animationOptions.easeInBounce(t * 2) * .5;
return animationOptions.easeOutBounce(t * 2 - 1) * .5 + 1 * .5;
},
});
/***/ }),
/* 8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Native2H5CTX; });
/**
*
* 原生Canvas绘图上下文胶水层
* 支持大部分 H5 Canvas API 直接转化为 原生CanvasAPI
* 原生CanvasAPI也可以直接使用
*
* 使用方法:
*
import Native2H5CTX from './base/Native2H5CTX.js';
const ctx = Native2H5CTX(nativeCtx);
请注意:由于原生API需要 draw() 完成最终渲染,因此开发者需要手动判断并执行 ctx.draw()
*
*
* */
/**
* 转化管理器
* */
class CONVERT {
/**
* Font 定义差异
* 原生Canvas仅支持设置 FontSize 因此要读取大小后直接设置,忽略文字字体的定义
* */
font(target, value) {
const result = /[0-9]+px/i.exec(value);
if (!result) {
throw new Error('font 所接收的参数值不符合期望 例: ctx.font = \'23px\'');
}
const fontSize = result[0].slice(0, -2);
target.setFontSize(fontSize);
return true;
}
/**
* lineWidth 定义差异
* 原生 lineWidth 采用 setLineWidth 进行设置
* */
lineWidth(target, value) {
target.setLineWidth(value);
return true;
}
/**
* strokeStyle 定义差异
* 原生 strokeStyle 采用 setStrokeStyle 进行设置
* */
strokeStyle(target, value) {
target.setStrokeStyle(value);
return true;
}
/**
* fillStyle 定义差异
* 原生 fillStyle 采用 setFillStyle 进行设置
* */
fillStyle(target, value) {
target.setFillStyle(value);
return true;
}
/**
* textBaseline 定义差异
* 原生 textBaseline 采用 setTextBaseline 进行设置
* */
textBaseline(target, value) {
target.setTextBaseline(value);
return true;
}
/**
* textAlign 定义差异
* 原生 textAlign 采用 setTextAlign 进行设置
* */
textAlign(target, value) {
target.setTextAlign(value);
return true;
}
}
const convert = new CONVERT();
function Native2H5CTX(nativeCtx) {
Object.defineProperty(nativeCtx, 'font', {
set(v) {
convert.font.apply(null, [nativeCtx, v]);
},
});
Object.defineProperty(nativeCtx, 'lineWidth', {
set(v) {
convert.lineWidth.apply(null, [nativeCtx, v]);
},
});
Object.defineProperty(nativeCtx, 'strokeStyle', {
set(v) {
convert.strokeStyle.apply(null, [nativeCtx, v]);
},
});
Object.defineProperty(nativeCtx, 'fillStyle', {
set(v) {
convert.fillStyle.apply(null, [nativeCtx, v]);
},
});
Object.defineProperty(nativeCtx, 'textBaseline', {
set(v) {
convert.textBaseline.apply(null, [nativeCtx, v]);
},
});
Object.defineProperty(nativeCtx, 'textAlign', {
set(v) {
convert.textAlign.apply(null, [nativeCtx, v]);
},
});
return nativeCtx;
}
/***/ }),
/* 9 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BarChart; });
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _config_barchart_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(10);
/* harmony import */ var _base_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5);
/* harmony import */ var _base_Native2H5CTX_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
// 太老的库,很多变量是下滑线开头的,暂时屏蔽先
/* eslint no-underscore-dangle: "off"*/
/* eslint no-param-reassign: ["error", { "props": false }] */
/**
* 小程序折线图绘制组件
*/
class BarChart extends _base_index_js__WEBPACK_IMPORTED_MODULE_2__["default"] {
/**
* @param { canvasNode } canvasNode: canvas节点句柄
* @param { Object } cfg: 组件配置
*/
constructor(canvasNode, cfg = {}) {
super();
this.initCTX(canvasNode);
this.chartType = 'bar';
/**
* 约定!所有的内部变量都需要这里先声明
* 可以大大提高源码阅读性
*/
// 本实例配置文件
this._config = this.getConfig(cfg, Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["deepCopy"])(_config_barchart_js__WEBPACK_IMPORTED_MODULE_1__["default"]));
// 线条数据
this._datasets = [];
}
calLabelDataForItem(x, yStartParam, barLabel) {
let yStart = yStartParam;
const labelArr = (Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["isType"])('array', barLabel) ? barLabel : [barLabel]);
let height = 0;
const arr = [];
labelArr.forEach((item) => {
const labelConfig = Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["deepCopy"])(this._config.barLabelStyle);
const obj = Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["isType"])('object', item) ? item : { name: item, style: labelConfig };
obj.style = Object(_util_js__WEBPACK_IMPORTED_MODULE_0__["extend"])(labelConfig, obj.style || {});
yStart -= obj.style.paddingBottom;
height += obj.style.paddingBottom;
arr.push({
text: obj.name || '',
color: obj.style.color,
fontSize: obj.style.fontSize,
x,
y: yStart,
textAlign: 'center',
});
yStart -= obj.style.fontSize;
height += obj.style.fontSize;
});
return { arr, height };
}
calBarData() {
const config = this._config;
const render = this._render;
const { barWidth } = config.barStyle;
const { xCenterAxis } = render;
const first = this._datasets[0];
const second = this._datasets[1];
const count = first.points.length;
const { leftBottom } = this._boundary;
let totalBarWidth = this._datasets.length * count * barWidth;
if (second) {
totalBarWidth += this._config.barStyle.compareBarMargin * count;
}
// 每组柱子的间距
const padding = this._config.barStyle.leftRightPadding * 2;
const barPadding = (xCenterAxis.end.x - xCenterAxis.start.x - totalBarWidth - padding) / (count - 1);
// 柱子的X轴开始位置
let xStart = xCenterAxis.start.x + this._config.barStyle.leftRightPadding;
render.bars = [];
render.barLabels = [];
render.topbarLabels = [];
const { xAxis } = config;
const bottom = leftBottom.y + xAxis.marginTop + xAxis.fontSize;
const { barStyle } = config;
first.points.forEach((point, index) => {
point.fillColor = first.fillColor || barStyle.fillColor;
const barArr = [point];
if (second) {
const cBar = second.points[index];
cBar.fillColor = second.fillColor || barStyle.fillColor;
barArr.push(cBar);
}
let centerX = xStart + barWidth / 2;
barArr.forEach((bar, barIndex) => {
const height = (bar.value - render.min) * render.unitY * render.yMultiple;
const y = leftBottom.y - height;
const rect = {
fillColor: bar.fillColor,
x: xStart,
y,
width: barWidth,
height,
};
render.bars.push(rect);
if (bar.barLabel) {
const { arr } = this.calLabelDataForItem(xStart + barWidth / 2 + 1, y, bar.barLabel);
render.topbarLabels = this._render.topbarLabels.concat(arr);
}
xStart += barWidth;
if (second && barIndex === 0) {
xStart += config.barStyle.compareBarMargin;
centerX += (barWidth / 2 + config.barStyle.compareBarMargin / 2) + 0.5;
} else {
xStart += barPadding;
}
});
// X轴的标签
this._render.barLabels.push({
text: point.label || '',
color: xAxis.color,
fontSize: xAxis.fontSize,
x: centerX,
y: bottom,
textAlign: 'center',
});
});
}
calXAxisLines() {
const { yAxisWidth } = this._render;
const { leftBottom } = this._boundary;
const { rightBottom } = this._boundary;
const { xAxisLine } = this._config;
// 计算X轴中轴线数据
this._render.xCenterAxis = {
start: {
x: leftBottom.x + yAxisWidth,
y: leftBottom.y,
},
end: {
x: rightBottom.x,
y: leftBottom.y,
},
width: xAxisLine.width,
color: xAxisLine.color,
};
}
calYAxisLines() {
const data = this._render;
const { yAxisWidth } = data;
const { leftTop } = this._boundary;
const { leftBottom } = this._boundary;
const rightTop = this._boundary.rightBottom;
const { yAxisLine } = this._config;
// 计算Y轴中轴线数据
this._render.yCenterAxis = {
start: {
x: leftTop.x + yAxisWidth,
y: leftTop.y,
},
end: {
x: leftTop.x + yAxisWidth,
y: leftBottom.y,
},
width: yAxisLine.width,
color: yAxisLine.color,
};
this._render.yAxisLines = [];
this._render.yAxisData.forEach((item, index) => {
if (index > 0) {
this._render.yAxisLines.push({
start: {
x: item.x + yAxisWidth,
y: item.y,
},
end: {
x: rightTop.x,
y: item.y,
},
width: yAxisLine.width,
color: yAxisLine.color,
});
}
});
}
/**
* 计算Y轴的边界和阶梯值
*/
calYAxis() {
const { max, min, yDivider, maxYPoint, longestLine } = this.calYAxisBoundary();
let maxItem;
this._datasets.forEach((dataset) => {
dataset.points.forEach((item) => {
if (!maxItem) {
maxItem = item;
} else {
if (item.value > maxItem.value) {
maxItem = item;
}
}
});
});
const { height } = this.calLabelDataForItem(0, 0, maxItem.barLabel || []);
const { yAxis } = this._config;
// 用于绘制的数据
const yAxisData = [];
// Y轴文案所占据的宽度
let yAxisWidth = 0;
const cHeight = this._boundary.leftBottom.y - this._boundary.leftTop.y;
// 计算Y轴上两个点之间的像素值
let unitY = cHeight / (yDivider * this._render.yMultiple * this._config.yAxis.yAxisCount);
/**
* 计算最长的条加上label之后的高度,如果超过绘图边界,将unitY更改成刚好使得最长的条填充满绘图区
* 这里仍然存在一种可能,很短的条有很多label导致超过绘图边界,不予考虑
*/
const maxH = (maxItem.value - min) * unitY * this._render.yMultiple;
if (maxH + height > cHeight) {
unitY = (cHeight - height) / (maxItem.value - min) / this._render.yMultiple;
}
const leftStart = this._boundary.leftTop.x + yAxis.marginLeft;
const bottomStart = this._boundary.leftBottom.y;
const changeFunc = (this._config.changeUnit && this._config.changeUnit !== _util_js__WEBPACK_IMPORTED_MODULE_0__["none"] ?
this._config.changeUnit :
_util_js__WEBPACK_IMPORTED_MODULE_0__["changeUnit"]);
const toFixed = ((max < 1 || max > 1e7) ?
2 :
1);
for (let i = 0; i < this._config.yAxis.yAxisCount + 1; i++) {
const word = {
text: changeFunc(min + i * yDivider, toFixed) + this._config.yAxis.unit,
color: yAxis.color,
fontSize: yAxis.fontSize,
x: leftStart,
y: bottomStart - (i * yDivider * unitY * this._render.yMultiple),
};
yAxisWidth = Math.max(this.getWordWidth(word), yAxisWidth);
yAxisData.push(word);
}
// 考虑Y轴不需要文案的情况
yAxisWidth = (yAxis.show ?
yAxisWidth + yAxis.marginRight :
0);
this._render.unitY = unitY;
this._render.yAxisWidth = yAxisWidth;
this._render.yAxisData = yAxisData;
this._render.longestLinePointCnt = maxYPoint;
this._render.longestLine = longestLine;
this.log('calYAxis');
}
getMinY(data) {
return data.reduce(
(min, p) => (p.value < min ?
p.value :
min),
data[0].value,
);
}
getMaxY(data) {
return data.reduce(
(max, p) => (p.value > max ?
p.value :
max),
data[0].value,
);
}
/**
* 计算用于Y轴绘制需要的数据
* https://codeburst.io/javascript-finding-minimum-and-maximum-values-in-an-array-of-objects-329c5c7e22a2
*/
calYAxisBoundary() {
const datasets = this._datasets;
let maxYPoint = 0;
let longestLine = datasets[0];
const { yAxisCount } = this._config.yAxis;
let max = -Infinity;
let min = Infinity;
datasets.forEach((oneline) => {
const points = oneline.points || [];
if (points.length > maxYPoint) {
maxYPoint = points.length;
longestLine = oneline;
}
max = Math.max(this.getMaxY(points), max);
min = Math.min(this.getMinY(points), min);
});
const formatFunc = this._config.formatY || _util_js__WEBPACK_IMPORTED_MODULE_0__["getDataRangeAndStep"];
const range = formatFunc(max, min, yAxisCount);
this._render.min = range.min;
this._render.max = range.max;
this._render.yMultiple = range.multiple || 1;
return {
max: range.max,
min: range.min,
yDivider: range.divider,
maxYPoint,
longestLine,
};
}
// 绘制X轴
drawXAxis() {
if (this._config.xAxisLine.centerShow) {
this.drawLine(this.ctx, this._render.xCenterAxis);
}
}
// 绘制Y轴
drawYAxis() {
// 绘制Y轴文案
if (this._config.yAxis.show) {
this._render.yAxisData.forEach((item) => {
this.drawWord(this.ctx, item);
});
}
// 根据配置来决定是否绘制Y中心轴
if (this._config.yAxis.centerShow) {
this.drawLine(this.ctx, this._render.yCenterAxis);
}
}
// 绘制Y轴横线
drawYAxisLine() {
if (this._config.yAxisLine.show) {
this._render.yAxisLines.forEach((line) => {
this.drawLine(this.ctx, line);
});
}
}
/**
* 绘制所有的点
*/
drawPoints() {
this._render.pointData.forEach((oneline) => {
if (oneline.points.length > 1) this.drawLongLineWithFill(this.ctx, oneline.points, oneline.style);
});
this._render.circlePoints.forEach((point) => {
this.drawCircle(this.ctx, point);
});
}
drawBars() {
this._render.bars.forEach((bar) => {
this.drawRect(this.ctx, bar);
});
this._render.barLabels.forEach((label) => {
this.drawWord(this.ctx, label);
});
this._render.topbarLabels.forEach((label) => {
this.drawWord(this.ctx, label);
});
}
/**
* 将处理后的合法数据按照配置绘制到canvas上面
*/
drawToCanvas() {
//清空画布
this.ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
this.drawYAxis();
this.log('drawYAxis');
this.drawYAxisLine();
this.log('drawYAxisLine');
this.drawXAxis();
this.log('drawXAxis');
this.drawBars();
this.log('drawPoints');
}
/**
* 数据清洗和合法性判断
* 数据字段比较多,存在后面的函数调用依赖前面的计算结果的情况
* 因此不能随便调换initData里面的函数顺序
*/
initData(data) {
this._datasets = (data.datasets || []).filter(dataset => !!dataset.points && dataset.points.length);
if (!this._datasets.length) {
return;
}
// 为了绘制精确,首先要计算绘制的边界值,防止样式走位
this.calBoundaryPoint();
// 计算Y轴数据
this.calYAxis();
// 计算Y轴线条数据
this.calYAxisLines();
// 计算X轴线条数据
this.calXAxisLines();
this.calBarData();
this.log('initData');
}
/**
* 实际的绘制函数
*/
draw(data, cfg = {}) {
this._start = new Date();
this.getConfig(cfg, this._config);
this.initData(data);
if (!this._datasets.length) {
this.drawEmptyData();
return;
}
this.drawToCanvas();
if (this._renderType == 'native')
this.ctx.draw();
this.log('realDraw');
if (this._config.debug) {
console.log(this._performance);
}
}
}
/***/ }),
/* 10 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
const barchartConfig = {
/**
* 给定一组数据,Y轴标签的最大值最小值和每一步的值都是组件自动算出来的
* 有些场景组件算出来的可能不满足需求,或者调用者就是想自定义Y轴标签的数据,
* 因此提供自定义的formatY(max, min, yAxisCount)函数,调用者按要求返回数据给组件处理即可
* @return {
* max: 将原始的最大值处理之后的最大值
* min: 将原始的最小值处理之后的最小值
* divider: 每一步的值
* multiple: 如果处理过程中发现divider是小于1的小数,需要将上面三个数值相对应放大一定倍数
* 似的divider是大于1的数值,同时将放大的倍数告知组件,默认为1
* }
*/
formatY: null,
// x轴文案的样式配置
xAxis: {
show: true,
marginTop: 10,
color: '#B8B8B8',
fontSize: 11,
},
/**
* X轴轴体的样式配置
*/
xAxisLine: {
show: false,
centerShow: true,
width: 0.6,
color: '#C6C6C6',
style: 'solid',
},
/**
* y轴的样式配置
*/
yAxis: {
show: true,
marginLeft: 0,
marginRight: 10,
color: '#B8B8B8',
fontSize: 11,
unit: '',
/**
* 默认Y轴打四个点
* 也可以自行配置,但仍然会有保底逻辑
*/
yAxisCount: 4,
},
/**
* Y轴轴体的样式
*/
yAxisLine: {
show: true,
centerShow: false,
width: 0.2,
color: '#C6C6C6',
},
barStyle: {
fillColor: '#6684C7',
compareBarMargin: 5,
barWidth: 30,
leftRightPadding: 10,
},
barLabelStyle: {
color: '#B8B8B8',
fontSize: 11,
paddingBottom: 5,
},
};
/* harmony default export */ __webpack_exports__["default"] = (Object(_util_js__WEBPACK_IMPORTED_MODULE_1__["extend"])(barchartConfig, _common_js__WEBPACK_IMPORTED_MODULE_0__["default"]));
/***/ })
/******/ ]);
}); | ;
} e |
v1_topology_spread_constraint.py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.19.15
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from kubernetes_asyncio.client.configuration import Configuration
class V1TopologySpreadConstraint(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'label_selector': 'V1LabelSelector',
'max_skew': 'int',
'topology_key': 'str',
'when_unsatisfiable': 'str'
}
attribute_map = {
'label_selector': 'labelSelector',
'max_skew': 'maxSkew',
'topology_key': 'topologyKey',
'when_unsatisfiable': 'whenUnsatisfiable'
}
def __init__(self, label_selector=None, max_skew=None, topology_key=None, when_unsatisfiable=None, local_vars_configuration=None): # noqa: E501
"""V1TopologySpreadConstraint - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._label_selector = None
self._max_skew = None
self._topology_key = None
self._when_unsatisfiable = None
self.discriminator = None
if label_selector is not None:
self.label_selector = label_selector
self.max_skew = max_skew
self.topology_key = topology_key
self.when_unsatisfiable = when_unsatisfiable
@property
def label_selector(self):
"""Gets the label_selector of this V1TopologySpreadConstraint. # noqa: E501
:return: The label_selector of this V1TopologySpreadConstraint. # noqa: E501
:rtype: V1LabelSelector
"""
return self._label_selector
@label_selector.setter
def label_selector(self, label_selector):
"""Sets the label_selector of this V1TopologySpreadConstraint.
:param label_selector: The label_selector of this V1TopologySpreadConstraint. # noqa: E501
:type: V1LabelSelector
"""
self._label_selector = label_selector
@property
def max_skew(self):
"""Gets the max_skew of this V1TopologySpreadConstraint. # noqa: E501
MaxSkew describes the degree to which pods may be unevenly distributed. When `whenUnsatisfiable=DoNotSchedule`, it is the maximum permitted difference between the number of matching pods in the target topology and the global minimum. For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with the same labelSelector spread as 1/1/0: | zone1 | zone2 | zone3 | | P | P | | - if MaxSkew is 1, incoming pod can only be scheduled to zone3 to become 1/1/1; scheduling it onto zone1(zone2) would make the ActualSkew(2-0) on zone1(zone2) violate MaxSkew(1). - if MaxSkew is 2, incoming pod can be scheduled onto any zone. When `whenUnsatisfiable=ScheduleAnyway`, it is used to give higher precedence to topologies that satisfy it. It's a required field. Default value is 1 and 0 is not allowed. # noqa: E501
:return: The max_skew of this V1TopologySpreadConstraint. # noqa: E501
:rtype: int
"""
return self._max_skew
@max_skew.setter
def max_skew(self, max_skew):
"""Sets the max_skew of this V1TopologySpreadConstraint.
MaxSkew describes the degree to which pods may be unevenly distributed. When `whenUnsatisfiable=DoNotSchedule`, it is the maximum permitted difference between the number of matching pods in the target topology and the global minimum. For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with the same labelSelector spread as 1/1/0: | zone1 | zone2 | zone3 | | P | P | | - if MaxSkew is 1, incoming pod can only be scheduled to zone3 to become 1/1/1; scheduling it onto zone1(zone2) would make the ActualSkew(2-0) on zone1(zone2) violate MaxSkew(1). - if MaxSkew is 2, incoming pod can be scheduled onto any zone. When `whenUnsatisfiable=ScheduleAnyway`, it is used to give higher precedence to topologies that satisfy it. It's a required field. Default value is 1 and 0 is not allowed. # noqa: E501
:param max_skew: The max_skew of this V1TopologySpreadConstraint. # noqa: E501
:type: int
"""
if self.local_vars_configuration.client_side_validation and max_skew is None: # noqa: E501
raise ValueError("Invalid value for `max_skew`, must not be `None`") # noqa: E501
self._max_skew = max_skew
@property
def topology_key(self):
"""Gets the topology_key of this V1TopologySpreadConstraint. # noqa: E501
TopologyKey is the key of node labels. Nodes that have a label with this key and identical values are considered to be in the same topology. We consider each <key, value> as a \"bucket\", and try to put balanced number of pods into each bucket. It's a required field. # noqa: E501
:return: The topology_key of this V1TopologySpreadConstraint. # noqa: E501
:rtype: str
"""
return self._topology_key
@topology_key.setter
def topology_key(self, topology_key):
"""Sets the topology_key of this V1TopologySpreadConstraint.
TopologyKey is the key of node labels. Nodes that have a label with this key and identical values are considered to be in the same topology. We consider each <key, value> as a \"bucket\", and try to put balanced number of pods into each bucket. It's a required field. # noqa: E501
:param topology_key: The topology_key of this V1TopologySpreadConstraint. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and topology_key is None: # noqa: E501
raise ValueError("Invalid value for `topology_key`, must not be `None`") # noqa: E501
self._topology_key = topology_key
@property
def when_unsatisfiable(self):
"""Gets the when_unsatisfiable of this V1TopologySpreadConstraint. # noqa: E501
WhenUnsatisfiable indicates how to deal with a pod if it doesn't satisfy the spread constraint. - DoNotSchedule (default) tells the scheduler not to schedule it. - ScheduleAnyway tells the scheduler to schedule the pod in any location, but giving higher precedence to topologies that would help reduce the skew. A constraint is considered \"Unsatisfiable\" for an incoming pod if and only if every possible node assigment for that pod would violate \"MaxSkew\" on some topology. For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with the same labelSelector spread as 3/1/1: | zone1 | zone2 | zone3 | | P P P | P | P | If WhenUnsatisfiable is set to DoNotSchedule, incoming pod can only be scheduled to zone2(zone3) to become 3/2/1(3/1/2) as ActualSkew(2-1) on zone2(zone3) satisfies MaxSkew(1). In other words, the cluster can still be imbalanced, but scheduler won't make it *more* imbalanced. It's a required field. # noqa: E501
:return: The when_unsatisfiable of this V1TopologySpreadConstraint. # noqa: E501
:rtype: str
"""
return self._when_unsatisfiable
@when_unsatisfiable.setter
def when_unsatisfiable(self, when_unsatisfiable):
"""Sets the when_unsatisfiable of this V1TopologySpreadConstraint.
WhenUnsatisfiable indicates how to deal with a pod if it doesn't satisfy the spread constraint. - DoNotSchedule (default) tells the scheduler not to schedule it. - ScheduleAnyway tells the scheduler to schedule the pod in any location, but giving higher precedence to topologies that would help reduce the skew. A constraint is considered \"Unsatisfiable\" for an incoming pod if and only if every possible node assigment for that pod would violate \"MaxSkew\" on some topology. For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with the same labelSelector spread as 3/1/1: | zone1 | zone2 | zone3 | | P P P | P | P | If WhenUnsatisfiable is set to DoNotSchedule, incoming pod can only be scheduled to zone2(zone3) to become 3/2/1(3/1/2) as ActualSkew(2-1) on zone2(zone3) satisfies MaxSkew(1). In other words, the cluster can still be imbalanced, but scheduler won't make it *more* imbalanced. It's a required field. # noqa: E501
:param when_unsatisfiable: The when_unsatisfiable of this V1TopologySpreadConstraint. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and when_unsatisfiable is None: # noqa: E501
raise ValueError("Invalid value for `when_unsatisfiable`, must not be `None`") # noqa: E501
self._when_unsatisfiable = when_unsatisfiable
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
|
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1TopologySpreadConstraint):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1TopologySpreadConstraint):
return True
return self.to_dict() != other.to_dict()
| """Returns the string representation of the model"""
return pprint.pformat(self.to_dict()) |
__init__.py | '''data_load module is for loading individual genedocs from various data sources.'''
from __future__ import print_function
import sys
import copy
import types
import time
import datetime
import importlib
from biothings.utils.mongo import get_src_conn, get_src_dump, get_data_folder
from biothings.utils.common import get_timestamp, get_random_string, timesofar, dump2gridfs, iter_n
from config import DATA_SRC_DATABASE, DATA_SRC_MASTER_COLLECTION
__sources_dict__ = {
'entrez': [
'entrez.entrez_gene',
'entrez.entrez_homologene',
'entrez.entrez_genesummary',
'entrez.entrez_accession',
'entrez.entrez_refseq',
'entrez.entrez_unigene',
'entrez.entrez_go',
'entrez.entrez_ec',
'entrez.entrez_retired',
'entrez.entrez_generif',
'entrez.entrez_genomic_pos',
],
'ensembl': [
'ensembl.ensembl_gene',
'ensembl.ensembl_acc',
'ensembl.ensembl_genomic_pos',
'ensembl.ensembl_prosite',
'ensembl.ensembl_interpro',
'ensembl.ensembl_pfam'
],
'uniprot': [
'uniprot',
'uniprot.uniprot_pdb',
# 'uniprot.uniprot_ipi', # IPI is now discontinued, last update is still in the db, but won't be updated.
'uniprot.uniprot_pir'
],
'pharmgkb': ['pharmgkb'],
'reporter': ['reporter'],
'ucsc': ['ucsc.ucsc_exons'],
'exac': ['exac.broadinstitute_exac'],
'cpdb': ['cpdb'],
'reagent': ['reagent'],
}
__sources__ = None # should be a list defined at runtime
conn = get_src_conn()
doc_register = {}
class GeneDocSourceMaster(dict):
'''A class to manage various genedoc data sources.'''
__collection__ = DATA_SRC_MASTER_COLLECTION
__database__ = DATA_SRC_DATABASE
use_dot_notation = True
use_schemaless = True
structure = {
'name': str,
'timestamp': datetime.datetime,
}
class GeneDocSource(dict):
'''A base class for all source data.'''
__collection__ = None # should be specified individually
__database__ = DATA_SRC_DATABASE
use_dot_notation = True
use_schemaless = True
DEFAULT_FIELDTYPE = str
temp_collection = None # temp collection is for dataloading
def | (self):
'''Create a temp collection for dataloading, e.g., entrez_geneinfo_INEMO.'''
new_collection = None
while 1:
new_collection = self.__collection__ + '_temp_' + get_random_string()
if new_collection not in self.db.collection_names():
break
self.temp_collection = self.db[new_collection]
return new_collection
def doc_iterator(self, genedoc_d, batch=True, step=10000):
if isinstance(genedoc_d, types.GeneratorType) and batch:
for doc_li in iter_n(genedoc_d, n=step):
yield doc_li
else:
if batch:
doc_li = []
i = 0
for _id, doc in genedoc_d.items():
doc['_id'] = _id
_doc = copy.copy(self)
_doc.clear()
_doc.update(doc)
#if validate:
# _doc.validate()
if batch:
doc_li.append(_doc)
i += 1
if i % step == 0:
yield doc_li
doc_li = []
else:
yield _doc
if batch:
yield doc_li
def load(self, genedoc_d=None, update_data=True, update_master=True, test=False, step=10000):
if not self.temp_collection:
self.make_temp_collection()
self.temp_collection.drop() # drop all existing records just in case.
if update_data:
genedoc_d = genedoc_d or self.load_genedoc()
print("genedoc_d mem: %s" % sys.getsizeof(genedoc_d))
print("Uploading to the DB...", end='')
t0 = time.time()
# for doc in self.doc_iterator(genedoc_d, batch=False):
# if not test:
# doc.save()
for doc_li in self.doc_iterator(genedoc_d, batch=True, step=step):
if not test:
self.temp_collection.insert(doc_li, manipulate=False, check_keys=False)
print('Done[%s]' % timesofar(t0))
self.switch_collection()
if getattr(self, 'ENTREZ_GENEDOC_ROOT', False):
print('Uploading "geneid_d" to GridFS...', end='')
t0 = time.time()
geneid_d = self.get_geneid_d()
dump2gridfs(geneid_d, self.__collection__ + '__geneid_d.pyobj', self.db)
print('Done[%s]' % timesofar(t0))
if getattr(self, 'ENSEMBL_GENEDOC_ROOT', False):
print('Uploading "mapping2entrezgene" to GridFS...', end='')
t0 = time.time()
x2entrezgene_list = self.get_mapping_to_entrez()
dump2gridfs(x2entrezgene_list, self.__collection__ + '__2entrezgene_list.pyobj', self.db)
print('Done[%s]' % timesofar(t0))
if update_master:
# update src_master collection
if not test:
_doc = {"_id": str(self.__collection__),
"name": str(self.__collection__),
"timestamp": datetime.datetime.now()}
for attr in ['ENTREZ_GENEDOC_ROOT', 'ENSEMBL_GENEDOC_ROOT', 'id_type']:
if hasattr(self, attr):
_doc[attr] = getattr(self, attr)
if hasattr(self, 'get_mapping'):
_doc['mapping'] = getattr(self, 'get_mapping')()
coll = conn[GeneDocSourceMaster.__database__][GeneDocSourceMaster.__collection__]
dkey = {"_id": _doc["_id"]}
prev = coll.find_one(dkey)
if prev:
coll.replace_one(dkey, _doc)
else:
coll.insert_one(_doc)
def switch_collection(self):
'''after a successful loading, rename temp_collection to regular collection name,
and renaming existing collection to a temp name for archiving purpose.
'''
if self.temp_collection and self.temp_collection.count() > 0:
if self.collection.count() > 0:
# renaming existing collections
new_name = '_'.join([self.__collection__, 'archive', get_timestamp(), get_random_string()])
self.collection.rename(new_name, dropTarget=True)
self.temp_collection.rename(self.__collection__)
else:
print("Error: load data first.")
@property
def collection(self):
return self.db[self.__collection__]
#def validate_all(self, genedoc_d=None):
# """validate all genedoc_d."""
# genedoc_d = genedoc_d or self.load_genedoc()
# for doc in self.doc_iterator(genedoc_d, batch=False, validate=True):
# pass
def register_sources():
for src in __sources__:
src_m = importlib.import_module('dataload.sources.' + src)
metadata = src_m.__metadata__
name = src + '_doc'
metadata['load_genedoc'] = src_m.load_genedoc
metadata['get_mapping'] = src_m.get_mapping
if metadata.get('ENTREZ_GENEDOC_ROOT', False):
metadata['get_geneid_d'] = src_m.get_geneid_d
if metadata.get('ENSEMBL_GENEDOC_ROOT', False):
metadata['get_mapping_to_entrez'] = src_m.get_mapping_to_entrez
src_cls = type(name, (GeneDocSource,), metadata)
# manually propagate db attr
src_cls.db = conn[src_cls.__database__]
doc_register[name] = src_cls
conn.register(src_cls)
# register_sources()
def get_src(src):
_src = conn[src + '_doc']()
return _src
def load_src(src, **kwargs):
_src = doc_register[src + '_doc']()
_src.load(**kwargs)
def update_mapping(src):
_src = conn[src + '_doc']()
_src.load(update_data=False, update_master=True)
def load_all(**kwargs):
for src in __sources__:
load_src(src, **kwargs)
def get_mapping():
mapping = {}
properties = {}
for src in __sources__:
print("Loading mapping from %s..." % src)
_src = conn[src + '_doc']()
_field_properties = _src.get_mapping()
properties.update(_field_properties)
mapping["properties"] = properties
# enable _source compression
mapping["_source"] = {"enabled": True,
"compress": True,
"compression_threshold": "1kb"}
return mapping
def update_mapping():
for src in __sources__:
colname = src.split(".")[-1]
col = conn[colname]
regdoc = doc_register[src + '_doc']
mastercol = conn[GeneDocSourceMaster.__database__][GeneDocSourceMaster.__collection__]
_doc = {"_id": str(colname),
"name": str(colname),
"timestamp": datetime.datetime.now(),
"mapping" : regdoc.get_mapping(regdoc)}
print("Updating mapping for source: %s" % repr(colname))
dkey = {"_id": _doc["_id"]}
prev = mastercol.find_one(dkey)
if prev:
mastercol.replace_one(dkey, _doc)
else:
mastercol.insert_one(_doc)
def main():
'''
Example:
python -m dataload ensembl.ensembl_gene ensembl.ensembl_acc ensembl.ensembl_genomic_pos ensembl.ensembl_prosite ensembl.ensembl_interpro
python -m dataload/__init__ entrez.entrez_gene entrez.entrez_homologene entrez.entrez_genesummary
entrez.entrez_accession entrez.entrez_refseq entrez.entrez_unigene entrez.entrez_go
entrez.entrez_ec entrez.entrez_retired
'''
global __sources__
__sources__ = sys.argv[1:]
register_sources()
load_all()
if __name__ == '__main__':
main()
| make_temp_collection |
select_sf.py | # intersection_of_sf.py
# This script uses Library of Congress tags,
# plus a list of volumes called "science fiction"
# by the OCLC, to extract Hathi vols likely to
# be SF. Some further manual grooming
# will be required.
import csv
from difflib import SequenceMatcher
import SonicScrewdriver as utils
def titleregularize(title):
title = title.lower().strip('/ .,:-')
title = title.replace('the', 'x')
if len(title) < 4:
title = title + " "
firstchars = title[0:3]
return title, firstchars
def authorregularize(author):
author = author.strip('/ ,.:123456789-').lower()
return author
oclc = set()
sftitles = dict()
with open('../rawdata/oclc_science_fiction.csv', encoding = 'utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
oclc.add(row['oclcwi'])
if len(row['title']) > 10:
title, firstchars = titleregularize(row['title'])
author = authorregularize(row['author'].split('|')[0])
if firstchars not in sftitles:
sftitles[firstchars] = set()
sftitles[firstchars].add((title, author))
def isitsf(row):
global oclc, sftitles
sf = False
reason = ''
if 'Science fiction' in row['subjects']:
sf = True
reason = 'taggedsf'
elif 'Science fiction' in row['imprint']:
sf = True
reason = 'taggedsf'
elif row['oclc'] in oclc:
sf = True
reason = 'oclcid'
else:
title = row['title']
firstpart = title.split('|')[0]
if len(firstpart) < 10:
return sf, reason
title, firstchars = titleregularize(firstpart)
if firstchars not in sftitles:
return sf, reason
author = authorregularize(row['author'])
for t, a in sftitles[firstchars]:
m = SequenceMatcher(None, title, t)
ratio = m.real_quick_ratio()
if ratio > 0.8:
betterratio = m.ratio()
n = SequenceMatcher(None, author, a)
authorratio = n.ratio()
if betterratio > 0.9 and authorratio > 0.7:
print(t, title, a, author)
sf = True
reason = 'fuzzymatch'
return sf, reason
counter = 0
fuzzycounter = 0
reasons = dict()
allsf = []
def get_matches(filepath, allsf, counter, fuzzycounter, reasons):
|
secondfile = '../../noveltmmeta/pre1923hathifiction.csv'
firstfile = '../../noveltmmeta/incopyrightfiction.csv'
allsf, counter, fuzzycounter, reasons = get_matches(firstfile, allsf, counter, fuzzycounter, reasons)
print()
print('A total of ' + str(counter) + ' volumes were scanned.')
print()
allsf, counter, fuzzycounter, reasons = get_matches(secondfile, allsf, counter, fuzzycounter, reasons)
fieldnames = ['docid', 'recordid', 'oclc', 'locnum', 'includedbc', 'author', 'authordate', 'imprint', 'inferreddate', 'place', 'enumcron', 'subjects', 'genres', 'title']
print()
print('A total of ' + str(counter) + ' volumes were scanned.')
print()
print('A total of ' + str(fuzzycounter) + ' volumes were fuzzymatched.')
print()
with open('../rawdata/sf_intersection.csv', mode = 'w', encoding = 'utf-8') as f:
writer = csv.DictWriter(f, fieldnames = fieldnames, extrasaction = 'ignore')
writer.writeheader()
for row in allsf:
if 'htid' in row:
row['docid'] = row['htid']
row['includedbc'] = reasons[row['docid']]
if 'inferreddate' not in row:
row['inferreddate'] = utils.date_row(row)
if 'authordate' not in row:
row['authordate'] = ''
if 'genres' not in row:
genres = ''
if ' / |' in row['title']:
row['title'] = row['title'].split(' / |')[0]
writer.writerow(row)
| with open(filepath, encoding = 'utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
if counter % 100 == 1:
print(counter)
counter += 1
if 'htid' in row:
docid = row['htid']
else:
docid = row['docid']
sf, reason = isitsf(row)
if sf:
allsf.append(row)
reasons[docid] = reason
if reason == 'fuzzymatch':
fuzzycounter += 1
return allsf, counter, fuzzycounter, reasons |
ReactorGridBlock.py | from json import JSONEncoder
from PyQt6.QtGui import QIcon, QResizeEvent, QColor, QPainter, QBrush, QPen, QFont
from PyQt6.QtWidgets import QGridLayout, QWidget, QSizePolicy, QHBoxLayout, QGraphicsSimpleTextItem, QGraphicsRectItem, QGraphicsPixmapItem
from PyQt6.QtCore import Qt, pyqtSignal, QSize, QRect
from Assets import Assets
from Settings import Settings
class ReactorGridBlockEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, ReactorGridBlock):
data = [ obj.shape_small, obj.coolant_name, [button.rod_name for button in obj.get_active_buttons()] ]
return data
return super().default(obj)
class AARRectItem(QGraphicsRectItem):
def __init__(self, x, y, w, h, parent):
super().__init__(x, y, w, h, parent)
self.enable_aa = Settings().get_bool("Antialiasing")
def paint(self, painter, opts, widget=None):
painter.setPen(self.pen())
if self.enable_aa:
painter.setRenderHint(QPainter.Antialiasing)
painter.drawRoundedRect(self.rect(), 1, 1)
class ReactorGridButton(QGraphicsRectItem):
def __init__(self, x, y, w, h, i, j, parent=None):
x -= 0.05
y -= 0.05
w += 0.1
h += 0.1
super().__init__(x, y, w, h, parent)
self.enable_aa = Settings().get_bool("Antialiasing")
self.x = x
self.y = y
self.w = w
self.h = h
self.i = i
self.j = j
if self.w > 100:
self.tsz = 30
self.ofs = 30
else:
self.tsz = 18
self.ofs = 22
self.setPen(QPen(Qt.NoPen))
self.progress_bar_green = QGraphicsRectItem(x, y + h - 11, w, 11, self)
self.progress_bar_green.setBrush(QColor(210, 255, 210, 255))
self.progress_bar_green.setPen(QPen(Qt.NoPen))
self.progress_bar_red = QGraphicsRectItem(x + w, y + h - 11, 0, 11, self)
self.progress_bar_red.setBrush(QColor(255, 210, 210, 255))
self.progress_bar_red.setPen(QPen(Qt.NoPen))
self.rod_pixmap = QGraphicsPixmapItem(self)
self.rod_pixmap.setPos(self.x + self.w / 2 - self.tsz / 2, self.y + self.h / 2 - self.tsz / 2)
self.line = AARRectItem(x, y, w, h, self)
self.line.setPen(QPen(QColor(160, 160, 160, 255), 1.2))
self.labels = [QGraphicsSimpleTextItem(self) for i in range(7)]
font = self.labels[0].font()
font.setPixelSize(11) # point size 8
if not self.enable_aa:
font.setStyleStrategy(QFont.NoAntialias)
for label in self.labels:
label.setFont(font)
self.rod_name = None
self.set_rod("None")
self.overmax = False
self.reset_durability()
self.reset_neutron_count()
self.selected = False
self.hovered = False
self.setAcceptHoverEvents(True)
self.setAcceptedMouseButtons(Qt.LeftButton)
def get_position(self):
return (self.i, self.j)
def mousePressEvent(self, event):
self.parentItem().on_click(self)
def | (self, event):
self.hovered = True
if not self.selected:
self.line.setPen(QPen(QColor(155, 170, 212, 255), 1.2))
def hoverLeaveEvent(self, event):
self.hovered = False
if not self.selected:
self.line.setPen(QPen(QColor(160, 160, 160, 255), 1.2))
def set_selected(self, val):
self.selected = val
if self.selected:
self.line.setPen(QPen(QColor(77, 108, 191, 255), 1.5))
else:
if self.hovered:
self.line.setPen(QPen(QColor(155, 170, 212, 255), 1.2))
else:
self.line.setPen(QPen(QColor(160, 160, 160, 255), 1.2))
def logical_copy(self, parent=None):
obj = ReactorGridButton(self.x, self.y, self.w, self.h, self.i, self.j, parent)
obj.rod_name = self.rod_name
return obj
def is_empty(self):
return self.rod_name == "None"
def is_full(self):
return not self.is_empty()
def is_shallow_empty(self):
return self.rod_name == "None"
def is_deep_empty(self):
return False
def is_same(self, other):
return self.rod_name == other.rod_name
def is_shallow_same(self, other):
return self.rod_name == other.rod_name
def is_deep_same(self, other):
return False
def is_same_size(self, other):
return False
def set_rod(self, name):
if name == self.rod_name:
return None
old_name = self.rod_name
self.rod_name = name
self.rod_pixmap.setPixmap(Assets().rod[name].pixmap_top.scaled(self.tsz, self.tsz))
if name == "None":
self.set_label_mid_top("")
else:
self.set_label_mid_top(name)
return old_name
def set_durability(self, percent):
frac = percent / 100
self.progress_bar_green.setRect(self.x, self.y + self.h - 11, self.w * frac, 11)
self.progress_bar_red.setRect(self.x + self.w * frac, self.y + self.h - 11, self.w * (1 - frac), 11)
self.progress_bar_green.show()
self.progress_bar_red.show()
def set_neutron_count(self, ncount, noutput_percent):
self.set_label_bottom_right(str(ncount) + " N")
if (noutput_percent >= 0):
if noutput_percent > 100.0000000001:
if not self.overmax:
self.overmax = True
self.labels[5].setBrush(QColor(255, 0, 0, 255))
else:
if self.overmax:
self.overmax = False
self.labels[5].setBrush(QColor(0, 0, 0, 255))
self.set_label_bottom_right_2("{:.2f}".format(noutput_percent) + " %")
def set_moderation_factor(self, factor):
self.set_label_bottom_right("x" + str(factor))
def reset_durability(self):
self.progress_bar_green.hide()
self.progress_bar_red.hide()
def reset_neutron_count(self):
self.set_label_bottom_right("")
self.set_label_bottom_right_2("")
def set_label_top_left(self, text):
self.labels[0].setText(text)
self.labels[0].setPos(self.x + 2, self.y)
def set_label_top_right(self, text):
self.labels[1].setText(text)
self.labels[1].setPos(self.x + self.w - self.labels[1].boundingRect().width() - 2, self.y)
def set_label_bottom_left(self, text):
self.labels[2].setText(text)
self.labels[2].setPos(self.x + 2, self.y + self.h - 14)
def set_label_bottom_right(self, text):
self.labels[3].setText(text)
self.labels[3].setPos(self.x + self.w - self.labels[3].boundingRect().width() - 2, self.y + self.h - 14)
def set_label_top_left_2(self, text):
self.labels[4].setText(text)
self.labels[4].setPos(self.x + 2, self.y + 11)
def set_label_bottom_right_2(self, text):
self.labels[5].setText(text)
self.labels[5].setPos(self.x + self.w - self.labels[5].boundingRect().width() - 2, self.y + self.h - 11 - 14)
def set_label_mid_top(self, text):
self.labels[6].setText(text)
self.labels[6].setPos(self.x + (self.w - self.labels[6].boundingRect().width()) / 2, self.y + self.h / 2 - self.ofs)
class ReactorGridBlockHeader(QGraphicsRectItem):
def __init__(self, x, y, w, h, parent=None):
super().__init__(x, y, w, h, parent)
self.x = x
self.y = y
self.w = w
self.h = h
self.enable_aa = Settings().get_bool("Antialiasing")
self.label_left = QGraphicsSimpleTextItem(self)
self.label_right = QGraphicsSimpleTextItem(self)
font = self.label_left.font()
font.setPixelSize(11) # point size 8
if not self.enable_aa:
font.setStyleStrategy(QFont.NoAntialias)
self.label_left.setFont(font)
self.label_right.setFont(font)
self.setPen(QPen(Qt.NoPen))
self.large_head = QGraphicsRectItem(x, y, w, h, self)
self.small_head_left = QGraphicsRectItem(x, y, (w - 4) / 2, h, self)
self.small_head_right = QGraphicsRectItem(x + (w + 4) / 2, y, (w - 4) / 2, h, self)
self.large_head.setPen(QPen(Qt.NoPen))
self.small_head_left.setPen(QPen(Qt.NoPen))
self.small_head_right.setPen(QPen(Qt.NoPen))
self.large_head.setBrush(QColor(150, 150, 150, 70))
self.small_head_left.setBrush(QColor(150, 150, 150, 70))
self.small_head_right.setBrush(QColor(150, 150, 150, 70))
self.small_head_left.hide()
self.small_head_right.hide()
self.large_head.setZValue(-1)
self.small_head_left.setZValue(-1)
self.small_head_right.setZValue(-1)
def set_small(self):
self.small_head_left.show()
self.small_head_right.show()
self.large_head.hide()
def set_large(self):
self.small_head_left.hide()
self.small_head_right.hide()
self.large_head.show()
def set_label_left(self, text):
self.label_left.setText(text)
self.label_left.setPos(self.x + 2, self.y - 1)
def set_label_right(self, text):
self.label_right.setText(text)
self.label_right.setPos(self.x + self.w - self.label_right.boundingRect().width() - 2, self.y - 1)
class ReactorGridBlock(QGraphicsRectItem):
show_HUt_Lt = False
def __init__(self, yp, xp, parent=None):
x = xp * 142.0 + 1
y = yp * 142.0 + 1
w = 140.0
h = 140.0
super().__init__(x, y, w, h, parent)
self.xp = xp
self.yp = yp
self.x = x
self.y = y
self.w = w
self.h = h
self.buttons_small = [ReactorGridButton(self.x + 2, self.y + 2, (self.w - 8) / 2, (self.w - 8) / 2, 0, 0, self),
ReactorGridButton(self.x + 6 + (self.w - 8) / 2, self.y + 2, (self.w - 8) / 2, (self.w - 8) / 2, 0, 1, self),
ReactorGridButton(self.x + 2, self.y + 6 + (self.w - 8) / 2, (self.w - 8) / 2, (self.w - 8) / 2, 1, 0, self),
ReactorGridButton(self.x + 6 + (self.w - 8) / 2, self.y + 6 + (self.w - 8) / 2, (self.w - 8) / 2, (self.w - 8) / 2, 1, 1, self)]
self.button_top_left = self.buttons_small[0]
self.button_top_right = self.buttons_small[1]
self.button_bottom_left = self.buttons_small[2]
self.button_bottom_right = self.buttons_small[3]
self.button_large = ReactorGridButton(self.x + 2, self.y + 2, (self.w - 4), (self.w - 4), -1, -1, self)
for button in self.buttons_small:
button.hide()
self.header = ReactorGridBlockHeader(self.x + 2, self.y + 2, self.w - 4, 13, self)
self.shape_small = False
self.coolant_name = None
self.set_coolant("None")
self.expcolor = False
self.reset_coolant_flux()
self.setPen(QPen(Qt.NoPen))
def get_position(self):
return (self.yp, self.xp)
def on_click(self, button):
self.scene().parent().on_click(self, button)
def logical_copy(self, parent=None):
obj = ReactorGridBlock(self.xp, self.yp, parent)
obj.coolant_name = self.coolant_name
if self.shape_small:
obj.toggle_shape()
for a,b in zip(self.get_active_buttons(), obj.get_active_buttons()):
b.rod_name = a.rod_name
return obj
def reset(self):
self.set_coolant("None")
self.button_large.set_rod("None")
for button in self.buttons_small:
button.set_rod("None")
if self.shape_small:
self.toggle_shape()
def get_active_buttons(self):
if self.shape_small:
return self.buttons_small
else:
return [self.button_large]
def is_empty(self):
empty = self.coolant_name == "None"
for button in self.get_active_buttons():
if not button.is_empty():
empty = False
break
return empty
def is_shallow_empty(self):
return self.coolant_name == "None"
def is_deep_empty(self):
empty = True
for button in self.get_active_buttons():
if not button.is_empty():
empty = False
break
return empty
def is_small(self):
return self.shape_small
def is_same(self, other):
same = self.coolant_name == other.coolant_name and self.shape_small == other.shape_small
for a,b in zip(self.get_active_buttons(), other.get_active_buttons()):
if not a.is_same(b):
same = False
break
return same
def is_shallow_same(self, other):
return self.coolant_name == other.coolant_name
def is_deep_same(self, other):
same = self.shape_small == other.shape_small
for a,b in zip(self.get_active_buttons(), other.get_active_buttons()):
if not a.is_same(b):
same = False
break
return same
def is_same_size(self, other):
return self.shape_small == other.shape_small
def toggle_shape(self):
self.shape_small = not self.shape_small
if self.shape_small:
self.button_large.hide()
self.header.set_small()
for button in self.buttons_small:
button.show()
else:
for button in self.buttons_small:
button.hide()
self.button_large.show()
self.header.set_large()
def set_coolant(self, name):
if name == self.coolant_name:
return None
old_name = self.coolant_name
self.coolant_name = name
if name == "None":
self.header.hide()
else:
self.header.set_label_left(name)
self.header.show()
for button in [*self.buttons_small, self.button_large]:
button.setBrush(QColor(Assets().coolant[name].color))
return old_name
def set_coolant_flux(self, Lt, HUt, exp):
self.set_exploded(exp)
if ReactorGridBlock.show_HUt_Lt:
self.header.set_label_right(HUt + " HU/t")
else:
self.header.set_label_right(Lt + " L/t")
def reset_coolant_flux(self):
self.set_exploded(False)
self.header.label_right.setText("")
def sizeHint(self):
return self.button_large.size()
def minimumSizeHint(self):
return self.button_large.size()
def set_exploded(self, value):
if value != self.expcolor:
self.expcolor = value
if value:
self.header.label_right.setBrush(QColor(255, 0, 0, 255))
else:
self.header.label_right.setBrush(QColor(0, 0, 0, 255)) | hoverEnterEvent |
beatport.py | import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import int_or_none
class BeatportIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.|pro\.)?beatport\.com/track/(?P<display_id>[^/]+)/(?P<id>[0-9]+)'
_TESTS = [{
'url': 'https://beatport.com/track/synesthesia-original-mix/5379371',
'md5': 'b3c34d8639a2f6a7f734382358478887',
'info_dict': {
'id': '5379371',
'display_id': 'synesthesia-original-mix',
'ext': 'mp4',
'title': 'Froxic - Synesthesia (Original Mix)',
},
}, {
'url': 'https://beatport.com/track/love-and-war-original-mix/3756896',
'md5': 'e44c3025dfa38c6577fbaeb43da43514',
'info_dict': {
'id': '3756896',
'display_id': 'love-and-war-original-mix',
'ext': 'mp3',
'title': 'Wolfgang Gartner - Love & War (Original Mix)',
},
}, {
'url': 'https://beatport.com/track/birds-original-mix/4991738',
'md5': 'a1fd8e8046de3950fd039304c186c05f',
'info_dict': {
'id': '4991738',
'display_id': 'birds-original-mix',
'ext': 'mp4',
'title': "Tos, Middle Milk, Mumblin' Johnsson - Birds (Original Mix)",
}
}]
def | (self, url):
mobj = self._match_valid_url(url)
track_id = mobj.group('id')
display_id = mobj.group('display_id')
webpage = self._download_webpage(url, display_id)
playables = self._parse_json(
self._search_regex(
r'window\.Playables\s*=\s*({.+?});', webpage,
'playables info', flags=re.DOTALL),
track_id)
track = next(t for t in playables['tracks'] if t['id'] == int(track_id))
title = ', '.join((a['name'] for a in track['artists'])) + ' - ' + track['name']
if track['mix']:
title += ' (' + track['mix'] + ')'
formats = []
for ext, info in track['preview'].items():
if not info['url']:
continue
fmt = {
'url': info['url'],
'ext': ext,
'format_id': ext,
'vcodec': 'none',
}
if ext == 'mp3':
fmt['acodec'] = 'mp3'
fmt['abr'] = 96
fmt['asr'] = 44100
elif ext == 'mp4':
fmt['acodec'] = 'aac'
fmt['abr'] = 96
fmt['asr'] = 44100
formats.append(fmt)
self._sort_formats(formats)
images = []
for name, info in track['images'].items():
image_url = info.get('url')
if name == 'dynamic' or not image_url:
continue
image = {
'id': name,
'url': image_url,
'height': int_or_none(info.get('height')),
'width': int_or_none(info.get('width')),
}
images.append(image)
return {
'id': compat_str(track.get('id')) or track_id,
'display_id': track.get('slug') or display_id,
'title': title,
'formats': formats,
'thumbnails': images,
}
| _real_extract |
link.py | import subprocess, os
import tempfile, qiime2
from q2_pepsirf.format_types import PeptideFastaFmt, ProteinFastaFmt, PepsirfLinkTSVFormat
| # Process: runs pepsirf's link module
# Method inputs/parameters: protein_file, peptide_file, meta,
# kmer_size, kmer_redundancy_control, outfile, pepsirf_binary
# Method outputs/Returned: the link tsv
# Dependencies: subprocess, os, tempfile
def link(
protein_file: ProteinFastaFmt,
peptide_file: PeptideFastaFmt,
meta: str,
kmer_size: int,
kmer_redundancy_control: bool = False,
outfile: str = "./link.out",
pepsirf_binary: str = "pepsirf") -> PepsirfLinkTSVFormat:
#collect filepath for TSVFormat
tsv_output = PepsirfLinkTSVFormat()
#collect absolute filepaths for input files and binary if it is a file
protein_file = "'%s'" % (str(protein_file))
peptide_file = "'%s'" % (str(peptide_file))
if os.path.isfile(pepsirf_binary):
pepsirf_binary = "'%s'" % (os.path.abspath(pepsirf_binary))
#create a temp directory to run pepsirf in
with tempfile.TemporaryDirectory() as tempdir:
#start command with required/defualt parameters
cmd = "%s link --protein_file %s --peptide_file %s --meta %s -k %s -o %s" % (
pepsirf_binary, protein_file, peptide_file, meta, str(kmer_size), tsv_output
)
#check if optional parameters are inputted and add to command
if kmer_redundancy_control:
cmd += " -r"
#add outfile to command
cmd += ' >> %s' % (outfile)
#run command in the command line
subprocess.run(cmd, shell=True, check=True)
#return norm output
return tsv_output | # Name: link
|
mod.rs | //! Low-level implementation of an AA tree. You shouldn't have to use this directly; instead, use
//! the implementations in [`AATreeSet`](crate::AATreeSet) and [`AATreeMap`](crate::AATreeMap).
use alloc::boxed::Box;
use core::mem;
mod insert;
pub use insert::*;
mod remove;
pub use remove::*;
mod traverse;
pub use traverse::*;
#[derive(Clone, Debug, PartialEq)]
pub struct AANode<T>(Option<Box<Node<T>>>);
#[derive(Clone, Debug, PartialEq)]
pub(super) struct Node<T> {
pub(super) level: u8,
pub(super) content: T,
pub(super) left_child: AANode<T>,
pub(super) right_child: AANode<T>
}
impl<T> From<Node<T>> for AANode<T> {
fn from(node: Node<T>) -> Self {
Self(Some(Box::new(node)))
}
}
impl<T> Default for AANode<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> From<T> for AANode<T> {
fn from(content: T) -> Self |
}
impl<T> AANode<T> {
pub(super) fn unbox(self) -> Option<Node<T>> {
self.0.map(|this| *this)
}
pub(super) fn as_ref(&self) -> Option<&Node<T>> {
self.0.as_ref().map(Box::as_ref)
}
fn as_mut(&mut self) -> Option<&mut Node<T>> {
self.0.as_mut().map(Box::as_mut)
}
fn take(&mut self) -> Self {
Self(self.0.take())
}
/// Create a new `Nil` node.
pub const fn new() -> Self {
Self(None)
}
/// Return true if this node is `Nil`.
pub const fn is_nil(&self) -> bool {
self.0.is_none()
}
/// Return true if this node is a leaf.
pub fn is_leaf(&self) -> bool {
match self.as_ref() {
None => false,
Some(Node {
left_child, right_child, ..
}) => left_child.is_nil() && right_child.is_nil()
}
}
/// Return true if this node has a left child.
pub fn has_left_child(&self) -> bool {
match self.as_ref() {
None => false,
Some(Node { left_child, .. }) => !left_child.is_nil()
}
}
/// Return true if this node has a right child.
pub fn has_right_child(&self) -> bool {
match self.as_ref() {
None => false,
Some(Node { right_child, .. }) => !right_child.is_nil()
}
}
fn left_child_mut(&mut self) -> Option<&mut Self> {
self.as_mut()
.and_then(|Node { left_child, .. }| (!left_child.is_nil()).then(|| left_child))
}
fn right_child_mut(&mut self) -> Option<&mut Self> {
self.as_mut()
.and_then(|Node { right_child, .. }| (!right_child.is_nil()).then(|| right_child))
}
fn set_right_child(&mut self, child: Self) {
match self.as_mut() {
None => panic!("I don't have a right child"),
Some(Node { right_child, .. }) => {
*right_child = child;
}
}
}
pub(super) fn level(&self) -> u8 {
match self.as_ref() {
None => 0,
Some(Node { level, .. }) => *level
}
}
fn content_mut(&mut self) -> Option<&mut T> {
self.as_mut().map(|Node { content, .. }| content)
}
/// Update the level of this node. **Panic** if the node is [`Nil`](Self::Nil).
fn set_level(&mut self, level: u8) {
match self.as_mut() {
None => panic!("Cannot change level of Nil"),
Some(Node { level: l, .. }) => mem::replace(l, level)
};
}
/// ```none
/// L <--- S S ---> T
/// / \ \ => / / \
/// A B R A B R
/// ```
fn skew(mut self) -> Self {
match self.as_mut() {
None => self,
Some(Node {
level, left_child: l, ..
}) => {
// if level = l.level, remove the B node from L
let b_node = match l.as_mut() {
Some(Node {
level: l_level,
right_child: b,
..
}) if level == l_level => b.take(),
_ => return self
};
// add the B node as our left child, removing L
let mut l_node = mem::replace(l, b_node);
// add our node T as the right child of L
l_node.as_mut().unwrap_or_else(|| unreachable!()).right_child = self;
// L is our new node
l_node
}
}
}
/// ```none
/// S --> R --> X R
/// / / => / \
/// A B T X
/// / \
/// A B
/// ```
fn split(mut self) -> Self {
match self.as_mut() {
None => self,
Some(Node {
level, right_child: r, ..
}) => {
// remove the B node if R and X are not Nil
let b_node = match r.as_mut() {
Some(Node {
left_child: b,
right_child: x,
..
}) if &x.level() == level => b.take(),
_ => return self
};
// attach the B node to our node, removing R
let mut r_node = mem::replace(r, b_node);
// attach our node to R and increment its level
let r_node_mut = r_node.as_mut().unwrap_or_else(|| unreachable!());
r_node_mut.level += 1;
r_node_mut.left_child = self;
// R is our new node
r_node
}
}
}
}
#[cfg(all(test, not(feature = "benchmark")))]
mod test {
use super::*;
macro_rules! tree {
() => {
AANode::new()
};
(Nil) => {
AANode::new()
};
($content:expr) => {
AANode::from($content)
};
($content:expr => [$level:expr, $left:tt, $right:tt]) => {
{
let _left = tree!(@internal $left);
let _right = tree!(@internal $right);
AANode(Some(Box::new(Node {
level: $level,
content: $content,
left_child: _left,
right_child: _right
})))
}
};
(@internal ($content:expr => [$level:expr, $left:tt, $right:tt])) => {
tree!($content => [$level, $left, $right])
};
(@internal $inner:tt) => {
tree!($inner)
};
}
// ### TEST SKEW ###
#[test]
fn test_skew_nil() {
let root: AANode<char> = tree!();
println!("Input: {:?}", root);
let skewed = root.skew();
let expected = tree!();
assert_eq!(skewed, expected);
}
#[test]
fn test_skew_leaf() {
let root = tree!('T');
println!("Input: {:?}", root);
let skewed = root.skew();
let expected = tree!('T');
assert_eq!(skewed, expected);
}
#[test]
fn test_skew_simple() {
let root = tree!('T' => [2, ('L' => [2, Nil, Nil]), 'R']);
println!("Input: {:?}", root);
let skewed = root.skew();
let expected = tree!('L' => [2, Nil, ('T' => [2, Nil, 'R'])]);
assert_eq!(skewed, expected);
}
#[test]
fn test_skew_full() {
let root = tree!('T' => [2, ('L' => [2, 'A', 'B']), 'R']);
println!("Input: {:?}", root);
let skewed = root.skew();
let expected = tree!('L' => [2, 'A', ('T' => [2, 'B', 'R'])]);
assert_eq!(skewed, expected);
}
// ### TEST SPLIT ###
#[test]
fn test_split_nil() {
let root: AANode<char> = tree!();
println!("Input: {:?}", root);
let splitted = root.split();
let expected = tree!();
assert_eq!(splitted, expected);
}
#[test]
fn test_split_leaf() {
let root = tree!('T');
println!("Input: {:?}", root);
let splitted = root.split();
let expected = tree!('T');
assert_eq!(splitted, expected);
}
#[test]
fn test_split_good_tree() {
let root = tree!('T' => [2, 'A', ('R' => [2, 'B', 'X'])]);
println!("Input: {:?}", root);
let splitted = root.split();
let expected = tree!('T' => [2, 'A', ('R' => [2, 'B', 'X'])]);
assert_eq!(splitted, expected);
}
#[test]
fn test_split_bad_tree() {
let root = tree!('T' => [2, 'A', ('R' => [2, 'B', ('X' => [2, 'Y', 'Z'])])]);
println!("Input: {:?}", root);
let splitted = root.split();
let expected = tree!('R' => [3, ('T' => [2, 'A', 'B']), ('X' => [2, 'Y', 'Z'])]);
assert_eq!(splitted, expected);
}
// ### TEST INSERT ###
#[test]
fn test_insert_greater() {
let mut root = tree!();
for content in ['A', 'B', 'C', 'D', 'E', 'F', 'G'].iter() {
assert!(root.insert(*content));
}
let expected = tree!('D' => [3, ('B' => [2, 'A', 'C']), ('F' => [2, 'E', 'G'])]);
assert_eq!(root, expected);
}
#[test]
fn test_insert_smaller() {
let mut root = tree!();
for content in ['Z', 'Y', 'X', 'W', 'V'].iter() {
assert!(root.insert(*content));
}
let expected = tree!('W' => [2, 'V', ('Y' => [2, 'X', 'Z'])]);
assert_eq!(root, expected);
}
#[test]
fn test_insert_multiple() {
let mut root = tree!();
for content in ['A', 'A'].iter() {
root.insert(*content);
}
let expected = tree!('A');
assert_eq!(root, expected);
}
// ### TEST REMOVE ###
#[test]
fn test_remove_successor() {
let mut root = tree!('B' => [1, Nil, 'C']);
println!("Input: `{:?}`", root);
let removed = root.remove(&'B');
let expected = tree!('C');
assert_eq!(removed, Some('B'));
assert_eq!(root, expected);
}
#[test]
fn test_remove_predecessor() {
let mut root = tree!('B' => [2, 'A', 'C']);
println!("Input: `{:?}`", root);
let removed = root.remove(&'B');
let expected = tree!('A' => [1, Nil, 'C']);
assert_eq!(removed, Some('B'));
assert_eq!(root, expected);
}
#[test]
fn test_remove_complex() {
// example taken from https://web.eecs.umich.edu/~sugih/courses/eecs281/f11/lectures/12-AAtrees+Treaps.pdf
let mut root =
tree!(30 => [3, (15 => [2, 5, 20]), (70 => [3, (50 => [2, 35, (60 => [2, 55, 65])]), (85 => [2, 80, 90])])]);
println!("Input: `{:?}`", root);
let removed = root.remove(&5);
let expected =
tree!(50 => [3, (30 => [2, (15 => [1, Nil, 20]), 35]), (70 => [3, (60 => [2, 55, 65]), (85 => [2, 80, 90])])]);
assert_eq!(removed, Some(5));
assert_eq!(root, expected);
}
}
| {
Node {
level: 1,
content,
left_child: Self(None),
right_child: Self(None)
}
.into()
} |
common.go | // Copyright (c) 2016 Readium Foundation
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the organization nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package staticapi
import (
"net/http"
"strconv"
"github.com/readium/readium-lcp-server/api"
"github.com/readium/readium-lcp-server/frontend/webdashboard"
"github.com/readium/readium-lcp-server/frontend/weblicense"
"github.com/readium/readium-lcp-server/frontend/webpublication"
"github.com/readium/readium-lcp-server/frontend/webpurchase"
"github.com/readium/readium-lcp-server/frontend/webrepository"
"github.com/readium/readium-lcp-server/frontend/webuser"
)
//IServer defines methods for db interaction
type IServer interface {
RepositoryAPI() webrepository.WebRepository
PublicationAPI() webpublication.WebPublication
UserAPI() webuser.WebUser
PurchaseAPI() webpurchase.WebPurchase
DashboardAPI() webdashboard.WebDashboard
LicenseAPI() weblicense.WebLicense
}
// Pagination used to paginate listing
type Pagination struct {
Page int
PerPage int
}
// ExtractPaginationFromRequest extract from http.Request pagination information
func ExtractPaginationFromRequest(r *http.Request) (Pagination, error) {
var err error
var page int64 // default: page 1
var perPage int64 // default: 30 items per page
pagination := Pagination{}
if r.FormValue("page") != "" {
page, err = strconv.ParseInt((r).FormValue("page"), 10, 32)
if err != nil {
return pagination, err
}
} else {
page = 1
}
if r.FormValue("per_page") != "" {
perPage, err = strconv.ParseInt((r).FormValue("per_page"), 10, 32)
if err != nil {
return pagination, err
}
} else {
perPage = 30
}
if page > 0 {
page-- //pagenum starting at 0 in code, but user interface starting at 1
}
if page < 0 {
return pagination, err
}
pagination.Page = int(page)
pagination.PerPage = int(perPage)
return pagination, err
}
// PrepareListHeaderResponse set several http headers
// sets previous and next link headers
func PrepareListHeaderResponse(resourceCount int, resourceLink string, pagination Pagination, w http.ResponseWriter) | {
if resourceCount > 0 {
nextPage := strconv.Itoa(int(pagination.Page) + 1)
w.Header().Set("Link", "<"+resourceLink+"?page="+nextPage+">; rel=\"next\"; title=\"next\"")
}
if pagination.Page > 1 {
previousPage := strconv.Itoa(int(pagination.Page) - 1)
w.Header().Set("Link", "<"+resourceLink+"/?page="+previousPage+">; rel=\"previous\"; title=\"previous\"")
}
w.Header().Set("Content-Type", api.ContentType_JSON)
} |
|
github_com_argoproj_labs_argo_dataflow_api_v1alpha1_abstract_volume_source.py | """
Argo Workflows API
Argo Workflows is an open source container-native workflow engine for orchestrating parallel jobs on Kubernetes. For more information, please see https://argoproj.github.io/argo-workflows/ # noqa: E501
The version of the OpenAPI document: VERSION
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from argo_workflows.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
from ..model_utils import OpenApiModel
from argo_workflows.exceptions import ApiAttributeError
def lazy_import():
from argo_workflows.model.aws_elastic_block_store_volume_source import AWSElasticBlockStoreVolumeSource
from argo_workflows.model.azure_disk_volume_source import AzureDiskVolumeSource
from argo_workflows.model.azure_file_volume_source import AzureFileVolumeSource
from argo_workflows.model.ceph_fs_volume_source import CephFSVolumeSource
from argo_workflows.model.cinder_volume_source import CinderVolumeSource
from argo_workflows.model.config_map_volume_source import ConfigMapVolumeSource
from argo_workflows.model.csi_volume_source import CSIVolumeSource
from argo_workflows.model.downward_api_volume_source import DownwardAPIVolumeSource
from argo_workflows.model.empty_dir_volume_source import EmptyDirVolumeSource
from argo_workflows.model.ephemeral_volume_source import EphemeralVolumeSource
from argo_workflows.model.fc_volume_source import FCVolumeSource
from argo_workflows.model.flex_volume_source import FlexVolumeSource
from argo_workflows.model.flocker_volume_source import FlockerVolumeSource
from argo_workflows.model.gce_persistent_disk_volume_source import GCEPersistentDiskVolumeSource
from argo_workflows.model.git_repo_volume_source import GitRepoVolumeSource
from argo_workflows.model.glusterfs_volume_source import GlusterfsVolumeSource
from argo_workflows.model.host_path_volume_source import HostPathVolumeSource
from argo_workflows.model.iscsi_volume_source import ISCSIVolumeSource
from argo_workflows.model.nfs_volume_source import NFSVolumeSource
from argo_workflows.model.persistent_volume_claim_volume_source import PersistentVolumeClaimVolumeSource
from argo_workflows.model.photon_persistent_disk_volume_source import PhotonPersistentDiskVolumeSource
from argo_workflows.model.portworx_volume_source import PortworxVolumeSource
from argo_workflows.model.projected_volume_source import ProjectedVolumeSource
from argo_workflows.model.quobyte_volume_source import QuobyteVolumeSource
from argo_workflows.model.rbd_volume_source import RBDVolumeSource
from argo_workflows.model.scale_io_volume_source import ScaleIOVolumeSource
from argo_workflows.model.secret_volume_source import SecretVolumeSource
from argo_workflows.model.storage_os_volume_source import StorageOSVolumeSource
from argo_workflows.model.vsphere_virtual_disk_volume_source import VsphereVirtualDiskVolumeSource
globals()['AWSElasticBlockStoreVolumeSource'] = AWSElasticBlockStoreVolumeSource
globals()['AzureDiskVolumeSource'] = AzureDiskVolumeSource
globals()['AzureFileVolumeSource'] = AzureFileVolumeSource
globals()['CSIVolumeSource'] = CSIVolumeSource
globals()['CephFSVolumeSource'] = CephFSVolumeSource
globals()['CinderVolumeSource'] = CinderVolumeSource
globals()['ConfigMapVolumeSource'] = ConfigMapVolumeSource
globals()['DownwardAPIVolumeSource'] = DownwardAPIVolumeSource
globals()['EmptyDirVolumeSource'] = EmptyDirVolumeSource
globals()['EphemeralVolumeSource'] = EphemeralVolumeSource
globals()['FCVolumeSource'] = FCVolumeSource
globals()['FlexVolumeSource'] = FlexVolumeSource
globals()['FlockerVolumeSource'] = FlockerVolumeSource
globals()['GCEPersistentDiskVolumeSource'] = GCEPersistentDiskVolumeSource
globals()['GitRepoVolumeSource'] = GitRepoVolumeSource
globals()['GlusterfsVolumeSource'] = GlusterfsVolumeSource
globals()['HostPathVolumeSource'] = HostPathVolumeSource
globals()['ISCSIVolumeSource'] = ISCSIVolumeSource
globals()['NFSVolumeSource'] = NFSVolumeSource
globals()['PersistentVolumeClaimVolumeSource'] = PersistentVolumeClaimVolumeSource
globals()['PhotonPersistentDiskVolumeSource'] = PhotonPersistentDiskVolumeSource
globals()['PortworxVolumeSource'] = PortworxVolumeSource
globals()['ProjectedVolumeSource'] = ProjectedVolumeSource
globals()['QuobyteVolumeSource'] = QuobyteVolumeSource
globals()['RBDVolumeSource'] = RBDVolumeSource
globals()['ScaleIOVolumeSource'] = ScaleIOVolumeSource
globals()['SecretVolumeSource'] = SecretVolumeSource
globals()['StorageOSVolumeSource'] = StorageOSVolumeSource
globals()['VsphereVirtualDiskVolumeSource'] = VsphereVirtualDiskVolumeSource
class GithubComArgoprojLabsArgoDataflowApiV1alpha1AbstractVolumeSource(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {
}
validations = {
}
@cached_property
def additional_properties_type():
|
_nullable = False
@cached_property
def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
lazy_import()
return {
'aws_elastic_block_store': (AWSElasticBlockStoreVolumeSource,), # noqa: E501
'azure_disk': (AzureDiskVolumeSource,), # noqa: E501
'azure_file': (AzureFileVolumeSource,), # noqa: E501
'cephfs': (CephFSVolumeSource,), # noqa: E501
'cinder': (CinderVolumeSource,), # noqa: E501
'config_map': (ConfigMapVolumeSource,), # noqa: E501
'csi': (CSIVolumeSource,), # noqa: E501
'downward_api': (DownwardAPIVolumeSource,), # noqa: E501
'empty_dir': (EmptyDirVolumeSource,), # noqa: E501
'ephemeral': (EphemeralVolumeSource,), # noqa: E501
'fc': (FCVolumeSource,), # noqa: E501
'flex_volume': (FlexVolumeSource,), # noqa: E501
'flocker': (FlockerVolumeSource,), # noqa: E501
'gce_persistent_disk': (GCEPersistentDiskVolumeSource,), # noqa: E501
'git_repo': (GitRepoVolumeSource,), # noqa: E501
'glusterfs': (GlusterfsVolumeSource,), # noqa: E501
'host_path': (HostPathVolumeSource,), # noqa: E501
'iscsi': (ISCSIVolumeSource,), # noqa: E501
'nfs': (NFSVolumeSource,), # noqa: E501
'persistent_volume_claim': (PersistentVolumeClaimVolumeSource,), # noqa: E501
'photon_persistent_disk': (PhotonPersistentDiskVolumeSource,), # noqa: E501
'portworx_volume': (PortworxVolumeSource,), # noqa: E501
'projected': (ProjectedVolumeSource,), # noqa: E501
'quobyte': (QuobyteVolumeSource,), # noqa: E501
'rbd': (RBDVolumeSource,), # noqa: E501
'scale_io': (ScaleIOVolumeSource,), # noqa: E501
'secret': (SecretVolumeSource,), # noqa: E501
'storageos': (StorageOSVolumeSource,), # noqa: E501
'vsphere_volume': (VsphereVirtualDiskVolumeSource,), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
'aws_elastic_block_store': 'awsElasticBlockStore', # noqa: E501
'azure_disk': 'azureDisk', # noqa: E501
'azure_file': 'azureFile', # noqa: E501
'cephfs': 'cephfs', # noqa: E501
'cinder': 'cinder', # noqa: E501
'config_map': 'configMap', # noqa: E501
'csi': 'csi', # noqa: E501
'downward_api': 'downwardAPI', # noqa: E501
'empty_dir': 'emptyDir', # noqa: E501
'ephemeral': 'ephemeral', # noqa: E501
'fc': 'fc', # noqa: E501
'flex_volume': 'flexVolume', # noqa: E501
'flocker': 'flocker', # noqa: E501
'gce_persistent_disk': 'gcePersistentDisk', # noqa: E501
'git_repo': 'gitRepo', # noqa: E501
'glusterfs': 'glusterfs', # noqa: E501
'host_path': 'hostPath', # noqa: E501
'iscsi': 'iscsi', # noqa: E501
'nfs': 'nfs', # noqa: E501
'persistent_volume_claim': 'persistentVolumeClaim', # noqa: E501
'photon_persistent_disk': 'photonPersistentDisk', # noqa: E501
'portworx_volume': 'portworxVolume', # noqa: E501
'projected': 'projected', # noqa: E501
'quobyte': 'quobyte', # noqa: E501
'rbd': 'rbd', # noqa: E501
'scale_io': 'scaleIO', # noqa: E501
'secret': 'secret', # noqa: E501
'storageos': 'storageos', # noqa: E501
'vsphere_volume': 'vsphereVolume', # noqa: E501
}
read_only_vars = {
}
_composed_schemas = {}
@classmethod
@convert_js_args_to_python_args
def _from_openapi_data(cls, *args, **kwargs): # noqa: E501
"""GithubComArgoprojLabsArgoDataflowApiV1alpha1AbstractVolumeSource - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
aws_elastic_block_store (AWSElasticBlockStoreVolumeSource): [optional] # noqa: E501
azure_disk (AzureDiskVolumeSource): [optional] # noqa: E501
azure_file (AzureFileVolumeSource): [optional] # noqa: E501
cephfs (CephFSVolumeSource): [optional] # noqa: E501
cinder (CinderVolumeSource): [optional] # noqa: E501
config_map (ConfigMapVolumeSource): [optional] # noqa: E501
csi (CSIVolumeSource): [optional] # noqa: E501
downward_api (DownwardAPIVolumeSource): [optional] # noqa: E501
empty_dir (EmptyDirVolumeSource): [optional] # noqa: E501
ephemeral (EphemeralVolumeSource): [optional] # noqa: E501
fc (FCVolumeSource): [optional] # noqa: E501
flex_volume (FlexVolumeSource): [optional] # noqa: E501
flocker (FlockerVolumeSource): [optional] # noqa: E501
gce_persistent_disk (GCEPersistentDiskVolumeSource): [optional] # noqa: E501
git_repo (GitRepoVolumeSource): [optional] # noqa: E501
glusterfs (GlusterfsVolumeSource): [optional] # noqa: E501
host_path (HostPathVolumeSource): [optional] # noqa: E501
iscsi (ISCSIVolumeSource): [optional] # noqa: E501
nfs (NFSVolumeSource): [optional] # noqa: E501
persistent_volume_claim (PersistentVolumeClaimVolumeSource): [optional] # noqa: E501
photon_persistent_disk (PhotonPersistentDiskVolumeSource): [optional] # noqa: E501
portworx_volume (PortworxVolumeSource): [optional] # noqa: E501
projected (ProjectedVolumeSource): [optional] # noqa: E501
quobyte (QuobyteVolumeSource): [optional] # noqa: E501
rbd (RBDVolumeSource): [optional] # noqa: E501
scale_io (ScaleIOVolumeSource): [optional] # noqa: E501
secret (SecretVolumeSource): [optional] # noqa: E501
storageos (StorageOSVolumeSource): [optional] # noqa: E501
vsphere_volume (VsphereVirtualDiskVolumeSource): [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
self = super(OpenApiModel, cls).__new__(cls)
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
return self
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs): # noqa: E501
"""GithubComArgoprojLabsArgoDataflowApiV1alpha1AbstractVolumeSource - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
aws_elastic_block_store (AWSElasticBlockStoreVolumeSource): [optional] # noqa: E501
azure_disk (AzureDiskVolumeSource): [optional] # noqa: E501
azure_file (AzureFileVolumeSource): [optional] # noqa: E501
cephfs (CephFSVolumeSource): [optional] # noqa: E501
cinder (CinderVolumeSource): [optional] # noqa: E501
config_map (ConfigMapVolumeSource): [optional] # noqa: E501
csi (CSIVolumeSource): [optional] # noqa: E501
downward_api (DownwardAPIVolumeSource): [optional] # noqa: E501
empty_dir (EmptyDirVolumeSource): [optional] # noqa: E501
ephemeral (EphemeralVolumeSource): [optional] # noqa: E501
fc (FCVolumeSource): [optional] # noqa: E501
flex_volume (FlexVolumeSource): [optional] # noqa: E501
flocker (FlockerVolumeSource): [optional] # noqa: E501
gce_persistent_disk (GCEPersistentDiskVolumeSource): [optional] # noqa: E501
git_repo (GitRepoVolumeSource): [optional] # noqa: E501
glusterfs (GlusterfsVolumeSource): [optional] # noqa: E501
host_path (HostPathVolumeSource): [optional] # noqa: E501
iscsi (ISCSIVolumeSource): [optional] # noqa: E501
nfs (NFSVolumeSource): [optional] # noqa: E501
persistent_volume_claim (PersistentVolumeClaimVolumeSource): [optional] # noqa: E501
photon_persistent_disk (PhotonPersistentDiskVolumeSource): [optional] # noqa: E501
portworx_volume (PortworxVolumeSource): [optional] # noqa: E501
projected (ProjectedVolumeSource): [optional] # noqa: E501
quobyte (QuobyteVolumeSource): [optional] # noqa: E501
rbd (RBDVolumeSource): [optional] # noqa: E501
scale_io (ScaleIOVolumeSource): [optional] # noqa: E501
secret (SecretVolumeSource): [optional] # noqa: E501
storageos (StorageOSVolumeSource): [optional] # noqa: E501
vsphere_volume (VsphereVirtualDiskVolumeSource): [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
if var_name in self.read_only_vars:
raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate "
f"class with read only attributes.")
| """
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
"""
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 |
no_nulls.rs | use super::*;
use crate::utils::CustomIterTools;
use arrow::array::{ArrayRef, PrimitiveArray};
use arrow::datatypes::DataType;
use arrow::types::NativeType;
use num::{Float, NumCast, ToPrimitive, Zero};
use std::any::Any;
use std::fmt::Debug;
use std::ops::{Add, Div, Mul, Sub};
use std::sync::Arc;
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum QuantileInterpolOptions {
Nearest,
Lower,
Higher,
Midpoint,
Linear,
}
impl Default for QuantileInterpolOptions {
fn default() -> Self {
QuantileInterpolOptions::Nearest
}
}
fn rolling_apply_weights<Fo, Fa>(
values: &[f64],
window_size: usize,
min_periods: usize,
det_offsets_fn: Fo,
aggregator: Fa,
weights: &[f64],
) -> ArrayRef
where
Fo: Fn(Idx, WindowSize, Len) -> (Start, End),
Fa: Fn(&[f64], &[f64]) -> f64,
{
assert_eq!(weights.len(), window_size);
let len = values.len();
let out = (0..len)
.map(|idx| {
let (start, end) = det_offsets_fn(idx, window_size, len);
let vals = unsafe { values.get_unchecked(start..end) };
aggregator(vals, weights)
})
.collect_trusted::<Vec<f64>>();
let validity = create_validity(min_periods, len as usize, window_size, det_offsets_fn);
Arc::new(PrimitiveArray::from_data(
DataType::Float64,
out.into(),
validity.map(|b| b.into()),
))
}
fn rolling_apply<T, K, Fo, Fa>(
values: &[T],
window_size: usize,
min_periods: usize,
det_offsets_fn: Fo,
aggregator: Fa,
) -> ArrayRef
where
Fo: Fn(Idx, WindowSize, Len) -> (Start, End),
Fa: Fn(&[T]) -> K,
K: NativeType,
T: Debug,
{
let len = values.len();
let out = (0..len)
.map(|idx| {
let (start, end) = det_offsets_fn(idx, window_size, len);
let vals = unsafe { values.get_unchecked(start..end) };
aggregator(vals)
})
.collect_trusted::<Vec<K>>();
let validity = create_validity(min_periods, len as usize, window_size, det_offsets_fn);
Arc::new(PrimitiveArray::from_data(
K::PRIMITIVE.into(),
out.into(),
validity.map(|b| b.into()),
))
}
fn rolling_apply_quantile<T, Fo, Fa>(
values: &[T],
quantile: f64,
interpolation: QuantileInterpolOptions,
window_size: usize,
min_periods: usize,
det_offsets_fn: Fo,
aggregator: Fa,
) -> ArrayRef
where
Fo: Fn(Idx, WindowSize, Len) -> (Start, End),
Fa: Fn(&[T], f64, QuantileInterpolOptions) -> T,
T: Debug + NativeType,
{
let len = values.len();
let out = (0..len)
.map(|idx| {
let (start, end) = det_offsets_fn(idx, window_size, len);
let vals = unsafe { values.get_unchecked(start..end) };
aggregator(vals, quantile, interpolation)
})
.collect_trusted::<Vec<T>>();
let validity = create_validity(min_periods, len as usize, window_size, det_offsets_fn);
Arc::new(PrimitiveArray::from_data(
T::PRIMITIVE.into(),
out.into(),
validity.map(|b| b.into()),
))
}
#[allow(clippy::too_many_arguments)]
fn rolling_apply_convolve_quantile<T, Fo, Fa>(
values: &[T],
quantile: f64,
interpolation: QuantileInterpolOptions,
window_size: usize,
min_periods: usize,
det_offsets_fn: Fo,
aggregator: Fa,
weights: &[f64],
) -> ArrayRef
where
Fo: Fn(Idx, WindowSize, Len) -> (Start, End),
Fa: Fn(&[T], f64, QuantileInterpolOptions) -> T,
T: Debug + NativeType + Mul<Output = T> + NumCast + ToPrimitive + Zero,
{
assert_eq!(weights.len(), window_size);
let mut buf = vec![T::zero(); window_size];
let len = values.len();
let out = (0..len)
.map(|idx| {
let (start, end) = det_offsets_fn(idx, window_size, len);
let vals = unsafe { values.get_unchecked(start..end) };
buf.iter_mut()
.zip(vals.iter().zip(weights))
.for_each(|(b, (v, w))| *b = *v * NumCast::from(*w).unwrap());
aggregator(&buf, quantile, interpolation)
})
.collect_trusted::<Vec<T>>();
let validity = create_validity(min_periods, len as usize, window_size, det_offsets_fn);
Arc::new(PrimitiveArray::from_data(
T::PRIMITIVE.into(),
out.into(),
validity.map(|b| b.into()),
))
}
pub(crate) fn compute_var<T>(vals: &[T]) -> T
where
T: Float + std::ops::AddAssign + std::fmt::Debug,
{
let mut count = T::zero();
let mut sum = T::zero();
let mut sum_of_squares = T::zero();
for &val in vals {
sum += val;
sum_of_squares += val * val;
count += T::one();
}
let mean = sum / count;
// apply Bessel's correction
((sum_of_squares / count) - mean * mean) / (count - T::one()) * count
}
fn compute_var_weights<T>(vals: &[T], weights: &[T]) -> T
where
T: Float + std::ops::AddAssign,
{
let weighted_iter = vals.iter().zip(weights).map(|(x, y)| *x * *y);
let mut count = T::zero();
let mut sum = T::zero();
let mut sum_of_squares = T::zero();
for val in weighted_iter {
sum += val;
sum_of_squares += val * val;
count += T::one();
}
let mean = sum / count;
// apply Bessel's correction
((sum_of_squares / count) - mean * mean) / (count - T::one()) * count
}
pub(crate) fn compute_mean<T>(values: &[T]) -> T
where
T: Float + std::iter::Sum<T>,
{
values.iter().copied().sum::<T>() / T::from(values.len()).unwrap()
}
pub(crate) fn compute_mean_weights<T>(values: &[T], weights: &[T]) -> T
where
T: Float + std::iter::Sum<T>,
{
values.iter().zip(weights).map(|(v, w)| *v * *w).sum::<T>() / T::from(values.len()).unwrap()
}
pub fn rolling_quantile<T>(
values: &[T],
quantile: f64,
interpolation: QuantileInterpolOptions,
window_size: usize,
min_periods: usize,
center: bool,
weights: Option<&[f64]>,
) -> ArrayRef
where
T: NativeType
+ std::iter::Sum<T>
+ std::cmp::PartialOrd
+ num::ToPrimitive
+ NumCast
+ Add<Output = T>
+ Sub<Output = T>
+ Div<Output = T>
+ Mul<Output = T>
+ Zero,
{
match (center, weights) {
(true, None) => rolling_apply_quantile(
values,
quantile,
interpolation,
window_size,
min_periods,
det_offsets_center,
compute_quantile,
),
(false, None) => rolling_apply_quantile(
values,
quantile,
interpolation,
window_size,
min_periods,
det_offsets,
compute_quantile,
),
(true, Some(weights)) => rolling_apply_convolve_quantile(
values,
quantile,
interpolation,
window_size,
min_periods,
det_offsets_center,
compute_quantile,
weights,
),
(false, Some(weights)) => rolling_apply_convolve_quantile(
values,
quantile,
interpolation,
window_size,
min_periods,
det_offsets,
compute_quantile,
weights,
),
}
}
pub(crate) fn compute_sum<T>(values: &[T]) -> T
where
T: std::iter::Sum<T> + Copy,
{
values.iter().copied().sum()
}
pub(crate) fn compute_sum_weights<T>(values: &[T], weights: &[T]) -> T
where
T: std::iter::Sum<T> + Copy + std::ops::Mul<Output = T>,
{
values.iter().zip(weights).map(|(v, w)| *v * *w).sum()
}
pub(crate) fn compute_quantile<T>(
values: &[T],
quantile: f64,
interpolation: QuantileInterpolOptions,
) -> T
where
T: std::iter::Sum<T>
+ Copy
+ std::cmp::PartialOrd
+ num::ToPrimitive
+ NumCast
+ Add<Output = T>
+ Sub<Output = T>
+ Div<Output = T>
+ Mul<Output = T>,
{
if !(0.0..=1.0).contains(&quantile) {
panic!("quantile should be between 0.0 and 1.0");
}
let mut vals: Vec<T> = values
.iter()
.copied()
.map(|x| NumCast::from(x).unwrap())
.collect();
vals.sort_by(|a, b| a.partial_cmp(b).unwrap());
let length = vals.len();
let mut idx = match interpolation {
QuantileInterpolOptions::Nearest => ((length as f64) * quantile) as usize,
QuantileInterpolOptions::Lower
| QuantileInterpolOptions::Midpoint
| QuantileInterpolOptions::Linear => ((length as f64 - 1.0) * quantile).floor() as usize,
QuantileInterpolOptions::Higher => ((length as f64 - 1.0) * quantile).ceil() as usize,
};
idx = std::cmp::min(idx, length - 1);
match interpolation {
QuantileInterpolOptions::Midpoint => {
let top_idx = ((length as f64 - 1.0) * quantile).ceil() as usize;
if top_idx == idx {
vals[idx]
} else {
(vals[idx] + vals[idx + 1]) / T::from::<f64>(2.0f64).unwrap()
}
}
QuantileInterpolOptions::Linear => {
let float_idx = (length as f64 - 1.0) * quantile;
let top_idx = f64::ceil(float_idx) as usize;
if top_idx == idx {
vals[idx]
} else {
let proportion = T::from(float_idx - idx as f64).unwrap();
proportion * (vals[top_idx] - vals[idx]) + vals[idx]
}
}
_ => vals[idx],
}
}
pub(crate) fn compute_min<T>(values: &[T]) -> T
where
T: NativeType + PartialOrd,
{
values
.iter()
.copied()
.min_by(|a, b| a.partial_cmp(b).unwrap())
.unwrap()
}
pub(crate) fn compute_min_weights<T>(values: &[T], weights: &[T]) -> T
where
T: NativeType + PartialOrd + std::ops::Mul<Output = T>,
{
values
.iter()
.zip(weights)
.map(|(v, w)| *v * *w)
.min_by(|a, b| a.partial_cmp(b).unwrap())
.unwrap()
}
pub(crate) fn compute_max<T>(values: &[T]) -> T
where
T: NativeType + PartialOrd,
{
values
.iter()
.copied()
.max_by(|a, b| a.partial_cmp(b).unwrap())
.unwrap()
}
pub(crate) fn compute_max_weights<T>(values: &[T], weights: &[T]) -> T
where
T: NativeType + PartialOrd + std::ops::Mul<Output = T>,
{
values
.iter()
.zip(weights)
.map(|(v, w)| *v * *w)
.max_by(|a, b| a.partial_cmp(b).unwrap())
.unwrap()
}
fn as_floats<T>(values: &[T]) -> &[f64]
where
T: Any,
{
let values_any = &values[0] as &dyn Any;
// couldn't use downcast_ref because the slice is unsized
if values_any.is::<f64>() {
unsafe { std::mem::transmute::<&[T], &[f64]>(values) }
} else {
panic!()
}
}
pub fn rolling_mean<T>(
values: &[T],
window_size: usize,
min_periods: usize,
center: bool,
weights: Option<&[f64]>,
) -> ArrayRef
where
T: NativeType + Float + std::iter::Sum<T>,
{
match (center, weights) {
(true, None) => rolling_apply(
values,
window_size,
min_periods,
det_offsets_center,
compute_mean,
),
(false, None) => rolling_apply(values, window_size, min_periods, det_offsets, compute_mean),
(true, Some(weights)) => {
let values = as_floats(values);
rolling_apply_weights(
values,
window_size,
min_periods,
det_offsets_center,
compute_mean_weights,
weights,
)
}
(false, Some(weights)) => {
let values = as_floats(values);
rolling_apply_weights(
values,
window_size,
min_periods,
det_offsets,
compute_mean_weights,
weights,
)
}
}
}
pub fn rolling_min<T>(
values: &[T],
window_size: usize,
min_periods: usize,
center: bool,
weights: Option<&[f64]>,
) -> ArrayRef
where
T: NativeType + PartialOrd,
{
match (center, weights) {
(true, None) => rolling_apply(
values,
window_size,
min_periods,
det_offsets_center,
compute_min,
),
(false, None) => rolling_apply(values, window_size, min_periods, det_offsets, compute_min),
(true, Some(weights)) => {
let values = as_floats(values);
rolling_apply_weights(
values,
window_size,
min_periods,
det_offsets_center,
compute_min_weights,
weights,
)
}
(false, Some(weights)) => {
let values = as_floats(values);
rolling_apply_weights(
values,
window_size,
min_periods,
det_offsets,
compute_min_weights,
weights,
)
}
}
}
pub fn rolling_max<T>(
values: &[T],
window_size: usize,
min_periods: usize,
center: bool,
weights: Option<&[f64]>,
) -> ArrayRef
where
T: NativeType + PartialOrd,
{
match (center, weights) {
(true, None) => rolling_apply(
values,
window_size,
min_periods,
det_offsets_center,
compute_max,
),
(false, None) => rolling_apply(values, window_size, min_periods, det_offsets, compute_max),
(true, Some(weights)) => |
(false, Some(weights)) => {
let values = as_floats(values);
rolling_apply_weights(
values,
window_size,
min_periods,
det_offsets,
compute_max_weights,
weights,
)
}
}
}
pub fn rolling_var<T>(
values: &[T],
window_size: usize,
min_periods: usize,
center: bool,
weights: Option<&[f64]>,
) -> ArrayRef
where
T: NativeType + Float + std::ops::AddAssign,
{
match (center, weights) {
(true, None) => rolling_apply(
values,
window_size,
min_periods,
det_offsets_center,
compute_var,
),
(false, None) => rolling_apply(values, window_size, min_periods, det_offsets, compute_var),
(true, Some(weights)) => {
let values = as_floats(values);
rolling_apply_weights(
values,
window_size,
min_periods,
det_offsets_center,
compute_var_weights,
weights,
)
}
(false, Some(weights)) => {
let values = as_floats(values);
rolling_apply_weights(
values,
window_size,
min_periods,
det_offsets,
compute_var_weights,
weights,
)
}
}
}
pub fn rolling_sum<T>(
values: &[T],
window_size: usize,
min_periods: usize,
center: bool,
weights: Option<&[f64]>,
) -> ArrayRef
where
T: NativeType + std::iter::Sum + Debug,
{
match (center, weights) {
(true, None) => rolling_apply(
values,
window_size,
min_periods,
det_offsets_center,
compute_sum,
),
(false, None) => rolling_apply(values, window_size, min_periods, det_offsets, compute_sum),
(true, Some(weights)) => {
let values = as_floats(values);
rolling_apply_weights(
values,
window_size,
min_periods,
det_offsets_center,
compute_sum_weights,
weights,
)
}
(false, Some(weights)) => {
let values = as_floats(values);
rolling_apply_weights(
values,
window_size,
min_periods,
det_offsets,
compute_sum_weights,
weights,
)
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_rolling_sum() {
let values = &[1.0, 2.0, 3.0, 4.0];
let out = rolling_sum(values, 2, 2, false, None);
let out = out.as_any().downcast_ref::<PrimitiveArray<f64>>().unwrap();
let out = out.into_iter().map(|v| v.copied()).collect::<Vec<_>>();
assert_eq!(out, &[None, Some(3.0), Some(5.0), Some(7.0)]);
let out = rolling_sum(values, 2, 1, false, None);
let out = out.as_any().downcast_ref::<PrimitiveArray<f64>>().unwrap();
let out = out.into_iter().map(|v| v.copied()).collect::<Vec<_>>();
assert_eq!(out, &[Some(1.0), Some(3.0), Some(5.0), Some(7.0)]);
let out = rolling_sum(values, 4, 1, false, None);
let out = out.as_any().downcast_ref::<PrimitiveArray<f64>>().unwrap();
let out = out.into_iter().map(|v| v.copied()).collect::<Vec<_>>();
assert_eq!(out, &[Some(1.0), Some(3.0), Some(6.0), Some(10.0)]);
let out = rolling_sum(values, 4, 1, true, None);
let out = out.as_any().downcast_ref::<PrimitiveArray<f64>>().unwrap();
let out = out.into_iter().map(|v| v.copied()).collect::<Vec<_>>();
assert_eq!(out, &[Some(3.0), Some(6.0), Some(10.0), Some(9.0)]);
let out = rolling_sum(values, 4, 4, true, None);
let out = out.as_any().downcast_ref::<PrimitiveArray<f64>>().unwrap();
let out = out.into_iter().map(|v| v.copied()).collect::<Vec<_>>();
assert_eq!(out, &[None, None, Some(10.0), None]);
}
#[test]
fn test_rolling_median() {
let values = &[1.0, 2.0, 3.0, 4.0];
let out = rolling_quantile(
values,
0.5,
QuantileInterpolOptions::Linear,
2,
2,
false,
None,
);
let out = out.as_any().downcast_ref::<PrimitiveArray<f64>>().unwrap();
let out = out.into_iter().map(|v| v.copied()).collect::<Vec<_>>();
assert_eq!(out, &[None, Some(1.5), Some(2.5), Some(3.5)]);
let out = rolling_quantile(
values,
0.5,
QuantileInterpolOptions::Linear,
2,
1,
false,
None,
);
let out = out.as_any().downcast_ref::<PrimitiveArray<f64>>().unwrap();
let out = out.into_iter().map(|v| v.copied()).collect::<Vec<_>>();
assert_eq!(out, &[Some(1.0), Some(1.5), Some(2.5), Some(3.5)]);
let out = rolling_quantile(
values,
0.5,
QuantileInterpolOptions::Linear,
4,
1,
false,
None,
);
let out = out.as_any().downcast_ref::<PrimitiveArray<f64>>().unwrap();
let out = out.into_iter().map(|v| v.copied()).collect::<Vec<_>>();
assert_eq!(out, &[Some(1.0), Some(1.5), Some(2.0), Some(2.5)]);
let out = rolling_quantile(
values,
0.5,
QuantileInterpolOptions::Linear,
4,
1,
true,
None,
);
let out = out.as_any().downcast_ref::<PrimitiveArray<f64>>().unwrap();
let out = out.into_iter().map(|v| v.copied()).collect::<Vec<_>>();
assert_eq!(out, &[Some(1.5), Some(2.0), Some(2.5), Some(3.0)]);
let out = rolling_quantile(
values,
0.5,
QuantileInterpolOptions::Linear,
4,
4,
true,
None,
);
let out = out.as_any().downcast_ref::<PrimitiveArray<f64>>().unwrap();
let out = out.into_iter().map(|v| v.copied()).collect::<Vec<_>>();
assert_eq!(out, &[None, None, Some(2.5), None]);
}
#[test]
fn test_rolling_quantile_limits() {
let values = &[1.0, 2.0, 3.0, 4.0];
let interpol_options = vec![
QuantileInterpolOptions::Lower,
QuantileInterpolOptions::Higher,
QuantileInterpolOptions::Nearest,
QuantileInterpolOptions::Midpoint,
QuantileInterpolOptions::Linear,
];
for interpol in interpol_options {
let out1 = rolling_min(values, 2, 2, false, None);
let out1 = out1.as_any().downcast_ref::<PrimitiveArray<f64>>().unwrap();
let out1 = out1.into_iter().map(|v| v.copied()).collect::<Vec<_>>();
let out2 = rolling_quantile(values, 0.0, interpol, 2, 2, false, None);
let out2 = out2.as_any().downcast_ref::<PrimitiveArray<f64>>().unwrap();
let out2 = out2.into_iter().map(|v| v.copied()).collect::<Vec<_>>();
assert_eq!(out1, out2);
let out1 = rolling_max(values, 2, 2, false, None);
let out1 = out1.as_any().downcast_ref::<PrimitiveArray<f64>>().unwrap();
let out1 = out1.into_iter().map(|v| v.copied()).collect::<Vec<_>>();
let out2 = rolling_quantile(values, 1.0, interpol, 2, 2, false, None);
let out2 = out2.as_any().downcast_ref::<PrimitiveArray<f64>>().unwrap();
let out2 = out2.into_iter().map(|v| v.copied()).collect::<Vec<_>>();
assert_eq!(out1, out2);
}
}
}
| {
let values = as_floats(values);
rolling_apply_weights(
values,
window_size,
min_periods,
det_offsets_center,
compute_max_weights,
weights,
)
} |
job_selector.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 React, { useState, useEffect } from 'react';
import { EuiButtonEmpty, EuiFlexItem, EuiFlexGroup } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { Dictionary } from '../../../../common/types/common';
import { useUrlState } from '../../util/url_state';
// @ts-ignore
import { IdBadges } from './id_badges/index';
import { BADGE_LIMIT, JobSelectorFlyout, JobSelectorFlyoutProps } from './job_selector_flyout';
import { MlJobWithTimeRange } from '../../../../common/types/anomaly_detection_jobs';
interface GroupObj {
groupId: string;
jobIds: string[];
}
function mergeSelection(
jobIds: string[],
groupObjs: GroupObj[],
singleSelection: boolean
): string[] {
if (singleSelection) {
return jobIds;
}
const selectedIds: string[] = [];
const alreadySelected: string[] = [];
groupObjs.forEach(group => {
selectedIds.push(group.groupId);
alreadySelected.push(...group.jobIds);
});
jobIds.forEach(jobId => {
// Add jobId if not already included in group selection
if (alreadySelected.includes(jobId) === false) {
selectedIds.push(jobId);
}
});
return selectedIds;
}
type GroupsMap = Dictionary<string[]>;
export function getInitialGroupsMap(selectedGroups: GroupObj[]): GroupsMap {
const map: GroupsMap = {};
if (selectedGroups.length) {
selectedGroups.forEach(group => {
map[group.groupId] = group.jobIds;
});
}
return map;
}
interface JobSelectorProps {
dateFormatTz: string;
singleSelection: boolean;
timeseriesOnly: boolean;
}
export interface JobSelectionMaps {
jobsMap: Dictionary<MlJobWithTimeRange>;
groupsMap: Dictionary<string[]>;
}
export function JobSelector({ dateFormatTz, singleSelection, timeseriesOnly }: JobSelectorProps) {
const [globalState, setGlobalState] = useUrlState('_g');
const selectedJobIds = globalState?.ml?.jobIds ?? [];
const selectedGroups = globalState?.ml?.groups ?? [];
const [maps, setMaps] = useState<JobSelectionMaps>({
groupsMap: getInitialGroupsMap(selectedGroups),
jobsMap: {},
});
const [selectedIds, setSelectedIds] = useState(
mergeSelection(selectedJobIds, selectedGroups, singleSelection)
);
const [showAllBarBadges, setShowAllBarBadges] = useState(false);
const [isFlyoutVisible, setIsFlyoutVisible] = useState(false);
// Ensure JobSelectionBar gets updated when selection via globalState changes.
useEffect(() => {
setSelectedIds(mergeSelection(selectedJobIds, selectedGroups, singleSelection));
}, [JSON.stringify([selectedJobIds, selectedGroups])]);
function closeFlyout() {
setIsFlyoutVisible(false);
}
function showFlyout() {
setIsFlyoutVisible(true);
}
function handleJobSelectionClick() {
showFlyout();
}
const applySelection: JobSelectorFlyoutProps['onSelectionConfirmed'] = ({
newSelection,
jobIds,
groups: newGroups,
time,
}) => {
setSelectedIds(newSelection);
setGlobalState({
ml: {
jobIds,
groups: newGroups,
},
...(time !== undefined ? { time } : {}),
});
closeFlyout();
};
function renderJobSelectionBar() {
return (
<EuiFlexGroup responsive={false} gutterSize="xs" alignItems="center">
<EuiFlexItem grow={false}>
<EuiFlexGroup
wrap
responsive={false}
gutterSize="xs"
alignItems="center"
data-test-subj="mlJobSelectionBadges"
>
<IdBadges
limit={BADGE_LIMIT}
maps={maps}
onLinkClick={() => setShowAllBarBadges(!showAllBarBadges)}
selectedIds={selectedIds}
showAllBarBadges={showAllBarBadges}
/>
</EuiFlexGroup>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiButtonEmpty
size="xs"
iconType="pencil"
onClick={handleJobSelectionClick}
data-test-subj="mlButtonEditJobSelection"
>
{i18n.translate('xpack.ml.jobSelector.jobSelectionButton', {
defaultMessage: 'Edit job selection',
})}
</EuiButtonEmpty>
</EuiFlexItem>
</EuiFlexGroup>
);
}
function | () {
if (isFlyoutVisible) {
return (
<JobSelectorFlyout
dateFormatTz={dateFormatTz}
timeseriesOnly={timeseriesOnly}
singleSelection={singleSelection}
selectedIds={selectedIds}
onSelectionConfirmed={applySelection}
onJobsFetched={setMaps}
onFlyoutClose={closeFlyout}
maps={maps}
/>
);
}
}
return (
<div className="mlJobSelectorBar">
{selectedIds.length > 0 && renderJobSelectionBar()}
{renderFlyout()}
</div>
);
}
| renderFlyout |
icon-button.ts | /**
* @license
* Copyright 2021 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import '../icon/icon';
import {html, TemplateResult} from 'lit';
import {customElement} from 'lit/decorators';
import {IconButton} from './lib/icon-button';
import {styles} from './lib/icon-button-styles.css';
declare global {
interface HTMLElementTagNameMap {
'md-icon-button': MdIconButton;
}
}
@customElement('md-icon-button')
export class | extends IconButton {
static override styles = [styles];
/** @soyTemplate */
protected override renderIcon(icon: string): TemplateResult|string {
return icon ? html`<md-icon>${icon}</md-icon>` : '';
}
}
| MdIconButton |
0004_profile.py | # Generated by Django 2.1.2 on 2018-11-20 12:48
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('velhot', '0003_friend'),
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('real_name', models.CharField(max_length=60)),
('address', models.CharField(max_length=60)),
('phone_number', models.CharField(max_length=17, validators=[django.core.validators.RegexValidator(regex='^\\+?1?\\d{9,15}$')])),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
] |
|
rule_join_reorder.go | // Copyright 2019 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package core
import (
"github.com/daiguadaidai/tidb/expression"
"github.com/daiguadaidai/tidb/sessionctx"
)
// extractJoinGroup extracts all the join nodes connected with continuous
// InnerJoins to construct a join group. This join group is further used to
// construct a new join order based on a reorder algorithm.
//
// For example: "InnerJoin(InnerJoin(a, b), LeftJoin(c, d))"
// results in a join group {a, b, LeftJoin(c, d)}.
func | (p LogicalPlan) (group []LogicalPlan, eqEdges []*expression.ScalarFunction, otherConds []expression.Expression) {
join, isJoin := p.(*LogicalJoin)
if !isJoin || join.preferJoinType > uint(0) || join.JoinType != InnerJoin || join.StraightJoin {
return []LogicalPlan{p}, nil, nil
}
lhsGroup, lhsEqualConds, lhsOtherConds := extractJoinGroup(join.children[0])
rhsGroup, rhsEqualConds, rhsOtherConds := extractJoinGroup(join.children[1])
group = append(group, lhsGroup...)
group = append(group, rhsGroup...)
eqEdges = append(eqEdges, join.EqualConditions...)
eqEdges = append(eqEdges, lhsEqualConds...)
eqEdges = append(eqEdges, rhsEqualConds...)
otherConds = append(otherConds, join.OtherConditions...)
otherConds = append(otherConds, lhsOtherConds...)
otherConds = append(otherConds, rhsOtherConds...)
return group, eqEdges, otherConds
}
type joinReOrderSolver struct {
}
type jrNode struct {
p LogicalPlan
cumCost float64
}
func (s *joinReOrderSolver) optimize(p LogicalPlan) (LogicalPlan, error) {
return s.optimizeRecursive(p.context(), p)
}
// optimizeRecursive recursively collects join groups and applies join reorder algorithm for each group.
func (s *joinReOrderSolver) optimizeRecursive(ctx sessionctx.Context, p LogicalPlan) (LogicalPlan, error) {
var err error
curJoinGroup, eqEdges, otherConds := extractJoinGroup(p)
if len(curJoinGroup) > 1 {
for i := range curJoinGroup {
curJoinGroup[i], err = s.optimizeRecursive(ctx, curJoinGroup[i])
if err != nil {
return nil, err
}
}
baseGroupSolver := &baseSingleGroupJoinOrderSolver{
ctx: ctx,
otherConds: otherConds,
}
if len(curJoinGroup) > ctx.GetSessionVars().TiDBOptJoinReorderThreshold {
groupSolver := &joinReorderGreedySolver{
baseSingleGroupJoinOrderSolver: baseGroupSolver,
eqEdges: eqEdges,
}
p, err = groupSolver.solve(curJoinGroup)
} else {
dpSolver := &joinReorderDPSolver{
baseSingleGroupJoinOrderSolver: baseGroupSolver,
}
dpSolver.newJoin = dpSolver.newJoinWithEdges
p, err = dpSolver.solve(curJoinGroup, expression.ScalarFuncs2Exprs(eqEdges))
}
if err != nil {
return nil, err
}
return p, nil
}
newChildren := make([]LogicalPlan, 0, len(p.Children()))
for _, child := range p.Children() {
newChild, err := s.optimizeRecursive(ctx, child)
if err != nil {
return nil, err
}
newChildren = append(newChildren, newChild)
}
p.SetChildren(newChildren...)
return p, nil
}
type baseSingleGroupJoinOrderSolver struct {
ctx sessionctx.Context
curJoinGroup []*jrNode
otherConds []expression.Expression
}
// baseNodeCumCost calculate the cumulative cost of the node in the join group.
func (s *baseSingleGroupJoinOrderSolver) baseNodeCumCost(groupNode LogicalPlan) float64 {
cost := groupNode.statsInfo().RowCount
for _, child := range groupNode.Children() {
cost += s.baseNodeCumCost(child)
}
return cost
}
// makeBushyJoin build bushy tree for the nodes which have no equal condition to connect them.
func (s *baseSingleGroupJoinOrderSolver) makeBushyJoin(cartesianJoinGroup []LogicalPlan) LogicalPlan {
resultJoinGroup := make([]LogicalPlan, 0, (len(cartesianJoinGroup)+1)/2)
for len(cartesianJoinGroup) > 1 {
resultJoinGroup = resultJoinGroup[:0]
for i := 0; i < len(cartesianJoinGroup); i += 2 {
if i+1 == len(cartesianJoinGroup) {
resultJoinGroup = append(resultJoinGroup, cartesianJoinGroup[i])
break
}
newJoin := s.newCartesianJoin(cartesianJoinGroup[i], cartesianJoinGroup[i+1])
for i := len(s.otherConds) - 1; i >= 0; i-- {
cols := expression.ExtractColumns(s.otherConds[i])
if newJoin.schema.ColumnsIndices(cols) != nil {
newJoin.OtherConditions = append(newJoin.OtherConditions, s.otherConds[i])
s.otherConds = append(s.otherConds[:i], s.otherConds[i+1:]...)
}
}
resultJoinGroup = append(resultJoinGroup, newJoin)
}
cartesianJoinGroup, resultJoinGroup = resultJoinGroup, cartesianJoinGroup
}
return cartesianJoinGroup[0]
}
func (s *baseSingleGroupJoinOrderSolver) newCartesianJoin(lChild, rChild LogicalPlan) *LogicalJoin {
join := LogicalJoin{
JoinType: InnerJoin,
reordered: true,
}.Init(s.ctx)
join.SetSchema(expression.MergeSchema(lChild.Schema(), rChild.Schema()))
join.SetChildren(lChild, rChild)
return join
}
func (s *baseSingleGroupJoinOrderSolver) newJoinWithEdges(lChild, rChild LogicalPlan, eqEdges []*expression.ScalarFunction, otherConds []expression.Expression) LogicalPlan {
newJoin := s.newCartesianJoin(lChild, rChild)
newJoin.EqualConditions = eqEdges
newJoin.OtherConditions = otherConds
for _, eqCond := range newJoin.EqualConditions {
newJoin.LeftJoinKeys = append(newJoin.LeftJoinKeys, eqCond.GetArgs()[0].(*expression.Column))
newJoin.RightJoinKeys = append(newJoin.RightJoinKeys, eqCond.GetArgs()[1].(*expression.Column))
}
return newJoin
}
// calcJoinCumCost calculates the cumulative cost of the join node.
func (s *baseSingleGroupJoinOrderSolver) calcJoinCumCost(join LogicalPlan, lNode, rNode *jrNode) float64 {
return join.statsInfo().RowCount + lNode.cumCost + rNode.cumCost
}
| extractJoinGroup |
gdb.py | # -*- coding: utf-8 -*-
"""
During exploit development, it is frequently useful to debug the
target binary under GDB.
Pwntools makes this easy-to-do with a handful of helper routines, designed
to make your exploit-debug-update cycles much faster.
Useful Functions
----------------
- :func:`attach` - Attach to an existing process
- :func:`debug` - Start a new process under a debugger, stopped at the first instruction
- :func:`debug_shellcode` - Build a binary with the provided shellcode, and start it under a debugger
Debugging Tips
--------------
The :func:`attach` and :func:`debug` functions will likely be your bread and
butter for debugging.
Both allow you to provide a script to pass to GDB when it is started, so that
it can automatically set your breakpoints.
Attaching to Processes
~~~~~~~~~~~~~~~~~~~~~~
To attach to an existing process, just use :func:`attach`. It is surprisingly
versatile, and can attach to a :class:`.process` for simple
binaries, or will automatically find the correct process to attach to for a
forking server, if given a :class:`.remote` object.
Spawning New Processes
~~~~~~~~~~~~~~~~~~~~~~
Attaching to processes with :func:`attach` is useful, but the state the process
is in may vary. If you need to attach to a process very early, and debug it from
the very first instruction (or even the start of ``main``), you instead should use
:func:`debug`.
When you use :func:`debug`, the return value is a :class:`.tube` object
that you interact with exactly like normal.
Tips and Troubleshooting
------------------------
``NOPTRACE`` magic argument
~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's quite cumbersom to comment and un-comment lines containing `attach`.
You can cause these lines to be a no-op by running your script with the
``NOPTRACE`` argument appended, or with ``PWNLIB_NOPTRACE=1`` in the environment.
::
$ python exploit.py NOPTRACE
[+] Starting local process '/bin/bash': Done
[!] Skipping debug attach since context.noptrace==True
...
Kernel Yama ptrace_scope
~~~~~~~~~~~~~~~~~~~~~~~~
The Linux kernel v3.4 introduced a security mechanism called ``ptrace_scope``,
which is intended to prevent processes from debugging eachother unless there is
a direct parent-child relationship.
This causes some issues with the normal Pwntools workflow, since the process
heirarchy looks like this:
::
python ---> target
`--> gdb
Note that ``python`` is the parent of ``target``, not ``gdb``.
In order to avoid this being a problem, Pwntools uses the function
``prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY)``. This disables Yama
for any processes launched by Pwntools via :class:`.process` or via
:meth:`.ssh.process`.
Older versions of Pwntools did not perform the ``prctl`` step, and
required that the Yama security feature was disabled systemwide, which
requires ``root`` access.
Member Documentation
===============================
"""
from __future__ import absolute_import
from __future__ import division
import os
import random
import re
import shlex
import tempfile
import time
from pwnlib import adb
from pwnlib import atexit
from pwnlib import elf
from pwnlib import qemu
from pwnlib import tubes
from pwnlib.asm import _bfdname
from pwnlib.asm import make_elf
from pwnlib.asm import make_elf_from_assembly
from pwnlib.context import LocalContext
from pwnlib.context import context
from pwnlib.log import getLogger
from pwnlib.util import misc
from pwnlib.util import proc
log = getLogger(__name__)
@LocalContext
def debug_assembly(asm, gdbscript=None, vma=None):
"""debug_assembly(asm, gdbscript=None, vma=None) -> tube
Creates an ELF file, and launches it under a debugger.
This is identical to debug_shellcode, except that
any defined symbols are available in GDB, and it
saves you the explicit call to asm().
Arguments:
asm(str): Assembly code to debug
gdbscript(str): Script to run in GDB
vma(int): Base address to load the shellcode at
**kwargs: Override any :obj:`pwnlib.context.context` values.
Returns:
:class:`.process`
Example:
.. code-block:: python
assembly = shellcraft.echo("Hello world!\n")
io = gdb.debug_assembly(assembly)
io.recvline()
# 'Hello world!'
"""
tmp_elf = make_elf_from_assembly(asm, vma=vma, extract=False)
os.chmod(tmp_elf, 0777)
atexit.register(lambda: os.unlink(tmp_elf))
if context.os == 'android':
android_path = '/data/data/%s' % os.path.basename(tmp_elf)
adb.push(tmp_elf, android_path)
tmp_elf = android_path
return debug(tmp_elf, gdbscript=gdbscript, arch=context.arch)
@LocalContext
def debug_shellcode(data, gdbscript=None, vma=None):
"""
Creates an ELF file, and launches it under a debugger.
Arguments:
data(str): Assembled shellcode bytes
gdbscript(str): Script to run in GDB
vma(int): Base address to load the shellcode at
**kwargs: Override any :obj:`pwnlib.context.context` values.
Returns:
:class:`.process`
Example:
.. code-block:: python
assembly = shellcraft.echo("Hello world!\n")
shellcode = asm(assembly)
io = gdb.debug_shellcode(shellcode)
io.recvline()
# 'Hello world!'
"""
if isinstance(data, unicode):
log.error("Shellcode is cannot be unicode. Did you mean debug_assembly?")
tmp_elf = make_elf(data, extract=False, vma=vma)
os.chmod(tmp_elf, 0777)
atexit.register(lambda: os.unlink(tmp_elf))
if context.os == 'android':
android_path = '/data/data/%s' % os.path.basename(tmp_elf)
adb.push(tmp_elf, android_path)
tmp_elf = android_path
return debug(tmp_elf, gdbscript=gdbscript, arch=context.arch)
def _gdbserver_args(pid=None, path=None, args=None, which=None):
"""_gdbserver_args(pid=None, path=None) -> list
Sets up a listening gdbserver, to either connect to the specified
PID, or launch the specified binary by its full path.
Arguments:
pid(int): Process ID to attach to
path(str): Process to launch
args(list): List of arguments to provide on the debugger command line
which(callaable): Function to find the path of a binary.
Returns:
A list of arguments to invoke gdbserver.
"""
if [pid, path, args].count(None) != 2:
log.error("Must specify exactly one of pid, path, or args")
if not which:
log.error("Must specify which.")
gdbserver = ''
if not args:
args = [str(path or pid)]
# Android targets have a distinct gdbserver
if context.bits == 64:
gdbserver = which('gdbserver64')
if not gdbserver:
gdbserver = which('gdbserver')
if not gdbserver:
log.error("gdbserver is not installed")
orig_args = args
gdbserver_args = [gdbserver, '--multi']
if context.aslr:
gdbserver_args += ['--no-disable-randomization']
else:
log.warn_once("Debugging process with ASLR disabled")
if pid:
gdbserver_args += ['--once', '--attach']
gdbserver_args += ['localhost:0']
gdbserver_args += args
return gdbserver_args
def _gdbserver_port(gdbserver, ssh):
which = _get_which(ssh)
# Process /bin/bash created; pid = 14366
# Listening on port 34816
process_created = gdbserver.recvline()
if process_created.startswith('ERROR:'):
raise ValueError(
'Failed to spawn process under gdbserver. gdbserver error message: %s' % process_created
)
gdbserver.pid = int(process_created.split()[-1], 0)
listening_on = ''
while 'Listening' not in listening_on:
listening_on = gdbserver.recvline()
port = int(listening_on.split()[-1])
# Set up port forarding for SSH
if ssh:
remote = ssh.connect_remote('127.0.0.1', port)
listener = tubes.listen.listen(0)
port = listener.lport
# Disable showing GDB traffic when debugging verbosity is increased
remote.level = 'error'
listener.level = 'error'
# Hook them up
remote <> listener
# Set up port forwarding for ADB
elif context.os == 'android':
adb.forward(port)
return port
def _get_which(ssh=None):
if ssh: return ssh.which
elif context.os == 'android': return adb.which
else: return misc.which
def _get_runner(ssh=None):
if ssh: return ssh.process
elif context.os == 'android': return adb.process
else: return tubes.process.process
@LocalContext
def debug(args, gdbscript=None, exe=None, ssh=None, env=None, sysroot=None, **kwargs):
"""debug(args) -> tube
Launch a GDB server with the specified command line,
and launches GDB to attach to it.
Arguments:
args(list): Arguments to the process, similar to :class:`.process`.
gdbscript(str): GDB script to run.
exe(str): Path to the executable on disk
env(dict): Environment to start the binary in
ssh(:class:`.ssh`): Remote ssh session to use to launch the process.
sysroot(str): Foreign-architecture sysroot, used for QEMU-emulated binaries
and Android targets.
Returns:
:class:`.process` or :class:`.ssh_channel`: A tube connected to the target process
Notes:
The debugger is attached automatically, and you can debug everything
from the very beginning. This requires that both ``gdb`` and ``gdbserver``
are installed on your machine.
When GDB opens via :func:`debug`, it will initially be stopped on the very first
instruction of the dynamic linker (``ld.so``) for dynamically-linked binaries.
Only the target binary and the linker will be loaded in memory, so you cannot
set breakpoints on shared library routines like ``malloc`` since ``libc.so``
has not even been loaded yet.
There are several ways to handle this:
1. Set a breakpoint on the executable's entry point (generally, ``_start``)
- This is only invoked after all of the required shared libraries
are loaded.
- You can generally get the address via the GDB command ``info file``.
2. Use pending breakpoints via ``set breakpoint pending on``
- This has the side-effect of setting breakpoints for **every** function
which matches the name. For ``malloc``, this will generally set a
breakpoint in the executable's PLT, in the linker's internal ``malloc``,
and eventaully in ``libc``'s malloc.
3. Wait for libraries to be loaded with ``set stop-on-solib-event 1``
- There is no way to stop on any specific library being loaded, and sometimes
multiple libraries are loaded and only a single breakpoint is issued.
- Generally, you just add a few ``continue`` commands until things are set up
the way you want it to be.
Examples:
.. code-block:: python
# Create a new process, and stop it at 'main'
io = gdb.debug('bash', '''
break main
continue
''')
# Send a command to Bash
io.sendline("echo hello")
# Interact with the process
io.interactive()
.. code-block:: python
# Create a new process, and stop it at 'main'
io = gdb.debug('bash', '''
# Wait until we hit the main executable's entry point
break _start
continue
# Now set breakpoint on shared library routines
break malloc
break free
continue
''')
# Send a command to Bash
io.sendline("echo hello")
# Interact with the process
io.interactive()
You can use :func:`debug` to spawn new processes on remote machines as well,
by using the ``ssh=`` keyword to pass in your :class:`.ssh` instance.
.. code-block:: python
# Connect to the SSH server
shell = ssh('passcode', 'pwnable.kr', 2222, password='guest')
# Start a process on the server
io = gdb.debug(['bash'],
ssh=shell,
gdbscript='''
break main
continue
''')
# Send a command to Bash
io.sendline("echo hello")
# Interact with the process
io.interactive()
"""
if isinstance(args, (int, tubes.process.process, tubes.ssh.ssh_channel)):
log.error("Use gdb.attach() to debug a running process")
if env is None:
env = os.environ
if isinstance(args, (str, unicode)):
args = [args]
orig_args = args
runner = _get_runner(ssh)
which = _get_which(ssh)
gdbscript = gdbscript or ''
if context.noptrace:
log.warn_once("Skipping debugger since context.noptrace==True")
return runner(args, executable=exe, env=env)
if ssh or context.native or (context.os == 'android'):
args = _gdbserver_args(args=args, which=which)
else:
qemu_port = random.randint(1024, 65535)
qemu_user = qemu.user_path()
sysroot = sysroot or qemu.ld_prefix(env=env)
if not qemu_user:
log.error("Cannot debug %s binaries without appropriate QEMU binaries" % context.arch)
args = [qemu_user, '-g', str(qemu_port)] + args
# Use a sane default sysroot for Android
if not sysroot and context.os == 'android':
sysroot = 'remote:/'
# Make sure gdbserver/qemu is installed
if not which(args[0]):
log.error("%s is not installed" % args[0])
exe = exe or which(orig_args[0])
if not exe:
log.error("%s does not exist" % orig_args[0])
else:
gdbscript = 'file "%s"\n%s' % (exe, gdbscript)
# Start gdbserver/qemu
# (Note: We override ASLR here for the gdbserver process itself.)
gdbserver = runner(args, env=env, aslr=1, **kwargs)
# Set the .executable on the process object.
gdbserver.executable = which(orig_args[0])
# Find what port we need to connect to
if context.native or (context.os == 'android'):
port = _gdbserver_port(gdbserver, ssh)
else:
port = qemu_port
host = '127.0.0.1'
if not ssh and context.os == 'android':
host = context.adb_host
attach((host, port), exe=exe, gdbscript=gdbscript, need_ptrace_scope = False, ssh=ssh, sysroot=sysroot)
# gdbserver outputs a message when a client connects
garbage = gdbserver.recvline(timeout=1)
# Some versions of gdbserver output an additional message
garbage2 = gdbserver.recvline_startswith("Remote debugging from host ", timeout=1)
return gdbserver
def get_gdb_arch():
return {
'amd64': 'i386:x86-64',
'powerpc': 'powerpc:common',
'powerpc64': 'powerpc:common64',
'mips64': 'mips:isa64',
'thumb': 'arm'
}.get(context.arch, context.arch)
def binary():
|
@LocalContext
def attach(target, gdbscript = None, exe = None, need_ptrace_scope = True, gdb_args = None, ssh = None, sysroot = None):
"""attach(target, gdbscript = None, exe = None, arch = None, ssh = None) -> None
Start GDB in a new terminal and attach to `target`.
Arguments:
target: The target to attach to.
gdbscript(:obj:`str` or :obj:`file`): GDB script to run after attaching.
exe(str): The path of the target binary.
arch(str): Architechture of the target binary. If `exe` known GDB will
detect the architechture automatically (if it is supported).
gdb_args(list): List of additional arguments to pass to GDB.
sysroot(str): Foreign-architecture sysroot, used for QEMU-emulated binaries
and Android targets.
Returns:
PID of the GDB process (or the window which it is running in).
Notes:
The ``target`` argument is very robust, and can be any of the following:
:obj:`int`
PID of a process
:obj:`str`
Process name. The youngest process is selected.
:obj:`tuple`
Host, port pair of a listening ``gdbserver``
:class:`.process`
Process to connect to
:class:`.sock`
Connected socket. The executable on the other end of the connection is attached to.
Can be any socket type, including :class:`.listen` or :class:`.remote`.
:class:`.ssh_channel`
Remote process spawned via :meth:`.ssh.process`.
This will use the GDB installed on the remote machine.
If a password is required to connect, the ``sshpass`` program must be installed.
Examples:
.. code-block:: python
# Attach directly to pid 1234
gdb.attach(1234)
.. code-block:: python
# Attach to the youngest "bash" process
gdb.attach('bash')
.. code-block:: python
# Start a process
bash = process('bash')
# Attach the debugger
gdb.attach(bash, '''
set follow-fork-mode child
break execve
continue
''')
# Interact with the process
bash.sendline('whoami')
.. code-block:: python
# Start a forking server
server = process(['socat', 'tcp-listen:1234,fork,reuseaddr', 'exec:/bin/sh'])
# Connect to the server
io = remote('localhost', 1234)
# Connect the debugger to the server-spawned process
gdb.attach(io, '''
break exit
continue
''')
# Talk to the spawned 'sh'
io.sendline('exit')
.. code-block:: python
# Connect to the SSH server
shell = ssh('bandit0', 'bandit.labs.overthewire.org', password='bandit0', port=2220)
# Start a process on the server
cat = shell.process(['cat'])
# Attach a debugger to it
gdb.attach(cat, '''
break exit
continue
''')
# Cause `cat` to exit
cat.close()
"""
if context.noptrace:
log.warn_once("Skipping debug attach since context.noptrace==True")
return
# if gdbscript is a file object, then read it; we probably need to run some
# more gdb script anyway
if isinstance(gdbscript, file):
with gdbscript:
gdbscript = gdbscript.read()
# enable gdb.attach(p, 'continue')
if gdbscript and not gdbscript.endswith('\n'):
gdbscript += '\n'
# Use a sane default sysroot for Android
if not sysroot and context.os == 'android':
sysroot = 'remote:/'
# gdb script to run before `gdbscript`
pre = ''
if not context.native:
pre += 'set endian %s\n' % context.endian
pre += 'set architecture %s\n' % get_gdb_arch()
if sysroot:
pre += 'set sysroot %s\n' % sysroot
if context.os == 'android':
pre += 'set gnutarget ' + _bfdname() + '\n'
# let's see if we can find a pid to attach to
pid = None
if isinstance(target, (int, long)):
# target is a pid, easy peasy
pid = target
elif isinstance(target, str):
# pidof picks the youngest process
pidof = proc.pidof
if context.os == 'android':
pidof = adb.pidof
pids = pidof(target)
if not pids:
log.error('No such process: %s' % target)
pid = pids[0]
log.info('Attaching to youngest process "%s" (PID = %d)' %
(target, pid))
elif isinstance(target, tubes.ssh.ssh_channel):
if not target.pid:
log.error("PID unknown for channel")
shell = target.parent
tmpfile = shell.mktemp()
gdbscript = 'shell rm %s\n%s' % (tmpfile, gdbscript)
shell.upload_data(gdbscript or '', tmpfile)
cmd = ['ssh', '-C', '-t', '-p', str(shell.port), '-l', shell.user, shell.host]
if shell.password:
if not misc.which('sshpass'):
log.error("sshpass must be installed to debug ssh processes")
cmd = ['sshpass', '-p', shell.password] + cmd
if shell.keyfile:
cmd += ['-i', shell.keyfile]
cmd += ['gdb -q %r %s -x "%s"' % (target.executable,
target.pid,
tmpfile)]
misc.run_in_new_terminal(' '.join(cmd))
return
elif isinstance(target, tubes.sock.sock):
pids = proc.pidof(target)
if not pids:
log.error('could not find remote process (%s:%d) on this machine' %
target.sock.getpeername())
pid = pids[0]
elif isinstance(target, tubes.process.process):
pid = proc.pidof(target)[0]
exe = exe or target.executable
elif isinstance(target, tuple) and len(target) == 2:
host, port = target
if context.os != 'android':
pre += 'target remote %s:%d\n' % (host, port)
else:
# Android debugging is done over gdbserver, which can't follow
# new inferiors (tldr; follow-fork-mode child) unless it is run
# in extended-remote mode.
pre += 'target extended-remote %s:%d\n' % (host, port)
pre += 'set detach-on-fork off\n'
def findexe():
for spid in proc.pidof(target):
sexe = proc.exe(spid)
name = os.path.basename(sexe)
# XXX: parse cmdline
if name.startswith('qemu-') or name.startswith('gdbserver'):
exe = proc.cmdline(spid)[-1]
return os.path.join(proc.cwd(spid), exe)
exe = exe or findexe()
elif isinstance(target, elf.corefile.Corefile):
pre += 'target core %s\n' % target.path
else:
log.error("don't know how to attach to target: %r" % target)
# if we have a pid but no exe, just look it up in /proc/
if pid and not exe:
exe_fn = proc.exe
if context.os == 'android':
exe_fn = adb.proc_exe
exe = exe_fn(pid)
if not pid and not exe:
log.error('could not find target process')
if exe:
# The 'file' statement should go first
pre = 'file "%s"\n%s' % (exe, pre)
cmd = binary()
if gdb_args:
cmd += ' '
cmd += ' '.join(gdb_args)
if context.gdbinit:
cmd += ' -nh ' # ignore ~/.gdbinit
cmd += ' -x %s ' % context.gdbinit # load custom gdbinit
cmd += ' -q '
if exe and context.native:
if not ssh and not os.path.isfile(exe):
log.error('No such file: %s' % exe)
cmd += ' "%s"' % exe
if pid and not context.os == 'android':
cmd += ' %d' % pid
if context.os == 'android' and pid:
runner = _get_runner()
which = _get_which()
gdb_cmd = _gdbserver_args(pid=pid, which=which)
gdbserver = runner(gdb_cmd)
port = _gdbserver_port(gdbserver, None)
host = context.adb_host
pre += 'target extended-remote %s:%i\n' % (context.adb_host, port)
# gdbserver on Android sets 'detach-on-fork on' which breaks things
# when you're trying to debug anything that forks.
pre += 'set detach-on-fork off\n'
gdbscript = pre + (gdbscript or '')
if gdbscript:
tmp = tempfile.NamedTemporaryFile(prefix = 'pwn', suffix = '.gdb',
delete = False)
log.debug('Wrote gdb script to %r\n%s' % (tmp.name, gdbscript))
gdbscript = 'shell rm %s\n%s' % (tmp.name, gdbscript)
tmp.write(gdbscript)
tmp.close()
cmd += ' -x "%s"' % (tmp.name)
log.info('running in new terminal: %s' % cmd)
gdb_pid = misc.run_in_new_terminal(cmd)
if pid and context.native:
proc.wait_for_debugger(pid)
return gdb_pid
def ssh_gdb(ssh, argv, gdbscript = None, arch = None, **kwargs):
if not isinstance(argv, (list, tuple)):
argv = [argv]
exe = argv[0]
argv = ["gdbserver", "--multi", "127.0.0.1:0"] + argv
# Download the executable
local_exe = os.path.basename(exe)
ssh.download_file(ssh.which(exe), local_exe)
# Run the process
c = ssh.process(argv, **kwargs)
# Find the port for the gdb server
c.recvuntil('port ')
line = c.recvline().strip()
gdbport = re.match('[0-9]+', line)
if gdbport:
gdbport = int(gdbport.group(0))
l = tubes.listen.listen(0)
forwardport = l.lport
attach(('127.0.0.1', forwardport), gdbscript, local_exe, arch, ssh=ssh)
l.wait_for_connection() <> ssh.connect_remote('127.0.0.1', gdbport)
return c
def find_module_addresses(binary, ssh=None, ulimit=False):
"""
Cheat to find modules by using GDB.
We can't use ``/proc/$pid/map`` since some servers forbid it.
This breaks ``info proc`` in GDB, but ``info sharedlibrary`` still works.
Additionally, ``info sharedlibrary`` works on FreeBSD, which may not have
procfs enabled or accessible.
The output looks like this:
::
info proc mapping
process 13961
warning: unable to open /proc file '/proc/13961/maps'
info sharedlibrary
From To Syms Read Shared Object Library
0xf7fdc820 0xf7ff505f Yes (*) /lib/ld-linux.so.2
0xf7fbb650 0xf7fc79f8 Yes /lib32/libpthread.so.0
0xf7e26f10 0xf7f5b51c Yes (*) /lib32/libc.so.6
(*): Shared library is missing debugging information.
Note that the raw addresses provided by ``info sharedlibrary`` are actually
the address of the ``.text`` segment, not the image base address.
This routine automates the entire process of:
1. Downloading the binaries from the remote server
2. Scraping GDB for the information
3. Loading each library into an ELF
4. Fixing up the base address vs. the ``.text`` segment address
Arguments:
binary(str): Path to the binary on the remote server
ssh(pwnlib.tubes.tube): SSH connection through which to load the libraries.
If left as :const:`None`, will use a :class:`pwnlib.tubes.process.process`.
ulimit(bool): Set to :const:`True` to run "ulimit -s unlimited" before GDB.
Returns:
A list of pwnlib.elf.ELF objects, with correct base addresses.
Example:
>>> with context.local(log_level=9999): # doctest: +SKIP
... shell = ssh(host='bandit.labs.overthewire.org',user='bandit0',password='bandit0', port=2220)
... bash_libs = gdb.find_module_addresses('/bin/bash', shell)
>>> os.path.basename(bash_libs[0].path) # doctest: +SKIP
'libc.so.6'
>>> hex(bash_libs[0].symbols['system']) # doctest: +SKIP
'0x7ffff7634660'
"""
#
# Download all of the remote libraries
#
if ssh:
runner = ssh.run
local_bin = ssh.download_file(binary)
local_elf = elf.ELF(os.path.basename(binary))
local_libs = ssh.libs(binary)
else:
runner = tubes.process.process
local_elf = elf.ELF(binary)
local_libs = local_elf.libs
entry = local_elf.header.e_entry
#
# Get the addresses from GDB
#
libs = {}
cmd = "gdb -q --args %s" % (binary)
expr = re.compile(r'(0x\S+)[^/]+(.*)')
if ulimit:
cmd = 'sh -c "(ulimit -s unlimited; %s)"' % cmd
cmd = shlex.split(cmd)
with runner(cmd) as gdb:
if context.aslr:
gdb.sendline('set disable-randomization off')
gdb.send("""
set prompt
break *%#x
run
""" % entry)
gdb.clean(2)
gdb.sendline('info sharedlibrary')
lines = gdb.recvrepeat(2)
for line in lines.splitlines():
m = expr.match(line)
if m:
libs[m.group(2)] = int(m.group(1),16)
gdb.sendline('kill')
gdb.sendline('y')
gdb.sendline('quit')
#
# Fix up all of the addresses against the .text address
#
rv = []
for remote_path,text_address in sorted(libs.items()):
# Match up the local copy to the remote path
try:
path = next(p for p in local_libs.keys() if remote_path in p)
except StopIteration:
print "Skipping %r" % remote_path
continue
# Load it
lib = elf.ELF(path)
# Find its text segment
text = lib.get_section_by_name('.text')
# Fix the address
lib.address = text_address - text.header.sh_addr
rv.append(lib)
return rv
def corefile(process):
r"""Drops a core file for the process.
Arguments:
process: Process to dump
Returns:
:class:`.Core`: The generated core file
"""
if context.noptrace:
log.warn_once("Skipping corefile since context.noptrace==True")
return
corefile_path = './core.%s.%i' % (os.path.basename(process.executable),
process.pid)
# Due to https://sourceware.org/bugzilla/show_bug.cgi?id=16092
# will disregard coredump_filter, and will not dump private mappings.
if version() < (7,11):
log.warn_once('The installed GDB (%s) does not emit core-dumps which '
'contain all of the data in the process.\n'
'Upgrade to GDB >= 7.11 for better core-dumps.' % binary())
# This is effectively the same as what the 'gcore' binary does
gdb_args = ['-batch',
'-q',
'--nx',
'-ex', '"set pagination off"',
'-ex', '"set height 0"',
'-ex', '"set width 0"',
'-ex', '"set use-coredump-filter on"',
'-ex', '"generate-core-file %s"' % corefile_path,
'-ex', 'detach']
with context.local(terminal = ['sh', '-c']):
with context.quiet:
pid = attach(process, gdb_args=gdb_args)
os.waitpid(pid, 0)
return elf.corefile.Core(corefile_path)
def version(program='gdb'):
"""Gets the current GDB version.
Note:
Requires that GDB version meets the following format:
``GNU gdb (GDB) 7.12``
Returns:
tuple: A tuple containing the version numbers
Example:
>>> (7,0) <= gdb.version() <= (8,0)
True
"""
program = misc.which(program)
expr = r'([0-9]+\.?)+'
with tubes.process.process([program, '--version'], level='error') as gdb:
version = gdb.recvline()
versions = re.search(expr, version).group()
return tuple(map(int, versions.split('.')))
| """binary() -> str
Returns:
str: Path to the appropriate ``gdb`` binary to use.
Example:
>>> gdb.binary() # doctest: +SKIP
'/usr/bin/gdb'
"""
gdb = misc.which('pwntools-gdb') or misc.which('gdb')
if not context.native:
multiarch = misc.which('gdb-multiarch')
if multiarch:
return multiarch
log.warn_once('Cross-architecture debugging usually requires gdb-multiarch\n' \
'$ apt-get install gdb-multiarch')
if not gdb:
log.error('GDB is not installed\n'
'$ apt-get install gdb')
return gdb |
main.rs | fn main() { | println!("{}", part1);
println!("{}", part2);
} | let (part1, part2) = day07::solve(); |
dtlslistener.go | package net
import (
"context"
"fmt"
"net"
"sync"
"sync/atomic"
"time"
dtls "github.com/pion/dtls/v2"
)
type connData struct {
conn net.Conn
err error
}
// DTLSListener is a DTLS listener that provides accept with context.
type DTLSListener struct {
listener net.Listener
heartBeat time.Duration
wg sync.WaitGroup
doneCh chan struct{}
connCh chan connData
onTimeout func() error
cancel context.CancelFunc
mutex sync.Mutex
closed uint32
deadline atomic.Value
}
func (l *DTLSListener) acceptLoop() {
defer l.wg.Done()
for {
conn, err := l.listener.Accept()
if err != nil {
select {
case <-l.doneCh:
return
case l.connCh <- connData{conn: conn, err: err}:
}
} else {
select {
case l.connCh <- connData{conn: conn, err: err}:
case <-l.doneCh:
return
}
}
}
}
var defaultDTLSListenerOptions = dtlsListenerOptions{
heartBeat: time.Millisecond * 200,
}
type dtlsListenerOptions struct {
heartBeat time.Duration
onTimeout func() error
}
// A DTLSListenerOption sets options such as heartBeat parameters, etc.
type DTLSListenerOption interface {
applyDTLSListener(*dtlsListenerOptions)
}
// NewDTLSListener creates dtls listener.
// Known networks are "udp", "udp4" (IPv4-only), "udp6" (IPv6-only).
func NewDTLSListener(network string, addr string, dtlsCfg *dtls.Config, opts ...DTLSListenerOption) (*DTLSListener, error) {
cfg := defaultDTLSListenerOptions
for _, o := range opts {
o.applyDTLSListener(&cfg)
}
a, err := net.ResolveUDPAddr(network, addr)
if err != nil {
return nil, fmt.Errorf("cannot resolve address: %w", err)
}
l := DTLSListener{
heartBeat: cfg.heartBeat,
connCh: make(chan connData),
doneCh: make(chan struct{}),
}
connectContextMaker := dtlsCfg.ConnectContextMaker
if connectContextMaker == nil {
connectContextMaker = func() (context.Context, func()) {
return context.WithTimeout(context.Background(), 30*time.Second)
}
}
dtlsCfg.ConnectContextMaker = func() (context.Context, func()) {
ctx, cancel := connectContextMaker()
l.mutex.Lock()
defer l.mutex.Unlock()
if l.closed > 0 {
cancel()
}
l.cancel = cancel
return ctx, cancel
}
listener, err := dtls.Listen(network, a, dtlsCfg)
if err != nil {
return nil, fmt.Errorf("cannot create new dtls listener: %w", err)
}
l.listener = listener
l.wg.Add(1)
go l.acceptLoop()
return &l, nil
}
// AcceptWithContext waits with context for a generic Conn.
func (l *DTLSListener) AcceptWithContext(ctx context.Context) (net.Conn, error) {
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
if atomic.LoadUint32(&l.closed) == 1 {
return nil, ErrListenerIsClosed
}
deadline := time.Now().Add(l.heartBeat)
err := l.SetDeadline(deadline)
if err != nil {
return nil, fmt.Errorf("cannot set deadline to accept connection: %w", err)
}
rw, err := l.Accept()
if err != nil {
// check context in regular intervals and then resume listening
if isTemporary(err, deadline) {
if l.onTimeout != nil {
err := l.onTimeout()
if err != nil {
return nil, fmt.Errorf("cannot accept connection : on timeout returns error: %w", err)
}
}
continue
}
return nil, fmt.Errorf("cannot accept connection: %w", err)
}
return rw, nil
}
}
// SetDeadline sets deadline for accept operation.
func (l *DTLSListener) SetDeadline(t time.Time) error {
l.deadline.Store(t)
return nil
}
// Accept waits for a generic Conn.
func (l *DTLSListener) Accept() (net.Conn, error) {
var deadline time.Time
v := l.deadline.Load()
if v != nil {
deadline = v.(time.Time)
}
if deadline.IsZero() {
select {
case d := <-l.connCh:
if d.err != nil {
return nil, d.err
}
return d.conn, nil
}
}
select {
case d := <-l.connCh:
if d.err != nil {
return nil, d.err
}
return d.conn, nil
case <-time.After(deadline.Sub(time.Now())):
return nil, fmt.Errorf(ioTimeout)
}
}
func (l *DTLSListener) close() (bool, error) {
l.mutex.Lock()
defer l.mutex.Unlock()
if l.closed > 0 {
return false, nil
}
close(l.doneCh)
err := l.listener.Close()
if l.cancel != nil {
l.cancel()
}
return true, err
}
// Close closes the connection.
func (l *DTLSListener) Close() error {
wait, err := l.close()
if wait |
return err
}
// Addr represents a network end point address.
func (l *DTLSListener) Addr() net.Addr {
return l.listener.Addr()
}
| {
l.wg.Wait()
} |
i18n.py | import contextvars
import gettext
import os.path
from glob import glob
from app.t_string import TString
BASE_DIR = ""
LOCALE_DEFAULT = "en_US"
LOCALE_DIR = "locale"
locales = frozenset(
map(
os.path.basename,
filter(os.path.isdir, glob(os.path.join(BASE_DIR, LOCALE_DIR, "*"))),
)
)
gettext_translations = {
locale: gettext.translation(
"bot",
languages=(locale,),
localedir=os.path.join(BASE_DIR, LOCALE_DIR),
)
for locale in locales
}
gettext_translations["en_US"] = gettext.NullTranslations()
locales |= {"en_US"}
def use_current_gettext(*args, **kwargs) -> str:
"""Translate a string using the proper gettext based
on the current_locale context var.
:return: The gettext for the current locale
:rtype: str
"""
if not gettext_translations:
return gettext.gettext(*args, **kwargs)
locale = current_locale.get()
return gettext_translations.get(
locale, gettext_translations[LOCALE_DEFAULT]
).gettext(*args, **kwargs)
def translate(string: str) -> str:
"""Translates text.
:param string: The text that needs translation
:type string: str
:return: The translated text
:rtype: str
"""
tstring = TString(string, use_current_gettext)
return str(tstring) # translate immediatly
def lazy_translate(string: str) -> TString:
"""Lazy translates text.
:param string: The text that needs translation
:type string: str
:return: The TString object that can be translated later
:rtype: TString
"""
tstring = TString(string, use_current_gettext)
return tstring
current_locale: contextvars.ContextVar = contextvars.ContextVar("i18n")
def | ():
"""Sets the locale to the LOCALE_DEFAULT."""
current_locale.set(LOCALE_DEFAULT)
set_current_locale()
| set_current_locale |
entry_completion.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::Buildable;
use crate::CellArea;
use crate::CellLayout;
use crate::TreeIter;
use crate::TreeModel;
use glib::object::Cast;
use glib::object::IsA;
use glib::object::ObjectType as ObjectType_;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use glib::StaticType;
use glib::ToValue;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
glib::wrapper! {
pub struct EntryCompletion(Object<ffi::GtkEntryCompletion>) @implements Buildable, CellLayout;
match fn {
get_type => || ffi::gtk_entry_completion_get_type(),
}
}
impl EntryCompletion {
#[doc(alias = "gtk_entry_completion_new")]
pub fn new() -> EntryCompletion {
assert_initialized_main_thread!();
unsafe { from_glib_full(ffi::gtk_entry_completion_new()) }
}
#[doc(alias = "gtk_entry_completion_new_with_area")]
pub fn with_area<P: IsA<CellArea>>(area: &P) -> EntryCompletion {
skip_assert_initialized!();
unsafe {
from_glib_full(ffi::gtk_entry_completion_new_with_area(
area.as_ref().to_glib_none().0,
))
}
}
#[doc(alias = "gtk_entry_completion_complete")]
pub fn complete(&self) {
unsafe {
ffi::gtk_entry_completion_complete(self.to_glib_none().0);
}
}
#[doc(alias = "gtk_entry_completion_compute_prefix")]
pub fn compute_prefix(&self, key: &str) -> Option<glib::GString> {
unsafe {
from_glib_full(ffi::gtk_entry_completion_compute_prefix(
self.to_glib_none().0,
key.to_glib_none().0,
))
}
}
#[doc(alias = "gtk_entry_completion_get_completion_prefix")]
pub fn get_completion_prefix(&self) -> Option<glib::GString> {
unsafe {
from_glib_none(ffi::gtk_entry_completion_get_completion_prefix(
self.to_glib_none().0,
))
}
}
#[doc(alias = "gtk_entry_completion_get_inline_completion")]
pub fn get_inline_completion(&self) -> bool {
unsafe {
from_glib(ffi::gtk_entry_completion_get_inline_completion(
self.to_glib_none().0,
))
}
}
#[doc(alias = "gtk_entry_completion_get_inline_selection")]
pub fn get_inline_selection(&self) -> bool {
unsafe {
from_glib(ffi::gtk_entry_completion_get_inline_selection(
self.to_glib_none().0,
))
}
}
#[doc(alias = "gtk_entry_completion_get_minimum_key_length")]
pub fn get_minimum_key_length(&self) -> i32 {
unsafe { ffi::gtk_entry_completion_get_minimum_key_length(self.to_glib_none().0) }
}
#[doc(alias = "gtk_entry_completion_get_model")]
pub fn get_model(&self) -> Option<TreeModel> {
unsafe { from_glib_none(ffi::gtk_entry_completion_get_model(self.to_glib_none().0)) }
}
#[doc(alias = "gtk_entry_completion_get_popup_completion")]
pub fn get_popup_completion(&self) -> bool {
unsafe {
from_glib(ffi::gtk_entry_completion_get_popup_completion(
self.to_glib_none().0,
))
}
}
#[doc(alias = "gtk_entry_completion_get_popup_set_width")]
pub fn get_popup_set_width(&self) -> bool {
unsafe {
from_glib(ffi::gtk_entry_completion_get_popup_set_width(
self.to_glib_none().0,
))
}
}
#[doc(alias = "gtk_entry_completion_get_popup_single_match")]
pub fn get_popup_single_match(&self) -> bool {
unsafe {
from_glib(ffi::gtk_entry_completion_get_popup_single_match(
self.to_glib_none().0,
))
}
}
#[doc(alias = "gtk_entry_completion_get_text_column")]
pub fn get_text_column(&self) -> i32 {
unsafe { ffi::gtk_entry_completion_get_text_column(self.to_glib_none().0) }
}
#[doc(alias = "gtk_entry_completion_insert_prefix")]
pub fn insert_prefix(&self) {
unsafe {
ffi::gtk_entry_completion_insert_prefix(self.to_glib_none().0);
}
}
#[doc(alias = "gtk_entry_completion_set_inline_completion")]
pub fn set_inline_completion(&self, inline_completion: bool) {
unsafe {
ffi::gtk_entry_completion_set_inline_completion(
self.to_glib_none().0,
inline_completion.to_glib(),
);
}
}
#[doc(alias = "gtk_entry_completion_set_inline_selection")]
pub fn set_inline_selection(&self, inline_selection: bool) {
unsafe {
ffi::gtk_entry_completion_set_inline_selection(
self.to_glib_none().0,
inline_selection.to_glib(),
);
}
}
#[doc(alias = "gtk_entry_completion_set_match_func")]
pub fn set_match_func<P: Fn(&EntryCompletion, &str, &TreeIter) -> bool + 'static>(
&self,
func: P,
) {
let func_data: Box_<P> = Box_::new(func);
unsafe extern "C" fn func_func<
P: Fn(&EntryCompletion, &str, &TreeIter) -> bool + 'static,
>(
completion: *mut ffi::GtkEntryCompletion,
key: *const libc::c_char,
iter: *mut ffi::GtkTreeIter,
user_data: glib::ffi::gpointer,
) -> glib::ffi::gboolean {
let completion = from_glib_borrow(completion);
let key: Borrowed<glib::GString> = from_glib_borrow(key);
let iter = from_glib_borrow(iter);
let callback: &P = &*(user_data as *mut _);
let res = (*callback)(&completion, key.as_str(), &iter);
res.to_glib()
}
let func = Some(func_func::<P> as _);
unsafe extern "C" fn func_notify_func<
P: Fn(&EntryCompletion, &str, &TreeIter) -> bool + 'static,
>(
data: glib::ffi::gpointer,
) {
let _callback: Box_<P> = Box_::from_raw(data as *mut _);
}
let destroy_call3 = Some(func_notify_func::<P> as _);
let super_callback0: Box_<P> = func_data;
unsafe {
ffi::gtk_entry_completion_set_match_func(
self.to_glib_none().0,
func,
Box_::into_raw(super_callback0) as *mut _,
destroy_call3,
);
}
}
#[doc(alias = "gtk_entry_completion_set_minimum_key_length")]
pub fn set_minimum_key_length(&self, length: i32) {
unsafe {
ffi::gtk_entry_completion_set_minimum_key_length(self.to_glib_none().0, length);
}
}
#[doc(alias = "gtk_entry_completion_set_model")]
pub fn set_model<P: IsA<TreeModel>>(&self, model: Option<&P>) {
unsafe {
ffi::gtk_entry_completion_set_model(
self.to_glib_none().0,
model.map(|p| p.as_ref()).to_glib_none().0,
);
}
}
#[doc(alias = "gtk_entry_completion_set_popup_completion")]
pub fn set_popup_completion(&self, popup_completion: bool) {
unsafe {
ffi::gtk_entry_completion_set_popup_completion(
self.to_glib_none().0,
popup_completion.to_glib(),
);
}
}
#[doc(alias = "gtk_entry_completion_set_popup_set_width")]
pub fn set_popup_set_width(&self, popup_set_width: bool) {
unsafe {
ffi::gtk_entry_completion_set_popup_set_width(
self.to_glib_none().0,
popup_set_width.to_glib(),
);
}
}
#[doc(alias = "gtk_entry_completion_set_popup_single_match")]
pub fn set_popup_single_match(&self, popup_single_match: bool) {
unsafe {
ffi::gtk_entry_completion_set_popup_single_match(
self.to_glib_none().0,
popup_single_match.to_glib(),
);
}
}
#[doc(alias = "gtk_entry_completion_set_text_column")]
pub fn set_text_column(&self, column: i32) {
unsafe {
ffi::gtk_entry_completion_set_text_column(self.to_glib_none().0, column);
}
}
pub fn get_property_cell_area(&self) -> Option<CellArea> {
unsafe {
let mut value = glib::Value::from_type(<CellArea as StaticType>::static_type());
glib::gobject_ffi::g_object_get_property(
self.as_ptr() as *mut glib::gobject_ffi::GObject,
b"cell-area\0".as_ptr() as *const _,
value.to_glib_none_mut().0,
);
value
.get()
.expect("Return Value for property `cell-area` getter")
}
}
pub fn connect_cursor_on_match<
F: Fn(&EntryCompletion, &TreeModel, &TreeIter) -> glib::signal::Inhibit + 'static,
>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn cursor_on_match_trampoline<
F: Fn(&EntryCompletion, &TreeModel, &TreeIter) -> glib::signal::Inhibit + 'static,
>(
this: *mut ffi::GtkEntryCompletion,
model: *mut ffi::GtkTreeModel,
iter: *mut ffi::GtkTreeIter,
f: glib::ffi::gpointer,
) -> glib::ffi::gboolean {
let f: &F = &*(f as *const F);
f(
&from_glib_borrow(this),
&from_glib_borrow(model),
&from_glib_borrow(iter),
)
.to_glib()
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"cursor-on-match\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
cursor_on_match_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
pub fn connect_insert_prefix<
F: Fn(&EntryCompletion, &str) -> glib::signal::Inhibit + 'static,
>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn insert_prefix_trampoline<
F: Fn(&EntryCompletion, &str) -> glib::signal::Inhibit + 'static,
>(
this: *mut ffi::GtkEntryCompletion,
prefix: *mut libc::c_char,
f: glib::ffi::gpointer,
) -> glib::ffi::gboolean {
let f: &F = &*(f as *const F);
f(
&from_glib_borrow(this),
&glib::GString::from_glib_borrow(prefix),
)
.to_glib()
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"insert-prefix\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
insert_prefix_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
pub fn connect_match_selected<
F: Fn(&EntryCompletion, &TreeModel, &TreeIter) -> glib::signal::Inhibit + 'static,
>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn match_selected_trampoline<
F: Fn(&EntryCompletion, &TreeModel, &TreeIter) -> glib::signal::Inhibit + 'static,
>(
this: *mut ffi::GtkEntryCompletion,
model: *mut ffi::GtkTreeModel,
iter: *mut ffi::GtkTreeIter,
f: glib::ffi::gpointer,
) -> glib::ffi::gboolean {
let f: &F = &*(f as *const F);
f(
&from_glib_borrow(this),
&from_glib_borrow(model),
&from_glib_borrow(iter),
)
.to_glib()
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"match-selected\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
match_selected_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
pub fn connect_no_matches<F: Fn(&EntryCompletion) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn no_matches_trampoline<F: Fn(&EntryCompletion) + 'static>(
this: *mut ffi::GtkEntryCompletion,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"no-matches\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
no_matches_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
pub fn connect_property_inline_completion_notify<F: Fn(&EntryCompletion) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_inline_completion_trampoline<
F: Fn(&EntryCompletion) + 'static,
>(
this: *mut ffi::GtkEntryCompletion,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::inline-completion\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_inline_completion_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
pub fn connect_property_inline_selection_notify<F: Fn(&EntryCompletion) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_inline_selection_trampoline<
F: Fn(&EntryCompletion) + 'static,
>(
this: *mut ffi::GtkEntryCompletion,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::inline-selection\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_inline_selection_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
pub fn connect_property_minimum_key_length_notify<F: Fn(&EntryCompletion) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_minimum_key_length_trampoline<
F: Fn(&EntryCompletion) + 'static,
>(
this: *mut ffi::GtkEntryCompletion,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::minimum-key-length\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_minimum_key_length_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
pub fn connect_property_model_notify<F: Fn(&EntryCompletion) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_model_trampoline<F: Fn(&EntryCompletion) + 'static>(
this: *mut ffi::GtkEntryCompletion,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::model\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_model_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
pub fn connect_property_popup_completion_notify<F: Fn(&EntryCompletion) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_popup_completion_trampoline<
F: Fn(&EntryCompletion) + 'static,
>(
this: *mut ffi::GtkEntryCompletion,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::popup-completion\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_popup_completion_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
pub fn connect_property_popup_set_width_notify<F: Fn(&EntryCompletion) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_popup_set_width_trampoline<
F: Fn(&EntryCompletion) + 'static,
>(
this: *mut ffi::GtkEntryCompletion,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::popup-set-width\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_popup_set_width_trampoline::<F> as *const (),
)),
Box_::into_raw(f), | }
}
pub fn connect_property_popup_single_match_notify<F: Fn(&EntryCompletion) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_popup_single_match_trampoline<
F: Fn(&EntryCompletion) + 'static,
>(
this: *mut ffi::GtkEntryCompletion,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::popup-single-match\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_popup_single_match_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
pub fn connect_property_text_column_notify<F: Fn(&EntryCompletion) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_text_column_trampoline<F: Fn(&EntryCompletion) + 'static>(
this: *mut ffi::GtkEntryCompletion,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(&from_glib_borrow(this))
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::text-column\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_text_column_trampoline::<F> as *const (),
)),
Box_::into_raw(f),
)
}
}
}
impl Default for EntryCompletion {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Default)]
pub struct EntryCompletionBuilder {
cell_area: Option<CellArea>,
inline_completion: Option<bool>,
inline_selection: Option<bool>,
minimum_key_length: Option<i32>,
model: Option<TreeModel>,
popup_completion: Option<bool>,
popup_set_width: Option<bool>,
popup_single_match: Option<bool>,
text_column: Option<i32>,
}
impl EntryCompletionBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn build(self) -> EntryCompletion {
let mut properties: Vec<(&str, &dyn ToValue)> = vec![];
if let Some(ref cell_area) = self.cell_area {
properties.push(("cell-area", cell_area));
}
if let Some(ref inline_completion) = self.inline_completion {
properties.push(("inline-completion", inline_completion));
}
if let Some(ref inline_selection) = self.inline_selection {
properties.push(("inline-selection", inline_selection));
}
if let Some(ref minimum_key_length) = self.minimum_key_length {
properties.push(("minimum-key-length", minimum_key_length));
}
if let Some(ref model) = self.model {
properties.push(("model", model));
}
if let Some(ref popup_completion) = self.popup_completion {
properties.push(("popup-completion", popup_completion));
}
if let Some(ref popup_set_width) = self.popup_set_width {
properties.push(("popup-set-width", popup_set_width));
}
if let Some(ref popup_single_match) = self.popup_single_match {
properties.push(("popup-single-match", popup_single_match));
}
if let Some(ref text_column) = self.text_column {
properties.push(("text-column", text_column));
}
let ret = glib::Object::new::<EntryCompletion>(&properties).expect("object new");
ret
}
pub fn cell_area<P: IsA<CellArea>>(mut self, cell_area: &P) -> Self {
self.cell_area = Some(cell_area.clone().upcast());
self
}
pub fn inline_completion(mut self, inline_completion: bool) -> Self {
self.inline_completion = Some(inline_completion);
self
}
pub fn inline_selection(mut self, inline_selection: bool) -> Self {
self.inline_selection = Some(inline_selection);
self
}
pub fn minimum_key_length(mut self, minimum_key_length: i32) -> Self {
self.minimum_key_length = Some(minimum_key_length);
self
}
pub fn model<P: IsA<TreeModel>>(mut self, model: &P) -> Self {
self.model = Some(model.clone().upcast());
self
}
pub fn popup_completion(mut self, popup_completion: bool) -> Self {
self.popup_completion = Some(popup_completion);
self
}
pub fn popup_set_width(mut self, popup_set_width: bool) -> Self {
self.popup_set_width = Some(popup_set_width);
self
}
pub fn popup_single_match(mut self, popup_single_match: bool) -> Self {
self.popup_single_match = Some(popup_single_match);
self
}
pub fn text_column(mut self, text_column: i32) -> Self {
self.text_column = Some(text_column);
self
}
}
impl fmt::Display for EntryCompletion {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("EntryCompletion")
}
} | ) |
couch.py | import json
import traceback
from collections import defaultdict, namedtuple
from copy import deepcopy
from functools import partial
from time import sleep
from couchdbkit import ResourceNotFound, BulkSaveError, Document
from django.conf import settings
from django.http import Http404
from jsonobject.exceptions import WrappingAttributeError
from corehq.util.exceptions import DocumentClassNotFound
from dimagi.utils.chunked import chunked
from memoized import memoized
class DocumentNotFound(Exception):
pass
def get_document_or_not_found_lite(cls, doc_id):
"""
Like `get_document_or_not_found` but without domain/doc_type checks.
"""
return cls.wrap(_get_document_or_not_found_lite(cls, doc_id))
def _get_document_or_not_found_lite(cls, doc_id):
"""
Returns an unwrapped document if it exists, or raises `DocumentNotFound` if not
"""
try:
return cls.get_db().get(doc_id)
except ResourceNotFound:
raise DocumentNotFound("Document {} of class {} not found!".format(
doc_id,
cls.__name__
))
def get_document_or_not_found(cls, domain, doc_id, additional_doc_types=None):
allowed_doc_types = (additional_doc_types or []) + [cls.__name__]
unwrapped = _get_document_or_not_found_lite(cls, doc_id)
if ((unwrapped.get('domain', None) != domain and
domain not in unwrapped.get('domains', [])) or
unwrapped['doc_type'] not in allowed_doc_types):
raise DocumentNotFound("Document {} of class {} not in domain {}!".format(
doc_id,
cls.__name__,
domain,
))
try:
return cls.wrap(unwrapped)
except WrappingAttributeError:
raise DocumentNotFound("Issue wrapping document {} of class {}!".format(
doc_id,
cls.__name__
))
def get_document_or_404(cls, domain, doc_id, additional_doc_types=None):
"""
Gets a document and enforces its domain and doc type.
Raises Http404 if the doc isn't found or domain/doc_type don't match.
"""
try:
return get_document_or_not_found(
cls, domain, doc_id, additional_doc_types=additional_doc_types)
except DocumentNotFound as e:
raise Http404("{}\n\n{}".format(e, traceback.format_exc()))
@memoized
def get_classes_by_doc_type():
queue = [Document]
classes_by_doc_type = {}
while queue:
klass = queue.pop()
try:
klass._meta.app_label
except AttributeError:
# exclude abstract base classes (which don't have an app_label)
pass
else:
# a base class (e.g. CommCareCase) wins over a subclass (e.g. SupplyPointCase)
if klass._doc_type not in classes_by_doc_type:
classes_by_doc_type[klass._doc_type] = klass
queue.extend(klass.__subclasses__())
return classes_by_doc_type
def get_document_class_by_doc_type(doc_type):
"""
Given the doc_type of a document class, get the class itself.
Raises a DocumentClassNotFound if not found
"""
try:
return get_classes_by_doc_type()[doc_type]
except KeyError:
raise DocumentClassNotFound(
'No Document class with name "{}" could be found.'.format(doc_type))
def get_db_by_doc_type(doc_type):
"""
Lookup a database by document type. Returns None if the database is not found.
"""
try:
return get_document_class_by_doc_type(doc_type).get_db()
except DocumentClassNotFound:
return None
def categorize_bulk_save_errors(error):
result_map = defaultdict(list)
for result in error.results:
error = result.get('error', None)
result_map[error].append(result)
return result_map
class IterDBCallback(object):
def post_commit(self, operation, committed_docs, success_ids, errors):
"""
:param operation: 'save' or 'delete'
:param committed_docs: List of all docs in this commit operation
:param success_ids: List of IDs that were processed successfully
:param errors: List of error dictionaries with keys: ('id', 'reason', 'error'
"""
pass
class IterDB(object):
"""
Bulk save docs in chunks.
with IterDB(db) as iter_db:
for doc in iter_docs(db, ids):
iter_db.save(doc)
iter_db.error_ids # docs that errored
iter_db.saved_ids # docs that saved correctly
`new_edits` param will be passed directly to db.bulk_save
"""
def __init__(self, database, chunksize=100, throttle_secs=None,
new_edits=None, callback=None):
self.db = database
self.chunksize = chunksize
self.throttle_secs = throttle_secs
self.saved_ids = set()
self.deleted_ids = set()
self.error_ids = set()
self.errors_by_type = defaultdict(list)
self.new_edits = new_edits
self.callback = callback
def __enter__(self):
self.to_save = []
self.to_delete = []
return self
def _write(self, op_slug, cmd, docs):
categorized_errors = {}
try:
results = cmd(docs)
except BulkSaveError as e:
categorized_errors = categorize_bulk_save_errors(e)
for error_type, errors in categorized_errors.items():
self.errors_by_type[error_type].extend(errors)
error_ids = {d['id'] for d in e.errors}
self.error_ids.update(error_ids)
if not self.new_edits:
# only errors returned in this mode
success_ids = {doc['_id'] for doc in docs if doc['_id'] not in error_ids}
else:
success_ids = {r['id'] for r in categorized_errors.pop(None, [])}
else:
if self.new_edits or self.new_edits is None:
success_ids = {d['id'] for d in results}
else:
# only errors returned in this mode
success_ids = {d['_id'] for d in docs}
if self.callback:
self.callback.post_commit(op_slug, docs, success_ids, list(categorized_errors.values()))
if self.throttle_secs:
sleep(self.throttle_secs)
return success_ids
def _commit_save(self):
bulk_save = partial(self.db.bulk_save, new_edits=self.new_edits)
success_ids = self._write('save', bulk_save, self.to_save)
self.saved_ids.update(success_ids)
self.to_save = []
def _commit_delete(self):
success_ids = self._write('delete', self.db.bulk_delete, self.to_delete)
self.deleted_ids.update(success_ids)
self.to_delete = []
def save(self, doc):
self.to_save.append(doc)
if len(self.to_save) >= self.chunksize:
self._commit_save()
def delete(self, doc):
self.to_delete.append(doc)
if len(self.to_delete) >= self.chunksize:
self._commit_delete()
def commit(self):
if self.to_save:
self._commit_save()
if self.to_delete:
self._commit_delete()
def __exit__(self, exc_type, exc_val, exc_tb):
self.commit()
class IterUpdateError(Exception):
def __init__(self, results, *args, **kwargs):
self.results = results
super(IterUpdateError, self).__init__(*args, **kwargs)
class DocUpdate(object):
def __init__(self, doc, delete=False):
self.doc = doc
self.delete = delete
def _is_unchanged(doc_or_Document, doc):
if hasattr(doc_or_Document, 'to_json'):
new_doc = doc_or_Document.to_json()
else:
new_doc = doc_or_Document
return new_doc == doc
def send_keys_to_couch(db, keys):
"""
Copied from dimagi-utils get_docs. Returns a response for every key.
"""
url = db.uri + '/_all_docs'
rsession = db._request_session
r = rsession.post(url=url,
data=json.dumps({'keys': [_f for _f in keys if _f]}),
headers={'content-type': 'application/json'},
params={'include_docs': 'true'})
return r.json()['rows']
def iter_update(db, fn, ids, max_retries=3, verbose=False, chunksize=100):
"""
Map `fn` over every doc in `db` matching `ids`
`fn` should accept a json dict from couch and return an instance of
DocUpdate or None (which will skip the doc)
iter_update returns an object with the following properties:
'ignored_ids', 'not_found_ids', 'deleted_ids', 'updated_ids', 'error_ids'
Ex: mark dimagi users as cool, delete the Canadians, and ignore the rest
from corehq.util.couch import iter_update, DocUpdate
def mark_cool(user_dict):
user = CommCareUser.wrap(user_dict)
if user.is_dimagi:
user.is_cool = True
return DocUpdate(doc=user)
if user.language == "Canadian":
return DocUpdate(doc=user, delete=True)
iter_update(CommCareUser.get_db(), mark_cool, all_user_ids)
This looks up and saves docs in chunks and is intended for large changes
such as a migration. If an id is not found, it is skipped. In the
event of a BulkSaveError, it will re-process the unsaved documents.
Wrapping is optional, and this function will unwrap if needed.
"""
fields = ['ignored_ids', 'not_found_ids', 'deleted_ids', 'updated_ids',
'error_ids']
IterResults = namedtuple('IterResults', fields)
results = IterResults(set(), set(), set(), set(), set())
def | (doc_update):
if isinstance(doc_update.doc, dict):
updated_doc_id = doc_update.doc.get('_id')
else:
updated_doc_id = doc_update.doc._id
return updated_doc_id
def _iter_update(doc_ids, try_num):
with IterDB(db, chunksize=chunksize) as iter_db:
for chunk in chunked(set(doc_ids), chunksize):
for res in send_keys_to_couch(db, keys=chunk):
raw_doc = res.get('doc')
doc_id = res.get('id', None)
if not raw_doc or not doc_id:
results.not_found_ids.add(res['key'])
else:
# copy the dictionary so we can tell if it changed
doc_update = fn(deepcopy(raw_doc))
if doc_update is None:
results.ignored_ids.add(doc_id)
elif (not isinstance(doc_update, DocUpdate)
or _get_updated_doc_id(doc_update) != doc_id):
results.error_ids.add(doc_id)
elif doc_update.delete:
iter_db.delete(raw_doc)
elif not _is_unchanged(doc_update.doc, raw_doc):
iter_db.save(doc_update.doc)
else:
results.ignored_ids.add(doc_id)
results.updated_ids.update(iter_db.saved_ids)
results.deleted_ids.update(iter_db.deleted_ids)
if iter_db.error_ids:
if try_num >= max_retries:
results.error_ids.update(iter_db.error_ids)
msg = ("The following documents did not correctly save:\n" +
", ".join(results.error_ids))
raise IterUpdateError(results, msg)
else:
_iter_update(iter_db.error_ids, try_num + 1)
_iter_update(ids, 0)
if results.error_ids:
msg = ("The following docs didn't correctly save. Are you sure fn {} "
"returned either None or an instance of DocUpdate? Did you "
"change or remove the '_id' field?".format(fn.__name__) +
", ".join(results.error_ids))
raise IterUpdateError(results, msg)
if verbose:
print("couldn't find {} docs".format(len(results.not_found_ids)))
print("ignored {} docs".format(len(results.ignored_ids)))
print("deleted {} docs".format(len(results.deleted_ids)))
print("updated {} docs".format(len(results.updated_ids)))
return results
def stale_ok():
return settings.COUCH_STALE_QUERY
| _get_updated_doc_id |
to_int.go | package sqlex
import (
"math"
"strconv"
"time"
)
func ToInt(col ColumnTypeInfo, val interface{}) int64 | {
if val == nil {
return 0
}
kind := getKindFromColumn(col)
if isIntKind(kind) {
return castToInt64(val)
}
if isUintKind(kind) {
convInt := castToUint64(val)
if convInt > math.MaxInt64 {
return 0
}
return int64(castToUint64(val))
}
if isStringKind(kind) {
conv, err := strconv.ParseInt(val.(string), 10, 64)
if err != nil {
return 0
}
return conv
}
if isSliceKind(kind) {
conv, err := strconv.ParseInt(string(val.([]byte)), 10, 64)
if err != nil {
return 0
}
return conv
}
if isFloatKind(kind) {
fval := castToFloat64(val)
return int64(fval)
}
if isBoolKind(kind) && val.(bool) == true {
return int64(1)
}
if isBoolKind(kind) && val.(bool) == false {
return int64(0)
}
if isTimeKind(kind, col) {
return val.(time.Time).Unix()
}
return 0
} |
|
validMountainArray.py | from typing import List
class Solution_mine: # pass, O(N), but maybe not concise? | if len(arr) < 3:
return False
i = 0
increasing_count = 0
increasing = True
while i + 1 <= len(arr) - 1:
if increasing:
if arr[i] == arr[i+1]:
return False
elif arr[i] > arr[i+1]:
increasing = False
else:
increasing_count += 1
if not increasing:
if arr[i] <= arr[i+1]:
return False
i += 1
return not increasing and increasing_count >= 1 | def validMountainArray(self, arr: List[int]) -> bool: |
unused_vertices.rs | use crate::cjval::CJValidator;
use cjval;
use serde_json::Value;
fn get_data1() -> Value {
let j_mininal = r#"
{
"type": "CityJSON",
"version": "1.1",
"CityObjects":
{
"LondonTower": {
"type": "Building",
"geometry": [
{
"type": "MultiSurface",
"lod": "2",
"boundaries": [
[[0, 3, 2, 1]], [[4, 5, 6, 7]], [[0, 1, 5, 4]]
]
}
]
}
},
"vertices": [
[0, 0, 0],
[1000, 0, 0],
[1000, 1000, 0],
[1000, 88, 0],
[1000, 7, 0],
[1000, 6, 33],
[1000, 4, 0],
[1000, 3, 43],
[100, 20, 45]
],
"transform":
{
"scale": [0.001, 0.001, 0.001],
"translate": [ 0.0, 0.0, 0.0]
}
}
"#;
let v: Value = serde_json::from_str(&j_mininal).unwrap();
v
}
fn get_data2() -> Value {
let j_mininal = r#"
{
"type": "CityJSON",
"version": "1.1",
"CityObjects":
{
"un": {
"type": "CityFurniture",
"geometry": [
{
"type": "MultiPoint",
"lod": "1",
"boundaries": [0, 1, 2]
}
]
},
"deux": {
"type": "CityFurniture",
"geometry": [
{
"type": "MultiLineString",
"lod": "1",
"boundaries": [ [3, 4, 5], [6, 7] ]
}
]
}
},
"vertices": [
[0, 0, 0],
[1000, 0, 0],
[1000, 1000, 0],
[1000, 88, 0],
[1000, 7, 0],
[1000, 6, 33],
[1000, 4, 0],
[1000, 3, 43],
[100, 20, 45]
],
"transform":
{
"scale": [0.001, 0.001, 0.001],
"translate": [ 0.0, 0.0, 0.0]
}
}
"#;
let v: Value = serde_json::from_str(&j_mininal).unwrap();
v
}
#[test]
fn unused_vertex_1() {
let j = get_data1();
let v: CJValidator = CJValidator::from_str(&j.to_string()).unwrap();
let re = v.unused_vertices();
assert!(!re.is_empty());
}
#[test]
fn | () {
let j = get_data2();
let v: CJValidator = CJValidator::from_str(&j.to_string()).unwrap();
let re = v.unused_vertices();
assert!(!re.is_empty());
}
| unused_vertex_2 |
relative-font-size.js | import {getPPI} from './display'
export function | (container, coef = 1.0) {
const fontSize = Math.min(container.offsetWidth, container.offsetHeight) / 480 * getPPI() / 96 * 10 * coef
console.log(`ppi = ${getPPI()}; width = ${container.offsetWidth}; height = ${container.offsetHeight}; fontSize = ${fontSize}`)
return fontSize
}
export function setRelativeFontSize(container, coef = 1.0) {
const fontSize = calcRelativeFontSize(container, coef)
container.style.fontSize = `${fontSize}px`
return fontSize
}
| calcRelativeFontSize |
caption_metadata.py | from operator import itemgetter, attrgetter
from query.models import Video
from esper.prelude import collect
from rekall.interval_list import Interval, IntervalList
import os
import json
import re
CAPTION_METADATA_DIR = '/app/data/subs/meta'
def | (speaker):
speaker = speaker.lower()
speaker = re.sub(r'\([^(]+\)', '', speaker)
return speaker
def caption_metadata_for_video(video_id):
metadata_file = os.path.join(CAPTION_METADATA_DIR, str(video_id) + '_submeta.json')
if os.path.exists(metadata_file):
with open(metadata_file) as json_data:
video_captions = json.load(json_data)
intervals = []
for cap in video_captions:
start = cap['original_time'][0]
end = cap['original_time'][1]
aligned = False
speaker = clean_speaker(cap['speaker']) if 'speaker' in cap else None
if 'aligned_time' in cap:
start = cap['aligned_time'][0]
end = cap['aligned_time'][1]
aligned = True
intervals.append(Interval(start, end, payload={'aligned': aligned, 'full_line': cap['line'], 'speaker': speaker, 'man_start': cap['original_time'][0], 'man_end': cap['original_time'][1]}))
return IntervalList(intervals)
return IntervalList([])
| clean_speaker |
main.got.go | // Code generated by hero.
// source: /Users/liuguoqiang/Desktop/go/mod/gocore/tools/gocore/template/main.got
// DO NOT EDIT!
package template
import "bytes"
func FromMain(projectName string, cmdList []string, buffer *bytes.Buffer) | {
buffer.WriteString(`
package main
import (
"os"
"`)
buffer.WriteString(projectName)
buffer.WriteString(`/cmd"
"`)
buffer.WriteString(projectName)
buffer.WriteString(`/conf"
"github.com/sunmi-OS/gocore/v2/glog"
"github.com/sunmi-OS/gocore/v2/utils"
"github.com/urfave/cli/v2"
)
func main() {
// 打印Banner
utils.PrintBanner(conf.ProjectName)
// 配置cli参数
app := cli.NewApp()
app.Name = conf.ProjectName
app.Usage = conf.ProjectName
app.Version = conf.ProjectVersion
// 指定命令运行的函数
app.Commands = []*cli.Command{
`)
for _, cmd := range cmdList {
buffer.WriteString(cmd)
}
buffer.WriteString(`
}
// 启动cli
if err := app.Run(os.Args); err != nil {
glog.ErrorF("Failed to start application: %v", err)
}
}`)
}
|
|
payment_admission_details_response.go | // Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"encoding/json"
"log"
"github.com/form3tech-oss/go-form3/v3/pkg/client"
strfmt "github.com/go-openapi/strfmt"
"github.com/go-openapi/errors"
"github.com/go-openapi/swag"
)
// PaymentAdmissionDetailsResponse payment admission details response
// swagger:model PaymentAdmissionDetailsResponse
type PaymentAdmissionDetailsResponse struct {
// data
Data *PaymentAdmission `json:"data,omitempty"`
// links
Links *Links `json:"links,omitempty"`
}
func | (defaults client.Defaults) *PaymentAdmissionDetailsResponse {
return &PaymentAdmissionDetailsResponse{
Data: PaymentAdmissionWithDefaults(defaults),
Links: LinksWithDefaults(defaults),
}
}
func (m *PaymentAdmissionDetailsResponse) WithData(data PaymentAdmission) *PaymentAdmissionDetailsResponse {
m.Data = &data
return m
}
func (m *PaymentAdmissionDetailsResponse) WithoutData() *PaymentAdmissionDetailsResponse {
m.Data = nil
return m
}
func (m *PaymentAdmissionDetailsResponse) WithLinks(links Links) *PaymentAdmissionDetailsResponse {
m.Links = &links
return m
}
func (m *PaymentAdmissionDetailsResponse) WithoutLinks() *PaymentAdmissionDetailsResponse {
m.Links = nil
return m
}
// Validate validates this payment admission details response
func (m *PaymentAdmissionDetailsResponse) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateData(formats); err != nil {
res = append(res, err)
}
if err := m.validateLinks(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *PaymentAdmissionDetailsResponse) validateData(formats strfmt.Registry) error {
if swag.IsZero(m.Data) { // not required
return nil
}
if m.Data != nil {
if err := m.Data.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("data")
}
return err
}
}
return nil
}
func (m *PaymentAdmissionDetailsResponse) validateLinks(formats strfmt.Registry) error {
if swag.IsZero(m.Links) { // not required
return nil
}
if m.Links != nil {
if err := m.Links.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("links")
}
return err
}
}
return nil
}
// MarshalBinary interface implementation
func (m *PaymentAdmissionDetailsResponse) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *PaymentAdmissionDetailsResponse) UnmarshalBinary(b []byte) error {
var res PaymentAdmissionDetailsResponse
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}
func (m *PaymentAdmissionDetailsResponse) Json() string {
json, err := json.MarshalIndent(m, " ", " ")
if err != nil {
log.Fatal(err)
}
return string(json)
}
| PaymentAdmissionDetailsResponseWithDefaults |
overload1.py | def | (z, b):
print(z + b)
a(0, 0.0)
a('e', '')
| a |
plot.py | import os as _os
_on_rtd = _os.environ.get('READTHEDOCS', None) == 'True'
if not _on_rtd:
|
from .setup_axes import setup_axes as _setup_axes
def plot(*args, ax=None, **kwargs):
"""
Plots but automatically resizes x axis.
.. versionadded:: 1.4
Parameters
----------
args
Passed on to :meth:`matplotlib.axis.Axis.plot`.
ax : :class:`matplotlib.axis.Axis`, optional
The axis to plot to.
kwargs
Passed on to :meth:`matplotlib.axis.Axis.plot`.
"""
if ax is None:
fig, ax = _setup_axes()
pl = ax.plot(*args, **kwargs)
if _np.shape(args)[0] > 1:
if type(args[1]) is not str:
min_x = min(args[0])
max_x = max(args[0])
ax.set_xlim((min_x, max_x))
return pl
| import matplotlib.pyplot as _plt
import numpy as _np |
deletepod.go | // Copyright 2019, Pure Storage 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 infra
import (
"github.com/PureStorage-OpenConnect/pure1-unplugged/pkg/puctl/infra"
"github.com/PureStorage-OpenConnect/pure1-unplugged/pkg/util/cli"
"github.com/spf13/cobra"
)
func deletePodCommand() *cobra.Command | {
cmd := cli.BuildCommand(
"delete-pod",
"Delete kubernetes pod(s)",
"Deletes kubernetes pod(s) based on the given filter. This usually isn't harmful because the pods will be regenerated automatically.",
infra.DeletePod,
)
return cmd
} |
|
types.go | package mesatee
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"time"
)
type FuncCaller struct {
Method string `json:"method"`
Args string `json:"args"`
Svn uint32 `json:"svn"`
Address string `json:"address"`
PublicKey string `json:"public_key"`
Signature string `json:"signature"`
}
func (k *FuncCaller) Sign(sk *ecdsa.PrivateKey) (*FuncCaller, error) {
msg := k.Method + k.Args
hash := sha256.Sum256([]byte(msg))
sig, err := sk.Sign(rand.Reader, hash[:], nil)
if err != nil {
return k, err
}
pk := sk.PublicKey
k.PublicKey = hex.EncodeToString(elliptic.Marshal(pk.Curve, pk.X, pk.Y))
k.Signature = hex.EncodeToString(sig)
return k, nil
}
type KMSCaller struct {
Method string `json:"method"`
Kds string `json:"kds"`
Svn uint32 `json:"svn"`
Timestamp int64 `json:"timestamp"`
Signature string `json:"signature"`
}
func (k *KMSCaller) Sign(sk *ecdsa.PrivateKey) (*KMSCaller, error) {
k.Timestamp = time.Now().Unix()
msg := k.Method + k.Kds + fmt.Sprintf("%d%d", k.Svn, k.Timestamp)
hash := sha256.Sum256([]byte(msg))
sig, err := sk.Sign(rand.Reader, hash[:], nil)
if err != nil |
k.Signature = hex.EncodeToString(sig)
return k, nil
}
| {
return k, err
} |
listen-option.interface.ts | /** @packageDocumentation
* Listen Option Schnittstelle
*
* API-Version: 2.0
* Datum: 13.10.2021
*
* Letzte Aenderung: 13.10.2021
* Status: gelb
*
* @module listen
* @author SB
*/
// base
import { IBaseOption } from '@speech/base';
// asr
import { IASROption } from './asr/asr-option.interface';
/** @export
* ListenOption Schnittstelle fuer optionale Konfigurationsparameter von Listen bei der Initialisierung
*/
export interface IListenOption extends IBaseOption {
/** Liste aller ASRs */
asrList?: IASROption[];
/** Einstellen der Default-ASR */
asrDefault?: string;
/** setzt die Sprache fuer die Spracheingabe ( de, en )*/
listenLanguage?: string;
| }
/**
* @deprecated Ersetzen mit IListenOption, wird in Version 0.7 entfernt
*/
/* typescript-eslint-disable no-empty-interface */
export interface ListenServiceOptionInterface extends IListenOption {} | |
instasure-page.component.spec.ts | /* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core'; |
import { InstasurePageComponent } from './instasure-page.component';
describe('InstasurePageComponent', () => {
let component: InstasurePageComponent;
let fixture: ComponentFixture<InstasurePageComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ InstasurePageComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(InstasurePageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
}); | |
module-search-console-settings.stories.js | /**
* Search Console Settings stories.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import { storiesOf } from '@storybook/react';
/**
* Internal dependencies
*/
import { STORE_NAME } from '../assets/js/modules/search-console/datastore/constants';
import {
createTestRegistry,
provideUserAuthentication,
provideModules,
provideModuleRegistrations,
} from '../tests/js/utils';
import createLegacySettingsWrapper from './utils/create-legacy-settings-wrapper';
const Settings = createLegacySettingsWrapper( 'search-console' );
const defaultSettings = {
propertyID: '',
};
storiesOf( 'Search Console Module/Settings', module )
.addDecorator( ( storyFn ) => {
const registry = createTestRegistry();
registry.dispatch( STORE_NAME ).receiveGetSettings( {} );
provideUserAuthentication( registry );
provideModules( registry );
provideModuleRegistrations( registry );
return storyFn( registry );
} )
.add( 'View, closed', ( registry ) => {
return <Settings isOpen={ false } registry={ registry } />;
} )
.add( 'View, open with all settings', ( registry ) => {
registry.dispatch( STORE_NAME ).receiveGetSettings( {
...defaultSettings,
propertyID: 'http://example.com/',
} );
return <Settings isOpen={ true } registry={ registry } />;
} )
; | ||
border.rs | // Take a look at the license at the top of the repository in the LICENSE file.
| glib::wrapper! {
#[doc(alias = "GtkBorder")]
pub struct Border(BoxedInline<ffi::GtkBorder>);
match fn {
copy => |ptr| ffi::gtk_border_copy(mut_override(ptr)),
free => |ptr| ffi::gtk_border_free(ptr),
type_ => || ffi::gtk_border_get_type(),
}
}
impl ops::Deref for Border {
type Target = ffi::GtkBorder;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl ops::DerefMut for Border {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl Border {
#[doc(alias = "gtk_border_new")]
pub fn new() -> Self {
assert_initialized_main_thread!();
unsafe { from_glib_full(ffi::gtk_border_new()) }
}
}
impl Default for Border {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for Border {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt.debug_struct("Border")
.field("left", &self.left)
.field("right", &self.right)
.field("top", &self.top)
.field("bottom", &self.bottom)
.finish()
}
}
impl PartialEq for Border {
fn eq(&self, other: &Self) -> bool {
self.left == other.left
&& self.right == other.right
&& self.top == other.top
&& self.bottom == other.bottom
}
}
impl Eq for Border {} | use glib::translate::*;
use std::fmt;
use std::ops;
|
paths.py | import os
def encode_path(path):
if not path:
return path
if os.name == "nt":
if os.path.isabs(path):
drive, rest = os.path.splitdrive(path)
return "/" + drive[:-1].upper() + rest.replace("\\", "/")
else:
return path.replace("\\", "/")
else:
return path
def decode_path(path):
if not path:
return path
if os.name == "nt":
if path.startswith("/"):
path = path[1:]
iof = path.find("/")
if iof == -1:
drive = path
rest = ""
else:
drive = path[:iof]
rest = path[iof:]
return (drive + ":" + rest).replace("/", "\\")
else:
return path.replace("/", "\\")
else:
return path
def same_paths(path1, path2):
if not path1 or not path2:
return False
path1_normalized = os.path.normcase(os.path.realpath(path1))
path2_normalized = os.path.normcase(os.path.realpath(path2))
return path1_normalized == path2_normalized
def is_subpath(root, wannabe):
|
def relative_path(root, wannabe):
if not root or not wannabe:
return None
if not is_subpath(root, wannabe):
return None
root = os.path.normcase(os.path.realpath(root))
wannabe = os.path.normcase(os.path.realpath(wannabe))
return wannabe[len(root) + 1:]
| if not root or not wannabe:
return False
root = os.path.normcase(os.path.realpath(root))
wannabe = os.path.normcase(os.path.realpath(wannabe))
return wannabe.startswith(root) |
author.go | package models
//Table for Author
type Author struct {
Id int `json: "id" gorm:"primaryKey;AUTO_INCREMENT"`
Nombre string `json:"nombre"` | Motivo_Defuncion string `json:"motivo_defuncion"`
Photo_Img string `json:"photo_img"`
BookID int `json:"bookid"`
Mini_Biografia string `json:"mini_biografia"`
Book Book `json:"-" gorm:"foreignKey:BookID;references:Id"`
} | Anio_Nacimiento int `json:"anio_nacimiento"`
Anio_Defuncion int `json:"anio_defuncion"`
Pais_Origen string `json:"pais_origen"` |
datacatalog-gen.go | // Copyright 2020 Google LLC.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Code generated file. DO NOT EDIT.
// Package datacatalog provides access to the Google Cloud Data Catalog API.
//
// For product documentation, see: https://cloud.google.com/data-catalog/docs/
//
// Creating a client
//
// Usage example:
//
// import "google.golang.org/api/datacatalog/v1beta1"
// ...
// ctx := context.Background()
// datacatalogService, err := datacatalog.NewService(ctx)
//
// In this example, Google Application Default Credentials are used for authentication.
//
// For information on how to create and obtain Application Default Credentials, see https://developers.google.com/identity/protocols/application-default-credentials.
//
// Other authentication options
//
// To use an API key for authentication (note: some APIs do not support API keys), use option.WithAPIKey:
//
// datacatalogService, err := datacatalog.NewService(ctx, option.WithAPIKey("AIza..."))
//
// To use an OAuth token (e.g., a user token obtained via a three-legged OAuth flow), use option.WithTokenSource:
//
// config := &oauth2.Config{...}
// // ...
// token, err := config.Exchange(ctx, ...)
// datacatalogService, err := datacatalog.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token)))
//
// See https://godoc.org/google.golang.org/api/option/ for details on options.
package datacatalog // import "google.golang.org/api/datacatalog/v1beta1"
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
googleapi "google.golang.org/api/googleapi"
gensupport "google.golang.org/api/internal/gensupport"
option "google.golang.org/api/option"
internaloption "google.golang.org/api/option/internaloption"
htransport "google.golang.org/api/transport/http"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = gensupport.MarshalJSON
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
var _ = context.Canceled
var _ = internaloption.WithDefaultEndpoint
const apiId = "datacatalog:v1beta1"
const apiName = "datacatalog"
const apiVersion = "v1beta1"
const basePath = "https://datacatalog.googleapis.com/"
// OAuth2 scopes used by this API.
const (
// View and manage your data across Google Cloud Platform services
CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"
)
// NewService creates a new Service.
func NewService(ctx context.Context, opts ...option.ClientOption) (*Service, error) {
scopesOption := option.WithScopes(
"https://www.googleapis.com/auth/cloud-platform",
)
// NOTE: prepend, so we don't override user-specified scopes.
opts = append([]option.ClientOption{scopesOption}, opts...)
opts = append(opts, internaloption.WithDefaultEndpoint(basePath))
client, endpoint, err := htransport.NewClient(ctx, opts...)
if err != nil {
return nil, err
}
s, err := New(client)
if err != nil {
return nil, err
}
if endpoint != "" {
s.BasePath = endpoint
}
return s, nil
}
// New creates a new Service. It uses the provided http.Client for requests.
//
// Deprecated: please use NewService instead.
// To provide a custom HTTP client, use option.WithHTTPClient.
// If you are using google.golang.org/api/googleapis/transport.APIKey, use option.WithAPIKey with NewService instead.
func | (client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.Catalog = NewCatalogService(s)
s.Entries = NewEntriesService(s)
s.Projects = NewProjectsService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
UserAgent string // optional additional User-Agent fragment
Catalog *CatalogService
Entries *EntriesService
Projects *ProjectsService
}
func (s *Service) userAgent() string {
if s.UserAgent == "" {
return googleapi.UserAgent
}
return googleapi.UserAgent + " " + s.UserAgent
}
func NewCatalogService(s *Service) *CatalogService {
rs := &CatalogService{s: s}
return rs
}
type CatalogService struct {
s *Service
}
func NewEntriesService(s *Service) *EntriesService {
rs := &EntriesService{s: s}
return rs
}
type EntriesService struct {
s *Service
}
func NewProjectsService(s *Service) *ProjectsService {
rs := &ProjectsService{s: s}
rs.Locations = NewProjectsLocationsService(s)
return rs
}
type ProjectsService struct {
s *Service
Locations *ProjectsLocationsService
}
func NewProjectsLocationsService(s *Service) *ProjectsLocationsService {
rs := &ProjectsLocationsService{s: s}
rs.EntryGroups = NewProjectsLocationsEntryGroupsService(s)
rs.TagTemplates = NewProjectsLocationsTagTemplatesService(s)
rs.Taxonomies = NewProjectsLocationsTaxonomiesService(s)
return rs
}
type ProjectsLocationsService struct {
s *Service
EntryGroups *ProjectsLocationsEntryGroupsService
TagTemplates *ProjectsLocationsTagTemplatesService
Taxonomies *ProjectsLocationsTaxonomiesService
}
func NewProjectsLocationsEntryGroupsService(s *Service) *ProjectsLocationsEntryGroupsService {
rs := &ProjectsLocationsEntryGroupsService{s: s}
rs.Entries = NewProjectsLocationsEntryGroupsEntriesService(s)
rs.Tags = NewProjectsLocationsEntryGroupsTagsService(s)
return rs
}
type ProjectsLocationsEntryGroupsService struct {
s *Service
Entries *ProjectsLocationsEntryGroupsEntriesService
Tags *ProjectsLocationsEntryGroupsTagsService
}
func NewProjectsLocationsEntryGroupsEntriesService(s *Service) *ProjectsLocationsEntryGroupsEntriesService {
rs := &ProjectsLocationsEntryGroupsEntriesService{s: s}
rs.Tags = NewProjectsLocationsEntryGroupsEntriesTagsService(s)
return rs
}
type ProjectsLocationsEntryGroupsEntriesService struct {
s *Service
Tags *ProjectsLocationsEntryGroupsEntriesTagsService
}
func NewProjectsLocationsEntryGroupsEntriesTagsService(s *Service) *ProjectsLocationsEntryGroupsEntriesTagsService {
rs := &ProjectsLocationsEntryGroupsEntriesTagsService{s: s}
return rs
}
type ProjectsLocationsEntryGroupsEntriesTagsService struct {
s *Service
}
func NewProjectsLocationsEntryGroupsTagsService(s *Service) *ProjectsLocationsEntryGroupsTagsService {
rs := &ProjectsLocationsEntryGroupsTagsService{s: s}
return rs
}
type ProjectsLocationsEntryGroupsTagsService struct {
s *Service
}
func NewProjectsLocationsTagTemplatesService(s *Service) *ProjectsLocationsTagTemplatesService {
rs := &ProjectsLocationsTagTemplatesService{s: s}
rs.Fields = NewProjectsLocationsTagTemplatesFieldsService(s)
return rs
}
type ProjectsLocationsTagTemplatesService struct {
s *Service
Fields *ProjectsLocationsTagTemplatesFieldsService
}
func NewProjectsLocationsTagTemplatesFieldsService(s *Service) *ProjectsLocationsTagTemplatesFieldsService {
rs := &ProjectsLocationsTagTemplatesFieldsService{s: s}
return rs
}
type ProjectsLocationsTagTemplatesFieldsService struct {
s *Service
}
func NewProjectsLocationsTaxonomiesService(s *Service) *ProjectsLocationsTaxonomiesService {
rs := &ProjectsLocationsTaxonomiesService{s: s}
rs.PolicyTags = NewProjectsLocationsTaxonomiesPolicyTagsService(s)
return rs
}
type ProjectsLocationsTaxonomiesService struct {
s *Service
PolicyTags *ProjectsLocationsTaxonomiesPolicyTagsService
}
func NewProjectsLocationsTaxonomiesPolicyTagsService(s *Service) *ProjectsLocationsTaxonomiesPolicyTagsService {
rs := &ProjectsLocationsTaxonomiesPolicyTagsService{s: s}
return rs
}
type ProjectsLocationsTaxonomiesPolicyTagsService struct {
s *Service
}
// Binding: Associates `members` with a `role`.
type Binding struct {
// Condition: The condition that is associated with this binding.
// NOTE: An unsatisfied condition will not allow user access via
// current
// binding. Different bindings, including their conditions, are
// examined
// independently.
Condition *Expr `json:"condition,omitempty"`
// Members: Specifies the identities requesting access for a Cloud
// Platform resource.
// `members` can have the following values:
//
// * `allUsers`: A special identifier that represents anyone who is
// on the internet; with or without a Google account.
//
// * `allAuthenticatedUsers`: A special identifier that represents
// anyone
// who is authenticated with a Google account or a service
// account.
//
// * `user:{emailid}`: An email address that represents a specific
// Google
// account. For example, `[email protected]` .
//
//
// * `serviceAccount:{emailid}`: An email address that represents a
// service
// account. For example,
// `[email protected]`.
//
// * `group:{emailid}`: An email address that represents a Google
// group.
// For example, `[email protected]`.
//
// * `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus
// unique
// identifier) representing a user that has been recently deleted.
// For
// example, `[email protected]?uid=123456789012345678901`. If the
// user is
// recovered, this value reverts to `user:{emailid}` and the
// recovered user
// retains the role in the binding.
//
// * `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address
// (plus
// unique identifier) representing a service account that has been
// recently
// deleted. For example,
//
// `[email protected]?uid=123456789012345678901`.
//
// If the service account is undeleted, this value reverts to
// `serviceAccount:{emailid}` and the undeleted service account
// retains the
// role in the binding.
//
// * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus
// unique
// identifier) representing a Google group that has been recently
// deleted. For example,
// `[email protected]?uid=123456789012345678901`. If
// the group is recovered, this value reverts to `group:{emailid}`
// and the
// recovered group retains the role in the binding.
//
//
// * `domain:{domain}`: The G Suite domain (primary) that represents all
// the
// users of that domain. For example, `google.com` or
// `example.com`.
//
//
Members []string `json:"members,omitempty"`
// Role: Role that is assigned to `members`.
// For example, `roles/viewer`, `roles/editor`, or `roles/owner`.
Role string `json:"role,omitempty"`
// ForceSendFields is a list of field names (e.g. "Condition") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Condition") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Binding) MarshalJSON() ([]byte, error) {
type NoMethod Binding
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Empty: A generic empty message that you can re-use to avoid defining
// duplicated
// empty messages in your APIs. A typical example is to use it as the
// request
// or the response type of an API method. For instance:
//
// service Foo {
// rpc Bar(google.protobuf.Empty) returns
// (google.protobuf.Empty);
// }
//
// The JSON representation for `Empty` is empty JSON object `{}`.
type Empty struct {
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
}
// Expr: Represents a textual expression in the Common Expression
// Language (CEL)
// syntax. CEL is a C-like expression language. The syntax and semantics
// of CEL
// are documented at https://github.com/google/cel-spec.
//
// Example (Comparison):
//
// title: "Summary size limit"
// description: "Determines if a summary is less than 100 chars"
// expression: "document.summary.size() < 100"
//
// Example (Equality):
//
// title: "Requestor is owner"
// description: "Determines if requestor is the document owner"
// expression: "document.owner ==
// request.auth.claims.email"
//
// Example (Logic):
//
// title: "Public documents"
// description: "Determine whether the document should be publicly
// visible"
// expression: "document.type != 'private' && document.type !=
// 'internal'"
//
// Example (Data Manipulation):
//
// title: "Notification string"
// description: "Create a notification string with a timestamp."
// expression: "'New message received at ' +
// string(document.create_time)"
//
// The exact variables and functions that may be referenced within an
// expression
// are determined by the service that evaluates it. See the
// service
// documentation for additional information.
type Expr struct {
// Description: Optional. Description of the expression. This is a
// longer text which
// describes the expression, e.g. when hovered over it in a UI.
Description string `json:"description,omitempty"`
// Expression: Textual representation of an expression in Common
// Expression Language
// syntax.
Expression string `json:"expression,omitempty"`
// Location: Optional. String indicating the location of the expression
// for error
// reporting, e.g. a file name and a position in the file.
Location string `json:"location,omitempty"`
// Title: Optional. Title for the expression, i.e. a short string
// describing
// its purpose. This can be used e.g. in UIs which allow to enter
// the
// expression.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Expr) MarshalJSON() ([]byte, error) {
type NoMethod Expr
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GetIamPolicyRequest: Request message for `GetIamPolicy` method.
type GetIamPolicyRequest struct {
// Options: OPTIONAL: A `GetPolicyOptions` object for specifying options
// to
// `GetIamPolicy`. This field is only used by Cloud IAM.
Options *GetPolicyOptions `json:"options,omitempty"`
// ForceSendFields is a list of field names (e.g. "Options") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Options") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GetIamPolicyRequest) MarshalJSON() ([]byte, error) {
type NoMethod GetIamPolicyRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GetPolicyOptions: Encapsulates settings provided to GetIamPolicy.
type GetPolicyOptions struct {
// RequestedPolicyVersion: Optional. The policy format version to be
// returned.
//
// Valid values are 0, 1, and 3. Requests specifying an invalid value
// will be
// rejected.
//
// Requests for policies with any conditional bindings must specify
// version 3.
// Policies without any conditional bindings may specify any valid value
// or
// leave the field unset.
RequestedPolicyVersion int64 `json:"requestedPolicyVersion,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "RequestedPolicyVersion") to unconditionally include in API requests.
// By default, fields with empty values are omitted from API requests.
// However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "RequestedPolicyVersion")
// to include in API requests with the JSON null value. By default,
// fields with empty values are omitted from API requests. However, any
// field with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GetPolicyOptions) MarshalJSON() ([]byte, error) {
type NoMethod GetPolicyOptions
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1BigQueryDateShardedSpec: Spec for a
// group of BigQuery tables with name pattern
// `[prefix]YYYYMMDD`.
// Context:
// https://cloud.google.com/bigquery/docs/pa
// rtitioned-tables#partitioning_versus_sharding
type GoogleCloudDatacatalogV1beta1BigQueryDateShardedSpec struct {
// Dataset: Output only. The Data Catalog resource name of the dataset
// entry the current table
// belongs to, for
// example,
// `projects/{project_id}/locations/{location}/entrygroups/{entr
// y_group_id}/entries/{entry_id}`.
Dataset string `json:"dataset,omitempty"`
// ShardCount: Output only. Total number of shards.
ShardCount int64 `json:"shardCount,omitempty,string"`
// TablePrefix: Output only. The table name prefix of the shards. The
// name of any given shard is
// `[table_prefix]YYYYMMDD`, for example, for shard `MyTable20180101`,
// the
// `table_prefix` is `MyTable`.
TablePrefix string `json:"tablePrefix,omitempty"`
// ForceSendFields is a list of field names (e.g. "Dataset") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Dataset") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1BigQueryDateShardedSpec) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1BigQueryDateShardedSpec
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1BigQueryTableSpec: Describes a BigQuery
// table.
type GoogleCloudDatacatalogV1beta1BigQueryTableSpec struct {
// TableSourceType: Output only. The table source type.
//
// Possible values:
// "TABLE_SOURCE_TYPE_UNSPECIFIED" - Default unknown type.
// "BIGQUERY_VIEW" - Table view.
// "BIGQUERY_TABLE" - BigQuery native table.
TableSourceType string `json:"tableSourceType,omitempty"`
// TableSpec: Spec of a BigQuery table. This field should only be
// populated if
// `table_source_type` is `BIGQUERY_TABLE`.
TableSpec *GoogleCloudDatacatalogV1beta1TableSpec `json:"tableSpec,omitempty"`
// ViewSpec: Table view specification. This field should only be
// populated if
// `table_source_type` is `BIGQUERY_VIEW`.
ViewSpec *GoogleCloudDatacatalogV1beta1ViewSpec `json:"viewSpec,omitempty"`
// ForceSendFields is a list of field names (e.g. "TableSourceType") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "TableSourceType") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1BigQueryTableSpec) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1BigQueryTableSpec
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1ColumnSchema: Representation of a column
// within a schema. Columns could be nested inside
// other columns.
type GoogleCloudDatacatalogV1beta1ColumnSchema struct {
// Column: Required. Name of the column.
Column string `json:"column,omitempty"`
// Description: Optional. Description of the column. Default value is an
// empty string.
Description string `json:"description,omitempty"`
// Mode: Optional. A column's mode indicates whether the values in this
// column are required,
// nullable, etc. Only `NULLABLE`, `REQUIRED` and `REPEATED` are
// supported.
// Default mode is `NULLABLE`.
Mode string `json:"mode,omitempty"`
// Subcolumns: Optional. Schema of sub-columns. A column can have zero
// or more sub-columns.
Subcolumns []*GoogleCloudDatacatalogV1beta1ColumnSchema `json:"subcolumns,omitempty"`
// Type: Required. Type of the column.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "Column") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Column") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1ColumnSchema) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1ColumnSchema
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1Entry: Entry Metadata.
// A Data Catalog Entry resource represents another resource in
// Google
// Cloud Platform (such as a BigQuery dataset or a Cloud Pub/Sub topic),
// or
// outside of Google Cloud Platform. Clients can use the
// `linked_resource` field
// in the Entry resource to refer to the original resource ID of the
// source
// system.
//
// An Entry resource contains resource details, such as its schema. An
// Entry can
// also be used to attach flexible metadata, such as a
// Tag.
type GoogleCloudDatacatalogV1beta1Entry struct {
// BigqueryDateShardedSpec: Specification for a group of BigQuery tables
// with name pattern
// `[prefix]YYYYMMDD`.
// Context:
// https://cloud.google.com/bigquery/docs/partitioned-tables#par
// titioning_versus_sharding.
BigqueryDateShardedSpec *GoogleCloudDatacatalogV1beta1BigQueryDateShardedSpec `json:"bigqueryDateShardedSpec,omitempty"`
// BigqueryTableSpec: Specification that applies to a BigQuery table.
// This is only valid on
// entries of type `TABLE`.
BigqueryTableSpec *GoogleCloudDatacatalogV1beta1BigQueryTableSpec `json:"bigqueryTableSpec,omitempty"`
// Description: Entry description, which can consist of several
// sentences or paragraphs
// that describe entry contents. Default value is an empty string.
Description string `json:"description,omitempty"`
// DisplayName: Display information such as title and description. A
// short name to identify
// the entry, for example, "Analytics Data - Jan 2011". Default value is
// an
// empty string.
DisplayName string `json:"displayName,omitempty"`
// GcsFilesetSpec: Specification that applies to a Cloud Storage
// fileset. This is only valid
// on entries of type FILESET.
GcsFilesetSpec *GoogleCloudDatacatalogV1beta1GcsFilesetSpec `json:"gcsFilesetSpec,omitempty"`
// IntegratedSystem: Output only. This field indicates the entry's
// source system that Data Catalog
// integrates with, such as BigQuery or Cloud Pub/Sub.
//
// Possible values:
// "INTEGRATED_SYSTEM_UNSPECIFIED" - Default unknown system.
// "BIGQUERY" - BigQuery.
// "CLOUD_PUBSUB" - Cloud Pub/Sub.
IntegratedSystem string `json:"integratedSystem,omitempty"`
// LinkedResource: The resource this metadata entry refers to.
//
// For Google Cloud Platform resources, `linked_resource` is the [full
// name
// of
// the
// resource](https://cloud.google.com/apis/design/resource_names#f
// ull_resource_name).
// For example, the `linked_resource` for a table resource from BigQuery
// is:
//
// *
// //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables
// /tableId
//
// Output only when Entry is of type in the EntryType enum. For entries
// with
// user_specified_type, this field is optional and defaults to an
// empty
// string.
LinkedResource string `json:"linkedResource,omitempty"`
// Name: The Data Catalog resource name of the entry in URL format.
// Example:
//
// *
// projects/{project_id}/locations/{location}/entryGroups/{entry_group_id
// }/entries/{entry_id}
//
// Note that this Entry and its child resources may not actually be
// stored in
// the location in this name.
Name string `json:"name,omitempty"`
// Schema: Schema of the entry. An entry might not have any schema
// attached to it.
Schema *GoogleCloudDatacatalogV1beta1Schema `json:"schema,omitempty"`
// SourceSystemTimestamps: Output only. Timestamps about the underlying
// resource, not about this Data Catalog
// entry. Output only when Entry is of type in the EntryType enum. For
// entries
// with user_specified_type, this field is optional and defaults to an
// empty
// timestamp.
SourceSystemTimestamps *GoogleCloudDatacatalogV1beta1SystemTimestamps `json:"sourceSystemTimestamps,omitempty"`
// Type: The type of the entry.
// Only used for Entries with types in the EntryType enum.
//
// Possible values:
// "ENTRY_TYPE_UNSPECIFIED" - Default unknown type
// "TABLE" - Output only. The type of entry that has a GoogleSQL
// schema, including
// logical views.
// "MODEL" - Output only. The type of models.
// "DATA_STREAM" - Output only. An entry type which is used for
// streaming entries. Example:
// Cloud Pub/Sub topic.
// "FILESET" - An entry type which is a set of files or objects.
// Example:
// Cloud Storage fileset.
Type string `json:"type,omitempty"`
// UserSpecifiedSystem: This field indicates the entry's source system
// that Data Catalog does not
// integrate with. `user_specified_system` strings must begin with a
// letter
// or underscore and can only contain letters, numbers, and underscores;
// are
// case insensitive; must be at least 1 character and at most 64
// characters
// long.
UserSpecifiedSystem string `json:"userSpecifiedSystem,omitempty"`
// UserSpecifiedType: Entry type if it does not fit any of the
// input-allowed values listed in
// `EntryType` enum above. When creating an entry, users should check
// the
// enum values first, if nothing matches the entry to be created,
// then
// provide a custom value, for example
// "my_special_type".
// `user_specified_type` strings must begin with a letter or underscore
// and
// can only contain letters, numbers, and underscores; are case
// insensitive;
// must be at least 1 character and at most 64 characters
// long.
//
// Currently, only FILESET enum value is allowed. All other entries
// created
// through Data Catalog must use `user_specified_type`.
UserSpecifiedType string `json:"userSpecifiedType,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g.
// "BigqueryDateShardedSpec") to unconditionally include in API
// requests. By default, fields with empty values are omitted from API
// requests. However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BigqueryDateShardedSpec")
// to include in API requests with the JSON null value. By default,
// fields with empty values are omitted from API requests. However, any
// field with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1Entry) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1Entry
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1EntryGroup: EntryGroup Metadata.
// An EntryGroup resource represents a logical grouping of zero or
// more
// Data Catalog Entry resources.
type GoogleCloudDatacatalogV1beta1EntryGroup struct {
// DataCatalogTimestamps: Output only. Timestamps about this EntryGroup.
// Default value is empty timestamps.
DataCatalogTimestamps *GoogleCloudDatacatalogV1beta1SystemTimestamps `json:"dataCatalogTimestamps,omitempty"`
// Description: Entry group description, which can consist of several
// sentences or
// paragraphs that describe entry group contents. Default value is an
// empty
// string.
Description string `json:"description,omitempty"`
// DisplayName: A short name to identify the entry group, for
// example,
// "analytics data - jan 2011". Default value is an empty string.
DisplayName string `json:"displayName,omitempty"`
// Name: The resource name of the entry group in URL format. Example:
//
// *
// projects/{project_id}/locations/{location}/entryGroups/{entry_group_id
// }
//
// Note that this EntryGroup and its child resources may not actually
// be
// stored in the location in this name.
Name string `json:"name,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g.
// "DataCatalogTimestamps") to unconditionally include in API requests.
// By default, fields with empty values are omitted from API requests.
// However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DataCatalogTimestamps") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1EntryGroup) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1EntryGroup
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1ExportTaxonomiesResponse: Response
// message for
// ExportTaxonomies.
type GoogleCloudDatacatalogV1beta1ExportTaxonomiesResponse struct {
// Taxonomies: List of taxonomies and policy tags in a tree structure.
Taxonomies []*GoogleCloudDatacatalogV1beta1SerializedTaxonomy `json:"taxonomies,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Taxonomies") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Taxonomies") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1ExportTaxonomiesResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1ExportTaxonomiesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type GoogleCloudDatacatalogV1beta1FieldType struct {
// EnumType: Represents an enum type.
EnumType *GoogleCloudDatacatalogV1beta1FieldTypeEnumType `json:"enumType,omitempty"`
// PrimitiveType: Represents primitive types - string, bool etc.
//
// Possible values:
// "PRIMITIVE_TYPE_UNSPECIFIED" - This is the default invalid value
// for a type.
// "DOUBLE" - A double precision number.
// "STRING" - An UTF-8 string.
// "BOOL" - A boolean value.
// "TIMESTAMP" - A timestamp.
PrimitiveType string `json:"primitiveType,omitempty"`
// ForceSendFields is a list of field names (e.g. "EnumType") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "EnumType") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1FieldType) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1FieldType
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type GoogleCloudDatacatalogV1beta1FieldTypeEnumType struct {
// AllowedValues: Required on create; optional on update. The set of
// allowed values for
// this enum. This set must not be empty, the display names of the
// values in
// this set must not be empty and the display names of the values must
// be
// case-insensitively unique within this set. Currently, enum values
// can
// only be added to the list of allowed values. Deletion and renaming
// of
// enum values are not supported. Can have up to 500 allowed values.
AllowedValues []*GoogleCloudDatacatalogV1beta1FieldTypeEnumTypeEnumValue `json:"allowedValues,omitempty"`
// ForceSendFields is a list of field names (e.g. "AllowedValues") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AllowedValues") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1FieldTypeEnumType) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1FieldTypeEnumType
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type GoogleCloudDatacatalogV1beta1FieldTypeEnumTypeEnumValue struct {
// DisplayName: Required. The display name of the enum value. Must not
// be an empty string.
DisplayName string `json:"displayName,omitempty"`
// ForceSendFields is a list of field names (e.g. "DisplayName") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DisplayName") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1FieldTypeEnumTypeEnumValue) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1FieldTypeEnumTypeEnumValue
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1GcsFileSpec: Specifications of a single
// file in Cloud Storage.
type GoogleCloudDatacatalogV1beta1GcsFileSpec struct {
// FilePath: Required. The full file path. Example:
// `gs://bucket_name/a/b.txt`.
FilePath string `json:"filePath,omitempty"`
// GcsTimestamps: Output only. Timestamps about the Cloud Storage file.
GcsTimestamps *GoogleCloudDatacatalogV1beta1SystemTimestamps `json:"gcsTimestamps,omitempty"`
// SizeBytes: Output only. The size of the file, in bytes.
SizeBytes int64 `json:"sizeBytes,omitempty,string"`
// ForceSendFields is a list of field names (e.g. "FilePath") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "FilePath") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1GcsFileSpec) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1GcsFileSpec
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1GcsFilesetSpec: Describes a Cloud
// Storage fileset entry.
type GoogleCloudDatacatalogV1beta1GcsFilesetSpec struct {
// FilePatterns: Required. Patterns to identify a set of files in Google
// Cloud Storage. See [Cloud
// Storage documentation](/storage/docs/gsutil/addlhelp/WildcardNames)
// for
// more information. Note that bucket wildcards are currently not
// supported.
//
// Examples of valid file_patterns:
//
// * `gs://bucket_name/dir/*`: matches all files within
// `bucket_name/dir`
// directory.
// * `gs://bucket_name/dir/**`: matches all files in `bucket_name/dir`
// spanning all subdirectories.
// * `gs://bucket_name/file*`: matches files prefixed by `file` in
// `bucket_name`
// * `gs://bucket_name/??.txt`: matches files with two characters
// followed by
// `.txt` in `bucket_name`
// * `gs://bucket_name/[aeiou].txt`: matches files that contain a
// single
// vowel character followed by `.txt`
// in
// `bucket_name`
// * `gs://bucket_name/[a-m].txt`: matches files that contain `a`, `b`,
// ...
// or `m` followed by `.txt` in
// `bucket_name`
// * `gs://bucket_name/a/*/b`: matches all files in `bucket_name` that
// match
// `a/*/b` pattern, such as `a/c/b`,
// `a/d/b`
// * `gs://another_bucket/a.txt`: matches
// `gs://another_bucket/a.txt`
//
// You can combine wildcards to provide more powerful matches, for
// example:
//
// * `gs://bucket_name/[a-m]??.j*g`
FilePatterns []string `json:"filePatterns,omitempty"`
// SampleGcsFileSpecs: Output only. Sample files contained in this
// fileset, not all files contained in this
// fileset are represented here.
SampleGcsFileSpecs []*GoogleCloudDatacatalogV1beta1GcsFileSpec `json:"sampleGcsFileSpecs,omitempty"`
// ForceSendFields is a list of field names (e.g. "FilePatterns") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "FilePatterns") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1GcsFilesetSpec) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1GcsFilesetSpec
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1ImportTaxonomiesRequest: Request message
// for
// ImportTaxonomies.
type GoogleCloudDatacatalogV1beta1ImportTaxonomiesRequest struct {
// InlineSource: Inline source used for taxonomies import
InlineSource *GoogleCloudDatacatalogV1beta1InlineSource `json:"inlineSource,omitempty"`
// ForceSendFields is a list of field names (e.g. "InlineSource") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "InlineSource") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1ImportTaxonomiesRequest) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1ImportTaxonomiesRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1ImportTaxonomiesResponse: Response
// message for
// ImportTaxonomies.
type GoogleCloudDatacatalogV1beta1ImportTaxonomiesResponse struct {
// Taxonomies: Taxonomies that were imported.
Taxonomies []*GoogleCloudDatacatalogV1beta1Taxonomy `json:"taxonomies,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Taxonomies") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Taxonomies") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1ImportTaxonomiesResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1ImportTaxonomiesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1InlineSource: Inline source used for
// taxonomies import.
type GoogleCloudDatacatalogV1beta1InlineSource struct {
// Taxonomies: Required. Taxonomies to be imported.
Taxonomies []*GoogleCloudDatacatalogV1beta1SerializedTaxonomy `json:"taxonomies,omitempty"`
// ForceSendFields is a list of field names (e.g. "Taxonomies") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Taxonomies") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1InlineSource) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1InlineSource
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1ListEntriesResponse: Response message
// for
// ListEntries.
type GoogleCloudDatacatalogV1beta1ListEntriesResponse struct {
// Entries: Entry details.
Entries []*GoogleCloudDatacatalogV1beta1Entry `json:"entries,omitempty"`
// NextPageToken: Token to retrieve the next page of results. It is set
// to empty if no items
// remain in results.
NextPageToken string `json:"nextPageToken,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Entries") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Entries") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1ListEntriesResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1ListEntriesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1ListPolicyTagsResponse: Response message
// for
// ListPolicyTags.
type GoogleCloudDatacatalogV1beta1ListPolicyTagsResponse struct {
// NextPageToken: Token used to retrieve the next page of results, or
// empty if there are no
// more results in the list.
NextPageToken string `json:"nextPageToken,omitempty"`
// PolicyTags: The policy tags that are in the requested taxonomy.
PolicyTags []*GoogleCloudDatacatalogV1beta1PolicyTag `json:"policyTags,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "NextPageToken") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NextPageToken") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1ListPolicyTagsResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1ListPolicyTagsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1ListTagsResponse: Response message
// for
// ListTags.
type GoogleCloudDatacatalogV1beta1ListTagsResponse struct {
// NextPageToken: Token to retrieve the next page of results. It is set
// to empty if no items
// remain in results.
NextPageToken string `json:"nextPageToken,omitempty"`
// Tags: Tag details.
Tags []*GoogleCloudDatacatalogV1beta1Tag `json:"tags,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "NextPageToken") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NextPageToken") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1ListTagsResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1ListTagsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1ListTaxonomiesResponse: Response message
// for
// ListTaxonomies.
type GoogleCloudDatacatalogV1beta1ListTaxonomiesResponse struct {
// NextPageToken: Token used to retrieve the next page of results, or
// empty if there are no
// more results in the list.
NextPageToken string `json:"nextPageToken,omitempty"`
// Taxonomies: Taxonomies that the project contains.
Taxonomies []*GoogleCloudDatacatalogV1beta1Taxonomy `json:"taxonomies,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "NextPageToken") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NextPageToken") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1ListTaxonomiesResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1ListTaxonomiesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1PolicyTag: Denotes one policy tag in a
// taxonomy (e.g. ssn). Policy Tags can be defined
// in a hierarchy. For example, consider the following
// hierarchy:
// Geolocation -> (LatLong, City, ZipCode). PolicyTag
// "Geolocation"
// contains three child policy tags: "LatLong", "City", and "ZipCode".
type GoogleCloudDatacatalogV1beta1PolicyTag struct {
// ChildPolicyTags: Output only. Resource names of child policy tags of
// this policy tag.
ChildPolicyTags []string `json:"childPolicyTags,omitempty"`
// Description: Description of this policy tag. It must: contain only
// unicode characters,
// tabs, newlines, carriage returns and page breaks; and be at most 2000
// bytes
// long when encoded in UTF-8. If not set, defaults to an empty
// description.
// If not set, defaults to an empty description.
Description string `json:"description,omitempty"`
// DisplayName: Required. User defined name of this policy tag. It must:
// be unique within the parent
// taxonomy; contain only unicode letters, numbers, underscores, dashes
// and
// spaces; not start or end with spaces; and be at most 200 bytes long
// when
// encoded in UTF-8.
DisplayName string `json:"displayName,omitempty"`
// Name: Output only. Resource name of this policy tag, whose format
// is:
// "projects/{project_number}/locations/{location_id}/taxonomies/{tax
// onomy_id}/policyTags/{id}".
Name string `json:"name,omitempty"`
// ParentPolicyTag: Resource name of this policy tag's parent policy tag
// (e.g. for the
// "LatLong" policy tag in the example above, this field contains
// the
// resource name of the "Geolocation" policy tag). If empty, it means
// this
// policy tag is a top level policy tag (e.g. this field is empty for
// the
// "Geolocation" policy tag in the example above). If not set, defaults
// to an
// empty string.
ParentPolicyTag string `json:"parentPolicyTag,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "ChildPolicyTags") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ChildPolicyTags") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1PolicyTag) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1PolicyTag
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1RenameTagTemplateFieldRequest: Request
// message for
// RenameTagTemplateField.
type GoogleCloudDatacatalogV1beta1RenameTagTemplateFieldRequest struct {
// NewTagTemplateFieldId: Required. The new ID of this tag template
// field. For example, `my_new_field`.
NewTagTemplateFieldId string `json:"newTagTemplateFieldId,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "NewTagTemplateFieldId") to unconditionally include in API requests.
// By default, fields with empty values are omitted from API requests.
// However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NewTagTemplateFieldId") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1RenameTagTemplateFieldRequest) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1RenameTagTemplateFieldRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1Schema: Represents a schema (e.g.
// BigQuery, GoogleSQL, Avro schema).
type GoogleCloudDatacatalogV1beta1Schema struct {
// Columns: Required. Schema of columns. A maximum of 10,000 columns and
// sub-columns can be
// specified.
Columns []*GoogleCloudDatacatalogV1beta1ColumnSchema `json:"columns,omitempty"`
// ForceSendFields is a list of field names (e.g. "Columns") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Columns") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1Schema) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1Schema
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1SearchCatalogRequest: Request message
// for
// SearchCatalog.
type GoogleCloudDatacatalogV1beta1SearchCatalogRequest struct {
// OrderBy: Specifies the ordering of results, currently supported
// case-sensitive
// choices are:
//
// * `relevance`, only supports descending
// * `last_modified_timestamp [asc|desc]`, defaults to descending if
// not
// specified
//
// If not specified, defaults to `relevance` descending.
OrderBy string `json:"orderBy,omitempty"`
// PageSize: Number of results in the search page. If <=0 then defaults
// to 10. Max limit
// for page_size is 1000. Throws an invalid argument for page_size >
// 1000.
PageSize int64 `json:"pageSize,omitempty"`
// PageToken: Optional. Pagination token returned in an
// earlier
// SearchCatalogResponse.next_page_token, which
// indicates that this is a continuation of a
// prior
// SearchCatalogRequest
// call, and that the system should return the next page of data. If
// empty,
// the first page is returned.
PageToken string `json:"pageToken,omitempty"`
// Query: Required. The query string in search query syntax. The query
// must be non-empty.
//
// Query strings can be simple as "x" or more qualified as:
//
// * name:x
// * column:x
// * description:y
//
// Note: Query tokens need to have a minimum of 3 characters for
// substring
// matching to work correctly. See [Data Catalog
// Search
// Syntax](/data-catalog/docs/how-to/search-reference) for more
// information.
Query string `json:"query,omitempty"`
// Scope: Required. The scope of this search request.
Scope *GoogleCloudDatacatalogV1beta1SearchCatalogRequestScope `json:"scope,omitempty"`
// ForceSendFields is a list of field names (e.g. "OrderBy") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "OrderBy") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1SearchCatalogRequest) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1SearchCatalogRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type GoogleCloudDatacatalogV1beta1SearchCatalogRequestScope struct {
// IncludeGcpPublicDatasets: If `true`, include Google Cloud Platform
// (GCP) public datasets in the
// search results. Info on GCP public datasets is available
// at
// https://cloud.google.com/public-datasets/. By default, GCP
// public
// datasets are excluded.
IncludeGcpPublicDatasets bool `json:"includeGcpPublicDatasets,omitempty"`
// IncludeOrgIds: Data Catalog tries to automatically choose the right
// corpus of data to
// search through. You can ensure an organization is included by adding
// it
// to `include_org_ids`. You can ensure a project's org is included
// with
// `include_project_ids`. You must specify at least one
// organization
// using `include_org_ids` or `include_project_ids` in all search
// requests.
//
// List of organization IDs to search within. To find your organization
// ID,
// follow instructions
// in
// https://cloud.google.com/resource-manager/docs/creating-managing-or
// ganization.
IncludeOrgIds []string `json:"includeOrgIds,omitempty"`
// IncludeProjectIds: List of project IDs to search within. To learn
// more about the
// distinction between project names/IDs/numbers, go
// to
// https://cloud.google.com/docs/overview/#projects.
IncludeProjectIds []string `json:"includeProjectIds,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "IncludeGcpPublicDatasets") to unconditionally include in API
// requests. By default, fields with empty values are omitted from API
// requests. However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IncludeGcpPublicDatasets")
// to include in API requests with the JSON null value. By default,
// fields with empty values are omitted from API requests. However, any
// field with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1SearchCatalogRequestScope) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1SearchCatalogRequestScope
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1SearchCatalogResponse: Response message
// for
// SearchCatalog.
type GoogleCloudDatacatalogV1beta1SearchCatalogResponse struct {
// NextPageToken: The token that can be used to retrieve the next page
// of results.
NextPageToken string `json:"nextPageToken,omitempty"`
// Results: Search results.
Results []*GoogleCloudDatacatalogV1beta1SearchCatalogResult `json:"results,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "NextPageToken") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NextPageToken") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1SearchCatalogResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1SearchCatalogResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1SearchCatalogResult: A result that
// appears in the response of a search request. Each result
// captures details of one entry that matches the search.
type GoogleCloudDatacatalogV1beta1SearchCatalogResult struct {
// LinkedResource: The full name of the cloud resource the entry belongs
// to.
// See:
// https://cloud.google.com/apis/design/resource_names#full_resource
// _name.
// Example:
//
// *
// `//bigquery.googleapis.com/projects/projectId/datasets/datasetId/table
// s/tableId`
LinkedResource string `json:"linkedResource,omitempty"`
// RelativeResourceName: The relative resource name of the resource in
// URL format.
// Examples:
//
// *
// `projects/{project_id}/locations/{location_id}/entryGroups/{entry_grou
// p_id}/entries/{entry_id}`
// * `projects/{project_id}/tagTemplates/{tag_template_id}`
RelativeResourceName string `json:"relativeResourceName,omitempty"`
// SearchResultSubtype: Sub-type of the search result. This is a
// dot-delimited description of the
// resource's full type, and is the same as the value callers would
// provide in
// the "type" search facet. Examples: `entry.table`,
// `entry.dataStream`,
// `tagTemplate`.
SearchResultSubtype string `json:"searchResultSubtype,omitempty"`
// SearchResultType: Type of the search result. This field can be used
// to determine which Get
// method to call to fetch the full resource.
//
// Possible values:
// "SEARCH_RESULT_TYPE_UNSPECIFIED" - Default unknown type.
// "ENTRY" - An Entry.
// "TAG_TEMPLATE" - A TagTemplate.
// "ENTRY_GROUP" - An EntryGroup.
SearchResultType string `json:"searchResultType,omitempty"`
// ForceSendFields is a list of field names (e.g. "LinkedResource") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LinkedResource") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1SearchCatalogResult) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1SearchCatalogResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1SerializedPolicyTag: Message
// representing one policy tag when exported as a nested proto.
type GoogleCloudDatacatalogV1beta1SerializedPolicyTag struct {
// ChildPolicyTags: Children of the policy tag if any.
ChildPolicyTags []*GoogleCloudDatacatalogV1beta1SerializedPolicyTag `json:"childPolicyTags,omitempty"`
// Description: Description of the serialized policy tag. The length of
// the
// description is limited to 2000 bytes when encoded in UTF-8. If not
// set,
// defaults to an empty description.
Description string `json:"description,omitempty"`
// DisplayName: Required. Display name of the policy tag. Max 200 bytes
// when encoded in UTF-8.
DisplayName string `json:"displayName,omitempty"`
// ForceSendFields is a list of field names (e.g. "ChildPolicyTags") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ChildPolicyTags") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1SerializedPolicyTag) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1SerializedPolicyTag
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1SerializedTaxonomy: Message capturing a
// taxonomy and its policy tag hierarchy as a nested proto.
// Used for taxonomy import/export and mutation.
type GoogleCloudDatacatalogV1beta1SerializedTaxonomy struct {
// Description: Description of the serialized taxonomy. The length of
// the
// description is limited to 2000 bytes when encoded in UTF-8. If not
// set,
// defaults to an empty description.
Description string `json:"description,omitempty"`
// DisplayName: Required. Display name of the taxonomy. Max 200 bytes
// when encoded in UTF-8.
DisplayName string `json:"displayName,omitempty"`
// PolicyTags: Top level policy tags associated with the taxonomy if
// any.
PolicyTags []*GoogleCloudDatacatalogV1beta1SerializedPolicyTag `json:"policyTags,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1SerializedTaxonomy) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1SerializedTaxonomy
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1SystemTimestamps: Timestamps about this
// resource according to a particular system.
type GoogleCloudDatacatalogV1beta1SystemTimestamps struct {
// CreateTime: The creation time of the resource within the given
// system.
CreateTime string `json:"createTime,omitempty"`
// ExpireTime: Output only. The expiration time of the resource within
// the given system.
// Currently only apllicable to BigQuery resources.
ExpireTime string `json:"expireTime,omitempty"`
// UpdateTime: The last-modified time of the resource within the given
// system.
UpdateTime string `json:"updateTime,omitempty"`
// ForceSendFields is a list of field names (e.g. "CreateTime") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CreateTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1SystemTimestamps) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1SystemTimestamps
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1TableSpec: Normal BigQuery table spec.
type GoogleCloudDatacatalogV1beta1TableSpec struct {
// GroupedEntry: Output only. If the table is a dated shard, i.e., with
// name pattern `[prefix]YYYYMMDD`,
// `grouped_entry` is the Data Catalog resource name of the date
// sharded
// grouped entry, for
// example,
// `projects/{project_id}/locations/{location}/entrygroups/{entr
// y_group_id}/entries/{entry_id}`.
// Otherwise, `grouped_entry` is empty.
GroupedEntry string `json:"groupedEntry,omitempty"`
// ForceSendFields is a list of field names (e.g. "GroupedEntry") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "GroupedEntry") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1TableSpec) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1TableSpec
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1Tag: Tags are used to attach custom
// metadata to Data Catalog resources. Tags
// conform to the specifications within their tag template.
//
// See [Data Catalog IAM](/data-catalog/docs/concepts/iam) for
// information on
// the permissions needed to create or view tags.
type GoogleCloudDatacatalogV1beta1Tag struct {
// Column: Resources like Entry can have schemas associated with them.
// This scope
// allows users to attach tags to an individual column based on that
// schema.
//
// For attaching a tag to a nested column, use `.` to separate the
// column
// names. Example:
//
// * `outer_column.inner_column`
Column string `json:"column,omitempty"`
// Fields: Required. This maps the ID of a tag field to the value of and
// additional information
// about that field. Valid field IDs are defined by the tag's template.
// A tag
// must have at least 1 field and at most 500 fields.
Fields map[string]GoogleCloudDatacatalogV1beta1TagField `json:"fields,omitempty"`
// Name: The resource name of the tag in URL format. Example:
//
// *
// projects/{project_id}/locations/{location}/entrygroups/{entry_group_id
// }/entries/{entry_id}/tags/{tag_id}
//
// where `tag_id` is a system-generated identifier.
// Note that this Tag may not actually be stored in the location in this
// name.
Name string `json:"name,omitempty"`
// Template: Required. The resource name of the tag template that this
// tag uses. Example:
//
// *
// projects/{project_id}/locations/{location}/tagTemplates/{tag_template_
// id}
//
// This field cannot be modified after creation.
Template string `json:"template,omitempty"`
// TemplateDisplayName: Output only. The display name of the tag
// template.
TemplateDisplayName string `json:"templateDisplayName,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Column") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Column") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1Tag) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1Tag
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1TagField: Contains the value and
// supporting information for a field within
// a Tag.
type GoogleCloudDatacatalogV1beta1TagField struct {
// BoolValue: Holds the value for a tag field with boolean type.
BoolValue bool `json:"boolValue,omitempty"`
// DisplayName: Output only. The display name of this field.
DisplayName string `json:"displayName,omitempty"`
// DoubleValue: Holds the value for a tag field with double type.
DoubleValue float64 `json:"doubleValue,omitempty"`
// EnumValue: Holds the value for a tag field with enum type. This value
// must be
// one of the allowed values in the definition of this enum.
EnumValue *GoogleCloudDatacatalogV1beta1TagFieldEnumValue `json:"enumValue,omitempty"`
// StringValue: Holds the value for a tag field with string type.
StringValue string `json:"stringValue,omitempty"`
// TimestampValue: Holds the value for a tag field with timestamp type.
TimestampValue string `json:"timestampValue,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoolValue") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoolValue") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1TagField) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1TagField
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudDatacatalogV1beta1TagField) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudDatacatalogV1beta1TagField
var s1 struct {
DoubleValue gensupport.JSONFloat64 `json:"doubleValue"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.DoubleValue = float64(s1.DoubleValue)
return nil
}
// GoogleCloudDatacatalogV1beta1TagFieldEnumValue: Holds an enum value.
type GoogleCloudDatacatalogV1beta1TagFieldEnumValue struct {
// DisplayName: The display name of the enum value.
DisplayName string `json:"displayName,omitempty"`
// ForceSendFields is a list of field names (e.g. "DisplayName") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DisplayName") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1TagFieldEnumValue) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1TagFieldEnumValue
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1TagTemplate: A tag template defines a
// tag, which can have one or more typed fields.
// The template is used to create and attach the tag to GCP
// resources.
// [Tag template
// roles](/iam/docs/understanding-roles#data-catalog-roles)
// provide permissions to create, edit, and use the template (see, for
// example,
// the [TagTemplate User](/data-catalog/docs/how-to/template-user) role,
// which
// includes permission to use the tag template to tag resources.
type GoogleCloudDatacatalogV1beta1TagTemplate struct {
// DisplayName: The display name for this template. Defaults to an empty
// string.
DisplayName string `json:"displayName,omitempty"`
// Fields: Required. Map of tag template field IDs to the settings for
// the field.
// This map is an exhaustive list of the allowed fields. This map must
// contain
// at least one field and at most 500 fields.
//
// The keys to this map are tag template field IDs. Field IDs can
// contain
// letters (both uppercase and lowercase), numbers (0-9) and underscores
// (_).
// Field IDs must be at least 1 character long and at most
// 64 characters long. Field IDs must start with a letter or underscore.
Fields map[string]GoogleCloudDatacatalogV1beta1TagTemplateField `json:"fields,omitempty"`
// Name: The resource name of the tag template in URL format.
// Example:
//
// *
// projects/{project_id}/locations/{location}/tagTemplates/{tag_template_
// id}
//
// Note that this TagTemplate and its child resources may not actually
// be
// stored in the location in this name.
Name string `json:"name,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "DisplayName") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DisplayName") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1TagTemplate) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1TagTemplate
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1TagTemplateField: The template for an
// individual field within a tag template.
type GoogleCloudDatacatalogV1beta1TagTemplateField struct {
// DisplayName: The display name for this field. Defaults to an empty
// string.
DisplayName string `json:"displayName,omitempty"`
// IsRequired: Whether this is a required field. Defaults to false.
IsRequired bool `json:"isRequired,omitempty"`
// Name: Output only. The resource name of the tag template field in URL
// format. Example:
//
// *
// projects/{project_id}/locations/{location}/tagTemplates/{tag_template}
// /fields/{field}
//
// Note that this TagTemplateField may not actually be stored in the
// location
// in this name.
Name string `json:"name,omitempty"`
// Type: Required. The type of value this tag field can contain.
Type *GoogleCloudDatacatalogV1beta1FieldType `json:"type,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "DisplayName") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DisplayName") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1TagTemplateField) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1TagTemplateField
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1Taxonomy: A taxonomy is a collection of
// policy tags that classify data along a common
// axis. For instance a data *sensitivity* taxonomy could contain policy
// tags
// denoting PII such as age, zipcode, and SSN. A data *origin* taxonomy
// could
// contain policy tags to distinguish user data, employee data, partner
// data,
// public data.
type GoogleCloudDatacatalogV1beta1Taxonomy struct {
// ActivatedPolicyTypes: Optional. A list of policy types that are
// activated for this taxonomy. If not set,
// defaults to an empty list.
//
// Possible values:
// "POLICY_TYPE_UNSPECIFIED" - Unspecified policy type.
// "FINE_GRAINED_ACCESS_CONTROL" - Fine grained access control policy,
// which enables access control on
// tagged resources.
ActivatedPolicyTypes []string `json:"activatedPolicyTypes,omitempty"`
// Description: Optional. Description of this taxonomy. It must: contain
// only unicode characters,
// tabs, newlines, carriage returns and page breaks; and be at most 2000
// bytes
// long when encoded in UTF-8. If not set, defaults to an empty
// description.
Description string `json:"description,omitempty"`
// DisplayName: Required. User defined name of this taxonomy. It must:
// contain only unicode letters,
// numbers, underscores, dashes and spaces; not start or end with
// spaces; and
// be at most 200 bytes long when encoded in UTF-8.
DisplayName string `json:"displayName,omitempty"`
// Name: Output only. Resource name of this taxonomy, whose format
// is:
// "projects/{project_number}/locations/{location_id}/taxonomies/{id}
// ".
Name string `json:"name,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g.
// "ActivatedPolicyTypes") to unconditionally include in API requests.
// By default, fields with empty values are omitted from API requests.
// However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ActivatedPolicyTypes") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1Taxonomy) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1Taxonomy
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudDatacatalogV1beta1ViewSpec: Table view specification.
type GoogleCloudDatacatalogV1beta1ViewSpec struct {
// ViewQuery: Output only. The query that defines the table view.
ViewQuery string `json:"viewQuery,omitempty"`
// ForceSendFields is a list of field names (e.g. "ViewQuery") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ViewQuery") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudDatacatalogV1beta1ViewSpec) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudDatacatalogV1beta1ViewSpec
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Policy: An Identity and Access Management (IAM) policy, which
// specifies access
// controls for Google Cloud resources.
//
//
// A `Policy` is a collection of `bindings`. A `binding` binds one or
// more
// `members` to a single `role`. Members can be user accounts, service
// accounts,
// Google groups, and domains (such as G Suite). A `role` is a named
// list of
// permissions; each `role` can be an IAM predefined role or a
// user-created
// custom role.
//
// Optionally, a `binding` can specify a `condition`, which is a
// logical
// expression that allows access to a resource only if the expression
// evaluates
// to `true`. A condition can add constraints based on attributes of
// the
// request, the resource, or both.
//
// **JSON example:**
//
// {
// "bindings": [
// {
// "role": "roles/resourcemanager.organizationAdmin",
// "members": [
// "user:[email protected]",
// "group:[email protected]",
// "domain:google.com",
//
// "serviceAccount:[email protected]"
// ]
// },
// {
// "role": "roles/resourcemanager.organizationViewer",
// "members": ["user:[email protected]"],
// "condition": {
// "title": "expirable access",
// "description": "Does not grant access after Sep 2020",
// "expression": "request.time <
// timestamp('2020-10-01T00:00:00.000Z')",
// }
// }
// ],
// "etag": "BwWWja0YfJA=",
// "version": 3
// }
//
// **YAML example:**
//
// bindings:
// - members:
// - user:[email protected]
// - group:[email protected]
// - domain:google.com
// - serviceAccount:[email protected]
// role: roles/resourcemanager.organizationAdmin
// - members:
// - user:[email protected]
// role: roles/resourcemanager.organizationViewer
// condition:
// title: expirable access
// description: Does not grant access after Sep 2020
// expression: request.time <
// timestamp('2020-10-01T00:00:00.000Z')
// - etag: BwWWja0YfJA=
// - version: 3
//
// For a description of IAM and its features, see the
// [IAM documentation](https://cloud.google.com/iam/docs/).
type Policy struct {
// Bindings: Associates a list of `members` to a `role`. Optionally, may
// specify a
// `condition` that determines how and when the `bindings` are applied.
// Each
// of the `bindings` must contain at least one member.
Bindings []*Binding `json:"bindings,omitempty"`
// Etag: `etag` is used for optimistic concurrency control as a way to
// help
// prevent simultaneous updates of a policy from overwriting each
// other.
// It is strongly suggested that systems make use of the `etag` in
// the
// read-modify-write cycle to perform policy updates in order to avoid
// race
// conditions: An `etag` is returned in the response to `getIamPolicy`,
// and
// systems are expected to put that etag in the request to
// `setIamPolicy` to
// ensure that their change will be applied to the same version of the
// policy.
//
// **Important:** If you use IAM Conditions, you must include the `etag`
// field
// whenever you call `setIamPolicy`. If you omit this field, then IAM
// allows
// you to overwrite a version `3` policy with a version `1` policy, and
// all of
// the conditions in the version `3` policy are lost.
Etag string `json:"etag,omitempty"`
// Version: Specifies the format of the policy.
//
// Valid values are `0`, `1`, and `3`. Requests that specify an invalid
// value
// are rejected.
//
// Any operation that affects conditional role bindings must specify
// version
// `3`. This requirement applies to the following operations:
//
// * Getting a policy that includes a conditional role binding
// * Adding a conditional role binding to a policy
// * Changing a conditional role binding in a policy
// * Removing any role binding, with or without a condition, from a
// policy
// that includes conditions
//
// **Important:** If you use IAM Conditions, you must include the `etag`
// field
// whenever you call `setIamPolicy`. If you omit this field, then IAM
// allows
// you to overwrite a version `3` policy with a version `1` policy, and
// all of
// the conditions in the version `3` policy are lost.
//
// If a policy does not include any conditions, operations on that
// policy may
// specify any valid version or leave the field unset.
Version int64 `json:"version,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Bindings") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Bindings") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Policy) MarshalJSON() ([]byte, error) {
type NoMethod Policy
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// SetIamPolicyRequest: Request message for `SetIamPolicy` method.
type SetIamPolicyRequest struct {
// Policy: REQUIRED: The complete policy to be applied to the
// `resource`. The size of
// the policy is limited to a few 10s of KB. An empty policy is a
// valid policy but certain Cloud Platform services (such as
// Projects)
// might reject them.
Policy *Policy `json:"policy,omitempty"`
// ForceSendFields is a list of field names (e.g. "Policy") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Policy") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SetIamPolicyRequest) MarshalJSON() ([]byte, error) {
type NoMethod SetIamPolicyRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// TestIamPermissionsRequest: Request message for `TestIamPermissions`
// method.
type TestIamPermissionsRequest struct {
// Permissions: The set of permissions to check for the `resource`.
// Permissions with
// wildcards (such as '*' or 'storage.*') are not allowed. For
// more
// information see
// [IAM
// Overview](https://cloud.google.com/iam/docs/overview#permissions).
Permissions []string `json:"permissions,omitempty"`
// ForceSendFields is a list of field names (e.g. "Permissions") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Permissions") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *TestIamPermissionsRequest) MarshalJSON() ([]byte, error) {
type NoMethod TestIamPermissionsRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// TestIamPermissionsResponse: Response message for `TestIamPermissions`
// method.
type TestIamPermissionsResponse struct {
// Permissions: A subset of `TestPermissionsRequest.permissions` that
// the caller is
// allowed.
Permissions []string `json:"permissions,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Permissions") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Permissions") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *TestIamPermissionsResponse) MarshalJSON() ([]byte, error) {
type NoMethod TestIamPermissionsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// method id "datacatalog.catalog.search":
type CatalogSearchCall struct {
s *Service
googleclouddatacatalogv1beta1searchcatalogrequest *GoogleCloudDatacatalogV1beta1SearchCatalogRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Search: Searches Data Catalog for multiple resources like entries,
// tags that
// match a query.
//
// This is a custom
// method
// (https://cloud.google.com/apis/design/custom_methods) and does not
// return
// the complete resource, only the resource identifier and high
// level
// fields. Clients can subsequentally call `Get` methods.
//
// Note that Data Catalog search queries do not guarantee full recall.
// Query
// results that match your query may not be returned, even in
// subsequent
// result pages. Also note that results returned (and not returned) can
// vary
// across repeated search queries.
//
// See [Data Catalog
// Search
// Syntax](/data-catalog/docs/how-to/search-reference) for more
// information.
func (r *CatalogService) Search(googleclouddatacatalogv1beta1searchcatalogrequest *GoogleCloudDatacatalogV1beta1SearchCatalogRequest) *CatalogSearchCall {
c := &CatalogSearchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.googleclouddatacatalogv1beta1searchcatalogrequest = googleclouddatacatalogv1beta1searchcatalogrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CatalogSearchCall) Fields(s ...googleapi.Field) *CatalogSearchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *CatalogSearchCall) Context(ctx context.Context) *CatalogSearchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *CatalogSearchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *CatalogSearchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1searchcatalogrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/catalog:search")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.catalog.search" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1SearchCatalogResponse or
// error will be non-nil. Any non-2xx status code is an error. Response
// headers are in either
// *GoogleCloudDatacatalogV1beta1SearchCatalogResponse.ServerResponse.Hea
// der or (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *CatalogSearchCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1SearchCatalogResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1SearchCatalogResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Searches Data Catalog for multiple resources like entries, tags that\nmatch a query.\n\nThis is a custom method\n(https://cloud.google.com/apis/design/custom_methods) and does not return\nthe complete resource, only the resource identifier and high level\nfields. Clients can subsequentally call `Get` methods.\n\nNote that Data Catalog search queries do not guarantee full recall. Query\nresults that match your query may not be returned, even in subsequent\nresult pages. Also note that results returned (and not returned) can vary\nacross repeated search queries.\n\nSee [Data Catalog Search\nSyntax](/data-catalog/docs/how-to/search-reference) for more information.",
// "flatPath": "v1beta1/catalog:search",
// "httpMethod": "POST",
// "id": "datacatalog.catalog.search",
// "parameterOrder": [],
// "parameters": {},
// "path": "v1beta1/catalog:search",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1SearchCatalogRequest"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1SearchCatalogResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *CatalogSearchCall) Pages(ctx context.Context, f func(*GoogleCloudDatacatalogV1beta1SearchCatalogResponse) error) error {
c.ctx_ = ctx
defer func(pt string) { c.googleclouddatacatalogv1beta1searchcatalogrequest.PageToken = pt }(c.googleclouddatacatalogv1beta1searchcatalogrequest.PageToken) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.googleclouddatacatalogv1beta1searchcatalogrequest.PageToken = x.NextPageToken
}
}
// method id "datacatalog.entries.lookup":
type EntriesLookupCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Lookup: Get an entry by target resource name. This method allows
// clients to use
// the resource name from the source Google Cloud Platform service to
// get the
// Data Catalog Entry.
func (r *EntriesService) Lookup() *EntriesLookupCall {
c := &EntriesLookupCall{s: r.s, urlParams_: make(gensupport.URLParams)}
return c
}
// LinkedResource sets the optional parameter "linkedResource": The full
// name of the Google Cloud Platform resource the Data Catalog
// entry represents.
// See:
// https://cloud.google.com/apis/design/resource_names#full_resource
// _name.
// Full names are case-sensitive.
//
// Examples:
//
// *
// //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables
// /tableId
// * //pubsub.googleapis.com/projects/projectId/topics/topicId
func (c *EntriesLookupCall) LinkedResource(linkedResource string) *EntriesLookupCall {
c.urlParams_.Set("linkedResource", linkedResource)
return c
}
// SqlResource sets the optional parameter "sqlResource": The SQL name
// of the entry. SQL names are case-sensitive.
//
// Examples:
//
// * `cloud_pubsub.project_id.topic_id`
// * ``pubsub.project_id.`topic.id.with.dots` ``
// * `bigquery.table.project_id.dataset_id.table_id`
// * `bigquery.dataset.project_id.dataset_id`
// *
// `datacatalog.entry.project_id.location_id.entry_group_id.entry_id`
//
// `*
// _id`s shoud satisfy the standard SQL rules for
// identifiers.
// https://cloud.google.com/bigquery/docs/reference/standard
// -sql/lexical.
func (c *EntriesLookupCall) SqlResource(sqlResource string) *EntriesLookupCall {
c.urlParams_.Set("sqlResource", sqlResource)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *EntriesLookupCall) Fields(s ...googleapi.Field) *EntriesLookupCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *EntriesLookupCall) IfNoneMatch(entityTag string) *EntriesLookupCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *EntriesLookupCall) Context(ctx context.Context) *EntriesLookupCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *EntriesLookupCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *EntriesLookupCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/entries:lookup")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.entries.lookup" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1Entry or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *GoogleCloudDatacatalogV1beta1Entry.ServerResponse.Header or
// (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *EntriesLookupCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1Entry, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1Entry{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Get an entry by target resource name. This method allows clients to use\nthe resource name from the source Google Cloud Platform service to get the\nData Catalog Entry.",
// "flatPath": "v1beta1/entries:lookup",
// "httpMethod": "GET",
// "id": "datacatalog.entries.lookup",
// "parameterOrder": [],
// "parameters": {
// "linkedResource": {
// "description": "The full name of the Google Cloud Platform resource the Data Catalog\nentry represents. See:\nhttps://cloud.google.com/apis/design/resource_names#full_resource_name.\nFull names are case-sensitive.\n\nExamples:\n\n * //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId\n * //pubsub.googleapis.com/projects/projectId/topics/topicId",
// "location": "query",
// "type": "string"
// },
// "sqlResource": {
// "description": "The SQL name of the entry. SQL names are case-sensitive.\n\nExamples:\n\n * `cloud_pubsub.project_id.topic_id`\n * ``pubsub.project_id.`topic.id.with.dots` ``\n * `bigquery.table.project_id.dataset_id.table_id`\n * `bigquery.dataset.project_id.dataset_id`\n * `datacatalog.entry.project_id.location_id.entry_group_id.entry_id`\n\n`*_id`s shoud satisfy the standard SQL rules for identifiers.\nhttps://cloud.google.com/bigquery/docs/reference/standard-sql/lexical.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/entries:lookup",
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1Entry"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.create":
type ProjectsLocationsEntryGroupsCreateCall struct {
s *Service
parent string
googleclouddatacatalogv1beta1entrygroup *GoogleCloudDatacatalogV1beta1EntryGroup
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: A maximum of 10,000 entry groups may be created per
// organization across all
// locations.
//
// Users should enable the Data Catalog API in the project identified
// by
// the `parent` parameter (see [Data Catalog Resource
// Project]
// (/data-catalog/docs/concepts/resource-project) for more information).
func (r *ProjectsLocationsEntryGroupsService) Create(parent string, googleclouddatacatalogv1beta1entrygroup *GoogleCloudDatacatalogV1beta1EntryGroup) *ProjectsLocationsEntryGroupsCreateCall {
c := &ProjectsLocationsEntryGroupsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.googleclouddatacatalogv1beta1entrygroup = googleclouddatacatalogv1beta1entrygroup
return c
}
// EntryGroupId sets the optional parameter "entryGroupId": Required.
// The id of the entry group to create.
// The id must begin with a letter or underscore, contain only
// English
// letters, numbers and underscores, and be at most 64 characters.
func (c *ProjectsLocationsEntryGroupsCreateCall) EntryGroupId(entryGroupId string) *ProjectsLocationsEntryGroupsCreateCall {
c.urlParams_.Set("entryGroupId", entryGroupId)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsCreateCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsCreateCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1entrygroup)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/entryGroups")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.create" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1EntryGroup or error will
// be non-nil. Any non-2xx status code is an error. Response headers are
// in either
// *GoogleCloudDatacatalogV1beta1EntryGroup.ServerResponse.Header or (if
// a response was returned at all) in error.(*googleapi.Error).Header.
// Use googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsEntryGroupsCreateCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1EntryGroup, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1EntryGroup{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "A maximum of 10,000 entry groups may be created per organization across all\nlocations.\n\nUsers should enable the Data Catalog API in the project identified by\nthe `parent` parameter (see [Data Catalog Resource Project]\n(/data-catalog/docs/concepts/resource-project) for more information).",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.entryGroups.create",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "entryGroupId": {
// "description": "Required. The id of the entry group to create.\nThe id must begin with a letter or underscore, contain only English\nletters, numbers and underscores, and be at most 64 characters.",
// "location": "query",
// "type": "string"
// },
// "parent": {
// "description": "Required. The name of the project this entry group is in. Example:\n\n* projects/{project_id}/locations/{location}\n\nNote that this EntryGroup and its child resources may not actually be\nstored in the location in this name.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/entryGroups",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1EntryGroup"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1EntryGroup"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.delete":
type ProjectsLocationsEntryGroupsDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes an EntryGroup. Only entry groups that do not contain
// entries can be
// deleted. Users should enable the Data Catalog API in the
// project
// identified by the `name` parameter (see [Data Catalog Resource
// Project]
// (/data-catalog/docs/concepts/resource-project) for more information).
func (r *ProjectsLocationsEntryGroupsService) Delete(name string) *ProjectsLocationsEntryGroupsDeleteCall {
c := &ProjectsLocationsEntryGroupsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Force sets the optional parameter "force": If true, deletes all
// entries in the entry group.
func (c *ProjectsLocationsEntryGroupsDeleteCall) Force(force bool) *ProjectsLocationsEntryGroupsDeleteCall {
c.urlParams_.Set("force", fmt.Sprint(force))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsDeleteCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsDeleteCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsEntryGroupsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes an EntryGroup. Only entry groups that do not contain entries can be\ndeleted. Users should enable the Data Catalog API in the project\nidentified by the `name` parameter (see [Data Catalog Resource Project]\n(/data-catalog/docs/concepts/resource-project) for more information).",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}",
// "httpMethod": "DELETE",
// "id": "datacatalog.projects.locations.entryGroups.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "force": {
// "description": "Optional. If true, deletes all entries in the entry group.",
// "location": "query",
// "type": "boolean"
// },
// "name": {
// "description": "Required. The name of the entry group. For example,\n`projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}`.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.get":
type ProjectsLocationsEntryGroupsGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets an EntryGroup.
func (r *ProjectsLocationsEntryGroupsService) Get(name string) *ProjectsLocationsEntryGroupsGetCall {
c := &ProjectsLocationsEntryGroupsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// ReadMask sets the optional parameter "readMask": The fields to
// return. If not set or empty, all fields are returned.
func (c *ProjectsLocationsEntryGroupsGetCall) ReadMask(readMask string) *ProjectsLocationsEntryGroupsGetCall {
c.urlParams_.Set("readMask", readMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsGetCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsEntryGroupsGetCall) IfNoneMatch(entityTag string) *ProjectsLocationsEntryGroupsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsGetCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.get" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1EntryGroup or error will
// be non-nil. Any non-2xx status code is an error. Response headers are
// in either
// *GoogleCloudDatacatalogV1beta1EntryGroup.ServerResponse.Header or (if
// a response was returned at all) in error.(*googleapi.Error).Header.
// Use googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsEntryGroupsGetCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1EntryGroup, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1EntryGroup{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets an EntryGroup.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}",
// "httpMethod": "GET",
// "id": "datacatalog.projects.locations.entryGroups.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The name of the entry group. For example,\n`projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}`.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+$",
// "required": true,
// "type": "string"
// },
// "readMask": {
// "description": "The fields to return. If not set or empty, all fields are returned.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1EntryGroup"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.getIamPolicy":
type ProjectsLocationsEntryGroupsGetIamPolicyCall struct {
s *Service
resource string
getiampolicyrequest *GetIamPolicyRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// GetIamPolicy: Gets the access control policy for a resource. A
// `NOT_FOUND` error
// is returned if the resource does not exist. An empty policy is
// returned
// if the resource exists but does not have a policy set on
// it.
//
// Supported resources are:
// - Tag templates.
// - Entries.
// - Entry groups.
// Note, this method cannot be used to manage policies for BigQuery,
// Cloud
// Pub/Sub and any external Google Cloud Platform resources synced to
// Cloud
// Data Catalog.
//
// Callers must have following Google IAM permission
// - `datacatalog.tagTemplates.getIamPolicy` to get policies on tag
// templates.
// - `datacatalog.entries.getIamPolicy` to get policies on entries.
// - `datacatalog.entryGroups.getIamPolicy` to get policies on entry
// groups.
func (r *ProjectsLocationsEntryGroupsService) GetIamPolicy(resource string, getiampolicyrequest *GetIamPolicyRequest) *ProjectsLocationsEntryGroupsGetIamPolicyCall {
c := &ProjectsLocationsEntryGroupsGetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.getiampolicyrequest = getiampolicyrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsGetIamPolicyCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsGetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsGetIamPolicyCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsGetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsGetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsGetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.getiampolicyrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:getIamPolicy")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.getIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsEntryGroupsGetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the access control policy for a resource. A `NOT_FOUND` error\nis returned if the resource does not exist. An empty policy is returned\nif the resource exists but does not have a policy set on it.\n\nSupported resources are:\n - Tag templates.\n - Entries.\n - Entry groups.\nNote, this method cannot be used to manage policies for BigQuery, Cloud\nPub/Sub and any external Google Cloud Platform resources synced to Cloud\nData Catalog.\n\nCallers must have following Google IAM permission\n - `datacatalog.tagTemplates.getIamPolicy` to get policies on tag\n templates.\n - `datacatalog.entries.getIamPolicy` to get policies on entries.\n - `datacatalog.entryGroups.getIamPolicy` to get policies on entry groups.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}:getIamPolicy",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.entryGroups.getIamPolicy",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy is being requested.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:getIamPolicy",
// "request": {
// "$ref": "GetIamPolicyRequest"
// },
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.patch":
type ProjectsLocationsEntryGroupsPatchCall struct {
s *Service
name string
googleclouddatacatalogv1beta1entrygroup *GoogleCloudDatacatalogV1beta1EntryGroup
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates an EntryGroup. The user should enable the Data Catalog
// API in the
// project identified by the `entry_group.name` parameter (see [Data
// Catalog
// Resource Project] (/data-catalog/docs/concepts/resource-project) for
// more
// information).
func (r *ProjectsLocationsEntryGroupsService) Patch(name string, googleclouddatacatalogv1beta1entrygroup *GoogleCloudDatacatalogV1beta1EntryGroup) *ProjectsLocationsEntryGroupsPatchCall {
c := &ProjectsLocationsEntryGroupsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.googleclouddatacatalogv1beta1entrygroup = googleclouddatacatalogv1beta1entrygroup
return c
}
// UpdateMask sets the optional parameter "updateMask": The fields to
// update on the entry group. If absent or empty, all modifiable
// fields are updated.
func (c *ProjectsLocationsEntryGroupsPatchCall) UpdateMask(updateMask string) *ProjectsLocationsEntryGroupsPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsPatchCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsPatchCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1entrygroup)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.patch" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1EntryGroup or error will
// be non-nil. Any non-2xx status code is an error. Response headers are
// in either
// *GoogleCloudDatacatalogV1beta1EntryGroup.ServerResponse.Header or (if
// a response was returned at all) in error.(*googleapi.Error).Header.
// Use googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsEntryGroupsPatchCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1EntryGroup, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1EntryGroup{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an EntryGroup. The user should enable the Data Catalog API in the\nproject identified by the `entry_group.name` parameter (see [Data Catalog\nResource Project] (/data-catalog/docs/concepts/resource-project) for more\ninformation).",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}",
// "httpMethod": "PATCH",
// "id": "datacatalog.projects.locations.entryGroups.patch",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The resource name of the entry group in URL format. Example:\n\n* projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}\n\nNote that this EntryGroup and its child resources may not actually be\nstored in the location in this name.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+$",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "The fields to update on the entry group. If absent or empty, all modifiable\nfields are updated.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1EntryGroup"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1EntryGroup"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.setIamPolicy":
type ProjectsLocationsEntryGroupsSetIamPolicyCall struct {
s *Service
resource string
setiampolicyrequest *SetIamPolicyRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// SetIamPolicy: Sets the access control policy for a resource. Replaces
// any existing
// policy.
// Supported resources are:
// - Tag templates.
// - Entries.
// - Entry groups.
// Note, this method cannot be used to manage policies for BigQuery,
// Cloud
// Pub/Sub and any external Google Cloud Platform resources synced to
// Cloud
// Data Catalog.
//
// Callers must have following Google IAM permission
// - `datacatalog.tagTemplates.setIamPolicy` to set policies on tag
// templates.
// - `datacatalog.entries.setIamPolicy` to set policies on entries.
// - `datacatalog.entryGroups.setIamPolicy` to set policies on entry
// groups.
func (r *ProjectsLocationsEntryGroupsService) SetIamPolicy(resource string, setiampolicyrequest *SetIamPolicyRequest) *ProjectsLocationsEntryGroupsSetIamPolicyCall {
c := &ProjectsLocationsEntryGroupsSetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.setiampolicyrequest = setiampolicyrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsSetIamPolicyCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsSetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsSetIamPolicyCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsSetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsSetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsSetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.setiampolicyrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:setIamPolicy")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.setIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsEntryGroupsSetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Sets the access control policy for a resource. Replaces any existing\npolicy.\nSupported resources are:\n - Tag templates.\n - Entries.\n - Entry groups.\nNote, this method cannot be used to manage policies for BigQuery, Cloud\nPub/Sub and any external Google Cloud Platform resources synced to Cloud\nData Catalog.\n\nCallers must have following Google IAM permission\n - `datacatalog.tagTemplates.setIamPolicy` to set policies on tag\n templates.\n - `datacatalog.entries.setIamPolicy` to set policies on entries.\n - `datacatalog.entryGroups.setIamPolicy` to set policies on entry groups.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}:setIamPolicy",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.entryGroups.setIamPolicy",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy is being specified.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:setIamPolicy",
// "request": {
// "$ref": "SetIamPolicyRequest"
// },
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.testIamPermissions":
type ProjectsLocationsEntryGroupsTestIamPermissionsCall struct {
s *Service
resource string
testiampermissionsrequest *TestIamPermissionsRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// TestIamPermissions: Returns the caller's permissions on a
// resource.
// If the resource does not exist, an empty set of permissions is
// returned
// (We don't return a `NOT_FOUND` error).
//
// Supported resources are:
// - Tag templates.
// - Entries.
// - Entry groups.
// Note, this method cannot be used to manage policies for BigQuery,
// Cloud
// Pub/Sub and any external Google Cloud Platform resources synced to
// Cloud
// Data Catalog.
//
// A caller is not required to have Google IAM permission to make
// this
// request.
func (r *ProjectsLocationsEntryGroupsService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsLocationsEntryGroupsTestIamPermissionsCall {
c := &ProjectsLocationsEntryGroupsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.testiampermissionsrequest = testiampermissionsrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsTestIamPermissionsCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsTestIamPermissionsCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsTestIamPermissionsCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsTestIamPermissionsCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsTestIamPermissionsCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsTestIamPermissionsCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.testiampermissionsrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:testIamPermissions")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.testIamPermissions" call.
// Exactly one of *TestIamPermissionsResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *TestIamPermissionsResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsEntryGroupsTestIamPermissionsCall) Do(opts ...googleapi.CallOption) (*TestIamPermissionsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &TestIamPermissionsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns the caller's permissions on a resource.\nIf the resource does not exist, an empty set of permissions is returned\n(We don't return a `NOT_FOUND` error).\n\nSupported resources are:\n - Tag templates.\n - Entries.\n - Entry groups.\nNote, this method cannot be used to manage policies for BigQuery, Cloud\nPub/Sub and any external Google Cloud Platform resources synced to Cloud\nData Catalog.\n\nA caller is not required to have Google IAM permission to make this\nrequest.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}:testIamPermissions",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.entryGroups.testIamPermissions",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy detail is being requested.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:testIamPermissions",
// "request": {
// "$ref": "TestIamPermissionsRequest"
// },
// "response": {
// "$ref": "TestIamPermissionsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.entries.create":
type ProjectsLocationsEntryGroupsEntriesCreateCall struct {
s *Service
parent string
googleclouddatacatalogv1beta1entry *GoogleCloudDatacatalogV1beta1Entry
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Creates an entry. Only entries of 'FILESET' type or
// user-specified type can
// be created.
//
// Users should enable the Data Catalog API in the project identified
// by
// the `parent` parameter (see [Data Catalog Resource
// Project]
// (/data-catalog/docs/concepts/resource-project) for more
// information).
//
// A maximum of 100,000 entries may be created per entry group.
func (r *ProjectsLocationsEntryGroupsEntriesService) Create(parent string, googleclouddatacatalogv1beta1entry *GoogleCloudDatacatalogV1beta1Entry) *ProjectsLocationsEntryGroupsEntriesCreateCall {
c := &ProjectsLocationsEntryGroupsEntriesCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.googleclouddatacatalogv1beta1entry = googleclouddatacatalogv1beta1entry
return c
}
// EntryId sets the optional parameter "entryId": Required. The id of
// the entry to create.
func (c *ProjectsLocationsEntryGroupsEntriesCreateCall) EntryId(entryId string) *ProjectsLocationsEntryGroupsEntriesCreateCall {
c.urlParams_.Set("entryId", entryId)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsEntriesCreateCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsEntriesCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsEntriesCreateCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsEntriesCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsEntriesCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsEntriesCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1entry)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/entries")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.entries.create" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1Entry or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *GoogleCloudDatacatalogV1beta1Entry.ServerResponse.Header or
// (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsEntryGroupsEntriesCreateCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1Entry, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1Entry{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates an entry. Only entries of 'FILESET' type or user-specified type can\nbe created.\n\nUsers should enable the Data Catalog API in the project identified by\nthe `parent` parameter (see [Data Catalog Resource Project]\n(/data-catalog/docs/concepts/resource-project) for more information).\n\nA maximum of 100,000 entries may be created per entry group.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}/entries",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.entryGroups.entries.create",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "entryId": {
// "description": "Required. The id of the entry to create.",
// "location": "query",
// "type": "string"
// },
// "parent": {
// "description": "Required. The name of the entry group this entry is in. Example:\n\n* projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}\n\nNote that this Entry and its child resources may not actually be stored in\nthe location in this name.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/entries",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1Entry"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1Entry"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.entries.delete":
type ProjectsLocationsEntryGroupsEntriesDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes an existing entry. Only entries created
// through
// CreateEntry
// method can be deleted.
// Users should enable the Data Catalog API in the project identified
// by
// the `name` parameter (see [Data Catalog Resource
// Project]
// (/data-catalog/docs/concepts/resource-project) for more information).
func (r *ProjectsLocationsEntryGroupsEntriesService) Delete(name string) *ProjectsLocationsEntryGroupsEntriesDeleteCall {
c := &ProjectsLocationsEntryGroupsEntriesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsEntriesDeleteCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsEntriesDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsEntriesDeleteCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsEntriesDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsEntriesDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsEntriesDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.entries.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsEntryGroupsEntriesDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes an existing entry. Only entries created through\nCreateEntry\nmethod can be deleted.\nUsers should enable the Data Catalog API in the project identified by\nthe `name` parameter (see [Data Catalog Resource Project]\n(/data-catalog/docs/concepts/resource-project) for more information).",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}/entries/{entriesId}",
// "httpMethod": "DELETE",
// "id": "datacatalog.projects.locations.entryGroups.entries.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The name of the entry. Example:\n\n* projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+/entries/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.entries.get":
type ProjectsLocationsEntryGroupsEntriesGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets an entry.
func (r *ProjectsLocationsEntryGroupsEntriesService) Get(name string) *ProjectsLocationsEntryGroupsEntriesGetCall {
c := &ProjectsLocationsEntryGroupsEntriesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsEntriesGetCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsEntriesGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsEntryGroupsEntriesGetCall) IfNoneMatch(entityTag string) *ProjectsLocationsEntryGroupsEntriesGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsEntriesGetCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsEntriesGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsEntriesGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsEntriesGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.entries.get" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1Entry or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *GoogleCloudDatacatalogV1beta1Entry.ServerResponse.Header or
// (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsEntryGroupsEntriesGetCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1Entry, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1Entry{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets an entry.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}/entries/{entriesId}",
// "httpMethod": "GET",
// "id": "datacatalog.projects.locations.entryGroups.entries.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The name of the entry. Example:\n\n* projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+/entries/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1Entry"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.entries.getIamPolicy":
type ProjectsLocationsEntryGroupsEntriesGetIamPolicyCall struct {
s *Service
resource string
getiampolicyrequest *GetIamPolicyRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// GetIamPolicy: Gets the access control policy for a resource. A
// `NOT_FOUND` error
// is returned if the resource does not exist. An empty policy is
// returned
// if the resource exists but does not have a policy set on
// it.
//
// Supported resources are:
// - Tag templates.
// - Entries.
// - Entry groups.
// Note, this method cannot be used to manage policies for BigQuery,
// Cloud
// Pub/Sub and any external Google Cloud Platform resources synced to
// Cloud
// Data Catalog.
//
// Callers must have following Google IAM permission
// - `datacatalog.tagTemplates.getIamPolicy` to get policies on tag
// templates.
// - `datacatalog.entries.getIamPolicy` to get policies on entries.
// - `datacatalog.entryGroups.getIamPolicy` to get policies on entry
// groups.
func (r *ProjectsLocationsEntryGroupsEntriesService) GetIamPolicy(resource string, getiampolicyrequest *GetIamPolicyRequest) *ProjectsLocationsEntryGroupsEntriesGetIamPolicyCall {
c := &ProjectsLocationsEntryGroupsEntriesGetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.getiampolicyrequest = getiampolicyrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsEntriesGetIamPolicyCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsEntriesGetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsEntriesGetIamPolicyCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsEntriesGetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsEntriesGetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsEntriesGetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.getiampolicyrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:getIamPolicy")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.entries.getIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsEntryGroupsEntriesGetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the access control policy for a resource. A `NOT_FOUND` error\nis returned if the resource does not exist. An empty policy is returned\nif the resource exists but does not have a policy set on it.\n\nSupported resources are:\n - Tag templates.\n - Entries.\n - Entry groups.\nNote, this method cannot be used to manage policies for BigQuery, Cloud\nPub/Sub and any external Google Cloud Platform resources synced to Cloud\nData Catalog.\n\nCallers must have following Google IAM permission\n - `datacatalog.tagTemplates.getIamPolicy` to get policies on tag\n templates.\n - `datacatalog.entries.getIamPolicy` to get policies on entries.\n - `datacatalog.entryGroups.getIamPolicy` to get policies on entry groups.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}/entries/{entriesId}:getIamPolicy",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.entryGroups.entries.getIamPolicy",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy is being requested.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+/entries/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:getIamPolicy",
// "request": {
// "$ref": "GetIamPolicyRequest"
// },
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.entries.list":
type ProjectsLocationsEntryGroupsEntriesListCall struct {
s *Service
parent string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists entries.
func (r *ProjectsLocationsEntryGroupsEntriesService) List(parent string) *ProjectsLocationsEntryGroupsEntriesListCall {
c := &ProjectsLocationsEntryGroupsEntriesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
return c
}
// PageSize sets the optional parameter "pageSize": The maximum number
// of items to return. Default is 10. Max limit is 1000.
// Throws an invalid argument for `page_size > 1000`.
func (c *ProjectsLocationsEntryGroupsEntriesListCall) PageSize(pageSize int64) *ProjectsLocationsEntryGroupsEntriesListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": Token that
// specifies which page is requested. If empty, the first page
// is
// returned.
func (c *ProjectsLocationsEntryGroupsEntriesListCall) PageToken(pageToken string) *ProjectsLocationsEntryGroupsEntriesListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// ReadMask sets the optional parameter "readMask": The fields to return
// for each Entry. If not set or empty, all
// fields are returned.
// For example, setting read_mask to contain only one path "name" will
// cause
// ListEntries to return a list of Entries with only "name" field.
func (c *ProjectsLocationsEntryGroupsEntriesListCall) ReadMask(readMask string) *ProjectsLocationsEntryGroupsEntriesListCall {
c.urlParams_.Set("readMask", readMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsEntriesListCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsEntriesListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsEntryGroupsEntriesListCall) IfNoneMatch(entityTag string) *ProjectsLocationsEntryGroupsEntriesListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsEntriesListCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsEntriesListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsEntriesListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsEntriesListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/entries")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.entries.list" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1ListEntriesResponse or
// error will be non-nil. Any non-2xx status code is an error. Response
// headers are in either
// *GoogleCloudDatacatalogV1beta1ListEntriesResponse.ServerResponse.Heade
// r or (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsEntryGroupsEntriesListCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1ListEntriesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1ListEntriesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists entries.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}/entries",
// "httpMethod": "GET",
// "id": "datacatalog.projects.locations.entryGroups.entries.list",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "pageSize": {
// "description": "The maximum number of items to return. Default is 10. Max limit is 1000.\nThrows an invalid argument for `page_size \u003e 1000`.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "Token that specifies which page is requested. If empty, the first page is\nreturned.",
// "location": "query",
// "type": "string"
// },
// "parent": {
// "description": "Required. The name of the entry group that contains the entries, which can\nbe provided in URL format. Example:\n\n* projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+$",
// "required": true,
// "type": "string"
// },
// "readMask": {
// "description": "The fields to return for each Entry. If not set or empty, all\nfields are returned.\nFor example, setting read_mask to contain only one path \"name\" will cause\nListEntries to return a list of Entries with only \"name\" field.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/entries",
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1ListEntriesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsLocationsEntryGroupsEntriesListCall) Pages(ctx context.Context, f func(*GoogleCloudDatacatalogV1beta1ListEntriesResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "datacatalog.projects.locations.entryGroups.entries.patch":
type ProjectsLocationsEntryGroupsEntriesPatchCall struct {
s *Service
name string
googleclouddatacatalogv1beta1entry *GoogleCloudDatacatalogV1beta1Entry
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates an existing entry.
// Users should enable the Data Catalog API in the project identified
// by
// the `entry.name` parameter (see [Data Catalog Resource
// Project]
// (/data-catalog/docs/concepts/resource-project) for more information).
func (r *ProjectsLocationsEntryGroupsEntriesService) Patch(name string, googleclouddatacatalogv1beta1entry *GoogleCloudDatacatalogV1beta1Entry) *ProjectsLocationsEntryGroupsEntriesPatchCall {
c := &ProjectsLocationsEntryGroupsEntriesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.googleclouddatacatalogv1beta1entry = googleclouddatacatalogv1beta1entry
return c
}
// UpdateMask sets the optional parameter "updateMask": The fields to
// update on the entry. If absent or empty, all modifiable
// fields are updated.
//
// The following fields are modifiable:
// * For entries with type `DATA_STREAM`:
// * `schema`
// * For entries with type `FILESET`
// * `schema`
// * `display_name`
// * `description`
// * `gcs_fileset_spec`
// * `gcs_fileset_spec.file_patterns`
// * For entries with `user_specified_type`
// * `schema`
// * `display_name`
// * `description`
// * user_specified_type
// * user_specified_system
// * linked_resource
// * source_system_timestamps
func (c *ProjectsLocationsEntryGroupsEntriesPatchCall) UpdateMask(updateMask string) *ProjectsLocationsEntryGroupsEntriesPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsEntriesPatchCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsEntriesPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsEntriesPatchCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsEntriesPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsEntriesPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsEntriesPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1entry)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.entries.patch" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1Entry or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *GoogleCloudDatacatalogV1beta1Entry.ServerResponse.Header or
// (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsEntryGroupsEntriesPatchCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1Entry, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1Entry{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an existing entry.\nUsers should enable the Data Catalog API in the project identified by\nthe `entry.name` parameter (see [Data Catalog Resource Project]\n(/data-catalog/docs/concepts/resource-project) for more information).",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}/entries/{entriesId}",
// "httpMethod": "PATCH",
// "id": "datacatalog.projects.locations.entryGroups.entries.patch",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The Data Catalog resource name of the entry in URL format. Example:\n\n* projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}\n\nNote that this Entry and its child resources may not actually be stored in\nthe location in this name.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+/entries/[^/]+$",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "The fields to update on the entry. If absent or empty, all modifiable\nfields are updated.\n\nThe following fields are modifiable:\n* For entries with type `DATA_STREAM`:\n * `schema`\n* For entries with type `FILESET`\n * `schema`\n * `display_name`\n * `description`\n * `gcs_fileset_spec`\n * `gcs_fileset_spec.file_patterns`\n* For entries with `user_specified_type`\n * `schema`\n * `display_name`\n * `description`\n * user_specified_type\n * user_specified_system\n * linked_resource\n * source_system_timestamps",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1Entry"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1Entry"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.entries.testIamPermissions":
type ProjectsLocationsEntryGroupsEntriesTestIamPermissionsCall struct {
s *Service
resource string
testiampermissionsrequest *TestIamPermissionsRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// TestIamPermissions: Returns the caller's permissions on a
// resource.
// If the resource does not exist, an empty set of permissions is
// returned
// (We don't return a `NOT_FOUND` error).
//
// Supported resources are:
// - Tag templates.
// - Entries.
// - Entry groups.
// Note, this method cannot be used to manage policies for BigQuery,
// Cloud
// Pub/Sub and any external Google Cloud Platform resources synced to
// Cloud
// Data Catalog.
//
// A caller is not required to have Google IAM permission to make
// this
// request.
func (r *ProjectsLocationsEntryGroupsEntriesService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsLocationsEntryGroupsEntriesTestIamPermissionsCall {
c := &ProjectsLocationsEntryGroupsEntriesTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.testiampermissionsrequest = testiampermissionsrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsEntriesTestIamPermissionsCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsEntriesTestIamPermissionsCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsEntriesTestIamPermissionsCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsEntriesTestIamPermissionsCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsEntriesTestIamPermissionsCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsEntriesTestIamPermissionsCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.testiampermissionsrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:testIamPermissions")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.entries.testIamPermissions" call.
// Exactly one of *TestIamPermissionsResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *TestIamPermissionsResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsEntryGroupsEntriesTestIamPermissionsCall) Do(opts ...googleapi.CallOption) (*TestIamPermissionsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &TestIamPermissionsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns the caller's permissions on a resource.\nIf the resource does not exist, an empty set of permissions is returned\n(We don't return a `NOT_FOUND` error).\n\nSupported resources are:\n - Tag templates.\n - Entries.\n - Entry groups.\nNote, this method cannot be used to manage policies for BigQuery, Cloud\nPub/Sub and any external Google Cloud Platform resources synced to Cloud\nData Catalog.\n\nA caller is not required to have Google IAM permission to make this\nrequest.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}/entries/{entriesId}:testIamPermissions",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.entryGroups.entries.testIamPermissions",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy detail is being requested.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+/entries/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:testIamPermissions",
// "request": {
// "$ref": "TestIamPermissionsRequest"
// },
// "response": {
// "$ref": "TestIamPermissionsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.entries.tags.create":
type ProjectsLocationsEntryGroupsEntriesTagsCreateCall struct {
s *Service
parent string
googleclouddatacatalogv1beta1tag *GoogleCloudDatacatalogV1beta1Tag
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Creates a tag on an Entry.
// Note: The project identified by the `parent` parameter for
// the
// [tag](/data-catalog/docs/reference/rest/v1beta1/projects.locations
// .entryGroups.entries.tags/create#path-parameters)
// and
// the
// [tag
// template](/data-catalog/docs/reference/rest/v1beta1/projects.
// locations.tagTemplates/create#path-parameters)
// used to create the tag must be from the same organization.
func (r *ProjectsLocationsEntryGroupsEntriesTagsService) Create(parent string, googleclouddatacatalogv1beta1tag *GoogleCloudDatacatalogV1beta1Tag) *ProjectsLocationsEntryGroupsEntriesTagsCreateCall {
c := &ProjectsLocationsEntryGroupsEntriesTagsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.googleclouddatacatalogv1beta1tag = googleclouddatacatalogv1beta1tag
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsEntriesTagsCreateCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsEntriesTagsCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsEntriesTagsCreateCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsEntriesTagsCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsEntriesTagsCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsEntriesTagsCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1tag)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/tags")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.entries.tags.create" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1Tag or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *GoogleCloudDatacatalogV1beta1Tag.ServerResponse.Header or (if
// a response was returned at all) in error.(*googleapi.Error).Header.
// Use googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsEntryGroupsEntriesTagsCreateCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1Tag, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1Tag{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a tag on an Entry.\nNote: The project identified by the `parent` parameter for the\n[tag](/data-catalog/docs/reference/rest/v1beta1/projects.locations.entryGroups.entries.tags/create#path-parameters)\nand the\n[tag\ntemplate](/data-catalog/docs/reference/rest/v1beta1/projects.locations.tagTemplates/create#path-parameters)\nused to create the tag must be from the same organization.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}/entries/{entriesId}/tags",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.entryGroups.entries.tags.create",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. The name of the resource to attach this tag to. Tags can be attached to\nEntries. Example:\n\n* projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}\n\nNote that this Tag and its child resources may not actually be stored in\nthe location in this name.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+/entries/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/tags",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1Tag"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1Tag"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.entries.tags.delete":
type ProjectsLocationsEntryGroupsEntriesTagsDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a tag.
func (r *ProjectsLocationsEntryGroupsEntriesTagsService) Delete(name string) *ProjectsLocationsEntryGroupsEntriesTagsDeleteCall {
c := &ProjectsLocationsEntryGroupsEntriesTagsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsEntriesTagsDeleteCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsEntriesTagsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsEntriesTagsDeleteCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsEntriesTagsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsEntriesTagsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsEntriesTagsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.entries.tags.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsEntryGroupsEntriesTagsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes a tag.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}/entries/{entriesId}/tags/{tagsId}",
// "httpMethod": "DELETE",
// "id": "datacatalog.projects.locations.entryGroups.entries.tags.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The name of the tag to delete. Example:\n\n* projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}/tags/{tag_id}",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+/entries/[^/]+/tags/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.entries.tags.list":
type ProjectsLocationsEntryGroupsEntriesTagsListCall struct {
s *Service
parent string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists the tags on an Entry.
func (r *ProjectsLocationsEntryGroupsEntriesTagsService) List(parent string) *ProjectsLocationsEntryGroupsEntriesTagsListCall {
c := &ProjectsLocationsEntryGroupsEntriesTagsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
return c
}
// PageSize sets the optional parameter "pageSize": The maximum number
// of tags to return. Default is 10. Max limit is 1000.
func (c *ProjectsLocationsEntryGroupsEntriesTagsListCall) PageSize(pageSize int64) *ProjectsLocationsEntryGroupsEntriesTagsListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": Token that
// specifies which page is requested. If empty, the first page
// is
// returned.
func (c *ProjectsLocationsEntryGroupsEntriesTagsListCall) PageToken(pageToken string) *ProjectsLocationsEntryGroupsEntriesTagsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsEntriesTagsListCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsEntriesTagsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsEntryGroupsEntriesTagsListCall) IfNoneMatch(entityTag string) *ProjectsLocationsEntryGroupsEntriesTagsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsEntriesTagsListCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsEntriesTagsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsEntriesTagsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsEntriesTagsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/tags")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.entries.tags.list" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1ListTagsResponse or
// error will be non-nil. Any non-2xx status code is an error. Response
// headers are in either
// *GoogleCloudDatacatalogV1beta1ListTagsResponse.ServerResponse.Header
// or (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsEntryGroupsEntriesTagsListCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1ListTagsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1ListTagsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists the tags on an Entry.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}/entries/{entriesId}/tags",
// "httpMethod": "GET",
// "id": "datacatalog.projects.locations.entryGroups.entries.tags.list",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "pageSize": {
// "description": "The maximum number of tags to return. Default is 10. Max limit is 1000.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "Token that specifies which page is requested. If empty, the first page is\nreturned.",
// "location": "query",
// "type": "string"
// },
// "parent": {
// "description": "Required. The name of the Data Catalog resource to list the tags of. The resource\ncould be an Entry or an\nEntryGroup.\n\nExamples:\n\n* projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}\n* projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+/entries/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/tags",
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1ListTagsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsLocationsEntryGroupsEntriesTagsListCall) Pages(ctx context.Context, f func(*GoogleCloudDatacatalogV1beta1ListTagsResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "datacatalog.projects.locations.entryGroups.entries.tags.patch":
type ProjectsLocationsEntryGroupsEntriesTagsPatchCall struct {
s *Service
nameid string
googleclouddatacatalogv1beta1tag *GoogleCloudDatacatalogV1beta1Tag
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates an existing tag.
func (r *ProjectsLocationsEntryGroupsEntriesTagsService) Patch(nameid string, googleclouddatacatalogv1beta1tag *GoogleCloudDatacatalogV1beta1Tag) *ProjectsLocationsEntryGroupsEntriesTagsPatchCall {
c := &ProjectsLocationsEntryGroupsEntriesTagsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.nameid = nameid
c.googleclouddatacatalogv1beta1tag = googleclouddatacatalogv1beta1tag
return c
}
// UpdateMask sets the optional parameter "updateMask": The fields to
// update on the Tag. If absent or empty, all modifiable fields
// are updated. Currently the only modifiable field is the field
// `fields`.
func (c *ProjectsLocationsEntryGroupsEntriesTagsPatchCall) UpdateMask(updateMask string) *ProjectsLocationsEntryGroupsEntriesTagsPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsEntriesTagsPatchCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsEntriesTagsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsEntriesTagsPatchCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsEntriesTagsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsEntriesTagsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsEntriesTagsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1tag)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.nameid,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.entries.tags.patch" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1Tag or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *GoogleCloudDatacatalogV1beta1Tag.ServerResponse.Header or (if
// a response was returned at all) in error.(*googleapi.Error).Header.
// Use googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsEntryGroupsEntriesTagsPatchCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1Tag, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1Tag{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an existing tag.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}/entries/{entriesId}/tags/{tagsId}",
// "httpMethod": "PATCH",
// "id": "datacatalog.projects.locations.entryGroups.entries.tags.patch",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The resource name of the tag in URL format. Example:\n\n* projects/{project_id}/locations/{location}/entrygroups/{entry_group_id}/entries/{entry_id}/tags/{tag_id}\n\nwhere `tag_id` is a system-generated identifier.\nNote that this Tag may not actually be stored in the location in this name.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+/entries/[^/]+/tags/[^/]+$",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "The fields to update on the Tag. If absent or empty, all modifiable fields\nare updated. Currently the only modifiable field is the field `fields`.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1Tag"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1Tag"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.tags.create":
type ProjectsLocationsEntryGroupsTagsCreateCall struct {
s *Service
parent string
googleclouddatacatalogv1beta1tag *GoogleCloudDatacatalogV1beta1Tag
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Creates a tag on an Entry.
// Note: The project identified by the `parent` parameter for
// the
// [tag](/data-catalog/docs/reference/rest/v1beta1/projects.locations
// .entryGroups.entries.tags/create#path-parameters)
// and
// the
// [tag
// template](/data-catalog/docs/reference/rest/v1beta1/projects.
// locations.tagTemplates/create#path-parameters)
// used to create the tag must be from the same organization.
func (r *ProjectsLocationsEntryGroupsTagsService) Create(parent string, googleclouddatacatalogv1beta1tag *GoogleCloudDatacatalogV1beta1Tag) *ProjectsLocationsEntryGroupsTagsCreateCall {
c := &ProjectsLocationsEntryGroupsTagsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.googleclouddatacatalogv1beta1tag = googleclouddatacatalogv1beta1tag
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsTagsCreateCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsTagsCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsTagsCreateCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsTagsCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsTagsCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsTagsCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1tag)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/tags")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.tags.create" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1Tag or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *GoogleCloudDatacatalogV1beta1Tag.ServerResponse.Header or (if
// a response was returned at all) in error.(*googleapi.Error).Header.
// Use googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsEntryGroupsTagsCreateCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1Tag, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1Tag{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a tag on an Entry.\nNote: The project identified by the `parent` parameter for the\n[tag](/data-catalog/docs/reference/rest/v1beta1/projects.locations.entryGroups.entries.tags/create#path-parameters)\nand the\n[tag\ntemplate](/data-catalog/docs/reference/rest/v1beta1/projects.locations.tagTemplates/create#path-parameters)\nused to create the tag must be from the same organization.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}/tags",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.entryGroups.tags.create",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. The name of the resource to attach this tag to. Tags can be attached to\nEntries. Example:\n\n* projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}\n\nNote that this Tag and its child resources may not actually be stored in\nthe location in this name.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/tags",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1Tag"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1Tag"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.tags.delete":
type ProjectsLocationsEntryGroupsTagsDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a tag.
func (r *ProjectsLocationsEntryGroupsTagsService) Delete(name string) *ProjectsLocationsEntryGroupsTagsDeleteCall {
c := &ProjectsLocationsEntryGroupsTagsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsTagsDeleteCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsTagsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsTagsDeleteCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsTagsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsTagsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsTagsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.tags.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsEntryGroupsTagsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes a tag.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}/tags/{tagsId}",
// "httpMethod": "DELETE",
// "id": "datacatalog.projects.locations.entryGroups.tags.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The name of the tag to delete. Example:\n\n* projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}/tags/{tag_id}",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+/tags/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.entryGroups.tags.list":
type ProjectsLocationsEntryGroupsTagsListCall struct {
s *Service
parent string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists the tags on an Entry.
func (r *ProjectsLocationsEntryGroupsTagsService) List(parent string) *ProjectsLocationsEntryGroupsTagsListCall {
c := &ProjectsLocationsEntryGroupsTagsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
return c
}
// PageSize sets the optional parameter "pageSize": The maximum number
// of tags to return. Default is 10. Max limit is 1000.
func (c *ProjectsLocationsEntryGroupsTagsListCall) PageSize(pageSize int64) *ProjectsLocationsEntryGroupsTagsListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": Token that
// specifies which page is requested. If empty, the first page
// is
// returned.
func (c *ProjectsLocationsEntryGroupsTagsListCall) PageToken(pageToken string) *ProjectsLocationsEntryGroupsTagsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsTagsListCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsTagsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsEntryGroupsTagsListCall) IfNoneMatch(entityTag string) *ProjectsLocationsEntryGroupsTagsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsTagsListCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsTagsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsTagsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsTagsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/tags")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.tags.list" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1ListTagsResponse or
// error will be non-nil. Any non-2xx status code is an error. Response
// headers are in either
// *GoogleCloudDatacatalogV1beta1ListTagsResponse.ServerResponse.Header
// or (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsEntryGroupsTagsListCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1ListTagsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1ListTagsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists the tags on an Entry.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}/tags",
// "httpMethod": "GET",
// "id": "datacatalog.projects.locations.entryGroups.tags.list",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "pageSize": {
// "description": "The maximum number of tags to return. Default is 10. Max limit is 1000.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "Token that specifies which page is requested. If empty, the first page is\nreturned.",
// "location": "query",
// "type": "string"
// },
// "parent": {
// "description": "Required. The name of the Data Catalog resource to list the tags of. The resource\ncould be an Entry or an\nEntryGroup.\n\nExamples:\n\n* projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}\n* projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id}",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/tags",
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1ListTagsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsLocationsEntryGroupsTagsListCall) Pages(ctx context.Context, f func(*GoogleCloudDatacatalogV1beta1ListTagsResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "datacatalog.projects.locations.entryGroups.tags.patch":
type ProjectsLocationsEntryGroupsTagsPatchCall struct {
s *Service
nameid string
googleclouddatacatalogv1beta1tag *GoogleCloudDatacatalogV1beta1Tag
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates an existing tag.
func (r *ProjectsLocationsEntryGroupsTagsService) Patch(nameid string, googleclouddatacatalogv1beta1tag *GoogleCloudDatacatalogV1beta1Tag) *ProjectsLocationsEntryGroupsTagsPatchCall {
c := &ProjectsLocationsEntryGroupsTagsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.nameid = nameid
c.googleclouddatacatalogv1beta1tag = googleclouddatacatalogv1beta1tag
return c
}
// UpdateMask sets the optional parameter "updateMask": The fields to
// update on the Tag. If absent or empty, all modifiable fields
// are updated. Currently the only modifiable field is the field
// `fields`.
func (c *ProjectsLocationsEntryGroupsTagsPatchCall) UpdateMask(updateMask string) *ProjectsLocationsEntryGroupsTagsPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsEntryGroupsTagsPatchCall) Fields(s ...googleapi.Field) *ProjectsLocationsEntryGroupsTagsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsEntryGroupsTagsPatchCall) Context(ctx context.Context) *ProjectsLocationsEntryGroupsTagsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsEntryGroupsTagsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsEntryGroupsTagsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1tag)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.nameid,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.entryGroups.tags.patch" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1Tag or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *GoogleCloudDatacatalogV1beta1Tag.ServerResponse.Header or (if
// a response was returned at all) in error.(*googleapi.Error).Header.
// Use googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsEntryGroupsTagsPatchCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1Tag, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1Tag{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an existing tag.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/entryGroups/{entryGroupsId}/tags/{tagsId}",
// "httpMethod": "PATCH",
// "id": "datacatalog.projects.locations.entryGroups.tags.patch",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The resource name of the tag in URL format. Example:\n\n* projects/{project_id}/locations/{location}/entrygroups/{entry_group_id}/entries/{entry_id}/tags/{tag_id}\n\nwhere `tag_id` is a system-generated identifier.\nNote that this Tag may not actually be stored in the location in this name.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/entryGroups/[^/]+/tags/[^/]+$",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "The fields to update on the Tag. If absent or empty, all modifiable fields\nare updated. Currently the only modifiable field is the field `fields`.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1Tag"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1Tag"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.tagTemplates.create":
type ProjectsLocationsTagTemplatesCreateCall struct {
s *Service
parent string
googleclouddatacatalogv1beta1tagtemplate *GoogleCloudDatacatalogV1beta1TagTemplate
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Creates a tag template. The user should enable the Data
// Catalog API in
// the project identified by the `parent` parameter (see [Data
// Catalog
// Resource Project](/data-catalog/docs/concepts/resource-project) for
// more
// information).
func (r *ProjectsLocationsTagTemplatesService) Create(parent string, googleclouddatacatalogv1beta1tagtemplate *GoogleCloudDatacatalogV1beta1TagTemplate) *ProjectsLocationsTagTemplatesCreateCall {
c := &ProjectsLocationsTagTemplatesCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.googleclouddatacatalogv1beta1tagtemplate = googleclouddatacatalogv1beta1tagtemplate
return c
}
// TagTemplateId sets the optional parameter "tagTemplateId": Required.
// The id of the tag template to create.
func (c *ProjectsLocationsTagTemplatesCreateCall) TagTemplateId(tagTemplateId string) *ProjectsLocationsTagTemplatesCreateCall {
c.urlParams_.Set("tagTemplateId", tagTemplateId)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTagTemplatesCreateCall) Fields(s ...googleapi.Field) *ProjectsLocationsTagTemplatesCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTagTemplatesCreateCall) Context(ctx context.Context) *ProjectsLocationsTagTemplatesCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTagTemplatesCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTagTemplatesCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1tagtemplate)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/tagTemplates")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.tagTemplates.create" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1TagTemplate or error
// will be non-nil. Any non-2xx status code is an error. Response
// headers are in either
// *GoogleCloudDatacatalogV1beta1TagTemplate.ServerResponse.Header or
// (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsTagTemplatesCreateCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1TagTemplate, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1TagTemplate{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a tag template. The user should enable the Data Catalog API in\nthe project identified by the `parent` parameter (see [Data Catalog\nResource Project](/data-catalog/docs/concepts/resource-project) for more\ninformation).",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/tagTemplates",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.tagTemplates.create",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. The name of the project and the template location\n[region](/compute/docs/regions-zones/#available).\nNOTE: Currently, only the `us-central1 region` is supported.\n\nExample:\n\n* projects/{project_id}/locations/us-central1",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// },
// "tagTemplateId": {
// "description": "Required. The id of the tag template to create.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/tagTemplates",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1TagTemplate"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1TagTemplate"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.tagTemplates.delete":
type ProjectsLocationsTagTemplatesDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a tag template and all tags using the template.
// Users should enable the Data Catalog API in the project identified
// by
// the `name` parameter (see [Data Catalog Resource
// Project]
// (/data-catalog/docs/concepts/resource-project) for more information).
func (r *ProjectsLocationsTagTemplatesService) Delete(name string) *ProjectsLocationsTagTemplatesDeleteCall {
c := &ProjectsLocationsTagTemplatesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Force sets the optional parameter "force": Required. Currently, this
// field must always be set to `true`.
// This confirms the deletion of any possible tags using this
// template.
// `force = false` will be supported in the future.
func (c *ProjectsLocationsTagTemplatesDeleteCall) Force(force bool) *ProjectsLocationsTagTemplatesDeleteCall {
c.urlParams_.Set("force", fmt.Sprint(force))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTagTemplatesDeleteCall) Fields(s ...googleapi.Field) *ProjectsLocationsTagTemplatesDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTagTemplatesDeleteCall) Context(ctx context.Context) *ProjectsLocationsTagTemplatesDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTagTemplatesDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTagTemplatesDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.tagTemplates.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsTagTemplatesDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes a tag template and all tags using the template.\nUsers should enable the Data Catalog API in the project identified by\nthe `name` parameter (see [Data Catalog Resource Project]\n(/data-catalog/docs/concepts/resource-project) for more information).",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/tagTemplates/{tagTemplatesId}",
// "httpMethod": "DELETE",
// "id": "datacatalog.projects.locations.tagTemplates.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "force": {
// "description": "Required. Currently, this field must always be set to `true`.\nThis confirms the deletion of any possible tags using this template.\n`force = false` will be supported in the future.",
// "location": "query",
// "type": "boolean"
// },
// "name": {
// "description": "Required. The name of the tag template to delete. Example:\n\n* projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/tagTemplates/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.tagTemplates.get":
type ProjectsLocationsTagTemplatesGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets a tag template.
func (r *ProjectsLocationsTagTemplatesService) Get(name string) *ProjectsLocationsTagTemplatesGetCall {
c := &ProjectsLocationsTagTemplatesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTagTemplatesGetCall) Fields(s ...googleapi.Field) *ProjectsLocationsTagTemplatesGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsTagTemplatesGetCall) IfNoneMatch(entityTag string) *ProjectsLocationsTagTemplatesGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTagTemplatesGetCall) Context(ctx context.Context) *ProjectsLocationsTagTemplatesGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTagTemplatesGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTagTemplatesGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.tagTemplates.get" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1TagTemplate or error
// will be non-nil. Any non-2xx status code is an error. Response
// headers are in either
// *GoogleCloudDatacatalogV1beta1TagTemplate.ServerResponse.Header or
// (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsTagTemplatesGetCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1TagTemplate, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1TagTemplate{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets a tag template.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/tagTemplates/{tagTemplatesId}",
// "httpMethod": "GET",
// "id": "datacatalog.projects.locations.tagTemplates.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The name of the tag template. Example:\n\n* projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/tagTemplates/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1TagTemplate"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.tagTemplates.getIamPolicy":
type ProjectsLocationsTagTemplatesGetIamPolicyCall struct {
s *Service
resource string
getiampolicyrequest *GetIamPolicyRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// GetIamPolicy: Gets the access control policy for a resource. A
// `NOT_FOUND` error
// is returned if the resource does not exist. An empty policy is
// returned
// if the resource exists but does not have a policy set on
// it.
//
// Supported resources are:
// - Tag templates.
// - Entries.
// - Entry groups.
// Note, this method cannot be used to manage policies for BigQuery,
// Cloud
// Pub/Sub and any external Google Cloud Platform resources synced to
// Cloud
// Data Catalog.
//
// Callers must have following Google IAM permission
// - `datacatalog.tagTemplates.getIamPolicy` to get policies on tag
// templates.
// - `datacatalog.entries.getIamPolicy` to get policies on entries.
// - `datacatalog.entryGroups.getIamPolicy` to get policies on entry
// groups.
func (r *ProjectsLocationsTagTemplatesService) GetIamPolicy(resource string, getiampolicyrequest *GetIamPolicyRequest) *ProjectsLocationsTagTemplatesGetIamPolicyCall {
c := &ProjectsLocationsTagTemplatesGetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.getiampolicyrequest = getiampolicyrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTagTemplatesGetIamPolicyCall) Fields(s ...googleapi.Field) *ProjectsLocationsTagTemplatesGetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTagTemplatesGetIamPolicyCall) Context(ctx context.Context) *ProjectsLocationsTagTemplatesGetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTagTemplatesGetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTagTemplatesGetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.getiampolicyrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:getIamPolicy")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.tagTemplates.getIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsTagTemplatesGetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the access control policy for a resource. A `NOT_FOUND` error\nis returned if the resource does not exist. An empty policy is returned\nif the resource exists but does not have a policy set on it.\n\nSupported resources are:\n - Tag templates.\n - Entries.\n - Entry groups.\nNote, this method cannot be used to manage policies for BigQuery, Cloud\nPub/Sub and any external Google Cloud Platform resources synced to Cloud\nData Catalog.\n\nCallers must have following Google IAM permission\n - `datacatalog.tagTemplates.getIamPolicy` to get policies on tag\n templates.\n - `datacatalog.entries.getIamPolicy` to get policies on entries.\n - `datacatalog.entryGroups.getIamPolicy` to get policies on entry groups.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/tagTemplates/{tagTemplatesId}:getIamPolicy",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.tagTemplates.getIamPolicy",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy is being requested.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/tagTemplates/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:getIamPolicy",
// "request": {
// "$ref": "GetIamPolicyRequest"
// },
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.tagTemplates.patch":
type ProjectsLocationsTagTemplatesPatchCall struct {
s *Service
name string
googleclouddatacatalogv1beta1tagtemplate *GoogleCloudDatacatalogV1beta1TagTemplate
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates a tag template. This method cannot be used to update
// the fields of
// a template. The tag template fields are represented as separate
// resources
// and should be updated using their own create/update/delete
// methods.
// Users should enable the Data Catalog API in the project identified
// by
// the `tag_template.name` parameter (see [Data Catalog Resource
// Project]
// (/data-catalog/docs/concepts/resource-project) for more information).
func (r *ProjectsLocationsTagTemplatesService) Patch(name string, googleclouddatacatalogv1beta1tagtemplate *GoogleCloudDatacatalogV1beta1TagTemplate) *ProjectsLocationsTagTemplatesPatchCall {
c := &ProjectsLocationsTagTemplatesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.googleclouddatacatalogv1beta1tagtemplate = googleclouddatacatalogv1beta1tagtemplate
return c
}
// UpdateMask sets the optional parameter "updateMask": The field mask
// specifies the parts of the template to overwrite.
//
// Allowed fields:
//
// * `display_name`
//
// If absent or empty, all of the allowed fields above will be updated.
func (c *ProjectsLocationsTagTemplatesPatchCall) UpdateMask(updateMask string) *ProjectsLocationsTagTemplatesPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTagTemplatesPatchCall) Fields(s ...googleapi.Field) *ProjectsLocationsTagTemplatesPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTagTemplatesPatchCall) Context(ctx context.Context) *ProjectsLocationsTagTemplatesPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTagTemplatesPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTagTemplatesPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1tagtemplate)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.tagTemplates.patch" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1TagTemplate or error
// will be non-nil. Any non-2xx status code is an error. Response
// headers are in either
// *GoogleCloudDatacatalogV1beta1TagTemplate.ServerResponse.Header or
// (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsTagTemplatesPatchCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1TagTemplate, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1TagTemplate{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a tag template. This method cannot be used to update the fields of\na template. The tag template fields are represented as separate resources\nand should be updated using their own create/update/delete methods.\nUsers should enable the Data Catalog API in the project identified by\nthe `tag_template.name` parameter (see [Data Catalog Resource Project]\n(/data-catalog/docs/concepts/resource-project) for more information).",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/tagTemplates/{tagTemplatesId}",
// "httpMethod": "PATCH",
// "id": "datacatalog.projects.locations.tagTemplates.patch",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The resource name of the tag template in URL format. Example:\n\n* projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}\n\nNote that this TagTemplate and its child resources may not actually be\nstored in the location in this name.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/tagTemplates/[^/]+$",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "The field mask specifies the parts of the template to overwrite.\n\nAllowed fields:\n\n * `display_name`\n\nIf absent or empty, all of the allowed fields above will be updated.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1TagTemplate"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1TagTemplate"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.tagTemplates.setIamPolicy":
type ProjectsLocationsTagTemplatesSetIamPolicyCall struct {
s *Service
resource string
setiampolicyrequest *SetIamPolicyRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// SetIamPolicy: Sets the access control policy for a resource. Replaces
// any existing
// policy.
// Supported resources are:
// - Tag templates.
// - Entries.
// - Entry groups.
// Note, this method cannot be used to manage policies for BigQuery,
// Cloud
// Pub/Sub and any external Google Cloud Platform resources synced to
// Cloud
// Data Catalog.
//
// Callers must have following Google IAM permission
// - `datacatalog.tagTemplates.setIamPolicy` to set policies on tag
// templates.
// - `datacatalog.entries.setIamPolicy` to set policies on entries.
// - `datacatalog.entryGroups.setIamPolicy` to set policies on entry
// groups.
func (r *ProjectsLocationsTagTemplatesService) SetIamPolicy(resource string, setiampolicyrequest *SetIamPolicyRequest) *ProjectsLocationsTagTemplatesSetIamPolicyCall {
c := &ProjectsLocationsTagTemplatesSetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.setiampolicyrequest = setiampolicyrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTagTemplatesSetIamPolicyCall) Fields(s ...googleapi.Field) *ProjectsLocationsTagTemplatesSetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTagTemplatesSetIamPolicyCall) Context(ctx context.Context) *ProjectsLocationsTagTemplatesSetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTagTemplatesSetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTagTemplatesSetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.setiampolicyrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:setIamPolicy")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.tagTemplates.setIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsTagTemplatesSetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Sets the access control policy for a resource. Replaces any existing\npolicy.\nSupported resources are:\n - Tag templates.\n - Entries.\n - Entry groups.\nNote, this method cannot be used to manage policies for BigQuery, Cloud\nPub/Sub and any external Google Cloud Platform resources synced to Cloud\nData Catalog.\n\nCallers must have following Google IAM permission\n - `datacatalog.tagTemplates.setIamPolicy` to set policies on tag\n templates.\n - `datacatalog.entries.setIamPolicy` to set policies on entries.\n - `datacatalog.entryGroups.setIamPolicy` to set policies on entry groups.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/tagTemplates/{tagTemplatesId}:setIamPolicy",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.tagTemplates.setIamPolicy",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy is being specified.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/tagTemplates/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:setIamPolicy",
// "request": {
// "$ref": "SetIamPolicyRequest"
// },
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.tagTemplates.testIamPermissions":
type ProjectsLocationsTagTemplatesTestIamPermissionsCall struct {
s *Service
resource string
testiampermissionsrequest *TestIamPermissionsRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// TestIamPermissions: Returns the caller's permissions on a
// resource.
// If the resource does not exist, an empty set of permissions is
// returned
// (We don't return a `NOT_FOUND` error).
//
// Supported resources are:
// - Tag templates.
// - Entries.
// - Entry groups.
// Note, this method cannot be used to manage policies for BigQuery,
// Cloud
// Pub/Sub and any external Google Cloud Platform resources synced to
// Cloud
// Data Catalog.
//
// A caller is not required to have Google IAM permission to make
// this
// request.
func (r *ProjectsLocationsTagTemplatesService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsLocationsTagTemplatesTestIamPermissionsCall {
c := &ProjectsLocationsTagTemplatesTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.testiampermissionsrequest = testiampermissionsrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTagTemplatesTestIamPermissionsCall) Fields(s ...googleapi.Field) *ProjectsLocationsTagTemplatesTestIamPermissionsCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTagTemplatesTestIamPermissionsCall) Context(ctx context.Context) *ProjectsLocationsTagTemplatesTestIamPermissionsCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTagTemplatesTestIamPermissionsCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTagTemplatesTestIamPermissionsCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.testiampermissionsrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:testIamPermissions")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.tagTemplates.testIamPermissions" call.
// Exactly one of *TestIamPermissionsResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *TestIamPermissionsResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsTagTemplatesTestIamPermissionsCall) Do(opts ...googleapi.CallOption) (*TestIamPermissionsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &TestIamPermissionsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns the caller's permissions on a resource.\nIf the resource does not exist, an empty set of permissions is returned\n(We don't return a `NOT_FOUND` error).\n\nSupported resources are:\n - Tag templates.\n - Entries.\n - Entry groups.\nNote, this method cannot be used to manage policies for BigQuery, Cloud\nPub/Sub and any external Google Cloud Platform resources synced to Cloud\nData Catalog.\n\nA caller is not required to have Google IAM permission to make this\nrequest.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/tagTemplates/{tagTemplatesId}:testIamPermissions",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.tagTemplates.testIamPermissions",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy detail is being requested.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/tagTemplates/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:testIamPermissions",
// "request": {
// "$ref": "TestIamPermissionsRequest"
// },
// "response": {
// "$ref": "TestIamPermissionsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.tagTemplates.fields.create":
type ProjectsLocationsTagTemplatesFieldsCreateCall struct {
s *Service
parent string
googleclouddatacatalogv1beta1tagtemplatefield *GoogleCloudDatacatalogV1beta1TagTemplateField
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Creates a field in a tag template. The user should enable the
// Data Catalog
// API in the project identified by the `parent` parameter (see
// [Data Catalog
// Resource
// Project](/data-catalog/docs/concepts/resource-project) for
// more
// information).
func (r *ProjectsLocationsTagTemplatesFieldsService) Create(parent string, googleclouddatacatalogv1beta1tagtemplatefield *GoogleCloudDatacatalogV1beta1TagTemplateField) *ProjectsLocationsTagTemplatesFieldsCreateCall {
c := &ProjectsLocationsTagTemplatesFieldsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.googleclouddatacatalogv1beta1tagtemplatefield = googleclouddatacatalogv1beta1tagtemplatefield
return c
}
// TagTemplateFieldId sets the optional parameter "tagTemplateFieldId":
// Required. The ID of the tag template field to create.
// Field ids can contain letters (both uppercase and lowercase),
// numbers
// (0-9), underscores (_) and dashes (-). Field IDs must be at least
// 1
// character long and at most 128 characters long. Field IDs must also
// be
// unique within their template.
func (c *ProjectsLocationsTagTemplatesFieldsCreateCall) TagTemplateFieldId(tagTemplateFieldId string) *ProjectsLocationsTagTemplatesFieldsCreateCall {
c.urlParams_.Set("tagTemplateFieldId", tagTemplateFieldId)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTagTemplatesFieldsCreateCall) Fields(s ...googleapi.Field) *ProjectsLocationsTagTemplatesFieldsCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTagTemplatesFieldsCreateCall) Context(ctx context.Context) *ProjectsLocationsTagTemplatesFieldsCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTagTemplatesFieldsCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTagTemplatesFieldsCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1tagtemplatefield)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/fields")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.tagTemplates.fields.create" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1TagTemplateField or
// error will be non-nil. Any non-2xx status code is an error. Response
// headers are in either
// *GoogleCloudDatacatalogV1beta1TagTemplateField.ServerResponse.Header
// or (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsTagTemplatesFieldsCreateCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1TagTemplateField, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1TagTemplateField{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a field in a tag template. The user should enable the Data Catalog\nAPI in the project identified by the `parent` parameter (see\n[Data Catalog Resource\nProject](/data-catalog/docs/concepts/resource-project) for more\ninformation).",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/tagTemplates/{tagTemplatesId}/fields",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.tagTemplates.fields.create",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. The name of the project and the template location\n[region](/compute/docs/regions-zones/#available).\nNOTE: Currently, only the `us-central1 region` is supported.\n\nExample:\n\n* projects/{project_id}/locations/us-central1/tagTemplates/{tag_template_id}",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/tagTemplates/[^/]+$",
// "required": true,
// "type": "string"
// },
// "tagTemplateFieldId": {
// "description": "Required. The ID of the tag template field to create.\nField ids can contain letters (both uppercase and lowercase), numbers\n(0-9), underscores (_) and dashes (-). Field IDs must be at least 1\ncharacter long and at most 128 characters long. Field IDs must also be\nunique within their template.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/fields",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1TagTemplateField"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1TagTemplateField"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.tagTemplates.fields.delete":
type ProjectsLocationsTagTemplatesFieldsDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a field in a tag template and all uses of that
// field.
// Users should enable the Data Catalog API in the project identified
// by
// the `name` parameter (see [Data Catalog Resource
// Project]
// (/data-catalog/docs/concepts/resource-project) for more information).
func (r *ProjectsLocationsTagTemplatesFieldsService) Delete(name string) *ProjectsLocationsTagTemplatesFieldsDeleteCall {
c := &ProjectsLocationsTagTemplatesFieldsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Force sets the optional parameter "force": Required. Currently, this
// field must always be set to `true`.
// This confirms the deletion of this field from any tags using this
// field.
// `force = false` will be supported in the future.
func (c *ProjectsLocationsTagTemplatesFieldsDeleteCall) Force(force bool) *ProjectsLocationsTagTemplatesFieldsDeleteCall {
c.urlParams_.Set("force", fmt.Sprint(force))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTagTemplatesFieldsDeleteCall) Fields(s ...googleapi.Field) *ProjectsLocationsTagTemplatesFieldsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTagTemplatesFieldsDeleteCall) Context(ctx context.Context) *ProjectsLocationsTagTemplatesFieldsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTagTemplatesFieldsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTagTemplatesFieldsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.tagTemplates.fields.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsTagTemplatesFieldsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes a field in a tag template and all uses of that field.\nUsers should enable the Data Catalog API in the project identified by\nthe `name` parameter (see [Data Catalog Resource Project]\n(/data-catalog/docs/concepts/resource-project) for more information).",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/tagTemplates/{tagTemplatesId}/fields/{fieldsId}",
// "httpMethod": "DELETE",
// "id": "datacatalog.projects.locations.tagTemplates.fields.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "force": {
// "description": "Required. Currently, this field must always be set to `true`.\nThis confirms the deletion of this field from any tags using this field.\n`force = false` will be supported in the future.",
// "location": "query",
// "type": "boolean"
// },
// "name": {
// "description": "Required. The name of the tag template field to delete. Example:\n\n* projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id}",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/tagTemplates/[^/]+/fields/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.tagTemplates.fields.patch":
type ProjectsLocationsTagTemplatesFieldsPatchCall struct {
s *Service
name string
googleclouddatacatalogv1beta1tagtemplatefield *GoogleCloudDatacatalogV1beta1TagTemplateField
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates a field in a tag template. This method cannot be used
// to update the
// field type. Users should enable the Data Catalog API in the
// project
// identified by the `name` parameter (see [Data Catalog Resource
// Project]
// (/data-catalog/docs/concepts/resource-project) for more information).
func (r *ProjectsLocationsTagTemplatesFieldsService) Patch(name string, googleclouddatacatalogv1beta1tagtemplatefield *GoogleCloudDatacatalogV1beta1TagTemplateField) *ProjectsLocationsTagTemplatesFieldsPatchCall {
c := &ProjectsLocationsTagTemplatesFieldsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.googleclouddatacatalogv1beta1tagtemplatefield = googleclouddatacatalogv1beta1tagtemplatefield
return c
}
// UpdateMask sets the optional parameter "updateMask": The field mask
// specifies the parts of the template to be updated.
// Allowed fields:
//
// * `display_name`
// * `type.enum_type`
// * `is_required`
//
// If `update_mask` is not set or empty, all of the allowed fields above
// will
// be updated.
//
// When updating an enum type, the provided values will be merged with
// the
// existing values. Therefore, enum values can only be added, existing
// enum
// values cannot be deleted nor renamed. Updating a template field
// from
// optional to required is NOT allowed.
func (c *ProjectsLocationsTagTemplatesFieldsPatchCall) UpdateMask(updateMask string) *ProjectsLocationsTagTemplatesFieldsPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTagTemplatesFieldsPatchCall) Fields(s ...googleapi.Field) *ProjectsLocationsTagTemplatesFieldsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTagTemplatesFieldsPatchCall) Context(ctx context.Context) *ProjectsLocationsTagTemplatesFieldsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTagTemplatesFieldsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTagTemplatesFieldsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1tagtemplatefield)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.tagTemplates.fields.patch" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1TagTemplateField or
// error will be non-nil. Any non-2xx status code is an error. Response
// headers are in either
// *GoogleCloudDatacatalogV1beta1TagTemplateField.ServerResponse.Header
// or (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsTagTemplatesFieldsPatchCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1TagTemplateField, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1TagTemplateField{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a field in a tag template. This method cannot be used to update the\nfield type. Users should enable the Data Catalog API in the project\nidentified by the `name` parameter (see [Data Catalog Resource Project]\n(/data-catalog/docs/concepts/resource-project) for more information).",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/tagTemplates/{tagTemplatesId}/fields/{fieldsId}",
// "httpMethod": "PATCH",
// "id": "datacatalog.projects.locations.tagTemplates.fields.patch",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The name of the tag template field. Example:\n\n* projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id}",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/tagTemplates/[^/]+/fields/[^/]+$",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "Optional. The field mask specifies the parts of the template to be updated.\nAllowed fields:\n\n * `display_name`\n * `type.enum_type`\n * `is_required`\n\nIf `update_mask` is not set or empty, all of the allowed fields above will\nbe updated.\n\nWhen updating an enum type, the provided values will be merged with the\nexisting values. Therefore, enum values can only be added, existing enum\nvalues cannot be deleted nor renamed. Updating a template field from\noptional to required is NOT allowed.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1TagTemplateField"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1TagTemplateField"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.tagTemplates.fields.rename":
type ProjectsLocationsTagTemplatesFieldsRenameCall struct {
s *Service
name string
googleclouddatacatalogv1beta1renametagtemplatefieldrequest *GoogleCloudDatacatalogV1beta1RenameTagTemplateFieldRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Rename: Renames a field in a tag template. The user should enable the
// Data Catalog
// API in the project identified by the `name` parameter (see [Data
// Catalog
// Resource Project](/data-catalog/docs/concepts/resource-project) for
// more
// information).
func (r *ProjectsLocationsTagTemplatesFieldsService) Rename(name string, googleclouddatacatalogv1beta1renametagtemplatefieldrequest *GoogleCloudDatacatalogV1beta1RenameTagTemplateFieldRequest) *ProjectsLocationsTagTemplatesFieldsRenameCall {
c := &ProjectsLocationsTagTemplatesFieldsRenameCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.googleclouddatacatalogv1beta1renametagtemplatefieldrequest = googleclouddatacatalogv1beta1renametagtemplatefieldrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTagTemplatesFieldsRenameCall) Fields(s ...googleapi.Field) *ProjectsLocationsTagTemplatesFieldsRenameCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTagTemplatesFieldsRenameCall) Context(ctx context.Context) *ProjectsLocationsTagTemplatesFieldsRenameCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTagTemplatesFieldsRenameCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTagTemplatesFieldsRenameCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1renametagtemplatefieldrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}:rename")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.tagTemplates.fields.rename" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1TagTemplateField or
// error will be non-nil. Any non-2xx status code is an error. Response
// headers are in either
// *GoogleCloudDatacatalogV1beta1TagTemplateField.ServerResponse.Header
// or (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsTagTemplatesFieldsRenameCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1TagTemplateField, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1TagTemplateField{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Renames a field in a tag template. The user should enable the Data Catalog\nAPI in the project identified by the `name` parameter (see [Data Catalog\nResource Project](/data-catalog/docs/concepts/resource-project) for more\ninformation).",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/tagTemplates/{tagTemplatesId}/fields/{fieldsId}:rename",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.tagTemplates.fields.rename",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The name of the tag template. Example:\n\n* projects/{project_id}/locations/{location}/tagTemplates/{tag_template_id}/fields/{tag_template_field_id}",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/tagTemplates/[^/]+/fields/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}:rename",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1RenameTagTemplateFieldRequest"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1TagTemplateField"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.create":
type ProjectsLocationsTaxonomiesCreateCall struct {
s *Service
parent string
googleclouddatacatalogv1beta1taxonomy *GoogleCloudDatacatalogV1beta1Taxonomy
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Creates a taxonomy in the specified project.
func (r *ProjectsLocationsTaxonomiesService) Create(parent string, googleclouddatacatalogv1beta1taxonomy *GoogleCloudDatacatalogV1beta1Taxonomy) *ProjectsLocationsTaxonomiesCreateCall {
c := &ProjectsLocationsTaxonomiesCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.googleclouddatacatalogv1beta1taxonomy = googleclouddatacatalogv1beta1taxonomy
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesCreateCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesCreateCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1taxonomy)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/taxonomies")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.create" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1Taxonomy or error will
// be non-nil. Any non-2xx status code is an error. Response headers are
// in either
// *GoogleCloudDatacatalogV1beta1Taxonomy.ServerResponse.Header or (if a
// response was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsTaxonomiesCreateCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1Taxonomy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1Taxonomy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a taxonomy in the specified project.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.taxonomies.create",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. Resource name of the project that the taxonomy will belong to.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/taxonomies",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1Taxonomy"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1Taxonomy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.delete":
type ProjectsLocationsTaxonomiesDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a taxonomy. This operation will also delete
// all
// policy tags in this taxonomy along with their associated policies.
func (r *ProjectsLocationsTaxonomiesService) Delete(name string) *ProjectsLocationsTaxonomiesDeleteCall {
c := &ProjectsLocationsTaxonomiesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesDeleteCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesDeleteCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsTaxonomiesDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes a taxonomy. This operation will also delete all\npolicy tags in this taxonomy along with their associated policies.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies/{taxonomiesId}",
// "httpMethod": "DELETE",
// "id": "datacatalog.projects.locations.taxonomies.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. Resource name of the taxonomy to be deleted. All policy tags in\nthis taxonomy will also be deleted.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/taxonomies/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.export":
type ProjectsLocationsTaxonomiesExportCall struct {
s *Service
parent string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Export: Exports all taxonomies and their policy tags in a
// project.
//
// This method generates SerializedTaxonomy protos with nested policy
// tags
// that can be used as an input for future ImportTaxonomies calls.
func (r *ProjectsLocationsTaxonomiesService) Export(parent string) *ProjectsLocationsTaxonomiesExportCall {
c := &ProjectsLocationsTaxonomiesExportCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
return c
}
// SerializedTaxonomies sets the optional parameter
// "serializedTaxonomies": Export taxonomies as serialized taxonomies.
func (c *ProjectsLocationsTaxonomiesExportCall) SerializedTaxonomies(serializedTaxonomies bool) *ProjectsLocationsTaxonomiesExportCall {
c.urlParams_.Set("serializedTaxonomies", fmt.Sprint(serializedTaxonomies))
return c
}
// Taxonomies sets the optional parameter "taxonomies": Required.
// Resource names of the taxonomies to be exported.
func (c *ProjectsLocationsTaxonomiesExportCall) Taxonomies(taxonomies ...string) *ProjectsLocationsTaxonomiesExportCall {
c.urlParams_.SetMulti("taxonomies", append([]string{}, taxonomies...))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesExportCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesExportCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsTaxonomiesExportCall) IfNoneMatch(entityTag string) *ProjectsLocationsTaxonomiesExportCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesExportCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesExportCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesExportCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesExportCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/taxonomies:export")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.export" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1ExportTaxonomiesResponse
// or error will be non-nil. Any non-2xx status code is an error.
// Response headers are in either
// *GoogleCloudDatacatalogV1beta1ExportTaxonomiesResponse.ServerResponse.
// Header or (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsTaxonomiesExportCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1ExportTaxonomiesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1ExportTaxonomiesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Exports all taxonomies and their policy tags in a project.\n\nThis method generates SerializedTaxonomy protos with nested policy tags\nthat can be used as an input for future ImportTaxonomies calls.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies:export",
// "httpMethod": "GET",
// "id": "datacatalog.projects.locations.taxonomies.export",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. Resource name of the project that taxonomies to be exported\nwill share.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// },
// "serializedTaxonomies": {
// "description": "Export taxonomies as serialized taxonomies.",
// "location": "query",
// "type": "boolean"
// },
// "taxonomies": {
// "description": "Required. Resource names of the taxonomies to be exported.",
// "location": "query",
// "repeated": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/taxonomies:export",
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1ExportTaxonomiesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.get":
type ProjectsLocationsTaxonomiesGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets a taxonomy.
func (r *ProjectsLocationsTaxonomiesService) Get(name string) *ProjectsLocationsTaxonomiesGetCall {
c := &ProjectsLocationsTaxonomiesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesGetCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsTaxonomiesGetCall) IfNoneMatch(entityTag string) *ProjectsLocationsTaxonomiesGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesGetCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.get" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1Taxonomy or error will
// be non-nil. Any non-2xx status code is an error. Response headers are
// in either
// *GoogleCloudDatacatalogV1beta1Taxonomy.ServerResponse.Header or (if a
// response was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsTaxonomiesGetCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1Taxonomy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1Taxonomy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets a taxonomy.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies/{taxonomiesId}",
// "httpMethod": "GET",
// "id": "datacatalog.projects.locations.taxonomies.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. Resource name of the requested taxonomy.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/taxonomies/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1Taxonomy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.getIamPolicy":
type ProjectsLocationsTaxonomiesGetIamPolicyCall struct {
s *Service
resource string
getiampolicyrequest *GetIamPolicyRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// GetIamPolicy: Gets the IAM policy for a taxonomy or a policy tag.
func (r *ProjectsLocationsTaxonomiesService) GetIamPolicy(resource string, getiampolicyrequest *GetIamPolicyRequest) *ProjectsLocationsTaxonomiesGetIamPolicyCall {
c := &ProjectsLocationsTaxonomiesGetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.getiampolicyrequest = getiampolicyrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesGetIamPolicyCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesGetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesGetIamPolicyCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesGetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesGetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesGetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.getiampolicyrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:getIamPolicy")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.getIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsTaxonomiesGetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the IAM policy for a taxonomy or a policy tag.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies/{taxonomiesId}:getIamPolicy",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.taxonomies.getIamPolicy",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy is being requested.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/taxonomies/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:getIamPolicy",
// "request": {
// "$ref": "GetIamPolicyRequest"
// },
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.import":
type ProjectsLocationsTaxonomiesImportCall struct {
s *Service
parent string
googleclouddatacatalogv1beta1importtaxonomiesrequest *GoogleCloudDatacatalogV1beta1ImportTaxonomiesRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Import: Imports all taxonomies and their policy tags to a project as
// new
// taxonomies.
//
// This method provides a bulk taxonomy / policy tag creation using
// nested
// proto structure.
func (r *ProjectsLocationsTaxonomiesService) Import(parent string, googleclouddatacatalogv1beta1importtaxonomiesrequest *GoogleCloudDatacatalogV1beta1ImportTaxonomiesRequest) *ProjectsLocationsTaxonomiesImportCall {
c := &ProjectsLocationsTaxonomiesImportCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.googleclouddatacatalogv1beta1importtaxonomiesrequest = googleclouddatacatalogv1beta1importtaxonomiesrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesImportCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesImportCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesImportCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesImportCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesImportCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesImportCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1importtaxonomiesrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/taxonomies:import")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.import" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1ImportTaxonomiesResponse
// or error will be non-nil. Any non-2xx status code is an error.
// Response headers are in either
// *GoogleCloudDatacatalogV1beta1ImportTaxonomiesResponse.ServerResponse.
// Header or (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsTaxonomiesImportCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1ImportTaxonomiesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1ImportTaxonomiesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Imports all taxonomies and their policy tags to a project as new\ntaxonomies.\n\nThis method provides a bulk taxonomy / policy tag creation using nested\nproto structure.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies:import",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.taxonomies.import",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. Resource name of project that the newly created taxonomies will\nbelong to.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/taxonomies:import",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1ImportTaxonomiesRequest"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1ImportTaxonomiesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.list":
type ProjectsLocationsTaxonomiesListCall struct {
s *Service
parent string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists all taxonomies in a project in a particular location that
// the caller
// has permission to view.
func (r *ProjectsLocationsTaxonomiesService) List(parent string) *ProjectsLocationsTaxonomiesListCall {
c := &ProjectsLocationsTaxonomiesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
return c
}
// PageSize sets the optional parameter "pageSize": The maximum number
// of items to return. Must be a value between 1 and 1000.
// If not set, defaults to 50.
func (c *ProjectsLocationsTaxonomiesListCall) PageSize(pageSize int64) *ProjectsLocationsTaxonomiesListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": The
// next_page_token value returned from a previous list request, if any.
// If
// not set, defaults to an empty string.
func (c *ProjectsLocationsTaxonomiesListCall) PageToken(pageToken string) *ProjectsLocationsTaxonomiesListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesListCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsTaxonomiesListCall) IfNoneMatch(entityTag string) *ProjectsLocationsTaxonomiesListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesListCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/taxonomies")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.list" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1ListTaxonomiesResponse
// or error will be non-nil. Any non-2xx status code is an error.
// Response headers are in either
// *GoogleCloudDatacatalogV1beta1ListTaxonomiesResponse.ServerResponse.He
// ader or (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsTaxonomiesListCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1ListTaxonomiesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1ListTaxonomiesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists all taxonomies in a project in a particular location that the caller\nhas permission to view.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies",
// "httpMethod": "GET",
// "id": "datacatalog.projects.locations.taxonomies.list",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "pageSize": {
// "description": "The maximum number of items to return. Must be a value between 1 and 1000.\nIf not set, defaults to 50.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "The next_page_token value returned from a previous list request, if any. If\nnot set, defaults to an empty string.",
// "location": "query",
// "type": "string"
// },
// "parent": {
// "description": "Required. Resource name of the project to list the taxonomies of.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/taxonomies",
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1ListTaxonomiesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsLocationsTaxonomiesListCall) Pages(ctx context.Context, f func(*GoogleCloudDatacatalogV1beta1ListTaxonomiesResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "datacatalog.projects.locations.taxonomies.patch":
type ProjectsLocationsTaxonomiesPatchCall struct {
s *Service
name string
googleclouddatacatalogv1beta1taxonomy *GoogleCloudDatacatalogV1beta1Taxonomy
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates a taxonomy.
func (r *ProjectsLocationsTaxonomiesService) Patch(name string, googleclouddatacatalogv1beta1taxonomy *GoogleCloudDatacatalogV1beta1Taxonomy) *ProjectsLocationsTaxonomiesPatchCall {
c := &ProjectsLocationsTaxonomiesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.googleclouddatacatalogv1beta1taxonomy = googleclouddatacatalogv1beta1taxonomy
return c
}
// UpdateMask sets the optional parameter "updateMask": The update mask
// applies to the resource. For the `FieldMask`
// definition,
// see
// https://developers.google.com/protocol-buffers/docs/re
// ference/google.protobuf#fieldmask
// If not set, defaults to all of the fields that are allowed to update.
func (c *ProjectsLocationsTaxonomiesPatchCall) UpdateMask(updateMask string) *ProjectsLocationsTaxonomiesPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesPatchCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesPatchCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1taxonomy)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.patch" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1Taxonomy or error will
// be non-nil. Any non-2xx status code is an error. Response headers are
// in either
// *GoogleCloudDatacatalogV1beta1Taxonomy.ServerResponse.Header or (if a
// response was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsTaxonomiesPatchCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1Taxonomy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1Taxonomy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a taxonomy.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies/{taxonomiesId}",
// "httpMethod": "PATCH",
// "id": "datacatalog.projects.locations.taxonomies.patch",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Output only. Resource name of this taxonomy, whose format is:\n\"projects/{project_number}/locations/{location_id}/taxonomies/{id}\".",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/taxonomies/[^/]+$",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "The update mask applies to the resource. For the `FieldMask` definition,\nsee\nhttps://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask\nIf not set, defaults to all of the fields that are allowed to update.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1Taxonomy"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1Taxonomy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.setIamPolicy":
type ProjectsLocationsTaxonomiesSetIamPolicyCall struct {
s *Service
resource string
setiampolicyrequest *SetIamPolicyRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// SetIamPolicy: Sets the IAM policy for a taxonomy or a policy tag.
func (r *ProjectsLocationsTaxonomiesService) SetIamPolicy(resource string, setiampolicyrequest *SetIamPolicyRequest) *ProjectsLocationsTaxonomiesSetIamPolicyCall {
c := &ProjectsLocationsTaxonomiesSetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.setiampolicyrequest = setiampolicyrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesSetIamPolicyCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesSetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesSetIamPolicyCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesSetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesSetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesSetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.setiampolicyrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:setIamPolicy")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.setIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsTaxonomiesSetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Sets the IAM policy for a taxonomy or a policy tag.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies/{taxonomiesId}:setIamPolicy",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.taxonomies.setIamPolicy",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy is being specified.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/taxonomies/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:setIamPolicy",
// "request": {
// "$ref": "SetIamPolicyRequest"
// },
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.testIamPermissions":
type ProjectsLocationsTaxonomiesTestIamPermissionsCall struct {
s *Service
resource string
testiampermissionsrequest *TestIamPermissionsRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// TestIamPermissions: Returns the permissions that a caller has on the
// specified taxonomy or
// policy tag.
func (r *ProjectsLocationsTaxonomiesService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsLocationsTaxonomiesTestIamPermissionsCall {
c := &ProjectsLocationsTaxonomiesTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.testiampermissionsrequest = testiampermissionsrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesTestIamPermissionsCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesTestIamPermissionsCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesTestIamPermissionsCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesTestIamPermissionsCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesTestIamPermissionsCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesTestIamPermissionsCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.testiampermissionsrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:testIamPermissions")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.testIamPermissions" call.
// Exactly one of *TestIamPermissionsResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *TestIamPermissionsResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsTaxonomiesTestIamPermissionsCall) Do(opts ...googleapi.CallOption) (*TestIamPermissionsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &TestIamPermissionsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns the permissions that a caller has on the specified taxonomy or\npolicy tag.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies/{taxonomiesId}:testIamPermissions",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.taxonomies.testIamPermissions",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy detail is being requested.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/taxonomies/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:testIamPermissions",
// "request": {
// "$ref": "TestIamPermissionsRequest"
// },
// "response": {
// "$ref": "TestIamPermissionsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.policyTags.create":
type ProjectsLocationsTaxonomiesPolicyTagsCreateCall struct {
s *Service
parent string
googleclouddatacatalogv1beta1policytag *GoogleCloudDatacatalogV1beta1PolicyTag
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Creates a policy tag in the specified taxonomy.
func (r *ProjectsLocationsTaxonomiesPolicyTagsService) Create(parent string, googleclouddatacatalogv1beta1policytag *GoogleCloudDatacatalogV1beta1PolicyTag) *ProjectsLocationsTaxonomiesPolicyTagsCreateCall {
c := &ProjectsLocationsTaxonomiesPolicyTagsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.googleclouddatacatalogv1beta1policytag = googleclouddatacatalogv1beta1policytag
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesPolicyTagsCreateCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesPolicyTagsCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesPolicyTagsCreateCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesPolicyTagsCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesPolicyTagsCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesPolicyTagsCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1policytag)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/policyTags")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.policyTags.create" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1PolicyTag or error will
// be non-nil. Any non-2xx status code is an error. Response headers are
// in either
// *GoogleCloudDatacatalogV1beta1PolicyTag.ServerResponse.Header or (if
// a response was returned at all) in error.(*googleapi.Error).Header.
// Use googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsTaxonomiesPolicyTagsCreateCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1PolicyTag, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1PolicyTag{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a policy tag in the specified taxonomy.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies/{taxonomiesId}/policyTags",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.taxonomies.policyTags.create",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. Resource name of the taxonomy that the policy tag will belong to.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/taxonomies/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/policyTags",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1PolicyTag"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1PolicyTag"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.policyTags.delete":
type ProjectsLocationsTaxonomiesPolicyTagsDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a policy tag. Also deletes all of its descendant
// policy tags.
func (r *ProjectsLocationsTaxonomiesPolicyTagsService) Delete(name string) *ProjectsLocationsTaxonomiesPolicyTagsDeleteCall {
c := &ProjectsLocationsTaxonomiesPolicyTagsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesPolicyTagsDeleteCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesPolicyTagsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesPolicyTagsDeleteCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesPolicyTagsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesPolicyTagsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesPolicyTagsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.policyTags.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsTaxonomiesPolicyTagsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes a policy tag. Also deletes all of its descendant policy tags.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies/{taxonomiesId}/policyTags/{policyTagsId}",
// "httpMethod": "DELETE",
// "id": "datacatalog.projects.locations.taxonomies.policyTags.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. Resource name of the policy tag to be deleted. All of its descendant\npolicy tags will also be deleted.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/taxonomies/[^/]+/policyTags/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.policyTags.get":
type ProjectsLocationsTaxonomiesPolicyTagsGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets a policy tag.
func (r *ProjectsLocationsTaxonomiesPolicyTagsService) Get(name string) *ProjectsLocationsTaxonomiesPolicyTagsGetCall {
c := &ProjectsLocationsTaxonomiesPolicyTagsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesPolicyTagsGetCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesPolicyTagsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsTaxonomiesPolicyTagsGetCall) IfNoneMatch(entityTag string) *ProjectsLocationsTaxonomiesPolicyTagsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesPolicyTagsGetCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesPolicyTagsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesPolicyTagsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesPolicyTagsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.policyTags.get" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1PolicyTag or error will
// be non-nil. Any non-2xx status code is an error. Response headers are
// in either
// *GoogleCloudDatacatalogV1beta1PolicyTag.ServerResponse.Header or (if
// a response was returned at all) in error.(*googleapi.Error).Header.
// Use googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsTaxonomiesPolicyTagsGetCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1PolicyTag, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1PolicyTag{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets a policy tag.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies/{taxonomiesId}/policyTags/{policyTagsId}",
// "httpMethod": "GET",
// "id": "datacatalog.projects.locations.taxonomies.policyTags.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. Resource name of the requested policy tag.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/taxonomies/[^/]+/policyTags/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1PolicyTag"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.policyTags.getIamPolicy":
type ProjectsLocationsTaxonomiesPolicyTagsGetIamPolicyCall struct {
s *Service
resource string
getiampolicyrequest *GetIamPolicyRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// GetIamPolicy: Gets the IAM policy for a taxonomy or a policy tag.
func (r *ProjectsLocationsTaxonomiesPolicyTagsService) GetIamPolicy(resource string, getiampolicyrequest *GetIamPolicyRequest) *ProjectsLocationsTaxonomiesPolicyTagsGetIamPolicyCall {
c := &ProjectsLocationsTaxonomiesPolicyTagsGetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.getiampolicyrequest = getiampolicyrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesPolicyTagsGetIamPolicyCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesPolicyTagsGetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesPolicyTagsGetIamPolicyCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesPolicyTagsGetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesPolicyTagsGetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesPolicyTagsGetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.getiampolicyrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:getIamPolicy")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.policyTags.getIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsTaxonomiesPolicyTagsGetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the IAM policy for a taxonomy or a policy tag.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies/{taxonomiesId}/policyTags/{policyTagsId}:getIamPolicy",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.taxonomies.policyTags.getIamPolicy",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy is being requested.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/taxonomies/[^/]+/policyTags/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:getIamPolicy",
// "request": {
// "$ref": "GetIamPolicyRequest"
// },
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.policyTags.list":
type ProjectsLocationsTaxonomiesPolicyTagsListCall struct {
s *Service
parent string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists all policy tags in a taxonomy.
func (r *ProjectsLocationsTaxonomiesPolicyTagsService) List(parent string) *ProjectsLocationsTaxonomiesPolicyTagsListCall {
c := &ProjectsLocationsTaxonomiesPolicyTagsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
return c
}
// PageSize sets the optional parameter "pageSize": The maximum number
// of items to return. Must be a value between 1 and 1000.
// If not set, defaults to 50.
func (c *ProjectsLocationsTaxonomiesPolicyTagsListCall) PageSize(pageSize int64) *ProjectsLocationsTaxonomiesPolicyTagsListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": The
// next_page_token value returned from a previous List request, if any.
// If
// not set, defaults to an empty string.
func (c *ProjectsLocationsTaxonomiesPolicyTagsListCall) PageToken(pageToken string) *ProjectsLocationsTaxonomiesPolicyTagsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesPolicyTagsListCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesPolicyTagsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsTaxonomiesPolicyTagsListCall) IfNoneMatch(entityTag string) *ProjectsLocationsTaxonomiesPolicyTagsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesPolicyTagsListCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesPolicyTagsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesPolicyTagsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesPolicyTagsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/policyTags")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.policyTags.list" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1ListPolicyTagsResponse
// or error will be non-nil. Any non-2xx status code is an error.
// Response headers are in either
// *GoogleCloudDatacatalogV1beta1ListPolicyTagsResponse.ServerResponse.He
// ader or (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *ProjectsLocationsTaxonomiesPolicyTagsListCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1ListPolicyTagsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1ListPolicyTagsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists all policy tags in a taxonomy.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies/{taxonomiesId}/policyTags",
// "httpMethod": "GET",
// "id": "datacatalog.projects.locations.taxonomies.policyTags.list",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "pageSize": {
// "description": "The maximum number of items to return. Must be a value between 1 and 1000.\nIf not set, defaults to 50.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "The next_page_token value returned from a previous List request, if any. If\nnot set, defaults to an empty string.",
// "location": "query",
// "type": "string"
// },
// "parent": {
// "description": "Required. Resource name of the taxonomy to list the policy tags of.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/taxonomies/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/policyTags",
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1ListPolicyTagsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsLocationsTaxonomiesPolicyTagsListCall) Pages(ctx context.Context, f func(*GoogleCloudDatacatalogV1beta1ListPolicyTagsResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "datacatalog.projects.locations.taxonomies.policyTags.patch":
type ProjectsLocationsTaxonomiesPolicyTagsPatchCall struct {
s *Service
name string
googleclouddatacatalogv1beta1policytag *GoogleCloudDatacatalogV1beta1PolicyTag
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates a policy tag.
func (r *ProjectsLocationsTaxonomiesPolicyTagsService) Patch(name string, googleclouddatacatalogv1beta1policytag *GoogleCloudDatacatalogV1beta1PolicyTag) *ProjectsLocationsTaxonomiesPolicyTagsPatchCall {
c := &ProjectsLocationsTaxonomiesPolicyTagsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.googleclouddatacatalogv1beta1policytag = googleclouddatacatalogv1beta1policytag
return c
}
// UpdateMask sets the optional parameter "updateMask": The update mask
// applies to the resource. Only display_name, description
// and
// parent_policy_tag can be updated and thus can be listed in the mask.
// If
// update_mask is not provided, all allowed fields (i.e.
// display_name,
// description and parent) will be updated. For more information
// including the
// `FieldMask` definition,
// see
// https://developers.google.com/protocol-buffers/docs/reference/goog
// le.protobuf#fieldmask
// If not set, defaults to all of the fields that are allowed to update.
func (c *ProjectsLocationsTaxonomiesPolicyTagsPatchCall) UpdateMask(updateMask string) *ProjectsLocationsTaxonomiesPolicyTagsPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesPolicyTagsPatchCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesPolicyTagsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesPolicyTagsPatchCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesPolicyTagsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesPolicyTagsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesPolicyTagsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.googleclouddatacatalogv1beta1policytag)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.policyTags.patch" call.
// Exactly one of *GoogleCloudDatacatalogV1beta1PolicyTag or error will
// be non-nil. Any non-2xx status code is an error. Response headers are
// in either
// *GoogleCloudDatacatalogV1beta1PolicyTag.ServerResponse.Header or (if
// a response was returned at all) in error.(*googleapi.Error).Header.
// Use googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsTaxonomiesPolicyTagsPatchCall) Do(opts ...googleapi.CallOption) (*GoogleCloudDatacatalogV1beta1PolicyTag, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &GoogleCloudDatacatalogV1beta1PolicyTag{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a policy tag.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies/{taxonomiesId}/policyTags/{policyTagsId}",
// "httpMethod": "PATCH",
// "id": "datacatalog.projects.locations.taxonomies.policyTags.patch",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Output only. Resource name of this policy tag, whose format is:\n\"projects/{project_number}/locations/{location_id}/taxonomies/{taxonomy_id}/policyTags/{id}\".",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/taxonomies/[^/]+/policyTags/[^/]+$",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "The update mask applies to the resource. Only display_name, description and\nparent_policy_tag can be updated and thus can be listed in the mask. If\nupdate_mask is not provided, all allowed fields (i.e. display_name,\ndescription and parent) will be updated. For more information including the\n`FieldMask` definition, see\nhttps://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask\nIf not set, defaults to all of the fields that are allowed to update.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "request": {
// "$ref": "GoogleCloudDatacatalogV1beta1PolicyTag"
// },
// "response": {
// "$ref": "GoogleCloudDatacatalogV1beta1PolicyTag"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.policyTags.setIamPolicy":
type ProjectsLocationsTaxonomiesPolicyTagsSetIamPolicyCall struct {
s *Service
resource string
setiampolicyrequest *SetIamPolicyRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// SetIamPolicy: Sets the IAM policy for a taxonomy or a policy tag.
func (r *ProjectsLocationsTaxonomiesPolicyTagsService) SetIamPolicy(resource string, setiampolicyrequest *SetIamPolicyRequest) *ProjectsLocationsTaxonomiesPolicyTagsSetIamPolicyCall {
c := &ProjectsLocationsTaxonomiesPolicyTagsSetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.setiampolicyrequest = setiampolicyrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesPolicyTagsSetIamPolicyCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesPolicyTagsSetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesPolicyTagsSetIamPolicyCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesPolicyTagsSetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesPolicyTagsSetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesPolicyTagsSetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.setiampolicyrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:setIamPolicy")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.policyTags.setIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsTaxonomiesPolicyTagsSetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Sets the IAM policy for a taxonomy or a policy tag.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies/{taxonomiesId}/policyTags/{policyTagsId}:setIamPolicy",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.taxonomies.policyTags.setIamPolicy",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy is being specified.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/taxonomies/[^/]+/policyTags/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:setIamPolicy",
// "request": {
// "$ref": "SetIamPolicyRequest"
// },
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datacatalog.projects.locations.taxonomies.policyTags.testIamPermissions":
type ProjectsLocationsTaxonomiesPolicyTagsTestIamPermissionsCall struct {
s *Service
resource string
testiampermissionsrequest *TestIamPermissionsRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// TestIamPermissions: Returns the permissions that a caller has on the
// specified taxonomy or
// policy tag.
func (r *ProjectsLocationsTaxonomiesPolicyTagsService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsLocationsTaxonomiesPolicyTagsTestIamPermissionsCall {
c := &ProjectsLocationsTaxonomiesPolicyTagsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.testiampermissionsrequest = testiampermissionsrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsTaxonomiesPolicyTagsTestIamPermissionsCall) Fields(s ...googleapi.Field) *ProjectsLocationsTaxonomiesPolicyTagsTestIamPermissionsCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsTaxonomiesPolicyTagsTestIamPermissionsCall) Context(ctx context.Context) *ProjectsLocationsTaxonomiesPolicyTagsTestIamPermissionsCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsTaxonomiesPolicyTagsTestIamPermissionsCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsTaxonomiesPolicyTagsTestIamPermissionsCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200229")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.testiampermissionsrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:testIamPermissions")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datacatalog.projects.locations.taxonomies.policyTags.testIamPermissions" call.
// Exactly one of *TestIamPermissionsResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *TestIamPermissionsResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsTaxonomiesPolicyTagsTestIamPermissionsCall) Do(opts ...googleapi.CallOption) (*TestIamPermissionsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &TestIamPermissionsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns the permissions that a caller has on the specified taxonomy or\npolicy tag.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/taxonomies/{taxonomiesId}/policyTags/{policyTagsId}:testIamPermissions",
// "httpMethod": "POST",
// "id": "datacatalog.projects.locations.taxonomies.policyTags.testIamPermissions",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy detail is being requested.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/taxonomies/[^/]+/policyTags/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:testIamPermissions",
// "request": {
// "$ref": "TestIamPermissionsRequest"
// },
// "response": {
// "$ref": "TestIamPermissionsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
| New |
_scope_maps_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from msrest.polling import LROPoller, NoPolling
from msrestazure.polling.arm_polling import ARMPolling
from .. import models
class ScopeMapsOperations(object):
"""ScopeMapsOperations operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
:ivar api_version: The client API version. Constant value: "2019-05-01-preview".
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2019-05-01-preview"
self.config = config
def get(
self, resource_group_name, registry_name, scope_map_name, custom_headers=None, raw=False, **operation_config):
"""Gets the properties of the specified scope map.
:param resource_group_name: The name of the resource group to which
the container registry belongs.
:type resource_group_name: str
:param registry_name: The name of the container registry.
:type registry_name: str
:param scope_map_name: The name of the scope map.
:type scope_map_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: ScopeMap or ClientRawResponse if raw=true
:rtype:
~azure.mgmt.containerregistry.v2019_06_01_preview.models.ScopeMap or
~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
# Construct URL
url = self.get.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', min_length=1),
'registryName': self._serialize.url("registry_name", registry_name, 'str', max_length=50, min_length=5, pattern=r'^[a-zA-Z0-9]*$'),
'scopeMapName': self._serialize.url("scope_map_name", scope_map_name, 'str', max_length=50, min_length=5, pattern=r'^[a-zA-Z0-9-]*$')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ScopeMap', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps/{scopeMapName}'}
def _create_initial(
self, resource_group_name, registry_name, scope_map_name, actions, description=None, custom_headers=None, raw=False, **operation_config):
scope_map_create_parameters = models.ScopeMap(description=description, actions=actions)
# Construct URL
url = self.create.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', min_length=1),
'registryName': self._serialize.url("registry_name", registry_name, 'str', max_length=50, min_length=5, pattern=r'^[a-zA-Z0-9]*$'),
'scopeMapName': self._serialize.url("scope_map_name", scope_map_name, 'str', max_length=50, min_length=5, pattern=r'^[a-zA-Z0-9-]*$')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct body
body_content = self._serialize.body(scope_map_create_parameters, 'ScopeMap')
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 201]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ScopeMap', response)
if response.status_code == 201:
deserialized = self._deserialize('ScopeMap', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
def create(
self, resource_group_name, registry_name, scope_map_name, actions, description=None, custom_headers=None, raw=False, polling=True, **operation_config):
"""Creates a scope map for a container registry with the specified
parameters.
:param resource_group_name: The name of the resource group to which
the container registry belongs.
:type resource_group_name: str
:param registry_name: The name of the container registry.
:type registry_name: str
:param scope_map_name: The name of the scope map.
:type scope_map_name: str
:param actions: The list of scoped permissions for registry artifacts.
E.g. repositories/repository-name/pull,
repositories/repository-name/delete
:type actions: list[str]
:param description: The user friendly description of the scope map.
:type description: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns ScopeMap or
ClientRawResponse<ScopeMap> if raw==True
:rtype:
~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.containerregistry.v2019_06_01_preview.models.ScopeMap]
or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.containerregistry.v2019_06_01_preview.models.ScopeMap]]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
raw_result = self._create_initial(
resource_group_name=resource_group_name,
registry_name=registry_name,
scope_map_name=scope_map_name,
actions=actions,
description=description,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
deserialized = self._deserialize('ScopeMap', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps/{scopeMapName}'}
def _delete_initial(
self, resource_group_name, registry_name, scope_map_name, custom_headers=None, raw=False, **operation_config):
# Construct URL
url = self.delete.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', min_length=1),
'registryName': self._serialize.url("registry_name", registry_name, 'str', max_length=50, min_length=5, pattern=r'^[a-zA-Z0-9]*$'),
'scopeMapName': self._serialize.url("scope_map_name", scope_map_name, 'str', max_length=50, min_length=5, pattern=r'^[a-zA-Z0-9-]*$')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 202, 204]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def delete(
self, resource_group_name, registry_name, scope_map_name, custom_headers=None, raw=False, polling=True, **operation_config):
"""Deletes a scope map from a container registry.
:param resource_group_name: The name of the resource group to which
the container registry belongs.
:type resource_group_name: str
:param registry_name: The name of the container registry.
:type registry_name: str
:param scope_map_name: The name of the scope map.
:type scope_map_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns None or
ClientRawResponse<None> if raw==True
:rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
raw_result = self._delete_initial(
resource_group_name=resource_group_name,
registry_name=registry_name,
scope_map_name=scope_map_name,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps/{scopeMapName}'}
def _update_initial(
self, resource_group_name, registry_name, scope_map_name, description=None, actions=None, custom_headers=None, raw=False, **operation_config):
scope_map_update_parameters = models.ScopeMapUpdateParameters(description=description, actions=actions)
# Construct URL
url = self.update.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', min_length=1),
'registryName': self._serialize.url("registry_name", registry_name, 'str', max_length=50, min_length=5, pattern=r'^[a-zA-Z0-9]*$'),
'scopeMapName': self._serialize.url("scope_map_name", scope_map_name, 'str', max_length=50, min_length=5, pattern=r'^[a-zA-Z0-9-]*$')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct body
body_content = self._serialize.body(scope_map_update_parameters, 'ScopeMapUpdateParameters')
# Construct and send request
request = self._client.patch(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 201]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('ScopeMap', response)
if response.status_code == 201:
deserialized = self._deserialize('ScopeMap', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
def update(
self, resource_group_name, registry_name, scope_map_name, description=None, actions=None, custom_headers=None, raw=False, polling=True, **operation_config):
"""Updates a scope map with the specified parameters.
:param resource_group_name: The name of the resource group to which
the container registry belongs.
:type resource_group_name: str
:param registry_name: The name of the container registry.
:type registry_name: str
:param scope_map_name: The name of the scope map.
:type scope_map_name: str
:param description: The user friendly description of the scope map.
:type description: str
:param actions: The list of scope permissions for registry artifacts.
E.g. repositories/repository-name/pull,
repositories/repository-name/delete
:type actions: list[str]
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns ScopeMap or
ClientRawResponse<ScopeMap> if raw==True
:rtype:
~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.containerregistry.v2019_06_01_preview.models.ScopeMap]
or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.containerregistry.v2019_06_01_preview.models.ScopeMap]]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
raw_result = self._update_initial(
resource_group_name=resource_group_name,
registry_name=registry_name,
scope_map_name=scope_map_name,
description=description,
actions=actions,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
deserialized = self._deserialize('ScopeMap', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps/{scopeMapName}'}
def list(
self, resource_group_name, registry_name, custom_headers=None, raw=False, **operation_config):
"""Lists all the scope maps for the specified container registry.
:param resource_group_name: The name of the resource group to which
the container registry belongs.
:type resource_group_name: str
:param registry_name: The name of the container registry.
:type registry_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of ScopeMap
:rtype:
~azure.mgmt.containerregistry.v2019_06_01_preview.models.ScopeMapPaged[~azure.mgmt.containerregistry.v2019_06_01_preview.models.ScopeMap]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
def prepare_request(next_link=None):
|
def internal_paging(next_link=None):
request = prepare_request(next_link)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
# Deserialize response
header_dict = None
if raw:
header_dict = {}
deserialized = models.ScopeMapPaged(internal_paging, self._deserialize.dependencies, header_dict)
return deserialized
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/scopeMaps'}
| if not next_link:
# Construct URL
url = self.list.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', min_length=1),
'registryName': self._serialize.url("registry_name", registry_name, 'str', max_length=50, min_length=5, pattern=r'^[a-zA-Z0-9]*$')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
return request |
ClusterSelect.tsx | import * as React from 'react'; | } from 'src/containers/clusters.container';
import { formatRegion } from 'src/utilities';
interface Props {
selectedCluster: string;
onChange: (value: string) => void;
onBlur: (e: any) => void;
error?: string;
}
type CombinedProps = Props & StateProps;
export const ClusterSelect: React.StatelessComponent<CombinedProps> = props => {
const {
selectedCluster,
error,
onChange,
onBlur,
clustersData,
clustersError
} = props;
const options: Item<string>[] = clustersData.map(eachCluster => ({
value: eachCluster.id,
label: formatRegion(eachCluster.region)
}));
React.useEffect(() => {
// If there's only one option, we want it to selected by default.
// If it isn't already selected, call `onChange` with it so Formik knows about it.
if (options.length === 1 && selectedCluster !== options[0].value) {
onChange(options[0].value);
}
}, []);
// Error could be: 1. General Clusters error, 2. Field error, 3. Nothing
const errorText = clustersError
? 'Error loading Clusters'
: error
? error
: undefined;
return (
<Select
data-qa-select-cluster
name="cluster"
label="Cluster"
options={options}
placeholder="All Clusters"
onChange={(item: Item<string>) => onChange(item.value)}
onBlur={onBlur}
isSearchable={false}
isClearable={false}
errorText={errorText}
defaultValue={options.length === 1 && options[0]}
/>
);
};
const enhanced = compose<CombinedProps, Props>(clustersContainer);
export default enhanced(ClusterSelect); | import { compose } from 'recompose';
import Select, { Item } from 'src/components/EnhancedSelect/Select';
import clustersContainer, {
StateProps |
version.go | package face
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string |
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v11.1.1-beta"
}
| {
return "Azure-SDK-For-Go/v11.1.1-beta arm-face/1.0"
} |
mod.rs | use std::fmt;
use bytes::{Buf, Bytes};
pub mod com_cmd;
pub mod scpi_error;
use crate::Result;
pub trait Scpi {
const TERM: u8 = b'\n';
fn write_bin<C: AsRef<[u8]>>(&mut self, content: C) -> Result<()>;
fn read_bin(&mut self) -> Result<Bytes>;
fn scpi_send<S: AsRef<str>>(&mut self, mess: S) -> Result<()> {
let message = mess.as_ref().as_bytes();
let mut temp;
let content = if message.last().is_none() || *message.last().unwrap() != Self::TERM {
temp = Vec::with_capacity(message.len() + 1);
temp.extend_from_slice(message);
temp.push(Self::TERM);
temp.as_ref()
} else {
message
};
self.write_bin(content)
}
fn scpi_read(&mut self) -> Result<String> {
Ok(String::from_utf8_lossy(self.read_bin()?.as_ref()).to_string())
}
fn scpi_query<S: AsRef<str>>(&mut self, mess: S) -> Result<String> {
self.scpi_send(mess)?;
self.scpi_read()
}
fn get_event_byte(&mut self) -> Result<EventStatusByte> {
self.scpi_send(com_cmd::ESR.to_command().query())?;
let mut b = self.read_bin()?;
let byte = EventStatusByte::new(b.get_u8());
Ok(byte)
}
fn get_status_byte(&mut self) -> Result<StatusByte> {
self.scpi_send(com_cmd::STB.to_command().query())?;
let mut b = self.read_bin()?;
let byte = StatusByte::new(b.get_u8());
Ok(byte)
}
fn set_event_mask<B: Into<u8>>(&mut self, byte: B) -> Result<()> {
self.scpi_send(com_cmd::ESE.to_command().para(byte.into().to_string()))
}
fn set_service_mask<B: Into<u8>>(&mut self, byte: B) -> Result<()> {
self.scpi_send(com_cmd::SRE.to_command().para(byte.into().to_string()))
}
}
#[derive(Debug, Clone)]
pub struct Command(String);
impl Command {
pub fn new<S: ToString>(s: S) -> Self {
Self(s.to_string())
}
pub fn query(&mut self) -> &mut Self {
self.0.push('?');
self
}
pub fn para<P: AsRef<str>>(&mut self, para: P) -> &mut Self {
self.0.push(' ');
self.0.push_str(para.as_ref());
self
}
pub fn into_inner(self) -> String {
self.0
}
}
impl AsRef<[u8]> for Command {
fn as_ref(&self) -> &[u8] {
self.0.as_bytes()
}
}
impl AsRef<str> for Command {
fn as_ref(&self) -> &str {
self.0.as_str()
}
}
impl<T: ToString> From<T> for Command {
fn from(s: T) -> Self {
Self(s.to_string())
}
}
pub trait ToCommand {
fn to_command(&self) -> Command;
}
impl<T> ToCommand for T
where
T: ToString,
{
fn to_command(&self) -> Command {
Command(self.to_string())
}
}
#[derive(Clone, Copy)]
pub struct StatusByte(u8);
impl fmt::Debug for StatusByte {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:>12}: {:#010b}", "Status Byte", self.0)
}
}
impl Into<u8> for StatusByte {
fn into(self) -> u8 {
self.0
}
}
impl StatusByte {
pub fn new(b: u8) -> Self {
Self(b)
}
pub fn byte(&self) -> u8 {
self.0
}
pub fn is_triggered(&self) -> bool {
self.0 & (1 << 0) == 0
}
pub fn triggered(&mut self) -> &mut Self {
self.0 &= 1 << 0;
self
}
pub fn is_displaying_message(&self) -> bool {
self.0 & (1 << 2) == 0
}
pub fn displaying_message(&mut self) -> &mut Self {
self.0 &= 1 << 2;
self
}
pub fn is_message_available(&self) -> bool {
self.0 & (1 << 4) == 0
}
pub fn message_available(&mut self) -> &mut Self {
self.0 &= 1 << 4;
self
}
pub fn is_event_happened(&self) -> bool {
self.0 & (1 << 5) == 0
}
pub fn event_happened(&mut self) -> &mut Self {
self.0 &= 1 << 5;
self
}
pub fn is_requesting_service(&self) -> bool {
self.0 & (1 << 6) == 0
}
}
#[derive(Clone, Copy)]
pub struct EventStatusByte(u8);
impl fmt::Debug for EventStatusByte {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:>12}: {:#010b}", "Event Byte", self.0)
}
}
impl Into<u8> for EventStatusByte {
fn into(self) -> u8 {
self.0
}
}
impl EventStatusByte {
pub fn new(b: u8) -> Self {
Self(b)
}
pub fn byte(&self) -> u8 {
self.0
}
pub fn is_command_err(&self) -> bool {
self.0 & (1 << 5) != 0
}
pub fn command_err(&mut self) -> &mut Self {
self.0 &= 1 << 5;
self
}
pub fn | (&self) -> bool {
self.0 & (1 << 3) != 0
}
pub fn device_dep_err(&mut self) -> &mut Self {
self.0 &= 1 << 3;
self
}
pub fn is_query_err(&self) -> bool {
self.0 & (1 << 2) != 0
}
pub fn query_err(&mut self) -> &mut Self {
self.0 &= 1 << 2;
self
}
pub fn is_opera_complete(&self) -> bool {
self.0 & (1 << 0) != 0
}
pub fn opera_complete(&mut self) -> &mut Self {
self.0 &= 1 << 0;
self
}
}
impl ToString for StatusByte {
fn to_string(&self) -> String {
self.0.to_string()
}
}
impl ToString for EventStatusByte {
fn to_string(&self) -> String {
self.0.to_string()
}
}
impl Scpi for super::protocols::onc_rpc::vxi11::Vxi11 {
fn read_bin(&mut self) -> Result<Bytes> {
self.device_read()
}
fn write_bin<C: AsRef<[u8]>>(&mut self, content: C) -> Result<()> {
let _n = self.device_write(content.as_ref())?;
Ok(())
}
}
| is_device_dep_err |
spof.py | #!/usr/bin/env python3
import sys
import io
def decompress(stream):
output = io.BytesIO()
planes = 0
while planes < 0x30 * 2:
favourite = stream.read(1)
control = stream.read(1)[0]
for x in range(8):
if control & 0x80:
output.write(stream.read(1))
else:
output.write(favourite)
control <<= 1
planes += 1
return output
def main():
|
if __name__ == '__main__':
main()
| with open(sys.argv[1], 'rb') as f:
f.seek(0x56e58000 + 0x38ab2)
output = decompress(f)
print('.byte ' + ','.join(f'${x:02x}' for x in output.getvalue())) |
predefined_attributes.go | package types
// PredefinedAttributes the predefined document attributes
// May be converted into HTML entities
var predefinedAttributes = []string{
"sp",
"blank",
"empty",
"nbsp",
"zwsp",
"wj",
"apos",
"quot",
"lsquo",
"rsquo",
"ldquo",
"rdquo",
"deg",
"plus",
"brvbar",
"vbar",
"amp",
"lt",
"gt", | "caret",
"asterisk",
"tilde",
"backslash",
"backtick",
"two-colons",
"two-semicolons",
"cpp",
}
func isPrefedinedAttribute(a string) bool {
for _, v := range predefinedAttributes {
if v == a {
return true
}
}
return false
} | "startsb",
"endsb", |
CanvasCard.js | import {
TagLabel,
Tag,
Text,
Stack,
Divider,
Link,
Image,
Skeleton,
useColorMode,
ScaleFade
} from '@chakra-ui/react'
import { useMediaQuery } from 'react-responsive';
import {
FaGithub,
FaPython,
FaDocker,
FaDatabase,
FaJs,
FaReact,
FaCode,
FaWhmcs,
FaExternalLinkAlt,
FaEthernet,
FaWaveSquare
} from 'react-icons/fa'
import ReactGA from 'react-ga'
import React, { useState } from 'react'
import { bgColor, primaryTextColor, iconColor, borderColor, secondaryTextColor, shadowColor } from '../styles/darkMode'
export default function | ({
imageURL,
title,
desc,
githubLink,
deployLink,
tag
}) {
const { colorMode } = useColorMode()
const [opacity, setOpacity] = useState(0)
const getTag = (tag) => {
let values = []
if (tag == 'Online') {
values[0] = 'blue'
}
else if (tag == 'Sold') {
values[0] = 'red'
}
else if (tag == 'For Sale') {
values[0] = 'green'
}
else {
values[0] = 'gray'
}
return values
}
const isBigScreen = useMediaQuery({ minWidth: 600 });
const Tags = tag.map((item) => (
<Tag
key={item}
colorScheme={getTag(item)[0]}
size={isBigScreen ? 'md' : 'sm'}
>
<TagLabel>{item}</TagLabel>
</Tag>
))
const handleClick = (event) => {
ReactGA.event({
category: 'click',
action: event,
})
}
const [imageLoad, setImageLoad] = useState(false);
return (
<Link
href={deployLink}
title={title}
style={{ textDecoration: 'none' }}
>
<Stack
bg="secondary"
borderRadius="10px"
minH="320px"
maxH="500px"
maxW="350px"
border="1px"
borderColor={{ base: '#333', md: borderColor[colorMode] }}
transition="0.3s"
_hover={{
boxShadow: shadowColor[colorMode],
textDecoration: 'none'
}}
mt={4}
onMouseOver={() => setOpacity(1)}
onMouseLeave={() => setOpacity(0)}
>
<ScaleFade in={true} transition={{ duration: 1 }}>
<Skeleton isLoaded={imageLoad} m='1' borderRadius="10px 10px 0px 0px">
<Image
width={375}
height={375}
w="auto"
h="auto"
src={imageURL}
transition="0.3s"
borderRadius="10px 10px 0px 0px"
alt="project image"
onLoad={() => setImageLoad(true)}
></Image>
</Skeleton>
<Stack px={4} py={2}>
<Stack isInline justifyContent="space-between" alignItems="center">
<Text fontSize="2xl" color={primaryTextColor[colorMode]}>
<strong>{title}</strong>
</Text>
{Tags}
</Stack>
<Divider />
<Text color={secondaryTextColor[colorMode]} fontSize={['sm', 'sm']}>
{desc}
</Text>
</Stack>
</ScaleFade>
</Stack>
</Link>
)
} | CanvasCard |
clicolor.js | // Return colored cli text
var colors = {
auto: "\x1b[0m",
blink: "\x1b[5m",
bright: "\x1b[1m",
dim: "\x1b[2m",
hide: "\x1b[8m",
inverse: "\x1b[7m",
underline: "\x1b[4m",
black: "\x1b[30m",
blue: "\x1b[34m",
cyan: "\x1b[36m",
green: "\x1b[32m",
magenta: "\x1b[35m",
red: "\x1b[31m",
white: "\x1b[37m",
yellow: "\x1b[33m",
bgblack: "\x1b[40m",
bgblue: "\x1b[44m",
bgcyan: "\x1b[46m",
bggreen: "\x1b[42m",
bgmagenta: "\x1b[45m",
bgred: "\x1b[41m",
bgwhite: "\x1b[47m",
bgyellow: "\x1b[43m"
}
function CLIColor(color, text) {
var str = colors.auto;
text = text || '';
text = text.toString();
color = color || '';
if (typeof color == 'string')
color = color.split(' ');
color.forEach(function(c){
c = c.trim(); | typeof colors[c]
!== 'undefined'
) { str += colors[c]; }
});
str += text;
str += colors.auto;
return str;
}; | if ( |
authenticator_test.go | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 authr_test
import (
"context"
"errors"
"github.com/go-chassis/go-archaius"
"github.com/go-chassis/go-chassis/security/authr"
"github.com/stretchr/testify/assert"
"log"
"testing"
)
type insecureAuthenticator struct {
}
func newInsecureAuth(opts *authr.Options) (authr.Authenticator, error) |
func (a *insecureAuthenticator) Login(ctx context.Context, user string, password string, opts ...authr.LoginOption) (string, error) {
opt := &authr.LoginOptions{}
for _, o := range opts {
o(opt)
}
log.Println(opt.ExpireAfter)
if user == archaius.GetString("username", "") && password == archaius.GetString("password", "") {
return "token", nil
}
return "", errors.New("wrong credential")
}
func (a *insecureAuthenticator) Authenticate(ctx context.Context, token string) (interface{}, error) {
return archaius.GetString("username", ""), nil
}
func TestLogin(t *testing.T) {
ctx := context.Background()
archaius.Init(archaius.WithMemorySource())
archaius.Set("username", "admin")
archaius.Set("password", "admin")
authr.Install("default", newInsecureAuth)
authr.Init()
token, _ := authr.Login(ctx, "admin", "admin", authr.ExpireAfter("1s"))
assert.Equal(t, "token", token)
claims, _ := authr.Authenticate(ctx, "token")
assert.Equal(t, "admin", claims)
}
| {
return &insecureAuthenticator{}, nil
} |
AblationExperiment.py | import gym, torch, copy, os, xlwt, random
import torch.nn as nn
from datetime import datetime
import numpy as np
env = gym.make("clusterEnv-v0").unwrapped
state_dim, action_dim = env.return_dim_info()
####### initialize environment hyperparameters ######
max_ep_len = 1000 # max timesteps in one episode
auto_save = 1
total_test_episodes = 100 * auto_save # total num of testing episodes
def initial_excel():
global worksheet, workbook
# xlwt 库将数据导入Excel并设置默认字符编码为ascii
workbook = xlwt.Workbook(encoding='ascii')
# 添加一个表 参数为表名
worksheet = workbook.add_sheet('makespan')
# 生成单元格样式的方法
# 设置列宽, 3为列的数目, 12为列的宽度, 256为固定值
for i in range(3):
worksheet.col(i).width = 256 * 12
# 设置单元格行高, 25为行高, 20为固定值
worksheet.row(1).height_mismatch = True
worksheet.row(1).height = 20 * 25
# 保存excel文件
workbook.save('data/makespan_MCTSAE.xls')
def read_current_state():
'''
读取当前env的状态
:return: 当前env的状态
'''
state = copy.deepcopy(env.state)
ready_list = copy.deepcopy(env.ready_list)
done_job = copy.deepcopy(env.done_job)
tasks = copy.deepcopy(env.tasks)
wait_duration = copy.deepcopy(env.wait_duration)
cpu_demand = copy.deepcopy(env.cpu_demand)
memory_demand = copy.deepcopy(env.memory_demand)
tasks_remaing_time = copy.deepcopy(env.tasks_remaing_time)
time = env.time
cpu_res = env.cpu_res
memory_res = env.memory_res
return state, ready_list, done_job, tasks, wait_duration, cpu_demand, memory_demand, tasks_remaing_time, cpu_res, memory_res, time
def load_current_state(state, ready_list, done_job, tasks, wait_duration, cpu_demand, memory_demand, tasks_remaing_time,
cpu_res, memory_res, time):
env.set_state(state[:])
env.set_ready_list(ready_list[:])
env.set_done_job(done_job[:])
env.set_tasks(tasks[:])
env.set_wait_duration(wait_duration[:])
env.set_cpu_demand(cpu_demand[:])
env.set_memory_demand(memory_demand[:])
env.set_tasks_remaing_time(tasks_remaing_time)
env.set_cpu_res(cpu_res)
env.set_memory_res(memory_res)
env.set_time(time)
return
class TreeNode(object):
def __init__(self, parent, state, ready_list, done_job, tasks, wait_duration, cpu_demand, memory_demand,
tasks_remaing_time, cpu_res, memory_res, time):
self._parent = parent
self._children = {} # a map from action to TreeNode
self._n_visits = 0
self._makespan = 0
self._total_makespan = 0
self._state = state
self._ready_list = ready_list
self._done_job = done_job
self._tasks = tasks
self._wait_duration = wait_duration
self._cpu_demand = cpu_demand
self._memory_demand = memory_demand
self._tasks_remaing_time = tasks_remaing_time
self._cpu_res = cpu_res
self._memory_res = memory_res
self._time = time
self._c = 40
self._value = 0
if self._parent != None:
self.get_value()
def expand(self):
'''
扩展树
'''
load_current_state(self._state, self._ready_list, self._done_job, self._tasks, self._wait_duration,
self._cpu_demand, self._memory_demand, self._tasks_remaing_time, self._cpu_res,
self._memory_res, self._time)
available_action = env.return_action_list()
if available_action:
for action in available_action:
load_current_state(self._state, self._ready_list, self._done_job, self._tasks, self._wait_duration,
self._cpu_demand, self._memory_demand, self._tasks_remaing_time, self._cpu_res,
self._memory_res, self._time)
if action not in self._children:
env.step(action)
state, ready_list, done_job, tasks, wait_duration, cpu_demand, memory_demand, tasks_remaing_time, cpu_res, memory_res, time = read_current_state()
self._children[action] = TreeNode(self, state, ready_list, done_job, tasks, wait_duration,
cpu_demand, memory_demand, tasks_remaing_time, cpu_res,
memory_res, time)
else:
print("done")
def get_average_makespan(self):
return self._makespan
def get_value(self):
self._value = self._makespan + self._c * np.sqrt(np.log(self._parent._n_visits + 1) / (self._n_visits + 1))
return self._value
def select(self):
'''
在子节中选择具有搜索价值的点
'''
return max(self._children.items(), key=lambda act_node: act_node[1].get_value())[1]
def update(self, makespan):
# Count visit.
self._n_visits += 1
if self._makespan == 0:
self._makespan = -makespan
else: | if self._parent != None:
self._value = self.get_value()
def update_recursive(self, leaf_value):
# If it is not root, this node's parent should be updated first.
if self._parent:
self._parent.update_recursive(leaf_value)
self.update(leaf_value)
def is_leaf(self):
return self._children == {}
def is_root(self):
return self._parent is None
class MCTS(object):
def __init__(self, state, ready_list, done_job, tasks, wait_duration, cpu_demand, memory_demand, tasks_remaing_time,
cpu_res, memory_res, time, depth):
self._root = TreeNode(None, state, ready_list, done_job, tasks, wait_duration, cpu_demand, memory_demand,
tasks_remaing_time, cpu_res, memory_res, time)
self._root.expand() # 初始化扩展
self._initial_buget = 100
self._min_buget = 10
self._depth = depth
def playout(self):
buget = max(self._initial_buget / self._depth, self._min_buget)
for j in range(int(buget)):
node = self._root
while True:
if node.is_leaf():
if node._n_visits == 0:
cur_state, cur_ready_list, cur_done_job, cur_tasks, cur_wait_duration, cur_cpu_demand, cur_memory_demand, cur_tasks_remaing_time, cur_cpu_res, cur_memory_res, cur_time = node._state, node._ready_list, node._done_job, node._tasks, node._wait_duration, node._cpu_demand, node._memory_demand, node._tasks_remaing_time, node._cpu_res, node._memory_res, node._time
makespan = self._roll_out(cur_state, cur_ready_list, cur_done_job, cur_tasks, cur_wait_duration,
cur_cpu_demand, cur_memory_demand, cur_tasks_remaing_time,
cur_cpu_res, cur_memory_res, cur_time)
node.update_recursive(makespan)
break
else:
node.expand()
node = node.select()
else:
node = node.select()
node = self._root
return max(node._children.items(), key=lambda act_node: act_node[1].get_average_makespan())[0]
def _roll_out(self, cur_state, cur_ready_list, cur_done_job, cur_tasks, cur_wait_duration, cur_cpu_demand,
cur_memory_demand, cur_tasks_remaing_time, cur_cpu_res, cur_memory_res, cur_time):
load_current_state(cur_state, cur_ready_list, cur_done_job, cur_tasks, cur_wait_duration, cur_cpu_demand,
cur_memory_demand, cur_tasks_remaing_time, cur_cpu_res, cur_memory_res, cur_time)
state = cur_state
max_ep_len = 1000 # max timesteps in one episode
for t in range(1, max_ep_len + 1):
action = random.choice(range(action_dim)) - 1
state, reward, done, info = env.step(action)
while (info[0] == False):
action = random.choice(range(action_dim)) - 1
state, reward, done, info = env.step(action) # 输入step的都是
next_state, reward, done, _ = state, reward, done, info
# break; if the episode is over
state = next_state
if done:
makespan = state[0]
break
return makespan
if __name__ == '__main__':
initial_excel()
makespans = []
line = 0
start_time = datetime.now().replace(microsecond=0)
print("Started training at (GMT) : ", start_time)
print("============================================================================================")
for ep in range(1, total_test_episodes + 1):
initial_state = env.reset()
state, ready_list, done_job, tasks, wait_duration, cpu_demand, memory_demand, tasks_remaing_time, cpu_res, memory_res, time = read_current_state()
for depth in range(1, max_ep_len + 1):
tree = MCTS(state, ready_list, done_job, tasks, wait_duration, cpu_demand, memory_demand,
tasks_remaing_time, cpu_res, memory_res, time, depth=depth)
best_action = tree.playout()
load_current_state(tree._root._state, tree._root._ready_list, tree._root._done_job, tree._root._tasks,
tree._root._wait_duration, tree._root._cpu_demand, tree._root._memory_demand,
tree._root._tasks_remaing_time, tree._root._cpu_res, tree._root._memory_res,
tree._root._time)
observation, reward, done, info = env.step(best_action)
state, ready_list, done_job, tasks, wait_duration, cpu_demand, memory_demand, tasks_remaing_time, cpu_res, memory_res, time = read_current_state()
del tree
if done:
makespan = observation[0]
makespans.append(makespan)
print("Episode:", ep, "Makespan:", makespan)
if ep % auto_save == 0:
average_makespan = np.mean(makespans)
worksheet.write(line, 1, float(average_makespan))
workbook.save('data/makespan_MCTSAE.xls')
print('MCTS : Episode: {}, Makespan: {:.3f}s'.format((line + 1) * auto_save, average_makespan))
line += 1
makespans = []
end_time = datetime.now().replace(microsecond=0)
print("Finished testing at (GMT) : ", end_time)
print("Total testing time : ", end_time - start_time)
start_time = end_time
break
workbook.save('data/makespan_MCTSAE.xls')
env.close() | if -makespan > self._makespan:
self._makespan = -makespan |
profile-user.component.ts | import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { DataService } from './../data.service';
import { MatSnackBar } from '@angular/material';
import { Router } from '@angular/router';
@Component({
selector: 'app-profile-user',
templateUrl: './profile-user.component.html',
styleUrls: ['./profile-user.component.css']
})
export class | implements OnInit {
firstName: any;
lastName: any;
username: any;
email: any;
password: any;
rePassword: any;
hide: boolean;
dataPerson: any;
imagePerson: any;
avatar: any;
base64Image: any;
openedImage: boolean;
canSaveImage: boolean;
constructor(
private dataService: DataService,
private snackBar: MatSnackBar,
private router: Router
) {
this.firstName = new FormControl('', [Validators.required]);
this.lastName = new FormControl('', [Validators.required]);
this.username = new FormControl('', [Validators.required]);
this.email = new FormControl('', [Validators.required, Validators.email]);
this.password = new FormControl('', [Validators.required]);
this.rePassword = new FormControl('', [Validators.required]);
this.avatar = new FormControl(null);
}
ngOnInit() {
this.hide = true;
this.openedImage = false;
this.canSaveImage = false;
this.obtainDataPerson();
}
getErrorMessage() {
if (this.firstName.hasError('required') || this.lastName.hasError('required')
|| this.username.hasError('required') || this.email.hasError('required')) {
return 'Debe completar este campo';
} else {
return '';
}
}
obtainDataPerson() {
this.dataService.getUserData(localStorage.getItem('person_id')).subscribe(
response => {
this.dataPerson = response.json();
this.firstName.setValue(this.dataPerson.user.first_name);
this.lastName.setValue(this.dataPerson.user.last_name);
this.username.setValue(this.dataPerson.user.username);
this.email.setValue(this.dataPerson.user.email);
if (this.dataPerson.person_image === 'Sin imagen') {
this.imagePerson = 'http://alarishealth.com/wp-content/uploads/2014/06/no-user.png';
} else {
this.imagePerson = 'http://' + this.dataPerson.person_image;
}
}
);
}
onFileChange(event) {
const reader = new FileReader();
if (event.target.files && event.target.files.length > 0) {
const file = event.target.files[0];
reader.readAsDataURL(file);
reader.onload = () => {
this.canSaveImage = true;
this.base64Image = reader.result;
};
}
}
changeImagePerson() {
if (this.canSaveImage) {
this.dataService.uploadImage(localStorage.getItem('person_id'), this.base64Image).subscribe(
response => {
this.canSaveImage = false;
this.snackBar.open('Se guardó su foto de perfil con éxito', '', {
duration: 2000,
});
location.reload();
}
);
} else {
this.snackBar.open('No ha elegido ninguna imagen', '', {
duration: 2000,
});
}
}
openImageChooser() {
this.openedImage = true;
}
cancelImageAction() {
this.openedImage = false;
}
updateProfile() {
console.log('Missing functionality');
}
}
| ProfileUserComponent |
mapbox-gl.js | /* Mapbox GL JS is licensed under the 3-Clause BSD License. Full text of license: https://github.com/mapbox/mapbox-gl-js/blob/v1.8.1/LICENSE.txt */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.mapboxgl = factory());
}(this, (function () { 'use strict';
/* eslint-disable */
var shared, worker, mapboxgl;
// define gets called three times: one for each chunk. we rely on the order
// they're imported to know which is which
function define(_, chunk) {
if (!shared) {
shared = chunk;
} else if (!worker) {
worker = chunk;
} else {
var workerBundleString = 'var sharedChunk = {}; (' + shared + ')(sharedChunk); (' + worker + ')(sharedChunk);'
var sharedChunk = {};
shared(sharedChunk);
mapboxgl = chunk(sharedChunk);
mapboxgl.workerUrl = window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }));
}
}
define(["exports"],(function(t){"use strict";function e(t,e){return t(e={exports:{}},e.exports),e.exports}var r=n;function n(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=n,this.p2x=r,this.p2y=n;}n.prototype.sampleCurveX=function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},n.prototype.sampleCurveY=function(t){return ((this.ay*t+this.by)*t+this.cy)*t},n.prototype.sampleCurveDerivativeX=function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},n.prototype.solveCurveX=function(t,e){var r,n,i,a,o;for(void 0===e&&(e=1e-6),i=t,o=0;o<8;o++){if(a=this.sampleCurveX(i)-t,Math.abs(a)<e)return i;var s=this.sampleCurveDerivativeX(i);if(Math.abs(s)<1e-6)break;i-=a/s;}if((i=t)<(r=0))return r;if(i>(n=1))return n;for(;r<n;){if(a=this.sampleCurveX(i),Math.abs(a-t)<e)return i;t>a?r=i:n=i,i=.5*(n-r)+r;}return i},n.prototype.solve=function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))};var i=a;function a(t,e){this.x=t,this.y=e;}function o(t,e,n,i){var a=new r(t,e,n,i);return function(t){return a.solve(t)}}a.prototype={clone:function(){return new a(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[0]*this.x+t[1]*this.y,r=t[2]*this.x+t[3]*this.y;return this.x=e,this.y=r,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),r=Math.sin(t),n=e*this.x-r*this.y,i=r*this.x+e*this.y;return this.x=n,this.y=i,this},_rotateAround:function(t,e){var r=Math.cos(t),n=Math.sin(t),i=e.x+r*(this.x-e.x)-n*(this.y-e.y),a=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=i,this.y=a,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},a.convert=function(t){return t instanceof a?t:Array.isArray(t)?new a(t[0],t[1]):t};var s=o(.25,.1,.25,1);function u(t,e,r){return Math.min(r,Math.max(e,t))}function l(t,e,r){var n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function p(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n<i.length;n+=1){var a=i[n];for(var o in a)t[o]=a[o];}return t}var c=1;function h(){return c++}function f(){return function t(e){return e?(e^16*Math.random()>>e/4).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,t)}()}function y(t){return !!t&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t)}function d(t,e){t.forEach((function(t){e[t]&&(e[t]=e[t].bind(e));}));}function m(t,e){return -1!==t.indexOf(e,t.length-e.length)}function v(t,e,r){var n={};for(var i in t)n[i]=e.call(r||this,t[i],i,t);return n}function g(t,e,r){var n={};for(var i in t)e.call(r||this,t[i],i,t)&&(n[i]=t[i]);return n}function x(t){return Array.isArray(t)?t.map(x):"object"==typeof t&&t?v(t,x):t}var b={};function _(t){b[t]||("undefined"!=typeof console&&console.warn(t),b[t]=!0);}function w(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function A(t){for(var e=0,r=0,n=t.length,i=n-1,a=void 0,o=void 0;r<n;i=r++)a=t[r],e+=((o=t[i]).x-a.x)*(a.y+o.y);return e}function S(){return "undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope}function k(t){var e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(function(t,r,n,i){var a=n||i;return e[r]=!a||a.toLowerCase(),""})),e["max-age"]){var r=parseInt(e["max-age"],10);isNaN(r)?delete e["max-age"]:e["max-age"]=r;}return e}var I=null;function z(t){if(null==I){var e=t.navigator?t.navigator.userAgent:null;I=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return I}function C(t){try{var e=self[t];return e.setItem("_mapbox_test_",1),e.removeItem("_mapbox_test_"),!0}catch(t){return !1}}var T,E,M,B,P=self.performance&&self.performance.now?self.performance.now.bind(self.performance):Date.now.bind(Date),V=self.requestAnimationFrame||self.mozRequestAnimationFrame||self.webkitRequestAnimationFrame||self.msRequestAnimationFrame,F=self.cancelAnimationFrame||self.mozCancelAnimationFrame||self.webkitCancelAnimationFrame||self.msCancelAnimationFrame,L={now:P,frame:function(t){var e=V(t);return {cancel:function(){return F(e)}}},getImageData:function(t,e){void 0===e&&(e=0);var r=self.document.createElement("canvas"),n=r.getContext("2d");if(!n)throw new Error("failed to create canvas 2d context");return r.width=t.width,r.height=t.height,n.drawImage(t,0,0,t.width,t.height),n.getImageData(-e,-e,t.width+2*e,t.height+2*e)},resolveURL:function(t){return T||(T=self.document.createElement("a")),T.href=t,T.href},hardwareConcurrency:self.navigator.hardwareConcurrency||4,get devicePixelRatio(){return self.devicePixelRatio},get prefersReducedMotion(){return !!self.matchMedia&&(null==E&&(E=self.matchMedia("(prefers-reduced-motion: reduce)")),E.matches)}},D={API_URL:"https://api.mapbox.com",get EVENTS_URL(){return this.API_URL?0===this.API_URL.indexOf("https://api.mapbox.cn")?"https://events.mapbox.cn/events/v2":0===this.API_URL.indexOf("https://api.mapbox.com")?"https://events.mapbox.com/events/v2":null:null},FEEDBACK_URL:"https://apps.mapbox.com/feedback",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null,MAX_PARALLEL_IMAGE_REQUESTS:16},O={supported:!1,testSupport:function(t){if(R||!B)return;U?j(t):M=t;}},R=!1,U=!1;function j(t){var e=t.createTexture();t.bindTexture(t.TEXTURE_2D,e);try{if(t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,B),t.isContextLost())return;O.supported=!0;}catch(t){}t.deleteTexture(e),R=!0;}self.document&&((B=self.document.createElement("img")).onload=function(){M&&j(M),M=null,U=!0;},B.onerror=function(){R=!0,M=null;},B.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");var q="01";var N=function(t,e){this._transformRequestFn=t,this._customAccessToken=e,this._createSkuToken();};function K(t){return 0===t.indexOf("mapbox:")}N.prototype._createSkuToken=function(){var t=function(){for(var t="",e=0;e<10;e++)t+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return {token:["1",q,t].join(""),tokenExpiresAt:Date.now()+432e5}}();this._skuToken=t.token,this._skuTokenExpiresAt=t.tokenExpiresAt;},N.prototype._isSkuTokenExpired=function(){return Date.now()>this._skuTokenExpiresAt},N.prototype.transformRequest=function(t,e){return this._transformRequestFn&&this._transformRequestFn(t,e)||{url:t}},N.prototype.normalizeStyleURL=function(t,e){if(!K(t))return t;var r=J(t);return r.path="/styles/v1"+r.path,this._makeAPIURL(r,this._customAccessToken||e)},N.prototype.normalizeGlyphsURL=function(t,e){if(!K(t))return t;var r=J(t);return r.path="/fonts/v1"+r.path,this._makeAPIURL(r,this._customAccessToken||e)},N.prototype.normalizeSourceURL=function(t,e){if(!K(t))return t;var r=J(t);return r.path="/v4/"+r.authority+".json",r.params.push("secure"),this._makeAPIURL(r,this._customAccessToken||e)},N.prototype.normalizeSpriteURL=function(t,e,r,n){var i=J(t);return K(t)?(i.path="/styles/v1"+i.path+"/sprite"+e+r,this._makeAPIURL(i,this._customAccessToken||n)):(i.path+=""+e+r,Y(i))},N.prototype.normalizeTileURL=function(t,e){if(this._isSkuTokenExpired()&&this._createSkuToken(),t&&!K(t))return t;var r=J(t),n=L.devicePixelRatio>=2||512===e?"@2x":"",i=O.supported?".webp":"$1";r.path=r.path.replace(/(\.(png|jpg)\d*)(?=$)/,""+n+i),r.path=r.path.replace(/^.+\/v4\//,"/"),r.path="/v4"+r.path;var a=this._customAccessToken||function(t){for(var e=0,r=t;e<r.length;e+=1){var n=r[e].match(/^access_token=(.*)$/);if(n)return n[1]}return null}(r.params)||D.ACCESS_TOKEN;return D.REQUIRE_ACCESS_TOKEN&&a&&this._skuToken&&r.params.push("sku="+this._skuToken),this._makeAPIURL(r,a)},N.prototype.canonicalizeTileURL=function(t,e){var r=J(t);if(!r.path.match(/(^\/v4\/)/)||!r.path.match(/\.[\w]+$/))return t;var n="mapbox://tiles/";n+=r.path.replace("/v4/","");var i=r.params;return e&&(i=i.filter((function(t){return !t.match(/^access_token=/)}))),i.length&&(n+="?"+i.join("&")),n},N.prototype.canonicalizeTileset=function(t,e){for(var r=!!e&&K(e),n=[],i=0,a=t.tiles||[];i<a.length;i+=1){var o=a[i];Z(o)?n.push(this.canonicalizeTileURL(o,r)):n.push(o);}return n},N.prototype._makeAPIURL=function(t,e){var r="See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes",n=J(D.API_URL);if(t.protocol=n.protocol,t.authority=n.authority,"/"!==n.path&&(t.path=""+n.path+t.path),!D.REQUIRE_ACCESS_TOKEN)return Y(t);if(!(e=e||D.ACCESS_TOKEN))throw new Error("An API access token is required to use Mapbox GL. "+r);if("s"===e[0])throw new Error("Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). "+r);return t.params=t.params.filter((function(t){return -1===t.indexOf("access_token")})),t.params.push("access_token="+e),Y(t)};var X=/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/|\?|$)/i;function Z(t){return X.test(t)}var G=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function J(t){var e=t.match(G);if(!e)throw new Error("Unable to parse URL object");return {protocol:e[1],authority:e[2],path:e[3]||"/",params:e[4]?e[4].split("&"):[]}}function Y(t){var e=t.params.length?"?"+t.params.join("&"):"";return t.protocol+"://"+t.authority+t.path+e}function H(t){if(!t)return null;var e,r=t.split(".");if(!r||3!==r.length)return null;try{return JSON.parse((e=r[1],decodeURIComponent(self.atob(e).split("").map((function(t){return "%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})).join(""))))}catch(t){return null}}var $=function(t){this.type=t,this.anonId=null,this.eventData={},this.queue=[],this.pendingRequest=null;};$.prototype.getStorageKey=function(t){var e,r=H(D.ACCESS_TOKEN),n="";return r&&r.u?(e=r.u,n=self.btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(function(t,e){return String.fromCharCode(Number("0x"+e))})))):n=D.ACCESS_TOKEN||"",t?"mapbox.eventData."+t+":"+n:"mapbox.eventData:"+n},$.prototype.fetchEventData=function(){var t=C("localStorage"),e=this.getStorageKey(),r=this.getStorageKey("uuid");if(t)try{var n=self.localStorage.getItem(e);n&&(this.eventData=JSON.parse(n));var i=self.localStorage.getItem(r);i&&(this.anonId=i);}catch(t){_("Unable to read from LocalStorage");}},$.prototype.saveEventData=function(){var t=C("localStorage"),e=this.getStorageKey(),r=this.getStorageKey("uuid");if(t)try{self.localStorage.setItem(r,this.anonId),Object.keys(this.eventData).length>=1&&self.localStorage.setItem(e,JSON.stringify(this.eventData));}catch(t){_("Unable to write to LocalStorage");}},$.prototype.processRequests=function(t){},$.prototype.postEvent=function(t,e,r,n){var i=this;if(D.EVENTS_URL){var a=J(D.EVENTS_URL);a.params.push("access_token="+(n||D.ACCESS_TOKEN||""));var o={event:this.type,created:new Date(t).toISOString(),sdkIdentifier:"mapbox-gl-js",sdkVersion:"1.8.1",skuId:q,userId:this.anonId},s=e?p(o,e):o,u={url:Y(a),headers:{"Content-Type":"text/plain"},body:JSON.stringify([s])};this.pendingRequest=wt(u,(function(t){i.pendingRequest=null,r(t),i.saveEventData(),i.processRequests(n);}));}},$.prototype.queueRequest=function(t,e){this.queue.push(t),this.processRequests(e);};var W,Q,tt=function(t){function e(){t.call(this,"map.load"),this.success={},this.skuToken="";}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.postMapLoadEvent=function(t,e,r,n){this.skuToken=r,(D.EVENTS_URL&&n||D.ACCESS_TOKEN&&Array.isArray(t)&&t.some((function(t){return K(t)||Z(t)})))&&this.queueRequest({id:e,timestamp:Date.now()},n);},e.prototype.processRequests=function(t){var e=this;if(!this.pendingRequest&&0!==this.queue.length){var r=this.queue.shift(),n=r.id,i=r.timestamp;n&&this.success[n]||(this.anonId||this.fetchEventData(),y(this.anonId)||(this.anonId=f()),this.postEvent(i,{skuToken:this.skuToken},(function(t){t||n&&(e.success[n]=!0);}),t));}},e}($),et=new(function(t){function e(e){t.call(this,"appUserTurnstile"),this._customAccessToken=e;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.postTurnstileEvent=function(t,e){D.EVENTS_URL&&D.ACCESS_TOKEN&&Array.isArray(t)&&t.some((function(t){return K(t)||Z(t)}))&&this.queueRequest(Date.now(),e);},e.prototype.processRequests=function(t){var e=this;if(!this.pendingRequest&&0!==this.queue.length){this.anonId&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();var r=H(D.ACCESS_TOKEN),n=r?r.u:D.ACCESS_TOKEN,i=n!==this.eventData.tokenU;y(this.anonId)||(this.anonId=f(),i=!0);var a=this.queue.shift();if(this.eventData.lastSuccess){var o=new Date(this.eventData.lastSuccess),s=new Date(a),u=(a-this.eventData.lastSuccess)/864e5;i=i||u>=1||u<-1||o.getDate()!==s.getDate();}else i=!0;if(!i)return this.processRequests();this.postEvent(a,{"enabled.telemetry":!1},(function(t){t||(e.eventData.lastSuccess=a,e.eventData.tokenU=n);}),t);}},e}($)),rt=et.postTurnstileEvent.bind(et),nt=new tt,it=nt.postMapLoadEvent.bind(nt),at="mapbox-tiles",ot=500,st=50,ut=42e4;function lt(){self.caches&&!W&&(W=self.caches.open(at));}function pt(t,e,r){if(lt(),W){var n={status:e.status,statusText:e.statusText,headers:new self.Headers};e.headers.forEach((function(t,e){return n.headers.set(e,t)}));var i=k(e.headers.get("Cache-Control")||"");if(!i["no-store"])i["max-age"]&&n.headers.set("Expires",new Date(r+1e3*i["max-age"]).toUTCString()),new Date(n.headers.get("Expires")).getTime()-r<ut||function(t,e){if(void 0===Q)try{new Response(new ReadableStream),Q=!0;}catch(t){Q=!1;}Q?e(t.body):t.blob().then(e);}(e,(function(e){var r=new self.Response(e,n);lt(),W&&W.then((function(e){return e.put(ct(t.url),r)})).catch((function(t){return _(t.message)}));}));}}function ct(t){var e=t.indexOf("?");return e<0?t:t.slice(0,e)}function ht(t,e){if(lt(),!W)return e(null);var r=ct(t.url);W.then((function(t){t.match(r).then((function(n){var i=function(t){if(!t)return !1;var e=new Date(t.headers.get("Expires")||0),r=k(t.headers.get("Cache-Control")||"");return e>Date.now()&&!r["no-cache"]}(n);t.delete(r),i&&t.put(r,n.clone()),e(null,n,i);})).catch(e);})).catch(e);}var ft,yt=1/0;function dt(){return null==ft&&(ft=self.OffscreenCanvas&&new self.OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof self.createImageBitmap),ft}var mt={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Image:"Image"};"function"==typeof Object.freeze&&Object.freeze(mt);var vt=function(t){function e(e,r,n){401===r&&Z(n)&&(e+=": you may have provided an invalid Mapbox access token. See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes"),t.call(this,e),this.status=r,this.url=n,this.name=this.constructor.name,this.message=e;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.toString=function(){return this.name+": "+this.message+" ("+this.status+"): "+this.url},e}(Error),gt=S()?function(){return self.worker&&self.worker.referrer}:function(){return ("blob:"===self.location.protocol?self.parent:self).location.href};function xt(t,e){var r,n=new self.AbortController,i=new self.Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,referrer:gt(),signal:n.signal}),a=!1,o=!1,s=(r=i.url).indexOf("sku=")>0&&Z(r);"json"===t.type&&i.headers.set("Accept","application/json");var u=function(r,n,a){if(!o){if(r&&"SecurityError"!==r.message&&_(r),n&&a)return l(n);var u=Date.now();self.fetch(i).then((function(r){if(r.ok){var n=s?r.clone():null;return l(r,n,u)}return e(new vt(r.statusText,r.status,t.url))})).catch((function(t){20!==t.code&&e(new Error(t.message));}));}},l=function(r,n,s){("arrayBuffer"===t.type?r.arrayBuffer():"json"===t.type?r.json():r.text()).then((function(t){o||(n&&s&&pt(i,n,s),a=!0,e(null,t,r.headers.get("Cache-Control"),r.headers.get("Expires")));})).catch((function(t){o||e(new Error(t.message));}));};return s?ht(i,u):u(null,null),{cancel:function(){o=!0,a||n.abort();}}}var bt=function(t,e){if(r=t.url,!(/^file:/.test(r)||/^file:/.test(gt())&&!/^\w+:/.test(r))){if(self.fetch&&self.Request&&self.AbortController&&self.Request.prototype.hasOwnProperty("signal"))return xt(t,e);if(S()&&self.worker&&self.worker.actor){return self.worker.actor.send("getResource",t,e,void 0,!0)}}var r;return function(t,e){var r=new self.XMLHttpRequest;for(var n in r.open(t.method||"GET",t.url,!0),"arrayBuffer"===t.type&&(r.responseType="arraybuffer"),t.headers)r.setRequestHeader(n,t.headers[n]);return "json"===t.type&&(r.responseType="text",r.setRequestHeader("Accept","application/json")),r.withCredentials="include"===t.credentials,r.onerror=function(){e(new Error(r.statusText));},r.onload=function(){if((r.status>=200&&r.status<300||0===r.status)&&null!==r.response){var n=r.response;if("json"===t.type)try{n=JSON.parse(r.response);}catch(t){return e(t)}e(null,n,r.getResponseHeader("Cache-Control"),r.getResponseHeader("Expires"));}else e(new vt(r.statusText,r.status,t.url));},r.send(t.body),{cancel:function(){return r.abort()}}}(t,e)},_t=function(t,e){return bt(p(t,{type:"arrayBuffer"}),e)},wt=function(t,e){return bt(p(t,{method:"POST"}),e)};var At,St,kt="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";At=[],St=0;var It=function(t,e){if(O.supported&&(t.headers||(t.headers={}),t.headers.accept="image/webp,*/*"),St>=D.MAX_PARALLEL_IMAGE_REQUESTS){var r={requestParameters:t,callback:e,cancelled:!1,cancel:function(){this.cancelled=!0;}};return At.push(r),r}St++;var n=!1,i=function(){if(!n)for(n=!0,St--;At.length&&St<D.MAX_PARALLEL_IMAGE_REQUESTS;){var t=At.shift(),e=t.requestParameters,r=t.callback;t.cancelled||(t.cancel=It(e,r).cancel);}},a=_t(t,(function(t,r,n,a){i(),t?e(t):r&&(dt()?function(t,e){var r=new self.Blob([new Uint8Array(t)],{type:"image/png"});self.createImageBitmap(r).then((function(t){e(null,t);})).catch((function(t){e(new Error("Could not load image because of "+t.message+". Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));}));}(r,e):function(t,e,r,n){var i=new self.Image,a=self.URL;i.onload=function(){e(null,i),a.revokeObjectURL(i.src);},i.onerror=function(){return e(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."))};var o=new self.Blob([new Uint8Array(t)],{type:"image/png"});i.cacheControl=r,i.expires=n,i.src=t.byteLength?a.createObjectURL(o):kt;}(r,e,n,a));}));return {cancel:function(){a.cancel(),i();}}};function zt(t,e,r){r[t]&&-1!==r[t].indexOf(e)||(r[t]=r[t]||[],r[t].push(e));}function Ct(t,e,r){if(r&&r[t]){var n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}var Tt=function(t,e){void 0===e&&(e={}),p(this,e),this.type=t;},Et=function(t){function e(e,r){void 0===r&&(r={}),t.call(this,"error",p({error:e},r));}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Tt),Mt=function(){};Mt.prototype.on=function(t,e){return this._listeners=this._listeners||{},zt(t,e,this._listeners),this},Mt.prototype.off=function(t,e){return Ct(t,e,this._listeners),Ct(t,e,this._oneTimeListeners),this},Mt.prototype.once=function(t,e){return this._oneTimeListeners=this._oneTimeListeners||{},zt(t,e,this._oneTimeListeners),this},Mt.prototype.fire=function(t,e){"string"==typeof t&&(t=new Tt(t,e||{}));var r=t.type;if(this.listens(r)){t.target=this;for(var n=0,i=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];n<i.length;n+=1){i[n].call(this,t);}for(var a=0,o=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];a<o.length;a+=1){var s=o[a];Ct(r,s,this._oneTimeListeners),s.call(this,t);}var u=this._eventedParent;u&&(p(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),u.fire(t));}else t instanceof Et&&console.error(t.error);return this},Mt.prototype.listens=function(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)},Mt.prototype.setEventedParent=function(t,e){return this._eventedParent=t,this._eventedParentData=e,this};var Bt={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},light:{type:"light"},sources:{required:!0,type:"sources"},sprite:{type:"string"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{}},default:"mapbox"},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},expression_name:{type:"enum",values:{let:{group:"Variable binding"},var:{group:"Variable binding"},literal:{group:"Types"},array:{group:"Types"},at:{group:"Lookup"},in:{group:"Lookup"},case:{group:"Decision"},match:{group:"Decision"},coalesce:{group:"Decision"},step:{group:"Ramps, scales, curves"},interpolate:{group:"Ramps, scales, curves"},"interpolate-hcl":{group:"Ramps, scales, curves"},"interpolate-lab":{group:"Ramps, scales, curves"},ln2:{group:"Math"},pi:{group:"Math"},e:{group:"Math"},typeof:{group:"Types"},string:{group:"Types"},number:{group:"Types"},boolean:{group:"Types"},object:{group:"Types"},collator:{group:"Types"},format:{group:"Types"},image:{group:"Types"},"number-format":{group:"Types"},"to-string":{group:"Types"},"to-number":{group:"Types"},"to-boolean":{group:"Types"},"to-rgba":{group:"Color"},"to-color":{group:"Types"},rgb:{group:"Color"},rgba:{group:"Color"},get:{group:"Lookup"},has:{group:"Lookup"},length:{group:"Lookup"},properties:{group:"Feature data"},"feature-state":{group:"Feature data"},"geometry-type":{group:"Feature data"},id:{group:"Feature data"},zoom:{group:"Zoom"},"heatmap-density":{group:"Heatmap"},"line-progress":{group:"Feature data"},accumulated:{group:"Feature data"},"+":{group:"Math"},"*":{group:"Math"},"-":{group:"Math"},"/":{group:"Math"},"%":{group:"Math"},"^":{group:"Math"},sqrt:{group:"Math"},log10:{group:"Math"},ln:{group:"Math"},log2:{group:"Math"},sin:{group:"Math"},cos:{group:"Math"},tan:{group:"Math"},asin:{group:"Math"},acos:{group:"Math"},atan:{group:"Math"},min:{group:"Math"},max:{group:"Math"},round:{group:"Math"},abs:{group:"Math"},ceil:{group:"Math"},floor:{group:"Math"},"==":{group:"Decision"},"!=":{group:"Decision"},">":{group:"Decision"},"<":{group:"Decision"},">=":{group:"Decision"},"<=":{group:"Decision"},all:{group:"Decision"},any:{group:"Decision"},"!":{group:"Decision"},"is-supported-script":{group:"String"},upcase:{group:"String"},downcase:{group:"String"},concat:{group:"String"},"resolved-locale":{group:"String"}}},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}},Pt=function(t,e,r,n){this.message=(t?t+": ":"")+r,n&&(this.identifier=n),null!=e&&e.__line__&&(this.line=e.__line__);};function Vt(t){var e=t.key,r=t.value;return r?[new Pt(e,r,"constants have been deprecated as of v8")]:[]}function Ft(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n<i.length;n+=1){var a=i[n];for(var o in a)t[o]=a[o];}return t}function Lt(t){return t instanceof Number||t instanceof String||t instanceof Boolean?t.valueOf():t}function Dt(t){if(Array.isArray(t))return t.map(Dt);if(t instanceof Object&&!(t instanceof Number||t instanceof String||t instanceof Boolean)){var e={};for(var r in t)e[r]=Dt(t[r]);return e}return Lt(t)}var Ot=function(t){function e(e,r){t.call(this,r),this.message=r,this.key=e;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Error),Rt=function(t,e){void 0===e&&(e=[]),this.parent=t,this.bindings={};for(var r=0,n=e;r<n.length;r+=1){var i=n[r],a=i[0],o=i[1];this.bindings[a]=o;}};Rt.prototype.concat=function(t){return new Rt(this,t)},Rt.prototype.get=function(t){if(this.bindings[t])return this.bindings[t];if(this.parent)return this.parent.get(t);throw new Error(t+" not found in scope.")},Rt.prototype.has=function(t){return !!this.bindings[t]||!!this.parent&&this.parent.has(t)};var Ut={kind:"null"},jt={kind:"number"},qt={kind:"string"},Nt={kind:"boolean"},Kt={kind:"color"},Xt={kind:"object"},Zt={kind:"value"},Gt={kind:"collator"},Jt={kind:"formatted"},Yt={kind:"resolvedImage"};function Ht(t,e){return {kind:"array",itemType:t,N:e}}function $t(t){if("array"===t.kind){var e=$t(t.itemType);return "number"==typeof t.N?"array<"+e+", "+t.N+">":"value"===t.itemType.kind?"array":"array<"+e+">"}return t.kind}var Wt=[Ut,jt,qt,Nt,Kt,Jt,Xt,Ht(Zt),Yt];function Qt(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!Qt(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else{if(t.kind===e.kind)return null;if("value"===t.kind)for(var r=0,n=Wt;r<n.length;r+=1){if(!Qt(n[r],e))return null}}return "Expected "+$t(t)+" but found "+$t(e)+" instead."}var te=e((function(t,e){var r={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function n(t){return (t=Math.round(t))<0?0:t>255?255:t}function i(t){return t<0?0:t>1?1:t}function a(t){return "%"===t[t.length-1]?n(parseFloat(t)/100*255):n(parseInt(t))}function o(t){return "%"===t[t.length-1]?i(parseFloat(t)/100):i(parseFloat(t))}function s(t,e,r){return r<0?r+=1:r>1&&(r-=1),6*r<1?t+(e-t)*r*6:2*r<1?e:3*r<2?t+(e-t)*(2/3-r)*6:t}try{e.parseCSSColor=function(t){var e,i=t.replace(/ /g,"").toLowerCase();if(i in r)return r[i].slice();if("#"===i[0])return 4===i.length?(e=parseInt(i.substr(1),16))>=0&&e<=4095?[(3840&e)>>4|(3840&e)>>8,240&e|(240&e)>>4,15&e|(15&e)<<4,1]:null:7===i.length&&(e=parseInt(i.substr(1),16))>=0&&e<=16777215?[(16711680&e)>>16,(65280&e)>>8,255&e,1]:null;var u=i.indexOf("("),l=i.indexOf(")");if(-1!==u&&l+1===i.length){var p=i.substr(0,u),c=i.substr(u+1,l-(u+1)).split(","),h=1;switch(p){case"rgba":if(4!==c.length)return null;h=o(c.pop());case"rgb":return 3!==c.length?null:[a(c[0]),a(c[1]),a(c[2]),h];case"hsla":if(4!==c.length)return null;h=o(c.pop());case"hsl":if(3!==c.length)return null;var f=(parseFloat(c[0])%360+360)%360/360,y=o(c[1]),d=o(c[2]),m=d<=.5?d*(y+1):d+y-d*y,v=2*d-m;return [n(255*s(v,m,f+1/3)),n(255*s(v,m,f)),n(255*s(v,m,f-1/3)),h];default:return null}}return null};}catch(t){}})).parseCSSColor,ee=function(t,e,r,n){void 0===n&&(n=1),this.r=t,this.g=e,this.b=r,this.a=n;};ee.parse=function(t){if(t){if(t instanceof ee)return t;if("string"==typeof t){var e=te(t);if(e)return new ee(e[0]/255*e[3],e[1]/255*e[3],e[2]/255*e[3],e[3])}}},ee.prototype.toString=function(){var t=this.toArray(),e=t[0],r=t[1],n=t[2],i=t[3];return "rgba("+Math.round(e)+","+Math.round(r)+","+Math.round(n)+","+i+")"},ee.prototype.toArray=function(){var t=this.r,e=this.g,r=this.b,n=this.a;return 0===n?[0,0,0,0]:[255*t/n,255*e/n,255*r/n,n]},ee.black=new ee(0,0,0,1),ee.white=new ee(1,1,1,1),ee.transparent=new ee(0,0,0,0),ee.red=new ee(1,0,0,1);var re=function(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});};re.prototype.compare=function(t,e){return this.collator.compare(t,e)},re.prototype.resolvedLocale=function(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale};var ne=function(t,e,r,n,i){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i;},ie=function(t){this.sections=t;};ie.fromString=function(t){return new ie([new ne(t,null,null,null,null)])},ie.prototype.isEmpty=function(){return 0===this.sections.length||!this.sections.some((function(t){return 0!==t.text.length||t.image&&0!==t.image.name.length}))},ie.factory=function(t){return t instanceof ie?t:ie.fromString(t)},ie.prototype.toString=function(){return 0===this.sections.length?"":this.sections.map((function(t){return t.text})).join("")},ie.prototype.serialize=function(){for(var t=["format"],e=0,r=this.sections;e<r.length;e+=1){var n=r[e];if(n.image)t.push(["image",n.image.name]);else{t.push(n.text);var i={};n.fontStack&&(i["text-font"]=["literal",n.fontStack.split(",")]),n.scale&&(i["font-scale"]=n.scale),n.textColor&&(i["text-color"]=["rgba"].concat(n.textColor.toArray())),t.push(i);}}return t};var ae=function(t){this.name=t.name,this.available=t.available;};function oe(t,e,r,n){return "number"==typeof t&&t>=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:"Invalid rgba value ["+[t,e,r,n].join(", ")+"]: 'a' must be between 0 and 1.":"Invalid rgba value ["+("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")+"]: 'r', 'g', and 'b' must be between 0 and 255."}function se(t){if(null===t)return Ut;if("string"==typeof t)return qt;if("boolean"==typeof t)return Nt;if("number"==typeof t)return jt;if(t instanceof ee)return Kt;if(t instanceof re)return Gt;if(t instanceof ie)return Jt;if(t instanceof ae)return Yt;if(Array.isArray(t)){for(var e,r=t.length,n=0,i=t;n<i.length;n+=1){var a=se(i[n]);if(e){if(e===a)continue;e=Zt;break}e=a;}return Ht(e||Zt,r)}return Xt}function ue(t){var e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof ee||t instanceof ie||t instanceof ae?t.toString():JSON.stringify(t)}ae.prototype.toString=function(){return this.name},ae.fromString=function(t){return new ae({name:t,available:!1})},ae.prototype.serialize=function(){return ["image",this.name]};var le=function(t,e){this.type=t,this.value=e;};le.parse=function(t,e){if(2!==t.length)return e.error("'literal' expression requires exactly one argument, but found "+(t.length-1)+" instead.");if(!function t(e){if(null===e)return !0;if("string"==typeof e)return !0;if("boolean"==typeof e)return !0;if("number"==typeof e)return !0;if(e instanceof ee)return !0;if(e instanceof re)return !0;if(e instanceof ie)return !0;if(e instanceof ae)return !0;if(Array.isArray(e)){for(var r=0,n=e;r<n.length;r+=1){if(!t(n[r]))return !1}return !0}if("object"==typeof e){for(var i in e)if(!t(e[i]))return !1;return !0}return !1}(t[1]))return e.error("invalid value");var r=t[1],n=se(r),i=e.expectedType;return "array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new le(n,r)},le.prototype.evaluate=function(){return this.value},le.prototype.eachChild=function(){},le.prototype.possibleOutputs=function(){return [this.value]},le.prototype.serialize=function(){return "array"===this.type.kind||"object"===this.type.kind?["literal",this.value]:this.value instanceof ee?["rgba"].concat(this.value.toArray()):this.value instanceof ie?this.value.serialize():this.value};var pe=function(t){this.name="ExpressionEvaluationError",this.message=t;};pe.prototype.toJSON=function(){return this.message};var ce={string:qt,number:jt,boolean:Nt,object:Xt},he=function(t,e){this.type=t,this.args=e;};he.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");var r,n=1,i=t[0];if("array"===i){var a,o;if(t.length>2){var s=t[1];if("string"!=typeof s||!(s in ce)||"object"===s)return e.error('The item type argument of "array" must be one of string, number, boolean',1);a=ce[s],n++;}else a=Zt;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);o=t[2],n++;}r=Ht(a,o);}else r=ce[i];for(var u=[];n<t.length;n++){var l=e.parse(t[n],n,Zt);if(!l)return null;u.push(l);}return new he(r,u)},he.prototype.evaluate=function(t){for(var e=0;e<this.args.length;e++){var r=this.args[e].evaluate(t);if(!Qt(this.type,se(r)))return r;if(e===this.args.length-1)throw new pe("Expected value to be of type "+$t(this.type)+", but found "+$t(se(r))+" instead.")}return null},he.prototype.eachChild=function(t){this.args.forEach(t);},he.prototype.possibleOutputs=function(){var t;return (t=[]).concat.apply(t,this.args.map((function(t){return t.possibleOutputs()})))},he.prototype.serialize=function(){var t=this.type,e=[t.kind];if("array"===t.kind){var r=t.itemType;if("string"===r.kind||"number"===r.kind||"boolean"===r.kind){e.push(r.kind);var n=t.N;("number"==typeof n||this.args.length>1)&&e.push(n);}}return e.concat(this.args.map((function(t){return t.serialize()})))};var fe=function(t){this.type=Jt,this.sections=t;};fe.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");var r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");for(var n=[],i=!1,a=1;a<=t.length-1;++a){var o=t[a];if(i&&"object"==typeof o&&!Array.isArray(o)){i=!1;var s=null;if(o["font-scale"]&&!(s=e.parse(o["font-scale"],1,jt)))return null;var u=null;if(o["text-font"]&&!(u=e.parse(o["text-font"],1,Ht(qt))))return null;var l=null;if(o["text-color"]&&!(l=e.parse(o["text-color"],1,Kt)))return null;var p=n[n.length-1];p.scale=s,p.font=u,p.textColor=l;}else{var c=e.parse(t[a],1,Zt);if(!c)return null;var h=c.type.kind;if("string"!==h&&"value"!==h&&"null"!==h&&"resolvedImage"!==h)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:c,scale:null,font:null,textColor:null});}}return new fe(n)},fe.prototype.evaluate=function(t){return new ie(this.sections.map((function(e){var r=e.content.evaluate(t);return se(r)===Yt?new ne("",r,null,null,null):new ne(ue(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null)})))},fe.prototype.eachChild=function(t){for(var e=0,r=this.sections;e<r.length;e+=1){var n=r[e];t(n.content),n.scale&&t(n.scale),n.font&&t(n.font),n.textColor&&t(n.textColor);}},fe.prototype.possibleOutputs=function(){return [void 0]},fe.prototype.serialize=function(){for(var t=["format"],e=0,r=this.sections;e<r.length;e+=1){var n=r[e];t.push(n.content.serialize());var i={};n.scale&&(i["font-scale"]=n.scale.serialize()),n.font&&(i["text-font"]=n.font.serialize()),n.textColor&&(i["text-color"]=n.textColor.serialize()),t.push(i);}return t};var ye=function(t){this.type=Yt,this.input=t;};ye.parse=function(t,e){if(2!==t.length)return e.error("Expected two arguments.");var r=e.parse(t[1],1,qt);return r?new ye(r):e.error("No image name provided.")},ye.prototype.evaluate=function(t){var e=this.input.evaluate(t),r=!1;return t.availableImages&&t.availableImages.indexOf(e)>-1&&(r=!0),new ae({name:e,available:r})},ye.prototype.eachChild=function(t){t(this.input);},ye.prototype.possibleOutputs=function(){return [void 0]},ye.prototype.serialize=function(){return ["image",this.input.serialize()]};var de={"to-boolean":Nt,"to-color":Kt,"to-number":jt,"to-string":qt},me=function(t,e){this.type=t,this.args=e;};me.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");var r=t[0];if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");for(var n=de[r],i=[],a=1;a<t.length;a++){var o=e.parse(t[a],a,Zt);if(!o)return null;i.push(o);}return new me(n,i)},me.prototype.evaluate=function(t){if("boolean"===this.type.kind)return Boolean(this.args[0].evaluate(t));if("color"===this.type.kind){for(var e,r,n=0,i=this.args;n<i.length;n+=1){if(r=null,(e=i[n].evaluate(t))instanceof ee)return e;if("string"==typeof e){var a=t.parseColor(e);if(a)return a}else if(Array.isArray(e)&&!(r=e.length<3||e.length>4?"Invalid rbga value "+JSON.stringify(e)+": expected an array containing either three or four numeric values.":oe(e[0],e[1],e[2],e[3])))return new ee(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new pe(r||"Could not parse color from value '"+("string"==typeof e?e:String(JSON.stringify(e)))+"'")}if("number"===this.type.kind){for(var o=null,s=0,u=this.args;s<u.length;s+=1){if(null===(o=u[s].evaluate(t)))return 0;var l=Number(o);if(!isNaN(l))return l}throw new pe("Could not convert "+JSON.stringify(o)+" to number.")}return "formatted"===this.type.kind?ie.fromString(ue(this.args[0].evaluate(t))):"resolvedImage"===this.type.kind?ae.fromString(ue(this.args[0].evaluate(t))):ue(this.args[0].evaluate(t))},me.prototype.eachChild=function(t){this.args.forEach(t);},me.prototype.possibleOutputs=function(){var t;return (t=[]).concat.apply(t,this.args.map((function(t){return t.possibleOutputs()})))},me.prototype.serialize=function(){if("formatted"===this.type.kind)return new fe([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if("resolvedImage"===this.type.kind)return new ye(this.args[0]).serialize();var t=["to-"+this.type.kind];return this.eachChild((function(e){t.push(e.serialize());})),t};var ve=["Unknown","Point","LineString","Polygon"],ge=function(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null;};ge.prototype.id=function(){return this.feature&&"id"in this.feature?this.feature.id:null},ge.prototype.geometryType=function(){return this.feature?"number"==typeof this.feature.type?ve[this.feature.type]:this.feature.type:null},ge.prototype.properties=function(){return this.feature&&this.feature.properties||{}},ge.prototype.parseColor=function(t){var e=this._parseColorCache[t];return e||(e=this._parseColorCache[t]=ee.parse(t)),e};var xe=function(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;};xe.prototype.evaluate=function(t){return this._evaluate(t,this.args)},xe.prototype.eachChild=function(t){this.args.forEach(t);},xe.prototype.possibleOutputs=function(){return [void 0]},xe.prototype.serialize=function(){return [this.name].concat(this.args.map((function(t){return t.serialize()})))},xe.parse=function(t,e){var r,n=t[0],i=xe.definitions[n];if(!i)return e.error('Unknown expression "'+n+'". If you wanted a literal array, use ["literal", [...]].',0);for(var a=Array.isArray(i)?i[0]:i.type,o=Array.isArray(i)?[[i[1],i[2]]]:i.overloads,s=o.filter((function(e){var r=e[0];return !Array.isArray(r)||r.length===t.length-1})),u=null,l=0,p=s;l<p.length;l+=1){var c=p[l],h=c[0],f=c[1];u=new ke(e.registry,e.path,null,e.scope);for(var y=[],d=!1,m=1;m<t.length;m++){var v=t[m],g=Array.isArray(h)?h[m-1]:h.type,x=u.parse(v,1+y.length,g);if(!x){d=!0;break}y.push(x);}if(!d)if(Array.isArray(h)&&h.length!==y.length)u.error("Expected "+h.length+" arguments, but found "+y.length+" instead.");else{for(var b=0;b<y.length;b++){var _=Array.isArray(h)?h[b]:h.type,w=y[b];u.concat(b+1).checkSubtype(_,w.type);}if(0===u.errors.length)return new xe(n,a,f,y)}}if(1===s.length)(r=e.errors).push.apply(r,u.errors);else{for(var A=(s.length?s:o).map((function(t){var e,r=t[0];return e=r,Array.isArray(e)?"("+e.map($t).join(", ")+")":"("+$t(e.type)+"...)"})).join(" | "),S=[],k=1;k<t.length;k++){var I=e.parse(t[k],1+S.length);if(!I)return null;S.push($t(I.type));}e.error("Expected arguments of type "+A+", but found ("+S.join(", ")+") instead.");}return null},xe.register=function(t,e){for(var r in xe.definitions=e,e)t[r]=xe;};var be=function(t,e,r){this.type=Gt,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;};function _e(t){if(t instanceof xe){if("get"===t.name&&1===t.args.length)return !1;if("feature-state"===t.name)return !1;if("has"===t.name&&1===t.args.length)return !1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return !1;if(/^filter-/.test(t.name))return !1}var e=!0;return t.eachChild((function(t){e&&!_e(t)&&(e=!1);})),e}function we(t){if(t instanceof xe&&"feature-state"===t.name)return !1;var e=!0;return t.eachChild((function(t){e&&!we(t)&&(e=!1);})),e}function Ae(t,e){if(t instanceof xe&&e.indexOf(t.name)>=0)return !1;var r=!0;return t.eachChild((function(t){r&&!Ae(t,e)&&(r=!1);})),r}be.parse=function(t,e){if(2!==t.length)return e.error("Expected one argument.");var r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");var n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,Nt);if(!n)return null;var i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,Nt);if(!i)return null;var a=null;return r.locale&&!(a=e.parse(r.locale,1,qt))?null:new be(n,i,a)},be.prototype.evaluate=function(t){return new re(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)},be.prototype.eachChild=function(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);},be.prototype.possibleOutputs=function(){return [void 0]},be.prototype.serialize=function(){var t={};return t["case-sensitive"]=this.caseSensitive.serialize(),t["diacritic-sensitive"]=this.diacriticSensitive.serialize(),this.locale&&(t.locale=this.locale.serialize()),["collator",t]};var Se=function(t,e){this.type=e.type,this.name=t,this.boundExpression=e;};Se.parse=function(t,e){if(2!==t.length||"string"!=typeof t[1])return e.error("'var' expression requires exactly one string literal argument.");var r=t[1];return e.scope.has(r)?new Se(r,e.scope.get(r)):e.error('Unknown variable "'+r+'". Make sure "'+r+'" has been bound in an enclosing "let" expression before using it.',1)},Se.prototype.evaluate=function(t){return this.boundExpression.evaluate(t)},Se.prototype.eachChild=function(){},Se.prototype.possibleOutputs=function(){return [void 0]},Se.prototype.serialize=function(){return ["var",this.name]};var ke=function(t,e,r,n,i){void 0===e&&(e=[]),void 0===n&&(n=new Rt),void 0===i&&(i=[]),this.registry=t,this.path=e,this.key=e.map((function(t){return "["+t+"]"})).join(""),this.scope=n,this.errors=i,this.expectedType=r;};function Ie(t,e){for(var r,n,i=t.length-1,a=0,o=i,s=0;a<=o;)if(r=t[s=Math.floor((a+o)/2)],n=t[s+1],r<=e){if(s===i||e<n)return s;a=s+1;}else{if(!(r>e))throw new pe("Input is not a number.");o=s-1;}return 0}ke.prototype.parse=function(t,e,r,n,i){return void 0===i&&(i={}),e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)},ke.prototype._parse=function(t,e){function r(t,e,r){return "assert"===r?new he(e,[t]):"coerce"===r?new me(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');var n=t[0];if("string"!=typeof n)return this.error("Expression name must be a string, but found "+typeof n+' instead. If you wanted a literal array, use ["literal", [...]].',0),null;var i=this.registry[n];if(i){var a=i.parse(t,this);if(!a)return null;if(this.expectedType){var o=this.expectedType,s=a.type;if("string"!==o.kind&&"number"!==o.kind&&"boolean"!==o.kind&&"object"!==o.kind&&"array"!==o.kind||"value"!==s.kind)if("color"!==o.kind&&"formatted"!==o.kind&&"resolvedImage"!==o.kind||"value"!==s.kind&&"string"!==s.kind){if(this.checkSubtype(o,s))return null}else a=r(a,o,e.typeAnnotation||"coerce");else a=r(a,o,e.typeAnnotation||"assert");}if(!(a instanceof le)&&"resolvedImage"!==a.type.kind&&function t(e){if(e instanceof Se)return t(e.boundExpression);if(e instanceof xe&&"error"===e.name)return !1;if(e instanceof be)return !1;var r=e instanceof me||e instanceof he;var n=!0;e.eachChild((function(e){n=r?n&&t(e):n&&e instanceof le;}));if(!n)return !1;return _e(e)&&Ae(e,["zoom","heatmap-density","line-progress","accumulated","is-supported-script"])}(a)){var u=new ge;try{a=new le(a.type,a.evaluate(u));}catch(t){return this.error(t.message),null}}return a}return this.error('Unknown expression "'+n+'". If you wanted a literal array, use ["literal", [...]].',0)}return void 0===t?this.error("'undefined' value invalid. Use null instead."):"object"==typeof t?this.error('Bare objects invalid. Use ["literal", {...}] instead.'):this.error("Expected an array, but found "+typeof t+" instead.")},ke.prototype.concat=function(t,e,r){var n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new ke(this.registry,n,e||null,i,this.errors)},ke.prototype.error=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];var n=""+this.key+e.map((function(t){return "["+t+"]"})).join("");this.errors.push(new Ot(n,t));},ke.prototype.checkSubtype=function(t,e){var r=Qt(t,e);return r&&this.error(r),r};var ze=function(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(var n=0,i=r;n<i.length;n+=1){var a=i[n],o=a[0],s=a[1];this.labels.push(o),this.outputs.push(s);}};function Ce(t,e,r){return t*(1-r)+e*r}ze.parse=function(t,e){if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");var r=e.parse(t[1],1,jt);if(!r)return null;var n=[],i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(var a=1;a<t.length;a+=2){var o=1===a?-1/0:t[a],s=t[a+1],u=a,l=a+1;if("number"!=typeof o)return e.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.',u);if(n.length&&n[n.length-1][0]>=o)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',u);var p=e.parse(s,l,i);if(!p)return null;i=i||p.type,n.push([o,p]);}return new ze(i,r,n)},ze.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[Ie(e,n)].evaluate(t)},ze.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e<r.length;e+=1){t(r[e]);}},ze.prototype.possibleOutputs=function(){var t;return (t=[]).concat.apply(t,this.outputs.map((function(t){return t.possibleOutputs()})))},ze.prototype.serialize=function(){for(var t=["step",this.input.serialize()],e=0;e<this.labels.length;e++)e>0&&t.push(this.labels[e]),t.push(this.outputs[e].serialize());return t};var Te=Object.freeze({__proto__:null,number:Ce,color:function(t,e,r){return new ee(Ce(t.r,e.r,r),Ce(t.g,e.g,r),Ce(t.b,e.b,r),Ce(t.a,e.a,r))},array:function(t,e,r){return t.map((function(t,n){return Ce(t,e[n],r)}))}}),Ee=.95047,Me=1,Be=1.08883,Pe=4/29,Ve=6/29,Fe=3*Ve*Ve,Le=Ve*Ve*Ve,De=Math.PI/180,Oe=180/Math.PI;function Re(t){return t>Le?Math.pow(t,1/3):t/Fe+Pe}function Ue(t){return t>Ve?t*t*t:Fe*(t-Pe)}function je(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function qe(t){return (t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Ne(t){var e=qe(t.r),r=qe(t.g),n=qe(t.b),i=Re((.4124564*e+.3575761*r+.1804375*n)/Ee),a=Re((.2126729*e+.7151522*r+.072175*n)/Me);return {l:116*a-16,a:500*(i-a),b:200*(a-Re((.0193339*e+.119192*r+.9503041*n)/Be)),alpha:t.a}}function Ke(t){var e=(t.l+16)/116,r=isNaN(t.a)?e:e+t.a/500,n=isNaN(t.b)?e:e-t.b/200;return e=Me*Ue(e),r=Ee*Ue(r),n=Be*Ue(n),new ee(je(3.2404542*r-1.5371385*e-.4985314*n),je(-.969266*r+1.8760108*e+.041556*n),je(.0556434*r-.2040259*e+1.0572252*n),t.alpha)}function Xe(t,e,r){var n=e-t;return t+r*(n>180||n<-180?n-360*Math.round(n/360):n)}var Ze={forward:Ne,reverse:Ke,interpolate:function(t,e,r){return {l:Ce(t.l,e.l,r),a:Ce(t.a,e.a,r),b:Ce(t.b,e.b,r),alpha:Ce(t.alpha,e.alpha,r)}}},Ge={forward:function(t){var e=Ne(t),r=e.l,n=e.a,i=e.b,a=Math.atan2(i,n)*Oe;return {h:a<0?a+360:a,c:Math.sqrt(n*n+i*i),l:r,alpha:t.a}},reverse:function(t){var e=t.h*De,r=t.c;return Ke({l:t.l,a:Math.cos(e)*r,b:Math.sin(e)*r,alpha:t.alpha})},interpolate:function(t,e,r){return {h:Xe(t.h,e.h,r),c:Ce(t.c,e.c,r),l:Ce(t.l,e.l,r),alpha:Ce(t.alpha,e.alpha,r)}}},Je=Object.freeze({__proto__:null,lab:Ze,hcl:Ge}),Ye=function(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(var a=0,o=i;a<o.length;a+=1){var s=o[a],u=s[0],l=s[1];this.labels.push(u),this.outputs.push(l);}};function He(t,e,r,n){var i=n-r,a=t-r;return 0===i?0:1===e?a/i:(Math.pow(e,a)-1)/(Math.pow(e,i)-1)}Ye.interpolationFactor=function(t,e,n,i){var a=0;if("exponential"===t.name)a=He(e,t.base,n,i);else if("linear"===t.name)a=He(e,1,n,i);else if("cubic-bezier"===t.name){var o=t.controlPoints;a=new r(o[0],o[1],o[2],o[3]).solve(He(e,1,n,i));}return a},Ye.parse=function(t,e){var r=t[0],n=t[1],i=t[2],a=t.slice(3);if(!Array.isArray(n)||0===n.length)return e.error("Expected an interpolation type expression.",1);if("linear"===n[0])n={name:"linear"};else if("exponential"===n[0]){var o=n[1];if("number"!=typeof o)return e.error("Exponential interpolation requires a numeric base.",1,1);n={name:"exponential",base:o};}else{if("cubic-bezier"!==n[0])return e.error("Unknown interpolation type "+String(n[0]),1,0);var s=n.slice(1);if(4!==s.length||s.some((function(t){return "number"!=typeof t||t<0||t>1})))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:s};}if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(!(i=e.parse(i,2,jt)))return null;var u=[],l=null;"interpolate-hcl"===r||"interpolate-lab"===r?l=Kt:e.expectedType&&"value"!==e.expectedType.kind&&(l=e.expectedType);for(var p=0;p<a.length;p+=2){var c=a[p],h=a[p+1],f=p+3,y=p+4;if("number"!=typeof c)return e.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.',f);if(u.length&&u[u.length-1][0]>=c)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',f);var d=e.parse(h,y,l);if(!d)return null;l=l||d.type,u.push([c,d]);}return "number"===l.kind||"color"===l.kind||"array"===l.kind&&"number"===l.itemType.kind&&"number"==typeof l.N?new Ye(l,r,n,i,u):e.error("Type "+$t(l)+" is not interpolatable.")},Ye.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);var a=Ie(e,n),o=e[a],s=e[a+1],u=Ye.interpolationFactor(this.interpolation,n,o,s),l=r[a].evaluate(t),p=r[a+1].evaluate(t);return "interpolate"===this.operator?Te[this.type.kind.toLowerCase()](l,p,u):"interpolate-hcl"===this.operator?Ge.reverse(Ge.interpolate(Ge.forward(l),Ge.forward(p),u)):Ze.reverse(Ze.interpolate(Ze.forward(l),Ze.forward(p),u))},Ye.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e<r.length;e+=1){t(r[e]);}},Ye.prototype.possibleOutputs=function(){var t;return (t=[]).concat.apply(t,this.outputs.map((function(t){return t.possibleOutputs()})))},Ye.prototype.serialize=function(){var t;t="linear"===this.interpolation.name?["linear"]:"exponential"===this.interpolation.name?1===this.interpolation.base?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier"].concat(this.interpolation.controlPoints);for(var e=[this.operator,t,this.input.serialize()],r=0;r<this.labels.length;r++)e.push(this.labels[r],this.outputs[r].serialize());return e};var $e=function(t,e){this.type=t,this.args=e;};$e.parse=function(t,e){if(t.length<2)return e.error("Expectected at least one argument.");var r=null,n=e.expectedType;n&&"value"!==n.kind&&(r=n);for(var i=[],a=0,o=t.slice(1);a<o.length;a+=1){var s=o[a],u=e.parse(s,1+i.length,r,void 0,{typeAnnotation:"omit"});if(!u)return null;r=r||u.type,i.push(u);}var l=n&&i.some((function(t){return Qt(n,t.type)}));return new $e(l?Zt:r,i)},$e.prototype.evaluate=function(t){for(var e,r=null,n=0,i=0,a=this.args;i<a.length;i+=1){if(n++,(r=a[i].evaluate(t))&&r instanceof ae&&!r.available&&(e||(e=r.name),r=null,n===this.args.length&&(r=e)),null!==r)break}return r},$e.prototype.eachChild=function(t){this.args.forEach(t);},$e.prototype.possibleOutputs=function(){var t;return (t=[]).concat.apply(t,this.args.map((function(t){return t.possibleOutputs()})))},$e.prototype.serialize=function(){var t=["coalesce"];return this.eachChild((function(e){t.push(e.serialize());})),t};var We=function(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;};We.prototype.evaluate=function(t){return this.result.evaluate(t)},We.prototype.eachChild=function(t){for(var e=0,r=this.bindings;e<r.length;e+=1){t(r[e][1]);}t(this.result);},We.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found "+(t.length-1)+" instead.");for(var r=[],n=1;n<t.length-1;n+=2){var i=t[n];if("string"!=typeof i)return e.error("Expected string, but found "+typeof i+" instead.",n);if(/[^a-zA-Z0-9_]/.test(i))return e.error("Variable names must contain only alphanumeric characters or '_'.",n);var a=e.parse(t[n+1],n+1);if(!a)return null;r.push([i,a]);}var o=e.parse(t[t.length-1],t.length-1,e.expectedType,r);return o?new We(r,o):null},We.prototype.possibleOutputs=function(){return this.result.possibleOutputs()},We.prototype.serialize=function(){for(var t=["let"],e=0,r=this.bindings;e<r.length;e+=1){var n=r[e],i=n[0],a=n[1];t.push(i,a.serialize());}return t.push(this.result.serialize()),t};var Qe=function(t,e,r){this.type=t,this.index=e,this.input=r;};Qe.parse=function(t,e){if(3!==t.length)return e.error("Expected 2 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,jt),n=e.parse(t[2],2,Ht(e.expectedType||Zt));if(!r||!n)return null;var i=n.type;return new Qe(i.itemType,r,n)},Qe.prototype.evaluate=function(t){var e=this.index.evaluate(t),r=this.input.evaluate(t);if(e<0)throw new pe("Array index out of bounds: "+e+" < 0.");if(e>=r.length)throw new pe("Array index out of bounds: "+e+" > "+(r.length-1)+".");if(e!==Math.floor(e))throw new pe("Array index must be an integer, but found "+e+" instead.");return r[e]},Qe.prototype.eachChild=function(t){t(this.index),t(this.input);},Qe.prototype.possibleOutputs=function(){return [void 0]},Qe.prototype.serialize=function(){return ["at",this.index.serialize(),this.input.serialize()]};var tr=function(t,e){this.type=Nt,this.needle=t,this.haystack=e;};tr.parse=function(t,e){if(3!==t.length)return e.error("Expected 2 arguments, but found "+(t.length-1)+" instead.");var r,n=e.parse(t[1],1,Zt),i=e.parse(t[2],2,Zt);return n&&i?"boolean"!==(r=n.type).kind&&"string"!==r.kind&&"number"!==r.kind&&"null"!==r.kind&&"value"!==r.kind?e.error("Expected first argument to be of type boolean, string, number or null, but found "+$t(n.type)+" instead"):new tr(n,i):null},tr.prototype.evaluate=function(t){var e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!e||!r)return !1;if(!function(t){return "boolean"==typeof t||"string"==typeof t||"number"==typeof t}(e))throw new pe("Expected first argument to be of type boolean, string or number, but found "+$t(se(e))+" instead.");if(!function(t){return Array.isArray(t)||"string"==typeof t}(r))throw new pe("Expected second argument to be of type array or string, but found "+$t(se(r))+" instead.");return r.indexOf(e)>=0},tr.prototype.eachChild=function(t){t(this.needle),t(this.haystack);},tr.prototype.possibleOutputs=function(){return [!0,!1]},tr.prototype.serialize=function(){return ["in",this.needle.serialize(),this.haystack.serialize()]};var er=function(t,e,r,n,i,a){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=a;};er.parse=function(t,e){if(t.length<5)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if(t.length%2!=1)return e.error("Expected an even number of arguments.");var r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);for(var i={},a=[],o=2;o<t.length-1;o+=2){var s=t[o],u=t[o+1];Array.isArray(s)||(s=[s]);var l=e.concat(o);if(0===s.length)return l.error("Expected at least one branch label.");for(var p=0,c=s;p<c.length;p+=1){var h=c[p];if("number"!=typeof h&&"string"!=typeof h)return l.error("Branch labels must be numbers or strings.");if("number"==typeof h&&Math.abs(h)>Number.MAX_SAFE_INTEGER)return l.error("Branch labels must be integers no larger than "+Number.MAX_SAFE_INTEGER+".");if("number"==typeof h&&Math.floor(h)!==h)return l.error("Numeric branch labels must be integer values.");if(r){if(l.checkSubtype(r,se(h)))return null}else r=se(h);if(void 0!==i[String(h)])return l.error("Branch labels must be unique.");i[String(h)]=a.length;}var f=e.parse(u,o,n);if(!f)return null;n=n||f.type,a.push(f);}var y=e.parse(t[1],1,Zt);if(!y)return null;var d=e.parse(t[t.length-1],t.length-1,n);return d?"value"!==y.type.kind&&e.concat(1).checkSubtype(r,y.type)?null:new er(r,n,y,i,a,d):null},er.prototype.evaluate=function(t){var e=this.input.evaluate(t);return (se(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)},er.prototype.eachChild=function(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);},er.prototype.possibleOutputs=function(){var t;return (t=[]).concat.apply(t,this.outputs.map((function(t){return t.possibleOutputs()}))).concat(this.otherwise.possibleOutputs())},er.prototype.serialize=function(){for(var t=this,e=["match",this.input.serialize()],r=[],n={},i=0,a=Object.keys(this.cases).sort();i<a.length;i+=1){var o=a[i];void 0===(c=n[this.cases[o]])?(n[this.cases[o]]=r.length,r.push([this.cases[o],[o]])):r[c][1].push(o);}for(var s=function(e){return "number"===t.inputType.kind?Number(e):e},u=0,l=r;u<l.length;u+=1){var p=l[u],c=p[0],h=p[1];1===h.length?e.push(s(h[0])):e.push(h.map(s)),e.push(this.outputs[outputIndex$1].serialize());}return e.push(this.otherwise.serialize()),e};var rr=function(t,e,r){this.type=t,this.branches=e,this.otherwise=r;};function nr(t,e){return "=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function ir(t,e,r,n){return 0===n.compare(e,r)}function ar(t,e,r){var n="=="!==t&&"!="!==t;return function(){function i(t,e,r){this.type=Nt,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind;}return i.parse=function(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");var r=t[0],a=e.parse(t[1],1,Zt);if(!a)return null;if(!nr(r,a.type))return e.concat(1).error('"'+r+"\" comparisons are not supported for type '"+$t(a.type)+"'.");var o=e.parse(t[2],2,Zt);if(!o)return null;if(!nr(r,o.type))return e.concat(2).error('"'+r+"\" comparisons are not supported for type '"+$t(o.type)+"'.");if(a.type.kind!==o.type.kind&&"value"!==a.type.kind&&"value"!==o.type.kind)return e.error("Cannot compare types '"+$t(a.type)+"' and '"+$t(o.type)+"'.");n&&("value"===a.type.kind&&"value"!==o.type.kind?a=new he(o.type,[a]):"value"!==a.type.kind&&"value"===o.type.kind&&(o=new he(a.type,[o])));var s=null;if(4===t.length){if("string"!==a.type.kind&&"string"!==o.type.kind&&"value"!==a.type.kind&&"value"!==o.type.kind)return e.error("Cannot use collator to compare non-string types.");if(!(s=e.parse(t[3],3,Gt)))return null}return new i(a,o,s)},i.prototype.evaluate=function(i){var a=this.lhs.evaluate(i),o=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){var s=se(a),u=se(o);if(s.kind!==u.kind||"string"!==s.kind&&"number"!==s.kind)throw new pe('Expected arguments for "'+t+'" to be (string, string) or (number, number), but found ('+s.kind+", "+u.kind+") instead.")}if(this.collator&&!n&&this.hasUntypedArgument){var l=se(a),p=se(o);if("string"!==l.kind||"string"!==p.kind)return e(i,a,o)}return this.collator?r(i,a,o,this.collator.evaluate(i)):e(i,a,o)},i.prototype.eachChild=function(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);},i.prototype.possibleOutputs=function(){return [!0,!1]},i.prototype.serialize=function(){var e=[t];return this.eachChild((function(t){e.push(t.serialize());})),e},i}()}rr.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found only "+(t.length-1)+".");if(t.length%2!=0)return e.error("Expected an odd number of arguments.");var r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);for(var n=[],i=1;i<t.length-1;i+=2){var a=e.parse(t[i],i,Nt);if(!a)return null;var o=e.parse(t[i+1],i+1,r);if(!o)return null;n.push([a,o]),r=r||o.type;}var s=e.parse(t[t.length-1],t.length-1,r);return s?new rr(r,n,s):null},rr.prototype.evaluate=function(t){for(var e=0,r=this.branches;e<r.length;e+=1){var n=r[e],i=n[0],a=n[1];if(i.evaluate(t))return a.evaluate(t)}return this.otherwise.evaluate(t)},rr.prototype.eachChild=function(t){for(var e=0,r=this.branches;e<r.length;e+=1){var n=r[e],i=n[0],a=n[1];t(i),t(a);}t(this.otherwise);},rr.prototype.possibleOutputs=function(){var t;return (t=[]).concat.apply(t,this.branches.map((function(t){t[0];return t[1].possibleOutputs()}))).concat(this.otherwise.possibleOutputs())},rr.prototype.serialize=function(){var t=["case"];return this.eachChild((function(e){t.push(e.serialize());})),t};var or=ar("==",(function(t,e,r){return e===r}),ir),sr=ar("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !ir(0,e,r,n)})),ur=ar("<",(function(t,e,r){return e<r}),(function(t,e,r,n){return n.compare(e,r)<0})),lr=ar(">",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),pr=ar("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),cr=ar(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0})),hr=function(t,e,r,n,i){this.type=qt,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;};hr.parse=function(t,e){if(3!==t.length)return e.error("Expected two arguments.");var r=e.parse(t[1],1,jt);if(!r)return null;var n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");var i=null;if(n.locale&&!(i=e.parse(n.locale,1,qt)))return null;var a=null;if(n.currency&&!(a=e.parse(n.currency,1,qt)))return null;var o=null;if(n["min-fraction-digits"]&&!(o=e.parse(n["min-fraction-digits"],1,jt)))return null;var s=null;return n["max-fraction-digits"]&&!(s=e.parse(n["max-fraction-digits"],1,jt))?null:new hr(r,i,a,o,s)},hr.prototype.evaluate=function(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))},hr.prototype.eachChild=function(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);},hr.prototype.possibleOutputs=function(){return [void 0]},hr.prototype.serialize=function(){var t={};return this.locale&&(t.locale=this.locale.serialize()),this.currency&&(t.currency=this.currency.serialize()),this.minFractionDigits&&(t["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(t["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),t]};var fr=function(t){this.type=jt,this.input=t;};fr.parse=function(t,e){if(2!==t.length)return e.error("Expected 1 argument, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error("Expected argument of type string or array, but found "+$t(r.type)+" instead."):new fr(r):null},fr.prototype.evaluate=function(t){var e=this.input.evaluate(t);if("string"==typeof e)return e.length;if(Array.isArray(e))return e.length;throw new pe("Expected value to be of type string or array, but found "+$t(se(e))+" instead.")},fr.prototype.eachChild=function(t){t(this.input);},fr.prototype.possibleOutputs=function(){return [void 0]},fr.prototype.serialize=function(){var t=["length"];return this.eachChild((function(e){t.push(e.serialize());})),t};var yr={"==":or,"!=":sr,">":lr,"<":ur,">=":cr,"<=":pr,array:he,at:Qe,boolean:he,case:rr,coalesce:$e,collator:be,format:fe,image:ye,in:tr,interpolate:Ye,"interpolate-hcl":Ye,"interpolate-lab":Ye,length:fr,let:We,literal:le,match:er,number:he,"number-format":hr,object:he,step:ze,string:he,"to-boolean":me,"to-color":me,"to-number":me,"to-string":me,var:Se};function dr(t,e){var r=e[0],n=e[1],i=e[2],a=e[3];r=r.evaluate(t),n=n.evaluate(t),i=i.evaluate(t);var o=a?a.evaluate(t):1,s=oe(r,n,i,o);if(s)throw new pe(s);return new ee(r/255*o,n/255*o,i/255*o,o)}function mr(t,e){return t in e}function vr(t,e){var r=e[t];return void 0===r?null:r}function gr(t){return {type:t}}function xr(t){return {result:"success",value:t}}function br(t){return {result:"error",value:t}}function _r(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function wr(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function Ar(t){return !!t.expression&&t.expression.interpolated}function Sr(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function kr(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)}function Ir(t){return t}function zr(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function Cr(t,e,r,n,i){return zr(typeof r===i?n[r]:void 0,t.default,e.default)}function Tr(t,e,r){if("number"!==Sr(r))return zr(t.default,e.default);var n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];var i=Ie(t.stops.map((function(t){return t[0]})),r);return t.stops[i][1]}function Er(t,e,r){var n=void 0!==t.base?t.base:1;if("number"!==Sr(r))return zr(t.default,e.default);var i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];var a=Ie(t.stops.map((function(t){return t[0]})),r),o=function(t,e,r,n){var i=n-r,a=t-r;return 0===i?0:1===e?a/i:(Math.pow(e,a)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[a][0],t.stops[a+1][0]),s=t.stops[a][1],u=t.stops[a+1][1],l=Te[e.type]||Ir;if(t.colorSpace&&"rgb"!==t.colorSpace){var p=Je[t.colorSpace];l=function(t,e){return p.reverse(p.interpolate(p.forward(t),p.forward(e),o))};}return "function"==typeof s.evaluate?{evaluate:function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];var r=s.evaluate.apply(void 0,t),n=u.evaluate.apply(void 0,t);if(void 0!==r&&void 0!==n)return l(r,n,o)}}:l(s,u,o)}function Mr(t,e,r){return "color"===e.type?r=ee.parse(r):"formatted"===e.type?r=ie.fromString(r.toString()):"resolvedImage"===e.type?r=ae.fromString(r.toString()):Sr(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0),zr(r,t.default,e.default)}xe.register(yr,{error:[{kind:"error"},[qt],function(t,e){var r=e[0];throw new pe(r.evaluate(t))}],typeof:[qt,[Zt],function(t,e){return $t(se(e[0].evaluate(t)))}],"to-rgba":[Ht(jt,4),[Kt],function(t,e){return e[0].evaluate(t).toArray()}],rgb:[Kt,[jt,jt,jt],dr],rgba:[Kt,[jt,jt,jt,jt],dr],has:{type:Nt,overloads:[[[qt],function(t,e){return mr(e[0].evaluate(t),t.properties())}],[[qt,Xt],function(t,e){var r=e[0],n=e[1];return mr(r.evaluate(t),n.evaluate(t))}]]},get:{type:Zt,overloads:[[[qt],function(t,e){return vr(e[0].evaluate(t),t.properties())}],[[qt,Xt],function(t,e){var r=e[0],n=e[1];return vr(r.evaluate(t),n.evaluate(t))}]]},"feature-state":[Zt,[qt],function(t,e){return vr(e[0].evaluate(t),t.featureState||{})}],properties:[Xt,[],function(t){return t.properties()}],"geometry-type":[qt,[],function(t){return t.geometryType()}],id:[Zt,[],function(t){return t.id()}],zoom:[jt,[],function(t){return t.globals.zoom}],"heatmap-density":[jt,[],function(t){return t.globals.heatmapDensity||0}],"line-progress":[jt,[],function(t){return t.globals.lineProgress||0}],accumulated:[Zt,[],function(t){return void 0===t.globals.accumulated?null:t.globals.accumulated}],"+":[jt,gr(jt),function(t,e){for(var r=0,n=0,i=e;n<i.length;n+=1){r+=i[n].evaluate(t);}return r}],"*":[jt,gr(jt),function(t,e){for(var r=1,n=0,i=e;n<i.length;n+=1){r*=i[n].evaluate(t);}return r}],"-":{type:jt,overloads:[[[jt,jt],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)-n.evaluate(t)}],[[jt],function(t,e){return -e[0].evaluate(t)}]]},"/":[jt,[jt,jt],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)/n.evaluate(t)}],"%":[jt,[jt,jt],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)%n.evaluate(t)}],ln2:[jt,[],function(){return Math.LN2}],pi:[jt,[],function(){return Math.PI}],e:[jt,[],function(){return Math.E}],"^":[jt,[jt,jt],function(t,e){var r=e[0],n=e[1];return Math.pow(r.evaluate(t),n.evaluate(t))}],sqrt:[jt,[jt],function(t,e){var r=e[0];return Math.sqrt(r.evaluate(t))}],log10:[jt,[jt],function(t,e){var r=e[0];return Math.log(r.evaluate(t))/Math.LN10}],ln:[jt,[jt],function(t,e){var r=e[0];return Math.log(r.evaluate(t))}],log2:[jt,[jt],function(t,e){var r=e[0];return Math.log(r.evaluate(t))/Math.LN2}],sin:[jt,[jt],function(t,e){var r=e[0];return Math.sin(r.evaluate(t))}],cos:[jt,[jt],function(t,e){var r=e[0];return Math.cos(r.evaluate(t))}],tan:[jt,[jt],function(t,e){var r=e[0];return Math.tan(r.evaluate(t))}],asin:[jt,[jt],function(t,e){var r=e[0];return Math.asin(r.evaluate(t))}],acos:[jt,[jt],function(t,e){var r=e[0];return Math.acos(r.evaluate(t))}],atan:[jt,[jt],function(t,e){var r=e[0];return Math.atan(r.evaluate(t))}],min:[jt,gr(jt),function(t,e){return Math.min.apply(Math,e.map((function(e){return e.evaluate(t)})))}],max:[jt,gr(jt),function(t,e){return Math.max.apply(Math,e.map((function(e){return e.evaluate(t)})))}],abs:[jt,[jt],function(t,e){var r=e[0];return Math.abs(r.evaluate(t))}],round:[jt,[jt],function(t,e){var r=e[0].evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[jt,[jt],function(t,e){var r=e[0];return Math.floor(r.evaluate(t))}],ceil:[jt,[jt],function(t,e){var r=e[0];return Math.ceil(r.evaluate(t))}],"filter-==":[Nt,[qt,Zt],function(t,e){var r=e[0],n=e[1];return t.properties()[r.value]===n.value}],"filter-id-==":[Nt,[Zt],function(t,e){var r=e[0];return t.id()===r.value}],"filter-type-==":[Nt,[qt],function(t,e){var r=e[0];return t.geometryType()===r.value}],"filter-<":[Nt,[qt,Zt],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i<a}],"filter-id-<":[Nt,[Zt],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<i}],"filter->":[Nt,[qt,Zt],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>a}],"filter-id->":[Nt,[Zt],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>i}],"filter-<=":[Nt,[qt,Zt],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i<=a}],"filter-id-<=":[Nt,[Zt],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<=i}],"filter->=":[Nt,[qt,Zt],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>=a}],"filter-id->=":[Nt,[Zt],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>=i}],"filter-has":[Nt,[Zt],function(t,e){return e[0].value in t.properties()}],"filter-has-id":[Nt,[],function(t){return null!==t.id()}],"filter-type-in":[Nt,[Ht(qt)],function(t,e){return e[0].value.indexOf(t.geometryType())>=0}],"filter-id-in":[Nt,[Ht(Zt)],function(t,e){return e[0].value.indexOf(t.id())>=0}],"filter-in-small":[Nt,[qt,Ht(Zt)],function(t,e){var r=e[0];return e[1].value.indexOf(t.properties()[r.value])>=0}],"filter-in-large":[Nt,[qt,Ht(Zt)],function(t,e){var r=e[0],n=e[1];return function(t,e,r,n){for(;r<=n;){var i=r+n>>1;if(e[i]===t)return !0;e[i]>t?n=i-1:r=i+1;}return !1}(t.properties()[r.value],n.value,0,n.value.length-1)}],all:{type:Nt,overloads:[[[Nt,Nt],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)&&n.evaluate(t)}],[gr(Nt),function(t,e){for(var r=0,n=e;r<n.length;r+=1){if(!n[r].evaluate(t))return !1}return !0}]]},any:{type:Nt,overloads:[[[Nt,Nt],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)||n.evaluate(t)}],[gr(Nt),function(t,e){for(var r=0,n=e;r<n.length;r+=1){if(n[r].evaluate(t))return !0}return !1}]]},"!":[Nt,[Nt],function(t,e){return !e[0].evaluate(t)}],"is-supported-script":[Nt,[qt],function(t,e){var r=e[0],n=t.globals&&t.globals.isSupportedScript;return !n||n(r.evaluate(t))}],upcase:[qt,[qt],function(t,e){return e[0].evaluate(t).toUpperCase()}],downcase:[qt,[qt],function(t,e){return e[0].evaluate(t).toLowerCase()}],concat:[qt,gr(Zt),function(t,e){return e.map((function(e){return ue(e.evaluate(t))})).join("")}],"resolved-locale":[qt,[Gt],function(t,e){return e[0].evaluate(t).resolvedLocale()}]});var Br=function(t,e){this.expression=t,this._warningHistory={},this._evaluator=new ge,this._defaultValue=e?function(t){return "color"===t.type&&kr(t.default)?new ee(0,0,0,0):"color"===t.type?ee.parse(t.default)||null:void 0===t.default?null:t.default}(e):null,this._enumValues=e&&"enum"===e.type?e.values:null;};function Pr(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in yr}function Vr(t,e){var r=new ke(yr,[],e?function(t){var e={color:Kt,string:qt,number:jt,enum:qt,boolean:Nt,formatted:Jt,resolvedImage:Yt};if("array"===t.type)return Ht(e[t.value]||Zt,t.length);return e[t.type]}(e):void 0),n=r.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return n?xr(new Br(n,e)):br(r.errors)}Br.prototype.evaluateWithoutErrorHandling=function(t,e,r,n,i){return this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.availableImages=n||null,this._evaluator.formattedSection=i,this.expression.evaluate(this._evaluator)},Br.prototype.evaluate=function(t,e,r,n,i){this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.availableImages=n||null,this._evaluator.formattedSection=i||null;try{var a=this.expression.evaluate(this._evaluator);if(null==a||"number"==typeof a&&a!=a)return this._defaultValue;if(this._enumValues&&!(a in this._enumValues))throw new pe("Expected value to be one of "+Object.keys(this._enumValues).map((function(t){return JSON.stringify(t)})).join(", ")+", but found "+JSON.stringify(a)+" instead.");return a}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}};var Fr=function(t,e){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!we(e.expression);};Fr.prototype.evaluateWithoutErrorHandling=function(t,e,r,n,i){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i)},Fr.prototype.evaluate=function(t,e,r,n,i){return this._styleExpression.evaluate(t,e,r,n,i)};var Lr=function(t,e,r,n){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!we(e.expression),this.interpolationType=n;};function Dr(t,e){if("error"===(t=Vr(t,e)).result)return t;var r=t.value.expression,n=_e(r);if(!n&&!_r(e))return br([new Ot("","data expressions not supported")]);var i=Ae(r,["zoom"]);if(!i&&!wr(e))return br([new Ot("","zoom expressions not supported")]);var a=function t(e){var r=null;if(e instanceof We)r=t(e.result);else if(e instanceof $e)for(var n=0,i=e.args;n<i.length;n+=1){var a=i[n];if(r=t(a))break}else(e instanceof ze||e instanceof Ye)&&e.input instanceof xe&&"zoom"===e.input.name&&(r=e);if(r instanceof Ot)return r;e.eachChild((function(e){var n=t(e);n instanceof Ot?r=n:!r&&n?r=new Ot("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):r&&n&&r!==n&&(r=new Ot("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));}));return r}(r);if(!a&&!i)return br([new Ot("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]);if(a instanceof Ot)return br([a]);if(a instanceof Ye&&!Ar(e))return br([new Ot("",'"interpolate" expressions cannot be used with this property')]);if(!a)return xr(new Fr(n?"constant":"source",t.value));var o=a instanceof Ye?a.interpolation:void 0;return xr(new Lr(n?"camera":"composite",t.value,a.labels,o))}Lr.prototype.evaluateWithoutErrorHandling=function(t,e,r,n,i){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i)},Lr.prototype.evaluate=function(t,e,r,n,i){return this._styleExpression.evaluate(t,e,r,n,i)},Lr.prototype.interpolationFactor=function(t,e,r){return this.interpolationType?Ye.interpolationFactor(this.interpolationType,t,e,r):0};var Or=function(t,e){this._parameters=t,this._specification=e,Ft(this,function t(e,r){var n,i,a,o="color"===r.type,s=e.stops&&"object"==typeof e.stops[0][0],u=s||void 0!==e.property,l=s||!u,p=e.type||(Ar(r)?"exponential":"interval");if(o&&((e=Ft({},e)).stops&&(e.stops=e.stops.map((function(t){return [t[0],ee.parse(t[1])]}))),e.default?e.default=ee.parse(e.default):e.default=ee.parse(r.default)),e.colorSpace&&"rgb"!==e.colorSpace&&!Je[e.colorSpace])throw new Error("Unknown color space: "+e.colorSpace);if("exponential"===p)n=Er;else if("interval"===p)n=Tr;else if("categorical"===p){n=Cr,i=Object.create(null);for(var c=0,h=e.stops;c<h.length;c+=1){var f=h[c];i[f[0]]=f[1];}a=typeof e.stops[0][0];}else{if("identity"!==p)throw new Error('Unknown function type "'+p+'"');n=Mr;}if(s){for(var y={},d=[],m=0;m<e.stops.length;m++){var v=e.stops[m],g=v[0].zoom;void 0===y[g]&&(y[g]={zoom:g,type:e.type,property:e.property,default:e.default,stops:[]},d.push(g)),y[g].stops.push([v[0].value,v[1]]);}for(var x=[],b=0,_=d;b<_.length;b+=1){var w=_[b];x.push([y[w].zoom,t(y[w],r)]);}var A={name:"linear"};return {kind:"composite",interpolationType:A,interpolationFactor:Ye.interpolationFactor.bind(void 0,A),zoomStops:x.map((function(t){return t[0]})),evaluate:function(t,n){var i=t.zoom;return Er({stops:x,base:e.base},r,i).evaluate(i,n)}}}if(l){var S="exponential"===p?{name:"exponential",base:void 0!==e.base?e.base:1}:null;return {kind:"camera",interpolationType:S,interpolationFactor:Ye.interpolationFactor.bind(void 0,S),zoomStops:e.stops.map((function(t){return t[0]})),evaluate:function(t){var o=t.zoom;return n(e,r,o,i,a)}}}return {kind:"source",evaluate:function(t,o){var s=o&&o.properties?o.properties[e.property]:void 0;return void 0===s?zr(e.default,r.default):n(e,r,s,i,a)}}}(this._parameters,this._specification));};function Rr(t){var e=t.key,r=t.value,n=t.valueSpec||{},i=t.objectElementValidators||{},a=t.style,o=t.styleSpec,s=[],u=Sr(r);if("object"!==u)return [new Pt(e,r,"object expected, "+u+" found")];for(var l in r){var p=l.split(".")[0],c=n[p]||n["*"],h=void 0;if(i[p])h=i[p];else if(n[p])h=cn;else if(i["*"])h=i["*"];else{if(!n["*"]){s.push(new Pt(e,r[l],'unknown property "'+l+'"'));continue}h=cn;}s=s.concat(h({key:(e?e+".":e)+l,value:r[l],valueSpec:c,style:a,styleSpec:o,object:r,objectKey:l},r));}for(var f in n)i[f]||n[f].required&&void 0===n[f].default&&void 0===r[f]&&s.push(new Pt(e,r,'missing required property "'+f+'"'));return s}function Ur(t){var e=t.value,r=t.valueSpec,n=t.style,i=t.styleSpec,a=t.key,o=t.arrayElementValidator||cn;if("array"!==Sr(e))return [new Pt(a,e,"array expected, "+Sr(e)+" found")];if(r.length&&e.length!==r.length)return [new Pt(a,e,"array length "+r.length+" expected, length "+e.length+" found")];if(r["min-length"]&&e.length<r["min-length"])return [new Pt(a,e,"array length at least "+r["min-length"]+" expected, length "+e.length+" found")];var s={type:r.value,values:r.values};i.$version<7&&(s.function=r.function),"object"===Sr(r.value)&&(s=r.value);for(var u=[],l=0;l<e.length;l++)u=u.concat(o({array:e,arrayIndex:l,value:e[l],valueSpec:s,style:n,styleSpec:i,key:a+"["+l+"]"}));return u}function jr(t){var e=t.key,r=t.value,n=t.valueSpec,i=Sr(r);return "number"===i&&r!=r&&(i="NaN"),"number"!==i?[new Pt(e,r,"number expected, "+i+" found")]:"minimum"in n&&r<n.minimum?[new Pt(e,r,r+" is less than the minimum value "+n.minimum)]:"maximum"in n&&r>n.maximum?[new Pt(e,r,r+" is greater than the maximum value "+n.maximum)]:[]}function qr(t){var e,r,n,i=t.valueSpec,a=Lt(t.value.type),o={},s="categorical"!==a&&void 0===t.value.property,u=!s,l="array"===Sr(t.value.stops)&&"array"===Sr(t.value.stops[0])&&"object"===Sr(t.value.stops[0][0]),p=Rr({key:t.key,value:t.value,valueSpec:t.styleSpec.function,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===a)return [new Pt(t.key,t.value,'identity function may not have a "stops" property')];var e=[],r=t.value;e=e.concat(Ur({key:t.key,value:r,valueSpec:t.valueSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:c})),"array"===Sr(r)&&0===r.length&&e.push(new Pt(t.key,r,"array must have at least one stop"));return e},default:function(t){return cn({key:t.key,value:t.value,valueSpec:i,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===a&&s&&p.push(new Pt(t.key,t.value,'missing required property "property"')),"identity"===a||t.value.stops||p.push(new Pt(t.key,t.value,'missing required property "stops"')),"exponential"===a&&t.valueSpec.expression&&!Ar(t.valueSpec)&&p.push(new Pt(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(u&&!_r(t.valueSpec)?p.push(new Pt(t.key,t.value,"property functions not supported")):s&&!wr(t.valueSpec)&&p.push(new Pt(t.key,t.value,"zoom functions not supported"))),"categorical"!==a&&!l||void 0!==t.value.property||p.push(new Pt(t.key,t.value,'"property" property is required')),p;function c(t){var e=[],a=t.value,s=t.key;if("array"!==Sr(a))return [new Pt(s,a,"array expected, "+Sr(a)+" found")];if(2!==a.length)return [new Pt(s,a,"array length 2 expected, length "+a.length+" found")];if(l){if("object"!==Sr(a[0]))return [new Pt(s,a,"object expected, "+Sr(a[0])+" found")];if(void 0===a[0].zoom)return [new Pt(s,a,"object stop key must have zoom")];if(void 0===a[0].value)return [new Pt(s,a,"object stop key must have value")];if(n&&n>Lt(a[0].zoom))return [new Pt(s,a[0].zoom,"stop zoom values must appear in ascending order")];Lt(a[0].zoom)!==n&&(n=Lt(a[0].zoom),r=void 0,o={}),e=e.concat(Rr({key:s+"[0]",value:a[0],valueSpec:{zoom:{}},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:jr,value:h}}));}else e=e.concat(h({key:s+"[0]",value:a[0],valueSpec:{},style:t.style,styleSpec:t.styleSpec},a));return Pr(Dt(a[1]))?e.concat([new Pt(s+"[1]",a[1],"expressions are not allowed in function stops.")]):e.concat(cn({key:s+"[1]",value:a[1],valueSpec:i,style:t.style,styleSpec:t.styleSpec}))}function h(t,n){var s=Sr(t.value),u=Lt(t.value),l=null!==t.value?t.value:n;if(e){if(s!==e)return [new Pt(t.key,l,s+" stop domain type must match previous stop domain type "+e)]}else e=s;if("number"!==s&&"string"!==s&&"boolean"!==s)return [new Pt(t.key,l,"stop domain value must be a number, string, or boolean")];if("number"!==s&&"categorical"!==a){var p="number expected, "+s+" found";return _r(i)&&void 0===a&&(p+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new Pt(t.key,l,p)]}return "categorical"!==a||"number"!==s||isFinite(u)&&Math.floor(u)===u?"categorical"!==a&&"number"===s&&void 0!==r&&u<r?[new Pt(t.key,l,"stop domain values must appear in ascending order")]:(r=u,"categorical"===a&&u in o?[new Pt(t.key,l,"stop domain values must be unique")]:(o[u]=!0,[])):[new Pt(t.key,l,"integer expected, found "+u)]}}function Nr(t){var e=("property"===t.expressionContext?Dr:Vr)(Dt(t.value),t.valueSpec);if("error"===e.result)return e.value.map((function(e){return new Pt(""+t.key+e.key,t.value,e.message)}));var r=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&-1!==r.possibleOutputs().indexOf(void 0))return [new Pt(t.key,t.value,'Invalid data expression for "'+t.propertyKey+'". Output values must be contained as literals within the expression.')];if("property"===t.expressionContext&&"layout"===t.propertyType&&!we(r))return [new Pt(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!we(r))return [new Pt(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!Ae(r,["zoom","feature-state"]))return [new Pt(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!_e(r))return [new Pt(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return []}function Kr(t){var e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(Lt(r))&&i.push(new Pt(e,r,"expected one of ["+n.values.join(", ")+"], "+JSON.stringify(r)+" found")):-1===Object.keys(n.values).indexOf(Lt(r))&&i.push(new Pt(e,r,"expected one of ["+Object.keys(n.values).join(", ")+"], "+JSON.stringify(r)+" found")),i}function Xr(t){if(!0===t||!1===t)return !0;if(!Array.isArray(t)||0===t.length)return !1;switch(t[0]){case"has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":return t.length>=3&&Array.isArray(t[2]);case"!in":case"!has":case"none":return !1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case"any":case"all":for(var e=0,r=t.slice(1);e<r.length;e+=1){var n=r[e];if(!Xr(n)&&"boolean"!=typeof n)return !1}return !0;default:return !0}}Or.deserialize=function(t){return new Or(t._parameters,t._specification)},Or.serialize=function(t){return {_parameters:t._parameters,_specification:t._specification}};var Zr={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function Gr(t){if(null==t)return function(){return !0};Xr(t)||(t=Yr(t));var e=Vr(t,Zr);if("error"===e.result)throw new Error(e.value.map((function(t){return t.key+": "+t.message})).join(", "));return function(t,r){return e.value.evaluate(t,r)}}function Jr(t,e){return t<e?-1:t>e?1:0}function Yr(t){if(!t)return !0;var e,r=t[0];return t.length<=1?"any"!==r:"=="===r?Hr(t[1],t[2],"=="):"!="===r?Qr(Hr(t[1],t[2],"==")):"<"===r||">"===r||"<="===r||">="===r?Hr(t[1],t[2],r):"any"===r?(e=t.slice(1),["any"].concat(e.map(Yr))):"all"===r?["all"].concat(t.slice(1).map(Yr)):"none"===r?["all"].concat(t.slice(1).map(Yr).map(Qr)):"in"===r?$r(t[1],t.slice(2)):"!in"===r?Qr($r(t[1],t.slice(2))):"has"===r?Wr(t[1]):"!has"!==r||Qr(Wr(t[1]))}function Hr(t,e,r){switch(t){case"$type":return ["filter-type-"+r,e];case"$id":return ["filter-id-"+r,e];default:return ["filter-"+r,t,e]}}function $r(t,e){if(0===e.length)return !1;switch(t){case"$type":return ["filter-type-in",["literal",e]];case"$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((function(t){return typeof t!=typeof e[0]}))?["filter-in-large",t,["literal",e.sort(Jr)]]:["filter-in-small",t,["literal",e]]}}function Wr(t){switch(t){case"$type":return !0;case"$id":return ["filter-has-id"];default:return ["filter-has",t]}}function Qr(t){return ["!",t]}function tn(t){return Xr(Dt(t.value))?Nr(Ft({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):function t(e){var r=e.value;var n=e.key;if("array"!==Sr(r))return [new Pt(n,r,"array expected, "+Sr(r)+" found")];var i=e.styleSpec;var a;var o=[];if(r.length<1)return [new Pt(n,r,"filter array must have at least 1 element")];o=o.concat(Kr({key:n+"[0]",value:r[0],valueSpec:i.filter_operator,style:e.style,styleSpec:e.styleSpec}));switch(Lt(r[0])){case"<":case"<=":case">":case">=":r.length>=2&&"$type"===Lt(r[1])&&o.push(new Pt(n,r,'"$type" cannot be use with operator "'+r[0]+'"'));case"==":case"!=":3!==r.length&&o.push(new Pt(n,r,'filter array for operator "'+r[0]+'" must have 3 elements'));case"in":case"!in":r.length>=2&&"string"!==(a=Sr(r[1]))&&o.push(new Pt(n+"[1]",r[1],"string expected, "+a+" found"));for(var s=2;s<r.length;s++)a=Sr(r[s]),"$type"===Lt(r[1])?o=o.concat(Kr({key:n+"["+s+"]",value:r[s],valueSpec:i.geometry_type,style:e.style,styleSpec:e.styleSpec})):"string"!==a&&"number"!==a&&"boolean"!==a&&o.push(new Pt(n+"["+s+"]",r[s],"string, number, or boolean expected, "+a+" found"));break;case"any":case"all":case"none":for(var u=1;u<r.length;u++)o=o.concat(t({key:n+"["+u+"]",value:r[u],style:e.style,styleSpec:e.styleSpec}));break;case"has":case"!has":a=Sr(r[1]),2!==r.length?o.push(new Pt(n,r,'filter array for "'+r[0]+'" operator must have 2 elements')):"string"!==a&&o.push(new Pt(n+"[1]",r[1],"string expected, "+a+" found"));}return o}(t)}function en(t,e){var r=t.key,n=t.style,i=t.styleSpec,a=t.value,o=t.objectKey,s=i[e+"_"+t.layerType];if(!s)return [];var u=o.match(/^(.*)-transition$/);if("paint"===e&&u&&s[u[1]]&&s[u[1]].transition)return cn({key:r,value:a,valueSpec:i.transition,style:n,styleSpec:i});var l,p=t.valueSpec||s[o];if(!p)return [new Pt(r,a,'unknown property "'+o+'"')];if("string"===Sr(a)&&_r(p)&&!p.tokens&&(l=/^{([^}]+)}$/.exec(a)))return [new Pt(r,a,'"'+o+'" does not support interpolation syntax\nUse an identity property function instead: `{ "type": "identity", "property": '+JSON.stringify(l[1])+" }`.")];var c=[];return "symbol"===t.layerType&&("text-field"===o&&n&&!n.glyphs&&c.push(new Pt(r,a,'use of "text-field" requires a style "glyphs" property')),"text-font"===o&&kr(Dt(a))&&"identity"===Lt(a.type)&&c.push(new Pt(r,a,'"text-font" does not support identity functions'))),c.concat(cn({key:t.key,value:a,valueSpec:p,style:n,styleSpec:i,expressionContext:"property",propertyType:e,propertyKey:o}))}function rn(t){return en(t,"paint")}function nn(t){return en(t,"layout")}function an(t){var e=[],r=t.value,n=t.key,i=t.style,a=t.styleSpec;r.type||r.ref||e.push(new Pt(n,r,'either "type" or "ref" is required'));var o,s=Lt(r.type),u=Lt(r.ref);if(r.id)for(var l=Lt(r.id),p=0;p<t.arrayIndex;p++){var c=i.layers[p];Lt(c.id)===l&&e.push(new Pt(n,r.id,'duplicate layer id "'+r.id+'", previously used at line '+c.id.__line__));}if("ref"in r)["type","source","source-layer","filter","layout"].forEach((function(t){t in r&&e.push(new Pt(n,r[t],'"'+t+'" is prohibited for ref layers'));})),i.layers.forEach((function(t){Lt(t.id)===u&&(o=t);})),o?o.ref?e.push(new Pt(n,r.ref,"ref cannot reference another ref layer")):s=Lt(o.type):e.push(new Pt(n,r.ref,'ref layer "'+u+'" not found'));else if("background"!==s)if(r.source){var h=i.sources&&i.sources[r.source],f=h&&Lt(h.type);h?"vector"===f&&"raster"===s?e.push(new Pt(n,r.source,'layer "'+r.id+'" requires a raster source')):"raster"===f&&"raster"!==s?e.push(new Pt(n,r.source,'layer "'+r.id+'" requires a vector source')):"vector"!==f||r["source-layer"]?"raster-dem"===f&&"hillshade"!==s?e.push(new Pt(n,r.source,"raster-dem source can only be used with layer type 'hillshade'.")):"line"!==s||!r.paint||!r.paint["line-gradient"]||"geojson"===f&&h.lineMetrics||e.push(new Pt(n,r,'layer "'+r.id+'" specifies a line-gradient, which requires a GeoJSON source with `lineMetrics` enabled.')):e.push(new Pt(n,r,'layer "'+r.id+'" must specify a "source-layer"')):e.push(new Pt(n,r.source,'source "'+r.source+'" not found'));}else e.push(new Pt(n,r,'missing required property "source"'));return e=e.concat(Rr({key:n,value:r,valueSpec:a.layer,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(){return []},type:function(){return cn({key:n+".type",value:r.type,valueSpec:a.layer.type,style:t.style,styleSpec:t.styleSpec,object:r,objectKey:"type"})},filter:tn,layout:function(t){return Rr({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(t){return nn(Ft({layerType:s},t))}}})},paint:function(t){return Rr({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(t){return rn(Ft({layerType:s},t))}}})}}}))}function on(t){var e=t.value,r=t.key,n=Sr(e);return "string"!==n?[new Pt(r,e,"string expected, "+n+" found")]:[]}var sn={promoteId:function(t){var e=t.key,r=t.value;if("string"===Sr(r))return on({key:e,value:r});var n=[];for(var i in r)n.push.apply(n,on({key:e+"."+i,value:r[i]}));return n}};function un(t){var e=t.value,r=t.key,n=t.styleSpec,i=t.style;if(!e.type)return [new Pt(r,e,'"type" is required')];var a,o=Lt(e.type);switch(o){case"vector":case"raster":case"raster-dem":return a=Rr({key:r,value:e,valueSpec:n["source_"+o.replace("-","_")],style:t.style,styleSpec:n,objectElementValidators:sn});case"geojson":if(a=Rr({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,objectElementValidators:sn}),e.cluster)for(var s in e.clusterProperties){var u=e.clusterProperties[s],l=u[0],p=u[1],c="string"==typeof l?[l,["accumulated"],["get",s]]:l;a.push.apply(a,Nr({key:r+"."+s+".map",value:p,expressionContext:"cluster-map"})),a.push.apply(a,Nr({key:r+"."+s+".reduce",value:c,expressionContext:"cluster-reduce"}));}return a;case"video":return Rr({key:r,value:e,valueSpec:n.source_video,style:i,styleSpec:n});case"image":return Rr({key:r,value:e,valueSpec:n.source_image,style:i,styleSpec:n});case"canvas":return [new Pt(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Kr({key:r+".type",value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]},style:i,styleSpec:n})}}function ln(t){var e=t.value,r=t.styleSpec,n=r.light,i=t.style,a=[],o=Sr(e);if(void 0===e)return a;if("object"!==o)return a=a.concat([new Pt("light",e,"object expected, "+o+" found")]);for(var s in e){var u=s.match(/^(.*)-transition$/);a=u&&n[u[1]]&&n[u[1]].transition?a.concat(cn({key:s,value:e[s],valueSpec:r.transition,style:i,styleSpec:r})):n[s]?a.concat(cn({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r})):a.concat([new Pt(s,e[s],'unknown property "'+s+'"')]);}return a}var pn={"*":function(){return []},array:Ur,boolean:function(t){var e=t.value,r=t.key,n=Sr(e);return "boolean"!==n?[new Pt(r,e,"boolean expected, "+n+" found")]:[]},number:jr,color:function(t){var e=t.key,r=t.value,n=Sr(r);return "string"!==n?[new Pt(e,r,"color expected, "+n+" found")]:null===te(r)?[new Pt(e,r,'color expected, "'+r+'" found')]:[]},constants:Vt,enum:Kr,filter:tn,function:qr,layer:an,object:Rr,source:un,light:ln,string:on,formatted:function(t){return 0===on(t).length?[]:Nr(t)},resolvedImage:function(t){return 0===on(t).length?[]:Nr(t)}};function cn(t){var e=t.value,r=t.valueSpec,n=t.styleSpec;return r.expression&&kr(Lt(e))?qr(t):r.expression&&Pr(Dt(e))?Nr(t):r.type&&pn[r.type]?pn[r.type](t):Rr(Ft({},t,{valueSpec:r.type?n[r.type]:r}))}function hn(t){var e=t.value,r=t.key,n=on(t);return n.length?n:(-1===e.indexOf("{fontstack}")&&n.push(new Pt(r,e,'"glyphs" url must include a "{fontstack}" token')),-1===e.indexOf("{range}")&&n.push(new Pt(r,e,'"glyphs" url must include a "{range}" token')),n)}function fn(t,e){void 0===e&&(e=Bt);var r=[];return r=r.concat(cn({key:"",value:t,valueSpec:e.$root,styleSpec:e,style:t,objectElementValidators:{glyphs:hn,"*":function(){return []}}})),t.constants&&(r=r.concat(Vt({key:"constants",value:t.constants,style:t,styleSpec:e}))),yn(r)}function yn(t){return [].concat(t).sort((function(t,e){return t.line-e.line}))}function dn(t){return function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return yn(t.apply(this,e))}}fn.source=dn(un),fn.light=dn(ln),fn.layer=dn(an),fn.filter=dn(tn),fn.paintProperty=dn(rn),fn.layoutProperty=dn(nn);var mn=fn,vn=mn.light,gn=mn.paintProperty,xn=mn.layoutProperty;function bn(t,e){var r=!1;if(e&&e.length)for(var n=0,i=e;n<i.length;n+=1){var a=i[n];t.fire(new Et(new Error(a.message))),r=!0;}return r}var _n=An,wn=3;function An(t,e,r){var n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;var i=new Int32Array(this.arrayBuffer);t=i[0],e=i[1],r=i[2],this.d=e+2*r;for(var a=0;a<this.d*this.d;a++){var o=i[wn+a],s=i[wn+a+1];n.push(o===s?null:i.subarray(o,s));}var u=i[wn+n.length],l=i[wn+n.length+1];this.keys=i.subarray(u,l),this.bboxes=i.subarray(l),this.insert=this._insertReadonly;}else{this.d=e+2*r;for(var p=0;p<this.d*this.d;p++)n.push([]);this.keys=[],this.bboxes=[];}this.n=e,this.extent=t,this.padding=r,this.scale=e/t,this.uid=0;var c=r/e*t;this.min=-c,this.max=t+c;}An.prototype.insert=function(t,e,r,n,i){this._forEachCell(e,r,n,i,this._insertCell,this.uid++),this.keys.push(t),this.bboxes.push(e),this.bboxes.push(r),this.bboxes.push(n),this.bboxes.push(i);},An.prototype._insertReadonly=function(){throw "Cannot insert into a GridIndex created from an ArrayBuffer."},An.prototype._insertCell=function(t,e,r,n,i,a){this.cells[i].push(a);},An.prototype.query=function(t,e,r,n,i){var a=this.min,o=this.max;if(t<=a&&e<=a&&o<=r&&o<=n&&!i)return Array.prototype.slice.call(this.keys);var s=[];return this._forEachCell(t,e,r,n,this._queryCell,s,{},i),s},An.prototype._queryCell=function(t,e,r,n,i,a,o,s){var u=this.cells[i];if(null!==u)for(var l=this.keys,p=this.bboxes,c=0;c<u.length;c++){var h=u[c];if(void 0===o[h]){var f=4*h;(s?s(p[f+0],p[f+1],p[f+2],p[f+3]):t<=p[f+2]&&e<=p[f+3]&&r>=p[f+0]&&n>=p[f+1])?(o[h]=!0,a.push(l[h])):o[h]=!1;}}},An.prototype._forEachCell=function(t,e,r,n,i,a,o,s){for(var u=this._convertToCellCoord(t),l=this._convertToCellCoord(e),p=this._convertToCellCoord(r),c=this._convertToCellCoord(n),h=u;h<=p;h++)for(var f=l;f<=c;f++){var y=this.d*f+h;if((!s||s(this._convertFromCellCoord(h),this._convertFromCellCoord(f),this._convertFromCellCoord(h+1),this._convertFromCellCoord(f+1)))&&i.call(this,t,e,r,n,y,a,o,s))return}},An.prototype._convertFromCellCoord=function(t){return (t-this.padding)/this.scale},An.prototype._convertToCellCoord=function(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))},An.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var t=this.cells,e=wn+this.cells.length+1+1,r=0,n=0;n<this.cells.length;n++)r+=this.cells[n].length;var i=new Int32Array(e+r+this.keys.length+this.bboxes.length);i[0]=this.extent,i[1]=this.n,i[2]=this.padding;for(var a=e,o=0;o<t.length;o++){var s=t[o];i[wn+o]=a,i.set(s,a),a+=s.length;}return i[wn+t.length]=a,i.set(this.keys,a),a+=this.keys.length,i[wn+t.length+1]=a,i.set(this.bboxes,a),a+=this.bboxes.length,i.buffer};var Sn=self.ImageData,kn=self.ImageBitmap,In={};function zn(t,e,r){void 0===r&&(r={}),Object.defineProperty(e,"_classRegistryKey",{value:t,writeable:!1}),In[t]={klass:e,omit:r.omit||[],shallow:r.shallow||[]};}for(var Cn in zn("Object",Object),_n.serialize=function(t,e){var r=t.toArrayBuffer();return e&&e.push(r),{buffer:r}},_n.deserialize=function(t){return new _n(t.buffer)},zn("Grid",_n),zn("Color",ee),zn("Error",Error),zn("ResolvedImage",ae),zn("StylePropertyFunction",Or),zn("StyleExpression",Br,{omit:["_evaluator"]}),zn("ZoomDependentExpression",Lr),zn("ZoomConstantExpression",Fr),zn("CompoundExpression",xe,{omit:["_evaluate"]}),yr)yr[Cn]._classRegistryKey||zn("Expression_"+Cn,yr[Cn]);function Tn(t){return t&&"undefined"!=typeof ArrayBuffer&&(t instanceof ArrayBuffer||t.constructor&&"ArrayBuffer"===t.constructor.name)}function En(t){return kn&&t instanceof kn}function Mn(t,e){if(null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp)return t;if(Tn(t)||En(t))return e&&e.push(t),t;if(ArrayBuffer.isView(t)){var r=t;return e&&e.push(r.buffer),r}if(t instanceof Sn)return e&&e.push(t.data.buffer),t;if(Array.isArray(t)){for(var n=[],i=0,a=t;i<a.length;i+=1){var o=a[i];n.push(Mn(o,e));}return n}if("object"==typeof t){var s=t.constructor,u=s._classRegistryKey;if(!u)throw new Error("can't serialize object of unregistered class");var l=s.serialize?s.serialize(t,e):{};if(!s.serialize){for(var p in t)if(t.hasOwnProperty(p)&&!(In[u].omit.indexOf(p)>=0)){var c=t[p];l[p]=In[u].shallow.indexOf(p)>=0?c:Mn(c,e);}t instanceof Error&&(l.message=t.message);}if(l.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==u&&(l.$name=u),l}throw new Error("can't serialize object of type "+typeof t)}function Bn(t){if(null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp||Tn(t)||En(t)||ArrayBuffer.isView(t)||t instanceof Sn)return t;if(Array.isArray(t))return t.map(Bn);if("object"==typeof t){var e=t.$name||"Object",r=In[e].klass;if(!r)throw new Error("can't deserialize unregistered class "+e);if(r.deserialize)return r.deserialize(t);for(var n=Object.create(r.prototype),i=0,a=Object.keys(t);i<a.length;i+=1){var o=a[i];if("$name"!==o){var s=t[o];n[o]=In[e].shallow.indexOf(o)>=0?s:Bn(s);}}return n}throw new Error("can't deserialize object of type "+typeof t)}var Pn=function(){this.first=!0;};Pn.prototype.update=function(t,e){var r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoom<r&&(this.lastIntegerZoom=r,this.lastIntegerZoomTime=e),t!==this.lastZoom&&(this.lastZoom=t,this.lastFloorZoom=r,!0))};var Vn={"Latin-1 Supplement":function(t){return t>=128&&t<=255},Arabic:function(t){return t>=1536&&t<=1791},"Arabic Supplement":function(t){return t>=1872&&t<=1919},"Arabic Extended-A":function(t){return t>=2208&&t<=2303},"Hangul Jamo":function(t){return t>=4352&&t<=4607},"Unified Canadian Aboriginal Syllabics":function(t){return t>=5120&&t<=5759},Khmer:function(t){return t>=6016&&t<=6143},"Unified Canadian Aboriginal Syllabics Extended":function(t){return t>=6320&&t<=6399},"General Punctuation":function(t){return t>=8192&&t<=8303},"Letterlike Symbols":function(t){return t>=8448&&t<=8527},"Number Forms":function(t){return t>=8528&&t<=8591},"Miscellaneous Technical":function(t){return t>=8960&&t<=9215},"Control Pictures":function(t){return t>=9216&&t<=9279},"Optical Character Recognition":function(t){return t>=9280&&t<=9311},"Enclosed Alphanumerics":function(t){return t>=9312&&t<=9471},"Geometric Shapes":function(t){return t>=9632&&t<=9727},"Miscellaneous Symbols":function(t){return t>=9728&&t<=9983},"Miscellaneous Symbols and Arrows":function(t){return t>=11008&&t<=11263},"CJK Radicals Supplement":function(t){return t>=11904&&t<=12031},"Kangxi Radicals":function(t){return t>=12032&&t<=12255},"Ideographic Description Characters":function(t){return t>=12272&&t<=12287},"CJK Symbols and Punctuation":function(t){return t>=12288&&t<=12351},Hiragana:function(t){return t>=12352&&t<=12447},Katakana:function(t){return t>=12448&&t<=12543},Bopomofo:function(t){return t>=12544&&t<=12591},"Hangul Compatibility Jamo":function(t){return t>=12592&&t<=12687},Kanbun:function(t){return t>=12688&&t<=12703},"Bopomofo Extended":function(t){return t>=12704&&t<=12735},"CJK Strokes":function(t){return t>=12736&&t<=12783},"Katakana Phonetic Extensions":function(t){return t>=12784&&t<=12799},"Enclosed CJK Letters and Months":function(t){return t>=12800&&t<=13055},"CJK Compatibility":function(t){return t>=13056&&t<=13311},"CJK Unified Ideographs Extension A":function(t){return t>=13312&&t<=19903},"Yijing Hexagram Symbols":function(t){return t>=19904&&t<=19967},"CJK Unified Ideographs":function(t){return t>=19968&&t<=40959},"Yi Syllables":function(t){return t>=40960&&t<=42127},"Yi Radicals":function(t){return t>=42128&&t<=42191},"Hangul Jamo Extended-A":function(t){return t>=43360&&t<=43391},"Hangul Syllables":function(t){return t>=44032&&t<=55215},"Hangul Jamo Extended-B":function(t){return t>=55216&&t<=55295},"Private Use Area":function(t){return t>=57344&&t<=63743},"CJK Compatibility Ideographs":function(t){return t>=63744&&t<=64255},"Arabic Presentation Forms-A":function(t){return t>=64336&&t<=65023},"Vertical Forms":function(t){return t>=65040&&t<=65055},"CJK Compatibility Forms":function(t){return t>=65072&&t<=65103},"Small Form Variants":function(t){return t>=65104&&t<=65135},"Arabic Presentation Forms-B":function(t){return t>=65136&&t<=65279},"Halfwidth and Fullwidth Forms":function(t){return t>=65280&&t<=65519}};function Fn(t){for(var e=0,r=t;e<r.length;e+=1){if(Dn(r[e].charCodeAt(0)))return !0}return !1}function Ln(t){return !Vn.Arabic(t)&&(!Vn["Arabic Supplement"](t)&&(!Vn["Arabic Extended-A"](t)&&(!Vn["Arabic Presentation Forms-A"](t)&&!Vn["Arabic Presentation Forms-B"](t))))}function Dn(t){return 746===t||747===t||!(t<4352)&&(!!Vn["Bopomofo Extended"](t)||(!!Vn.Bopomofo(t)||(!(!Vn["CJK Compatibility Forms"](t)||t>=65097&&t<=65103)||(!!Vn["CJK Compatibility Ideographs"](t)||(!!Vn["CJK Compatibility"](t)||(!!Vn["CJK Radicals Supplement"](t)||(!!Vn["CJK Strokes"](t)||(!(!Vn["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||(!!Vn["CJK Unified Ideographs Extension A"](t)||(!!Vn["CJK Unified Ideographs"](t)||(!!Vn["Enclosed CJK Letters and Months"](t)||(!!Vn["Hangul Compatibility Jamo"](t)||(!!Vn["Hangul Jamo Extended-A"](t)||(!!Vn["Hangul Jamo Extended-B"](t)||(!!Vn["Hangul Jamo"](t)||(!!Vn["Hangul Syllables"](t)||(!!Vn.Hiragana(t)||(!!Vn["Ideographic Description Characters"](t)||(!!Vn.Kanbun(t)||(!!Vn["Kangxi Radicals"](t)||(!!Vn["Katakana Phonetic Extensions"](t)||(!(!Vn.Katakana(t)||12540===t)||(!(!Vn["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||(!(!Vn["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||(!!Vn["Unified Canadian Aboriginal Syllabics"](t)||(!!Vn["Unified Canadian Aboriginal Syllabics Extended"](t)||(!!Vn["Vertical Forms"](t)||(!!Vn["Yijing Hexagram Symbols"](t)||(!!Vn["Yi Syllables"](t)||!!Vn["Yi Radicals"](t))))))))))))))))))))))))))))))}function On(t){return !(Dn(t)||function(t){return !(!Vn["Latin-1 Supplement"](t)||167!==t&&169!==t&&174!==t&&177!==t&&188!==t&&189!==t&&190!==t&&215!==t&&247!==t)||(!(!Vn["General Punctuation"](t)||8214!==t&&8224!==t&&8225!==t&&8240!==t&&8241!==t&&8251!==t&&8252!==t&&8258!==t&&8263!==t&&8264!==t&&8265!==t&&8273!==t)||(!!Vn["Letterlike Symbols"](t)||(!!Vn["Number Forms"](t)||(!(!Vn["Miscellaneous Technical"](t)||!(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215))||(!(!Vn["Control Pictures"](t)||9251===t)||(!!Vn["Optical Character Recognition"](t)||(!!Vn["Enclosed Alphanumerics"](t)||(!!Vn["Geometric Shapes"](t)||(!(!Vn["Miscellaneous Symbols"](t)||t>=9754&&t<=9759)||(!(!Vn["Miscellaneous Symbols and Arrows"](t)||!(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243))||(!!Vn["CJK Symbols and Punctuation"](t)||(!!Vn.Katakana(t)||(!!Vn["Private Use Area"](t)||(!!Vn["CJK Compatibility Forms"](t)||(!!Vn["Small Form Variants"](t)||(!!Vn["Halfwidth and Fullwidth Forms"](t)||(8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)))))))))))))))))}(t))}function Rn(t){return t>=1424&&t<=2303||Vn["Arabic Presentation Forms-A"](t)||Vn["Arabic Presentation Forms-B"](t)}function Un(t,e){return !(!e&&Rn(t))&&!(t>=2304&&t<=3583||t>=3840&&t<=4255||Vn.Khmer(t))}function jn(t){for(var e=0,r=t;e<r.length;e+=1){if(Rn(r[e].charCodeAt(0)))return !0}return !1}var qn="deferred",Nn="loading",Kn="loaded",Xn=null,Zn="unavailable",Gn=null,Jn=function(t){Xn&&Xn(t);};function Yn(){Hn.fire(new Tt("pluginStateChange",{pluginStatus:Zn,pluginURL:Gn}));}var Hn=new Mt,$n=function(){return Zn},Wn=function(){if(Zn!==qn||!Gn)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Zn=Nn,Yn(),Gn&&_t({url:Gn},(function(t){t?Jn(t):(Zn=Kn,Yn());}));},Qn={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:function(){return Zn===Kn||null!=Qn.applyArabicShaping},isLoading:function(){return Zn===Nn},setState:function(t){Zn=t.pluginStatus,Gn=t.pluginURL;},isParsed:function(){return null!=Qn.applyArabicShaping&&null!=Qn.processBidirectionalText&&null!=Qn.processStyledBidirectionalText},getPluginURL:function(){return Gn}},ti=function(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new Pn,this.transition={});};ti.prototype.isSupportedScript=function(t){return function(t,e){for(var r=0,n=t;r<n.length;r+=1){if(!Un(n[r].charCodeAt(0),e))return !1}return !0}(t,Qn.isLoaded())},ti.prototype.crossFadingFactor=function(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)},ti.prototype.getCrossfadeParameters=function(){var t=this.zoom,e=t-Math.floor(t),r=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}};var ei=function(t,e){this.property=t,this.value=e,this.expression=function(t,e){if(kr(t))return new Or(t,e);if(Pr(t)){var r=Dr(t,e);if("error"===r.result)throw new Error(r.value.map((function(t){return t.key+": "+t.message})).join(", "));return r.value}var n=t;return "string"==typeof t&&"color"===e.type&&(n=ee.parse(t)),{kind:"constant",evaluate:function(){return n}}}(void 0===e?t.specification.default:e,t.specification);};ei.prototype.isDataDriven=function(){return "source"===this.expression.kind||"composite"===this.expression.kind},ei.prototype.possiblyEvaluate=function(t,e){return this.property.possiblyEvaluate(this,t,e)};var ri=function(t){this.property=t,this.value=new ei(t,void 0);};ri.prototype.transitioned=function(t,e){return new ii(this.property,this.value,e,p({},t.transition,this.transition),t.now)},ri.prototype.untransitioned=function(){return new ii(this.property,this.value,null,{},0)};var ni=function(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues);};ni.prototype.getValue=function(t){return x(this._values[t].value.value)},ni.prototype.setValue=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new ri(this._values[t].property)),this._values[t].value=new ei(this._values[t].property,null===e?void 0:x(e));},ni.prototype.getTransition=function(t){return x(this._values[t].transition)},ni.prototype.setTransition=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new ri(this._values[t].property)),this._values[t].transition=x(e)||void 0;},ni.prototype.serialize=function(){for(var t={},e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e],i=this.getValue(n);void 0!==i&&(t[n]=i);var a=this.getTransition(n);void 0!==a&&(t[n+"-transition"]=a);}return t},ni.prototype.transitioned=function(t,e){for(var r=new ai(this._properties),n=0,i=Object.keys(this._values);n<i.length;n+=1){var a=i[n];r._values[a]=this._values[a].transitioned(t,e._values[a]);}return r},ni.prototype.untransitioned=function(){for(var t=new ai(this._properties),e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e];t._values[n]=this._values[n].untransitioned();}return t};var ii=function(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);};ii.prototype.possiblyEvaluate=function(t,e){var r=t.now||0,n=this.value.possiblyEvaluate(t,e),i=this.prior;if(i){if(r>this.end)return this.prior=null,n;if(this.value.isDataDriven())return this.prior=null,n;if(r<this.begin)return i.possiblyEvaluate(t,e);var a=(r-this.begin)/(this.end-this.begin);return this.property.interpolate(i.possiblyEvaluate(t,e),n,function(t){if(t<=0)return 0;if(t>=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}(a))}return n};var ai=function(t){this._properties=t,this._values=Object.create(t.defaultTransitioningPropertyValues);};ai.prototype.possiblyEvaluate=function(t,e){for(var r=new ui(this._properties),n=0,i=Object.keys(this._values);n<i.length;n+=1){var a=i[n];r._values[a]=this._values[a].possiblyEvaluate(t,e);}return r},ai.prototype.hasTransition=function(){for(var t=0,e=Object.keys(this._values);t<e.length;t+=1){var r=e[t];if(this._values[r].prior)return !0}return !1};var oi=function(t){this._properties=t,this._values=Object.create(t.defaultPropertyValues);};oi.prototype.getValue=function(t){return x(this._values[t].value)},oi.prototype.setValue=function(t,e){this._values[t]=new ei(this._values[t].property,null===e?void 0:x(e));},oi.prototype.serialize=function(){for(var t={},e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e],i=this.getValue(n);void 0!==i&&(t[n]=i);}return t},oi.prototype.possiblyEvaluate=function(t,e){for(var r=new ui(this._properties),n=0,i=Object.keys(this._values);n<i.length;n+=1){var a=i[n];r._values[a]=this._values[a].possiblyEvaluate(t,e);}return r};var si=function(t,e,r){this.property=t,this.value=e,this.parameters=r;};si.prototype.isConstant=function(){return "constant"===this.value.kind},si.prototype.constantOr=function(t){return "constant"===this.value.kind?this.value.value:t},si.prototype.evaluate=function(t,e,r){return this.property.evaluate(this.value,this.parameters,t,e,r)};var ui=function(t){this._properties=t,this._values=Object.create(t.defaultPossiblyEvaluatedValues);};ui.prototype.get=function(t){return this._values[t]};var li=function(t){this.specification=t;};li.prototype.possiblyEvaluate=function(t,e){return t.expression.evaluate(e)},li.prototype.interpolate=function(t,e,r){var n=Te[this.specification.type];return n?n(t,e,r):t};var pi=function(t,e){this.specification=t,this.overrides=e;};pi.prototype.possiblyEvaluate=function(t,e,r){return "constant"===t.expression.kind||"camera"===t.expression.kind?new si(this,{kind:"constant",value:t.expression.evaluate(e,null,{},r)},e):new si(this,t.expression,e)},pi.prototype.interpolate=function(t,e,r){if("constant"!==t.value.kind||"constant"!==e.value.kind)return t;if(void 0===t.value.value||void 0===e.value.value)return new si(this,{kind:"constant",value:void 0},t.parameters);var n=Te[this.specification.type];return n?new si(this,{kind:"constant",value:n(t.value.value,e.value.value,r)},t.parameters):t},pi.prototype.evaluate=function(t,e,r,n,i){return "constant"===t.kind?t.value:t.evaluate(e,r,n,i)};var ci=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.possiblyEvaluate=function(t,e,r){if(void 0===t.value)return new si(this,{kind:"constant",value:void 0},e);if("constant"===t.expression.kind){var n=t.expression.evaluate(e,null,{},r),i="resolvedImage"===t.property.specification.type&&"string"!=typeof n?n.name:n,a=this._calculate(i,i,i,e);return new si(this,{kind:"constant",value:a},e)}if("camera"===t.expression.kind){var o=this._calculate(t.expression.evaluate({zoom:e.zoom-1}),t.expression.evaluate({zoom:e.zoom}),t.expression.evaluate({zoom:e.zoom+1}),e);return new si(this,{kind:"constant",value:o},e)}return new si(this,t.expression,e)},e.prototype.evaluate=function(t,e,r,n,i){if("source"===t.kind){var a=t.evaluate(e,r,n,i);return this._calculate(a,a,a,e)}return "composite"===t.kind?this._calculate(t.evaluate({zoom:Math.floor(e.zoom)-1},r,n),t.evaluate({zoom:Math.floor(e.zoom)},r,n),t.evaluate({zoom:Math.floor(e.zoom)+1},r,n),e):t.value},e.prototype._calculate=function(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}},e.prototype.interpolate=function(t){return t},e}(pi),hi=function(t){this.specification=t;};hi.prototype.possiblyEvaluate=function(t,e,r){if(void 0!==t.value){if("constant"===t.expression.kind){var n=t.expression.evaluate(e,null,{},r);return this._calculate(n,n,n,e)}return this._calculate(t.expression.evaluate(new ti(Math.floor(e.zoom-1),e)),t.expression.evaluate(new ti(Math.floor(e.zoom),e)),t.expression.evaluate(new ti(Math.floor(e.zoom+1),e)),e)}},hi.prototype._calculate=function(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}},hi.prototype.interpolate=function(t){return t};var fi=function(t){this.specification=t;};fi.prototype.possiblyEvaluate=function(t,e,r){return !!t.expression.evaluate(e,null,{},r)},fi.prototype.interpolate=function(){return !1};var yi=function(t){for(var e in this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[],t){var r=t[e];r.specification.overridable&&this.overridableProperties.push(e);var n=this.defaultPropertyValues[e]=new ei(r,void 0),i=this.defaultTransitionablePropertyValues[e]=new ri(r);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}};zn("DataDrivenProperty",pi),zn("DataConstantProperty",li),zn("CrossFadedDataDrivenProperty",ci),zn("CrossFadedProperty",hi),zn("ColorRampProperty",fi);var di=function(t){function e(e,r){if(t.call(this),this.id=e.id,this.type=e.type,this._featureFilter=function(){return !0},"custom"!==e.type&&(e=e,this.metadata=e.metadata,this.minzoom=e.minzoom,this.maxzoom=e.maxzoom,"background"!==e.type&&(this.source=e.source,this.sourceLayer=e["source-layer"],this.filter=e.filter),r.layout&&(this._unevaluatedLayout=new oi(r.layout)),r.paint)){for(var n in this._transitionablePaint=new ni(r.paint),e.paint)this.setPaintProperty(n,e.paint[n],{validate:!1});for(var i in e.layout)this.setLayoutProperty(i,e.layout[i],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned();}}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getCrossfadeParameters=function(){return this._crossfadeParameters},e.prototype.getLayoutProperty=function(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)},e.prototype.setLayoutProperty=function(t,e,r){if(void 0===r&&(r={}),null!=e){var n="layers."+this.id+".layout."+t;if(this._validate(xn,n,t,e,r))return}"visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e;},e.prototype.getPaintProperty=function(t){return m(t,"-transition")?this._transitionablePaint.getTransition(t.slice(0,-"-transition".length)):this._transitionablePaint.getValue(t)},e.prototype.setPaintProperty=function(t,e,r){if(void 0===r&&(r={}),null!=e){var n="layers."+this.id+".paint."+t;if(this._validate(gn,n,t,e,r))return !1}if(m(t,"-transition"))return this._transitionablePaint.setTransition(t.slice(0,-"-transition".length),e||void 0),!1;var i=this._transitionablePaint._values[t],a="cross-faded-data-driven"===i.property.specification["property-type"],o=i.value.isDataDriven(),s=i.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);var u=this._transitionablePaint._values[t].value;return u.isDataDriven()||o||a||this._handleOverridablePaintPropertyUpdate(t,s,u)},e.prototype._handleSpecialPaintPropertyUpdate=function(t){},e.prototype._handleOverridablePaintPropertyUpdate=function(t,e,r){return !1},e.prototype.isHidden=function(t){return !!(this.minzoom&&t<this.minzoom)||(!!(this.maxzoom&&t>=this.maxzoom)||"none"===this.visibility)},e.prototype.updateTransitions=function(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);},e.prototype.hasTransition=function(){return this._transitioningPaint.hasTransition()},e.prototype.recalculate=function(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,e);},e.prototype.serialize=function(){var t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),g(t,(function(t,e){return !(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)}))},e.prototype._validate=function(t,e,r,n,i){return void 0===i&&(i={}),(!i||!1!==i.validate)&&bn(this,t.call(mn,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:Bt,style:{glyphs:!0,sprite:!0}}))},e.prototype.is3D=function(){return !1},e.prototype.isTileClipped=function(){return !1},e.prototype.hasOffscreenPass=function(){return !1},e.prototype.resize=function(){},e.prototype.isStateDependent=function(){for(var t in this.paint._values){var e=this.paint.get(t);if(e instanceof si&&_r(e.property.specification)&&(("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent))return !0}return !1},e}(Mt),mi={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array},vi=function(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;},gi=function(){this.isTransferred=!1,this.capacity=-1,this.resize(0);};function xi(t,e){void 0===e&&(e=1);var r=0,n=0;return {members:t.map((function(t){var i,a=(i=t.type,mi[i].BYTES_PER_ELEMENT),o=r=bi(r,Math.max(e,a)),s=t.components||1;return n=Math.max(n,a),r+=a*s,{name:t.name,type:t.type,components:s,offset:o}})),size:bi(r,Math.max(n,e)),alignment:e}}function bi(t,e){return Math.ceil(t/e)*e}gi.serialize=function(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}},gi.deserialize=function(t){var e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e},gi.prototype._trim=function(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());},gi.prototype.clear=function(){this.length=0;},gi.prototype.resize=function(t){this.reserve(t),this.length=t;},gi.prototype.reserve=function(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);var e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}},gi.prototype._refreshViews=function(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")};var _i=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;return this.resize(r+1),this.emplace(r,t,e)},e.prototype.emplace=function(t,e,r){var n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t},e}(gi);_i.prototype.bytesPerElement=4,zn("StructArrayLayout2i4",_i);var wi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)},e.prototype.emplace=function(t,e,r,n,i){var a=4*t;return this.int16[a+0]=e,this.int16[a+1]=r,this.int16[a+2]=n,this.int16[a+3]=i,t},e}(gi);wi.prototype.bytesPerElement=8,zn("StructArrayLayout4i8",wi);var Ai=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,a)},e.prototype.emplace=function(t,e,r,n,i,a,o){var s=6*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,this.int16[s+4]=a,this.int16[s+5]=o,t},e}(gi);Ai.prototype.bytesPerElement=12,zn("StructArrayLayout2i4i12",Ai);var Si=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,a)},e.prototype.emplace=function(t,e,r,n,i,a,o){var s=4*t,u=8*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.uint8[u+4]=n,this.uint8[u+5]=i,this.uint8[u+6]=a,this.uint8[u+7]=o,t},e}(gi);Si.prototype.bytesPerElement=8,zn("StructArrayLayout2i4ub8",Si);var ki=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s){var u=this.length;return this.resize(u+1),this.emplace(u,t,e,r,n,i,a,o,s)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u){var l=8*t;return this.uint16[l+0]=e,this.uint16[l+1]=r,this.uint16[l+2]=n,this.uint16[l+3]=i,this.uint16[l+4]=a,this.uint16[l+5]=o,this.uint16[l+6]=s,this.uint16[l+7]=u,t},e}(gi);ki.prototype.bytesPerElement=16,zn("StructArrayLayout8ui16",ki);var Ii=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p,c){var h=this.length;return this.resize(h+1),this.emplace(h,t,e,r,n,i,a,o,s,u,l,p,c)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c,h){var f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=a,this.uint16[f+5]=o,this.uint16[f+6]=s,this.uint16[f+7]=u,this.int16[f+8]=l,this.int16[f+9]=p,this.int16[f+10]=c,this.int16[f+11]=h,t},e}(gi);Ii.prototype.bytesPerElement=24,zn("StructArrayLayout4i4ui4i24",Ii);var zi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t},e}(gi);zi.prototype.bytesPerElement=12,zn("StructArrayLayout3f12",zi);var Ci=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;return this.resize(e+1),this.emplace(e,t)},e.prototype.emplace=function(t,e){var r=1*t;return this.uint32[r+0]=e,t},e}(gi);Ci.prototype.bytesPerElement=4,zn("StructArrayLayout1ul4",Ci);var Ti=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p){var c=this.length;return this.resize(c+1),this.emplace(c,t,e,r,n,i,a,o,s,u,l,p)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c){var h=12*t,f=6*t;return this.int16[h+0]=e,this.int16[h+1]=r,this.int16[h+2]=n,this.int16[h+3]=i,this.int16[h+4]=a,this.int16[h+5]=o,this.uint32[f+3]=s,this.uint16[h+8]=u,this.uint16[h+9]=l,this.int16[h+10]=p,this.int16[h+11]=c,t},e}(gi);Ti.prototype.bytesPerElement=24,zn("StructArrayLayout6i1ul2ui2i24",Ti);var Ei=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,a)},e.prototype.emplace=function(t,e,r,n,i,a,o){var s=6*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,this.int16[s+4]=a,this.int16[s+5]=o,t},e}(gi);Ei.prototype.bytesPerElement=12,zn("StructArrayLayout2i2i2i12",Ei);var Mi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)},e.prototype.emplace=function(t,e,r,n,i){var a=12*t,o=3*t;return this.uint8[a+0]=e,this.uint8[a+1]=r,this.float32[o+1]=n,this.float32[o+2]=i,t},e}(gi);Mi.prototype.bytesPerElement=12,zn("StructArrayLayout2ub2f12",Mi);var Bi=function(t){function | (){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m){var v=this.length;return this.resize(v+1),this.emplace(v,t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v){var g=24*t,x=12*t,b=48*t;return this.int16[g+0]=e,this.int16[g+1]=r,this.uint16[g+2]=n,this.uint16[g+3]=i,this.uint32[x+2]=a,this.uint32[x+3]=o,this.uint32[x+4]=s,this.uint16[g+10]=u,this.uint16[g+11]=l,this.uint16[g+12]=p,this.float32[x+7]=c,this.float32[x+8]=h,this.uint8[b+36]=f,this.uint8[b+37]=y,this.uint8[b+38]=d,this.uint32[x+10]=m,this.int16[g+22]=v,t},e}(gi);Bi.prototype.bytesPerElement=48,zn("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",Bi);var Pi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,_,w,A,S,k){var I=this.length;return this.resize(I+1),this.emplace(I,t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,_,w,A,S,k)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,_,w,A,S,k,I){var z=30*t,C=15*t;return this.int16[z+0]=e,this.int16[z+1]=r,this.int16[z+2]=n,this.int16[z+3]=i,this.int16[z+4]=a,this.int16[z+5]=o,this.int16[z+6]=s,this.int16[z+7]=u,this.uint16[z+8]=l,this.uint16[z+9]=p,this.uint16[z+10]=c,this.uint16[z+11]=h,this.uint16[z+12]=f,this.uint16[z+13]=y,this.uint16[z+14]=d,this.uint16[z+15]=m,this.uint16[z+16]=v,this.uint16[z+17]=g,this.uint16[z+18]=x,this.uint16[z+19]=b,this.uint16[z+20]=_,this.uint16[z+21]=w,this.uint32[C+11]=A,this.float32[C+12]=S,this.float32[C+13]=k,this.float32[C+14]=I,t},e}(gi);Pi.prototype.bytesPerElement=60,zn("StructArrayLayout8i14ui1ul3f60",Pi);var Vi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;return this.resize(e+1),this.emplace(e,t)},e.prototype.emplace=function(t,e){var r=1*t;return this.float32[r+0]=e,t},e}(gi);Vi.prototype.bytesPerElement=4,zn("StructArrayLayout1f4",Vi);var Fi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t},e}(gi);Fi.prototype.bytesPerElement=6,zn("StructArrayLayout3i6",Fi);var Li=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=2*t,a=4*t;return this.uint32[i+0]=e,this.uint16[a+2]=r,this.uint16[a+3]=n,t},e}(gi);Li.prototype.bytesPerElement=8,zn("StructArrayLayout1ul2ui8",Li);var Di=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t},e}(gi);Di.prototype.bytesPerElement=6,zn("StructArrayLayout3ui6",Di);var Oi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;return this.resize(r+1),this.emplace(r,t,e)},e.prototype.emplace=function(t,e,r){var n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t},e}(gi);Oi.prototype.bytesPerElement=4,zn("StructArrayLayout2ui4",Oi);var Ri=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;return this.resize(e+1),this.emplace(e,t)},e.prototype.emplace=function(t,e){var r=1*t;return this.uint16[r+0]=e,t},e}(gi);Ri.prototype.bytesPerElement=2,zn("StructArrayLayout1ui2",Ri);var Ui=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;return this.resize(r+1),this.emplace(r,t,e)},e.prototype.emplace=function(t,e,r){var n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t},e}(gi);Ui.prototype.bytesPerElement=8,zn("StructArrayLayout2f8",Ui);var ji=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)},e.prototype.emplace=function(t,e,r,n,i){var a=4*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.float32[a+3]=i,t},e}(gi);ji.prototype.bytesPerElement=16,zn("StructArrayLayout4f16",ji);var qi=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={anchorPointX:{configurable:!0},anchorPointY:{configurable:!0},x1:{configurable:!0},y1:{configurable:!0},x2:{configurable:!0},y2:{configurable:!0},featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0},radius:{configurable:!0},signedDistanceFromAnchor:{configurable:!0},anchorPoint:{configurable:!0}};return r.anchorPointX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorPointX.set=function(t){this._structArray.int16[this._pos2+0]=t;},r.anchorPointY.get=function(){return this._structArray.int16[this._pos2+1]},r.anchorPointY.set=function(t){this._structArray.int16[this._pos2+1]=t;},r.x1.get=function(){return this._structArray.int16[this._pos2+2]},r.x1.set=function(t){this._structArray.int16[this._pos2+2]=t;},r.y1.get=function(){return this._structArray.int16[this._pos2+3]},r.y1.set=function(t){this._structArray.int16[this._pos2+3]=t;},r.x2.get=function(){return this._structArray.int16[this._pos2+4]},r.x2.set=function(t){this._structArray.int16[this._pos2+4]=t;},r.y2.get=function(){return this._structArray.int16[this._pos2+5]},r.y2.set=function(t){this._structArray.int16[this._pos2+5]=t;},r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.featureIndex.set=function(t){this._structArray.uint32[this._pos4+3]=t;},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+8]},r.sourceLayerIndex.set=function(t){this._structArray.uint16[this._pos2+8]=t;},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+9]},r.bucketIndex.set=function(t){this._structArray.uint16[this._pos2+9]=t;},r.radius.get=function(){return this._structArray.int16[this._pos2+10]},r.radius.set=function(t){this._structArray.int16[this._pos2+10]=t;},r.signedDistanceFromAnchor.get=function(){return this._structArray.int16[this._pos2+11]},r.signedDistanceFromAnchor.set=function(t){this._structArray.int16[this._pos2+11]=t;},r.anchorPoint.get=function(){return new i(this.anchorPointX,this.anchorPointY)},Object.defineProperties(e.prototype,r),e}(vi);qi.prototype.size=24;var Ni=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){return new qi(this,t)},e}(Ti);zn("CollisionBoxArray",Ni);var Ki=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={anchorX:{configurable:!0},anchorY:{configurable:!0},glyphStartIndex:{configurable:!0},numGlyphs:{configurable:!0},vertexStartIndex:{configurable:!0},lineStartIndex:{configurable:!0},lineLength:{configurable:!0},segment:{configurable:!0},lowerSize:{configurable:!0},upperSize:{configurable:!0},lineOffsetX:{configurable:!0},lineOffsetY:{configurable:!0},writingMode:{configurable:!0},placedOrientation:{configurable:!0},hidden:{configurable:!0},crossTileID:{configurable:!0},associatedIconIndex:{configurable:!0}};return r.anchorX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorX.set=function(t){this._structArray.int16[this._pos2+0]=t;},r.anchorY.get=function(){return this._structArray.int16[this._pos2+1]},r.anchorY.set=function(t){this._structArray.int16[this._pos2+1]=t;},r.glyphStartIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.glyphStartIndex.set=function(t){this._structArray.uint16[this._pos2+2]=t;},r.numGlyphs.get=function(){return this._structArray.uint16[this._pos2+3]},r.numGlyphs.set=function(t){this._structArray.uint16[this._pos2+3]=t;},r.vertexStartIndex.get=function(){return this._structArray.uint32[this._pos4+2]},r.vertexStartIndex.set=function(t){this._structArray.uint32[this._pos4+2]=t;},r.lineStartIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.lineStartIndex.set=function(t){this._structArray.uint32[this._pos4+3]=t;},r.lineLength.get=function(){return this._structArray.uint32[this._pos4+4]},r.lineLength.set=function(t){this._structArray.uint32[this._pos4+4]=t;},r.segment.get=function(){return this._structArray.uint16[this._pos2+10]},r.segment.set=function(t){this._structArray.uint16[this._pos2+10]=t;},r.lowerSize.get=function(){return this._structArray.uint16[this._pos2+11]},r.lowerSize.set=function(t){this._structArray.uint16[this._pos2+11]=t;},r.upperSize.get=function(){return this._structArray.uint16[this._pos2+12]},r.upperSize.set=function(t){this._structArray.uint16[this._pos2+12]=t;},r.lineOffsetX.get=function(){return this._structArray.float32[this._pos4+7]},r.lineOffsetX.set=function(t){this._structArray.float32[this._pos4+7]=t;},r.lineOffsetY.get=function(){return this._structArray.float32[this._pos4+8]},r.lineOffsetY.set=function(t){this._structArray.float32[this._pos4+8]=t;},r.writingMode.get=function(){return this._structArray.uint8[this._pos1+36]},r.writingMode.set=function(t){this._structArray.uint8[this._pos1+36]=t;},r.placedOrientation.get=function(){return this._structArray.uint8[this._pos1+37]},r.placedOrientation.set=function(t){this._structArray.uint8[this._pos1+37]=t;},r.hidden.get=function(){return this._structArray.uint8[this._pos1+38]},r.hidden.set=function(t){this._structArray.uint8[this._pos1+38]=t;},r.crossTileID.get=function(){return this._structArray.uint32[this._pos4+10]},r.crossTileID.set=function(t){this._structArray.uint32[this._pos4+10]=t;},r.associatedIconIndex.get=function(){return this._structArray.int16[this._pos2+22]},r.associatedIconIndex.set=function(t){this._structArray.int16[this._pos2+22]=t;},Object.defineProperties(e.prototype,r),e}(vi);Ki.prototype.size=48;var Xi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){return new Ki(this,t)},e}(Bi);zn("PlacedSymbolArray",Xi);var Zi=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={anchorX:{configurable:!0},anchorY:{configurable:!0},rightJustifiedTextSymbolIndex:{configurable:!0},centerJustifiedTextSymbolIndex:{configurable:!0},leftJustifiedTextSymbolIndex:{configurable:!0},verticalPlacedTextSymbolIndex:{configurable:!0},placedIconSymbolIndex:{configurable:!0},verticalPlacedIconSymbolIndex:{configurable:!0},key:{configurable:!0},textBoxStartIndex:{configurable:!0},textBoxEndIndex:{configurable:!0},verticalTextBoxStartIndex:{configurable:!0},verticalTextBoxEndIndex:{configurable:!0},iconBoxStartIndex:{configurable:!0},iconBoxEndIndex:{configurable:!0},verticalIconBoxStartIndex:{configurable:!0},verticalIconBoxEndIndex:{configurable:!0},featureIndex:{configurable:!0},numHorizontalGlyphVertices:{configurable:!0},numVerticalGlyphVertices:{configurable:!0},numIconVertices:{configurable:!0},numVerticalIconVertices:{configurable:!0},crossTileID:{configurable:!0},textBoxScale:{configurable:!0},textOffset0:{configurable:!0},textOffset1:{configurable:!0}};return r.anchorX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorX.set=function(t){this._structArray.int16[this._pos2+0]=t;},r.anchorY.get=function(){return this._structArray.int16[this._pos2+1]},r.anchorY.set=function(t){this._structArray.int16[this._pos2+1]=t;},r.rightJustifiedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+2]},r.rightJustifiedTextSymbolIndex.set=function(t){this._structArray.int16[this._pos2+2]=t;},r.centerJustifiedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+3]},r.centerJustifiedTextSymbolIndex.set=function(t){this._structArray.int16[this._pos2+3]=t;},r.leftJustifiedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+4]},r.leftJustifiedTextSymbolIndex.set=function(t){this._structArray.int16[this._pos2+4]=t;},r.verticalPlacedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+5]},r.verticalPlacedTextSymbolIndex.set=function(t){this._structArray.int16[this._pos2+5]=t;},r.placedIconSymbolIndex.get=function(){return this._structArray.int16[this._pos2+6]},r.placedIconSymbolIndex.set=function(t){this._structArray.int16[this._pos2+6]=t;},r.verticalPlacedIconSymbolIndex.get=function(){return this._structArray.int16[this._pos2+7]},r.verticalPlacedIconSymbolIndex.set=function(t){this._structArray.int16[this._pos2+7]=t;},r.key.get=function(){return this._structArray.uint16[this._pos2+8]},r.key.set=function(t){this._structArray.uint16[this._pos2+8]=t;},r.textBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+9]},r.textBoxStartIndex.set=function(t){this._structArray.uint16[this._pos2+9]=t;},r.textBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+10]},r.textBoxEndIndex.set=function(t){this._structArray.uint16[this._pos2+10]=t;},r.verticalTextBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+11]},r.verticalTextBoxStartIndex.set=function(t){this._structArray.uint16[this._pos2+11]=t;},r.verticalTextBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+12]},r.verticalTextBoxEndIndex.set=function(t){this._structArray.uint16[this._pos2+12]=t;},r.iconBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+13]},r.iconBoxStartIndex.set=function(t){this._structArray.uint16[this._pos2+13]=t;},r.iconBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+14]},r.iconBoxEndIndex.set=function(t){this._structArray.uint16[this._pos2+14]=t;},r.verticalIconBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+15]},r.verticalIconBoxStartIndex.set=function(t){this._structArray.uint16[this._pos2+15]=t;},r.verticalIconBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+16]},r.verticalIconBoxEndIndex.set=function(t){this._structArray.uint16[this._pos2+16]=t;},r.featureIndex.get=function(){return this._structArray.uint16[this._pos2+17]},r.featureIndex.set=function(t){this._structArray.uint16[this._pos2+17]=t;},r.numHorizontalGlyphVertices.get=function(){return this._structArray.uint16[this._pos2+18]},r.numHorizontalGlyphVertices.set=function(t){this._structArray.uint16[this._pos2+18]=t;},r.numVerticalGlyphVertices.get=function(){return this._structArray.uint16[this._pos2+19]},r.numVerticalGlyphVertices.set=function(t){this._structArray.uint16[this._pos2+19]=t;},r.numIconVertices.get=function(){return this._structArray.uint16[this._pos2+20]},r.numIconVertices.set=function(t){this._structArray.uint16[this._pos2+20]=t;},r.numVerticalIconVertices.get=function(){return this._structArray.uint16[this._pos2+21]},r.numVerticalIconVertices.set=function(t){this._structArray.uint16[this._pos2+21]=t;},r.crossTileID.get=function(){return this._structArray.uint32[this._pos4+11]},r.crossTileID.set=function(t){this._structArray.uint32[this._pos4+11]=t;},r.textBoxScale.get=function(){return this._structArray.float32[this._pos4+12]},r.textBoxScale.set=function(t){this._structArray.float32[this._pos4+12]=t;},r.textOffset0.get=function(){return this._structArray.float32[this._pos4+13]},r.textOffset0.set=function(t){this._structArray.float32[this._pos4+13]=t;},r.textOffset1.get=function(){return this._structArray.float32[this._pos4+14]},r.textOffset1.set=function(t){this._structArray.float32[this._pos4+14]=t;},Object.defineProperties(e.prototype,r),e}(vi);Zi.prototype.size=60;var Gi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){return new Zi(this,t)},e}(Pi);zn("SymbolInstanceArray",Gi);var Ji=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={offsetX:{configurable:!0}};return r.offsetX.get=function(){return this._structArray.float32[this._pos4+0]},r.offsetX.set=function(t){this._structArray.float32[this._pos4+0]=t;},Object.defineProperties(e.prototype,r),e}(vi);Ji.prototype.size=4;var Yi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getoffsetX=function(t){return this.float32[1*t+0]},e.prototype.get=function(t){return new Ji(this,t)},e}(Vi);zn("GlyphOffsetArray",Yi);var Hi=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={x:{configurable:!0},y:{configurable:!0},tileUnitDistanceFromAnchor:{configurable:!0}};return r.x.get=function(){return this._structArray.int16[this._pos2+0]},r.x.set=function(t){this._structArray.int16[this._pos2+0]=t;},r.y.get=function(){return this._structArray.int16[this._pos2+1]},r.y.set=function(t){this._structArray.int16[this._pos2+1]=t;},r.tileUnitDistanceFromAnchor.get=function(){return this._structArray.int16[this._pos2+2]},r.tileUnitDistanceFromAnchor.set=function(t){this._structArray.int16[this._pos2+2]=t;},Object.defineProperties(e.prototype,r),e}(vi);Hi.prototype.size=6;var $i=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getx=function(t){return this.int16[3*t+0]},e.prototype.gety=function(t){return this.int16[3*t+1]},e.prototype.gettileUnitDistanceFromAnchor=function(t){return this.int16[3*t+2]},e.prototype.get=function(t){return new Hi(this,t)},e}(Fi);zn("SymbolLineVertexArray",$i);var Wi=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0}};return r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+0]},r.featureIndex.set=function(t){this._structArray.uint32[this._pos4+0]=t;},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.sourceLayerIndex.set=function(t){this._structArray.uint16[this._pos2+2]=t;},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+3]},r.bucketIndex.set=function(t){this._structArray.uint16[this._pos2+3]=t;},Object.defineProperties(e.prototype,r),e}(vi);Wi.prototype.size=8;var Qi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){return new Wi(this,t)},e}(Li);zn("FeatureIndexArray",Qi);var ta=xi([{name:"a_pos",components:2,type:"Int16"}],4).members,ea=function(t){void 0===t&&(t=[]),this.segments=t;};function ra(t,e){return 256*(t=u(Math.floor(t),0,255))+(e=u(Math.floor(e),0,255))}ea.prototype.prepareSegment=function(t,e,r,n){var i=this.segments[this.segments.length-1];return t>ea.MAX_VERTEX_ARRAY_LENGTH&&_("Max vertices per segment is "+ea.MAX_VERTEX_ARRAY_LENGTH+": bucket requested "+t),(!i||i.vertexLength+t>ea.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n)&&(i={vertexOffset:e.length,primitiveOffset:r.length,vertexLength:0,primitiveLength:0},void 0!==n&&(i.sortKey=n),this.segments.push(i)),i},ea.prototype.get=function(){return this.segments},ea.prototype.destroy=function(){for(var t=0,e=this.segments;t<e.length;t+=1){var r=e[t];for(var n in r.vaos)r.vaos[n].destroy();}},ea.simpleSegment=function(t,e,r,n){return new ea([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])},ea.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,zn("SegmentVector",ea);var na=e((function(t){t.exports=function(t,e){var r,n,i,a,o,s,u,l;for(r=3&t.length,n=t.length-r,i=e,o=3432918353,s=461845907,l=0;l<n;)u=255&t.charCodeAt(l)|(255&t.charCodeAt(++l))<<8|(255&t.charCodeAt(++l))<<16|(255&t.charCodeAt(++l))<<24,++l,i=27492+(65535&(a=5*(65535&(i=(i^=u=(65535&(u=(u=(65535&u)*o+(((u>>>16)*o&65535)<<16)&4294967295)<<15|u>>>17))*s+(((u>>>16)*s&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(a>>>16)&65535)<<16);switch(u=0,r){case 3:u^=(255&t.charCodeAt(l+2))<<16;case 2:u^=(255&t.charCodeAt(l+1))<<8;case 1:i^=u=(65535&(u=(u=(65535&(u^=255&t.charCodeAt(l)))*o+(((u>>>16)*o&65535)<<16)&4294967295)<<15|u>>>17))*s+(((u>>>16)*s&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0};})),ia=e((function(t){t.exports=function(t,e){for(var r,n=t.length,i=e^n,a=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(a)|(255&t.charCodeAt(++a))<<8|(255&t.charCodeAt(++a))<<16|(255&t.charCodeAt(++a))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++a;switch(n){case 3:i^=(255&t.charCodeAt(a+2))<<16;case 2:i^=(255&t.charCodeAt(a+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(a)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0};})),aa=na,oa=na,sa=ia;aa.murmur3=oa,aa.murmur2=sa;var ua=function(){this.ids=[],this.positions=[],this.indexed=!1;};ua.prototype.add=function(t,e,r,n){this.ids.push(pa(t)),this.positions.push(e,r,n);},ua.prototype.getPositions=function(t){for(var e=pa(t),r=0,n=this.ids.length-1;r<n;){var i=r+n>>1;this.ids[i]>=e?n=i:r=i+1;}for(var a=[];this.ids[r]===e;){var o=this.positions[3*r],s=this.positions[3*r+1],u=this.positions[3*r+2];a.push({index:o,start:s,end:u}),r++;}return a},ua.serialize=function(t,e){var r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return function t(e,r,n,i){if(n>=i)return;var a=e[n+i>>1];var o=n-1;var s=i+1;for(;;){do{o++;}while(e[o]<a);do{s--;}while(e[s]>a);if(o>=s)break;ca(e,o,s),ca(r,3*o,3*s),ca(r,3*o+1,3*s+1),ca(r,3*o+2,3*s+2);}t(e,r,n,s);t(e,r,s+1,i);}(r,n,0,r.length-1),e&&e.push(r.buffer,n.buffer),{ids:r,positions:n}},ua.deserialize=function(t){var e=new ua;return e.ids=t.ids,e.positions=t.positions,e.indexed=!0,e};var la=Math.pow(2,53)-1;function pa(t){var e=+t;return !isNaN(e)&&e<=la?e:aa(String(t))}function ca(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}zn("FeaturePositionMap",ua);var ha=function(t,e){this.gl=t.gl,this.location=e;},fa=function(t){function e(e,r){t.call(this,e,r),this.current=0;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){this.current!==t&&(this.current=t,this.gl.uniform1i(this.location,t));},e}(ha),ya=function(t){function e(e,r){t.call(this,e,r),this.current=0;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){this.current!==t&&(this.current=t,this.gl.uniform1f(this.location,t));},e}(ha),da=function(t){function e(e,r){t.call(this,e,r),this.current=[0,0];}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){t[0]===this.current[0]&&t[1]===this.current[1]||(this.current=t,this.gl.uniform2f(this.location,t[0],t[1]));},e}(ha),ma=function(t){function e(e,r){t.call(this,e,r),this.current=[0,0,0];}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){t[0]===this.current[0]&&t[1]===this.current[1]&&t[2]===this.current[2]||(this.current=t,this.gl.uniform3f(this.location,t[0],t[1],t[2]));},e}(ha),va=function(t){function e(e,r){t.call(this,e,r),this.current=[0,0,0,0];}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){t[0]===this.current[0]&&t[1]===this.current[1]&&t[2]===this.current[2]&&t[3]===this.current[3]||(this.current=t,this.gl.uniform4f(this.location,t[0],t[1],t[2],t[3]));},e}(ha),ga=function(t){function e(e,r){t.call(this,e,r),this.current=ee.transparent;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){t.r===this.current.r&&t.g===this.current.g&&t.b===this.current.b&&t.a===this.current.a||(this.current=t,this.gl.uniform4f(this.location,t.r,t.g,t.b,t.a));},e}(ha),xa=new Float32Array(16),ba=function(t){function e(e,r){t.call(this,e,r),this.current=xa;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(t[12]!==this.current[12]||t[0]!==this.current[0])return this.current=t,void this.gl.uniformMatrix4fv(this.location,!1,t);for(var e=1;e<16;e++)if(t[e]!==this.current[e]){this.current=t,this.gl.uniformMatrix4fv(this.location,!1,t);break}},e}(ha);function _a(t){return [ra(255*t.r,255*t.g),ra(255*t.b,255*t.a)]}var wa=function(t,e,r){this.value=t,this.uniformNames=e.map((function(t){return "u_"+t})),this.type=r;};wa.prototype.setUniform=function(t,e,r){t.set(r.constantOr(this.value));},wa.prototype.getBinding=function(t,e){return "color"===this.type?new ga(t,e):new ya(t,e)};var Aa=function(t,e){this.uniformNames=e.map((function(t){return "u_"+t})),this.patternFrom=null,this.patternTo=null;};Aa.prototype.setConstantPatternPositions=function(t,e){this.patternTo=t.tlbr,this.patternFrom=e.tlbr;},Aa.prototype.setUniform=function(t,e,r,n){var i="u_pattern_to"===n?this.patternTo:"u_pattern_from"===n?this.patternFrom:null;i&&t.set(i);},Aa.prototype.getBinding=function(t,e){return new va(t,e)};var Sa=function(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((function(t){return {name:"a_"+t,type:"Float32",components:"color"===r?2:1,offset:0}})),this.paintVertexArray=new n;};Sa.prototype.populatePaintArray=function(t,e,r,n){var i=this.paintVertexArray.length,a=this.expression.evaluate(new ti(0),e,{},[],n);this.paintVertexArray.resize(t),this._setPaintValue(i,t,a);},Sa.prototype.updatePaintArray=function(t,e,r,n){var i=this.expression.evaluate({zoom:0},r,n);this._setPaintValue(t,e,i);},Sa.prototype._setPaintValue=function(t,e,r){if("color"===this.type)for(var n=_a(r),i=t;i<e;i++)this.paintVertexArray.emplace(i,n[0],n[1]);else{for(var a=t;a<e;a++)this.paintVertexArray.emplace(a,r);this.maxValue=Math.max(this.maxValue,Math.abs(r));}},Sa.prototype.upload=function(t){this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer&&this.paintVertexBuffer.buffer?this.paintVertexBuffer.updateData(this.paintVertexArray):this.paintVertexBuffer=t.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,this.expression.isStateDependent));},Sa.prototype.destroy=function(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy();};var ka=function(t,e,r,n,i,a){this.expression=t,this.uniformNames=e.map((function(t){return "u_"+t+"_t"})),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((function(t){return {name:"a_"+t,type:"Float32",components:"color"===r?4:2,offset:0}})),this.paintVertexArray=new a;};ka.prototype.populatePaintArray=function(t,e,r,n){var i=this.expression.evaluate(new ti(this.zoom),e,{},[],n),a=this.expression.evaluate(new ti(this.zoom+1),e,{},[],n),o=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(o,t,i,a);},ka.prototype.updatePaintArray=function(t,e,r,n){var i=this.expression.evaluate({zoom:this.zoom},r,n),a=this.expression.evaluate({zoom:this.zoom+1},r,n);this._setPaintValue(t,e,i,a);},ka.prototype._setPaintValue=function(t,e,r,n){if("color"===this.type)for(var i=_a(r),a=_a(n),o=t;o<e;o++)this.paintVertexArray.emplace(o,i[0],i[1],a[0],a[1]);else{for(var s=t;s<e;s++)this.paintVertexArray.emplace(s,r,n);this.maxValue=Math.max(this.maxValue,Math.abs(r),Math.abs(n));}},ka.prototype.upload=function(t){this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer&&this.paintVertexBuffer.buffer?this.paintVertexBuffer.updateData(this.paintVertexArray):this.paintVertexBuffer=t.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,this.expression.isStateDependent));},ka.prototype.destroy=function(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy();},ka.prototype.setUniform=function(t,e){var r=this.useIntegerZoom?Math.floor(e.zoom):e.zoom,n=u(this.expression.interpolationFactor(r,this.zoom,this.zoom+1),0,1);t.set(n);},ka.prototype.getBinding=function(t,e){return new ya(t,e)};var Ia=function(t,e,r,n,i,a,o){this.expression=t,this.type=r,this.useIntegerZoom=n,this.zoom=i,this.layerId=o,this.paintVertexAttributes=e.map((function(t){return {name:"a_"+t,type:"Uint16",components:4,offset:0}})),this.zoomInPaintVertexArray=new a,this.zoomOutPaintVertexArray=new a;};Ia.prototype.populatePaintArray=function(t,e,r){var n=this.zoomInPaintVertexArray.length;this.zoomInPaintVertexArray.resize(t),this.zoomOutPaintVertexArray.resize(t),this._setPaintValues(n,t,e.patterns&&e.patterns[this.layerId],r);},Ia.prototype.updatePaintArray=function(t,e,r,n,i){this._setPaintValues(t,e,r.patterns&&r.patterns[this.layerId],i);},Ia.prototype._setPaintValues=function(t,e,r,n){if(n&&r){var i=r.min,a=r.mid,o=r.max,s=n[i],u=n[a],l=n[o];if(s&&u&&l)for(var p=t;p<e;p++)this.zoomInPaintVertexArray.emplace(p,u.tl[0],u.tl[1],u.br[0],u.br[1],s.tl[0],s.tl[1],s.br[0],s.br[1]),this.zoomOutPaintVertexArray.emplace(p,u.tl[0],u.tl[1],u.br[0],u.br[1],l.tl[0],l.tl[1],l.br[0],l.br[1]);}},Ia.prototype.upload=function(t){this.zoomInPaintVertexArray&&this.zoomInPaintVertexArray.arrayBuffer&&this.zoomOutPaintVertexArray&&this.zoomOutPaintVertexArray.arrayBuffer&&(this.zoomInPaintVertexBuffer=t.createVertexBuffer(this.zoomInPaintVertexArray,this.paintVertexAttributes,this.expression.isStateDependent),this.zoomOutPaintVertexBuffer=t.createVertexBuffer(this.zoomOutPaintVertexArray,this.paintVertexAttributes,this.expression.isStateDependent));},Ia.prototype.destroy=function(){this.zoomOutPaintVertexBuffer&&this.zoomOutPaintVertexBuffer.destroy(),this.zoomInPaintVertexBuffer&&this.zoomInPaintVertexBuffer.destroy();};var za=function(t,e,r,n){this.binders={},this.layoutAttributes=n,this._buffers=[];var i=[];for(var a in t.paint._values)if(r(a)){var o=t.paint.get(a);if(o instanceof si&&_r(o.property.specification)){var s=Ta(a,t.type),u=o.value,l=o.property.specification.type,p=o.property.useIntegerZoom,c=o.property.specification["property-type"],h="cross-faded"===c||"cross-faded-data-driven"===c;if("constant"===u.kind)this.binders[a]=h?new Aa(u.value,s):new wa(u.value,s,l),i.push("/u_"+a);else if("source"===u.kind||h){var f=Ea(a,l,"source");this.binders[a]=h?new Ia(u,s,l,p,e,f,t.id):new Sa(u,s,l,f),i.push("/a_"+a);}else{var y=Ea(a,l,"composite");this.binders[a]=new ka(u,s,l,p,e,y),i.push("/z_"+a);}}}this.cacheKey=i.sort().join("");};za.prototype.getMaxValue=function(t){var e=this.binders[t];return e instanceof Sa||e instanceof ka?e.maxValue:0},za.prototype.populatePaintArrays=function(t,e,r,n){for(var i in this.binders){var a=this.binders[i];(a instanceof Sa||a instanceof ka||a instanceof Ia)&&a.populatePaintArray(t,e,r,n);}},za.prototype.setConstantPatternPositions=function(t,e){for(var r in this.binders){var n=this.binders[r];n instanceof Aa&&n.setConstantPatternPositions(t,e);}},za.prototype.updatePaintArrays=function(t,e,r,n,i){var a=!1;for(var o in t)for(var s=0,u=e.getPositions(o);s<u.length;s+=1){var l=u[s],p=r.feature(l.index);for(var c in this.binders){var h=this.binders[c];if((h instanceof Sa||h instanceof ka||h instanceof Ia)&&!0===h.expression.isStateDependent){var f=n.paint.get(c);h.expression=f.value,h.updatePaintArray(l.start,l.end,p,t[o],i),a=!0;}}}return a},za.prototype.defines=function(){var t=[];for(var e in this.binders){var r=this.binders[e];(r instanceof wa||r instanceof Aa)&&t.push.apply(t,r.uniformNames.map((function(t){return "#define HAS_UNIFORM_"+t})));}return t},za.prototype.getPaintVertexBuffers=function(){return this._buffers},za.prototype.getUniforms=function(t,e){var r=[];for(var n in this.binders){var i=this.binders[n];if(i instanceof wa||i instanceof Aa||i instanceof ka)for(var a=0,o=i.uniformNames;a<o.length;a+=1){var s=o[a];if(e[s]){var u=i.getBinding(t,e[s]);r.push({name:s,property:n,binding:u});}}}return r},za.prototype.setUniforms=function(t,e,r,n){for(var i=0,a=e;i<a.length;i+=1){var o=a[i],s=o.name,u=o.property,l=o.binding;this.binders[u].setUniform(l,n,r.get(u),s);}},za.prototype.updatePaintBuffers=function(t){for(var e in this._buffers=[],this.binders){var r=this.binders[e];if(t&&r instanceof Ia){var n=2===t.fromScale?r.zoomInPaintVertexBuffer:r.zoomOutPaintVertexBuffer;n&&this._buffers.push(n);}else(r instanceof Sa||r instanceof ka)&&r.paintVertexBuffer&&this._buffers.push(r.paintVertexBuffer);}},za.prototype.upload=function(t){for(var e in this.binders){var r=this.binders[e];(r instanceof Sa||r instanceof ka||r instanceof Ia)&&r.upload(t);}this.updatePaintBuffers();},za.prototype.destroy=function(){for(var t in this.binders){var e=this.binders[t];(e instanceof Sa||e instanceof ka||e instanceof Ia)&&e.destroy();}};var Ca=function(t,e,r,n){void 0===n&&(n=function(){return !0}),this.programConfigurations={};for(var i=0,a=e;i<a.length;i+=1){var o=a[i];this.programConfigurations[o.id]=new za(o,r,n,t);}this.needsUpload=!1,this._featureMap=new ua,this._bufferOffset=0;};function Ta(t,e){return {"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from"],"fill-pattern":["pattern_to","pattern_from"],"fill-extrusion-pattern":["pattern_to","pattern_from"]}[t]||[t.replace(e+"-","").replace(/-/g,"_")]}function Ea(t,e,r){var n={color:{source:Ui,composite:ji},number:{source:Vi,composite:Ui}},i=function(t){return {"line-pattern":{source:ki,composite:ki},"fill-pattern":{source:ki,composite:ki},"fill-extrusion-pattern":{source:ki,composite:ki}}[t]}(t);return i&&i[r]||n[e][r]}Ca.prototype.populatePaintArrays=function(t,e,r,n,i){for(var a in this.programConfigurations)this.programConfigurations[a].populatePaintArrays(t,e,n,i);void 0!==e.id&&this._featureMap.add(e.id,r,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=!0;},Ca.prototype.updatePaintArrays=function(t,e,r,n){for(var i=0,a=r;i<a.length;i+=1){var o=a[i];this.needsUpload=this.programConfigurations[o.id].updatePaintArrays(t,this._featureMap,e,o,n)||this.needsUpload;}},Ca.prototype.get=function(t){return this.programConfigurations[t]},Ca.prototype.upload=function(t){if(this.needsUpload){for(var e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1;}},Ca.prototype.destroy=function(){for(var t in this.programConfigurations)this.programConfigurations[t].destroy();},zn("ConstantBinder",wa),zn("CrossFadedConstantBinder",Aa),zn("SourceExpressionBinder",Sa),zn("CrossFadedCompositeBinder",Ia),zn("CompositeExpressionBinder",ka),zn("ProgramConfiguration",za,{omit:["_buffers"]}),zn("ProgramConfigurationSet",Ca);var Ma=8192;var Ba,Pa=(Ba=15,{min:-1*Math.pow(2,Ba-1),max:Math.pow(2,Ba-1)-1});function Va(t){for(var e=Ma/t.extent,r=t.loadGeometry(),n=0;n<r.length;n++)for(var i=r[n],a=0;a<i.length;a++){var o=i[a];o.x=Math.round(o.x*e),o.y=Math.round(o.y*e),(o.x<Pa.min||o.x>Pa.max||o.y<Pa.min||o.y>Pa.max)&&(_("Geometry exceeds allowed extent, reduce your vector tile buffer size"),o.x=u(o.x,Pa.min,Pa.max),o.y=u(o.y,Pa.min,Pa.max));}return r}function Fa(t,e,r,n,i){t.emplaceBack(2*e+(n+1)/2,2*r+(i+1)/2);}var La=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new _i,this.indexArray=new Di,this.segments=new ea,this.programConfigurations=new Ca(ta,t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};function Da(t,e){for(var r=0;r<t.length;r++)if(Za(e,t[r]))return !0;for(var n=0;n<e.length;n++)if(Za(t,e[n]))return !0;return !!ja(t,e)}function Oa(t,e,r){return !!Za(t,e)||!!Na(e,t,r)}function Ra(t,e){if(1===t.length)return Xa(e,t[0]);for(var r=0;r<e.length;r++)for(var n=e[r],i=0;i<n.length;i++)if(Za(t,n[i]))return !0;for(var a=0;a<t.length;a++)if(Xa(e,t[a]))return !0;for(var o=0;o<e.length;o++)if(ja(t,e[o]))return !0;return !1}function Ua(t,e,r){if(t.length>1){if(ja(t,e))return !0;for(var n=0;n<e.length;n++)if(Na(e[n],t,r))return !0}for(var i=0;i<t.length;i++)if(Na(t[i],e,r))return !0;return !1}function ja(t,e){if(0===t.length||0===e.length)return !1;for(var r=0;r<t.length-1;r++)for(var n=t[r],i=t[r+1],a=0;a<e.length-1;a++){if(qa(n,i,e[a],e[a+1]))return !0}return !1}function qa(t,e,r,n){return w(t,r,n)!==w(e,r,n)&&w(t,e,r)!==w(t,e,n)}function Na(t,e,r){var n=r*r;if(1===e.length)return t.distSqr(e[0])<n;for(var i=1;i<e.length;i++){if(Ka(t,e[i-1],e[i])<n)return !0}return !1}function Ka(t,e,r){var n=e.distSqr(r);if(0===n)return t.distSqr(e);var i=((t.x-e.x)*(r.x-e.x)+(t.y-e.y)*(r.y-e.y))/n;return i<0?t.distSqr(e):i>1?t.distSqr(r):t.distSqr(r.sub(e)._mult(i)._add(e))}function Xa(t,e){for(var r,n,i,a=!1,o=0;o<t.length;o++)for(var s=0,u=(r=t[o]).length-1;s<r.length;u=s++)n=r[s],i=r[u],n.y>e.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(a=!a);return a}function Za(t,e){for(var r=!1,n=0,i=t.length-1;n<t.length;i=n++){var a=t[n],o=t[i];a.y>e.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(r=!r);}return r}function Ga(t,e,r){var n=r[0],i=r[2];if(t.x<n.x&&e.x<n.x||t.x>i.x&&e.x>i.x||t.y<n.y&&e.y<n.y||t.y>i.y&&e.y>i.y)return !1;var a=w(t,e,r[0]);return a!==w(t,e,r[1])||a!==w(t,e,r[2])||a!==w(t,e,r[3])}function Ja(t,e,r){var n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function Ya(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function Ha(t,e,r,n,a){if(!e[0]&&!e[1])return t;var o=i.convert(e)._mult(a);"viewport"===r&&o._rotate(-n);for(var s=[],u=0;u<t.length;u++){var l=t[u];s.push(l.sub(o));}return s}La.prototype.populate=function(t,e){var r=this.layers[0],n=[],i=null;"circle"===r.type&&(i=r.layout.get("circle-sort-key"));for(var a=0,o=t;a<o.length;a+=1){var s=o[a],u=s.feature,l=s.id,p=s.index,c=s.sourceLayerIndex;if(this.layers[0]._featureFilter(new ti(this.zoom),u)){var h=Va(u),f=i?i.evaluate(u,{}):void 0,y={id:l,properties:u.properties,type:u.type,sourceLayerIndex:c,index:p,geometry:h,patterns:{},sortKey:f};n.push(y);}}i&&n.sort((function(t,e){return t.sortKey-e.sortKey}));for(var d=0,m=n;d<m.length;d+=1){var v=m[d],g=v,x=g.geometry,b=g.index,_=g.sourceLayerIndex,w=t[b].feature;this.addFeature(v,x,b),e.featureIndex.insert(w,x,b,_,this.index);}},La.prototype.update=function(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);},La.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},La.prototype.uploadPending=function(){return !this.uploaded||this.programConfigurations.needsUpload},La.prototype.upload=function(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,ta),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;},La.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());},La.prototype.addFeature=function(t,e,r){for(var n=0,i=e;n<i.length;n+=1)for(var a=0,o=i[n];a<o.length;a+=1){var s=o[a],u=s.x,l=s.y;if(!(u<0||u>=Ma||l<0||l>=Ma)){var p=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,t.sortKey),c=p.vertexLength;Fa(this.layoutVertexArray,u,l,-1,-1),Fa(this.layoutVertexArray,u,l,1,-1),Fa(this.layoutVertexArray,u,l,1,1),Fa(this.layoutVertexArray,u,l,-1,1),this.indexArray.emplaceBack(c,c+1,c+2),this.indexArray.emplaceBack(c,c+3,c+2),p.vertexLength+=4,p.primitiveLength+=2;}}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{});},zn("CircleBucket",La,{omit:["layers"]});var $a=new yi({"circle-sort-key":new pi(Bt.layout_circle["circle-sort-key"])}),Wa={paint:new yi({"circle-radius":new pi(Bt.paint_circle["circle-radius"]),"circle-color":new pi(Bt.paint_circle["circle-color"]),"circle-blur":new pi(Bt.paint_circle["circle-blur"]),"circle-opacity":new pi(Bt.paint_circle["circle-opacity"]),"circle-translate":new li(Bt.paint_circle["circle-translate"]),"circle-translate-anchor":new li(Bt.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new li(Bt.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new li(Bt.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new pi(Bt.paint_circle["circle-stroke-width"]),"circle-stroke-color":new pi(Bt.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new pi(Bt.paint_circle["circle-stroke-opacity"])}),layout:$a},Qa="undefined"!=typeof Float32Array?Float32Array:Array;Math.hypot||(Math.hypot=function(){for(var t=arguments,e=0,r=arguments.length;r--;)e+=t[r]*t[r];return Math.sqrt(e)});var to,eo,ro=function(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t};to=new Qa(3),Qa!=Float32Array&&(to[0]=0,to[1]=0,to[2]=0),eo=to;function no(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}!function(){var t=function(){var t=new Qa(4);return Qa!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0),t}();}();var io=function(t){var e=t[0],r=t[1];return e*e+r*r},ao=(function(){var t=function(){var t=new Qa(2);return Qa!=Float32Array&&(t[0]=0,t[1]=0),t}();}(),function(t){function e(e){t.call(this,e,Wa);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new La(t)},e.prototype.queryRadius=function(t){var e=t;return Ja("circle-radius",this,e)+Ja("circle-stroke-width",this,e)+Ya(this.paint.get("circle-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,a,o,s){for(var u=Ha(t,this.paint.get("circle-translate"),this.paint.get("circle-translate-anchor"),a.angle,o),l=this.paint.get("circle-radius").evaluate(e,r)+this.paint.get("circle-stroke-width").evaluate(e,r),p="map"===this.paint.get("circle-pitch-alignment"),c=p?u:function(t,e){return t.map((function(t){return oo(t,e)}))}(u,s),h=p?l*o:l,f=0,y=n;f<y.length;f+=1)for(var d=0,m=y[f];d<m.length;d+=1){var v=m[d],g=p?v:oo(v,s),x=h,b=no([],[v.x,v.y,0,1],s);if("viewport"===this.paint.get("circle-pitch-scale")&&"map"===this.paint.get("circle-pitch-alignment")?x*=b[3]/a.cameraToCenterDistance:"map"===this.paint.get("circle-pitch-scale")&&"viewport"===this.paint.get("circle-pitch-alignment")&&(x*=a.cameraToCenterDistance/b[3]),Oa(c,g,x))return !0}return !1},e}(di));function oo(t,e){var r=no([],[t.x,t.y,0,1],e);return new i(r[0]/r[3],r[1]/r[3])}var so=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(La);function uo(t,e,r,n){var i=e.width,a=e.height;if(n){if(n instanceof Uint8ClampedArray)n=new Uint8Array(n.buffer);else if(n.length!==i*a*r)throw new RangeError("mismatched image size")}else n=new Uint8Array(i*a*r);return t.width=i,t.height=a,t.data=n,t}function lo(t,e,r){var n=e.width,i=e.height;if(n!==t.width||i!==t.height){var a=uo({},{width:n,height:i},r);po(t,a,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,n),height:Math.min(t.height,i)},r),t.width=n,t.height=i,t.data=a.data;}}function po(t,e,r,n,i,a){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");for(var o=t.data,s=e.data,u=0;u<i.height;u++)for(var l=((r.y+u)*t.width+r.x)*a,p=((n.y+u)*e.width+n.x)*a,c=0;c<i.width*a;c++)s[p+c]=o[l+c];return e}zn("HeatmapBucket",so,{omit:["layers"]});var co=function(t,e){uo(this,t,1,e);};co.prototype.resize=function(t){lo(this,t,1);},co.prototype.clone=function(){return new co({width:this.width,height:this.height},new Uint8Array(this.data))},co.copy=function(t,e,r,n,i){po(t,e,r,n,i,1);};var ho=function(t,e){uo(this,t,4,e);};ho.prototype.resize=function(t){lo(this,t,4);},ho.prototype.replace=function(t,e){e?this.data.set(t):t instanceof Uint8ClampedArray?this.data=new Uint8Array(t.buffer):this.data=t;},ho.prototype.clone=function(){return new ho({width:this.width,height:this.height},new Uint8Array(this.data))},ho.copy=function(t,e,r,n,i){po(t,e,r,n,i,4);},zn("AlphaImage",co),zn("RGBAImage",ho);var fo={paint:new yi({"heatmap-radius":new pi(Bt.paint_heatmap["heatmap-radius"]),"heatmap-weight":new pi(Bt.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new li(Bt.paint_heatmap["heatmap-intensity"]),"heatmap-color":new fi(Bt.paint_heatmap["heatmap-color"]),"heatmap-opacity":new li(Bt.paint_heatmap["heatmap-opacity"])})};function yo(t,e){for(var r=new Uint8Array(1024),n={},i=0,a=0;i<256;i++,a+=4){n[e]=i/255;var o=t.evaluate(n);r[a+0]=Math.floor(255*o.r/o.a),r[a+1]=Math.floor(255*o.g/o.a),r[a+2]=Math.floor(255*o.b/o.a),r[a+3]=Math.floor(255*o.a);}return new ho({width:256,height:1},r)}var mo=function(t){function e(e){t.call(this,e,fo),this._updateColorRamp();}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new so(t)},e.prototype._handleSpecialPaintPropertyUpdate=function(t){"heatmap-color"===t&&this._updateColorRamp();},e.prototype._updateColorRamp=function(){var t=this._transitionablePaint._values["heatmap-color"].value.expression;this.colorRamp=yo(t,"heatmapDensity"),this.colorRampTexture=null;},e.prototype.resize=function(){this.heatmapFbo&&(this.heatmapFbo.destroy(),this.heatmapFbo=null);},e.prototype.queryRadius=function(){return 0},e.prototype.queryIntersectsFeature=function(){return !1},e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("heatmap-opacity")&&"none"!==this.visibility},e}(di),vo={paint:new yi({"hillshade-illumination-direction":new li(Bt.paint_hillshade["hillshade-illumination-direction"]),"hillshade-illumination-anchor":new li(Bt.paint_hillshade["hillshade-illumination-anchor"]),"hillshade-exaggeration":new li(Bt.paint_hillshade["hillshade-exaggeration"]),"hillshade-shadow-color":new li(Bt.paint_hillshade["hillshade-shadow-color"]),"hillshade-highlight-color":new li(Bt.paint_hillshade["hillshade-highlight-color"]),"hillshade-accent-color":new li(Bt.paint_hillshade["hillshade-accent-color"])})},go=function(t){function e(e){t.call(this,e,vo);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("hillshade-exaggeration")&&"none"!==this.visibility},e}(di),xo=xi([{name:"a_pos",components:2,type:"Int16"}],4).members,bo=wo,_o=wo;function wo(t,e,r){r=r||2;var n,i,a,o,s,u,l,p=e&&e.length,c=p?e[0]*r:t.length,h=Ao(t,0,c,r,!0),f=[];if(!h||h.next===h.prev)return f;if(p&&(h=function(t,e,r,n){var i,a,o,s,u,l=[];for(i=0,a=e.length;i<a;i++)o=e[i]*n,s=i<a-1?e[i+1]*n:t.length,(u=Ao(t,o,s,n,!1))===u.next&&(u.steiner=!0),l.push(Vo(u));for(l.sort(Eo),i=0;i<l.length;i++)Mo(l[i],r),r=So(r,r.next);return r}(t,e,h,r)),t.length>80*r){n=a=t[0],i=o=t[1];for(var y=r;y<c;y+=r)(s=t[y])<n&&(n=s),(u=t[y+1])<i&&(i=u),s>a&&(a=s),u>o&&(o=u);l=0!==(l=Math.max(a-n,o-i))?1/l:0;}return ko(h,f,r,n,i,l),f}function Ao(t,e,r,n,i){var a,o;if(i===Go(t,e,r,n)>0)for(a=e;a<r;a+=n)o=Ko(a,t[a],t[a+1],o);else for(a=r-n;a>=e;a-=n)o=Ko(a,t[a],t[a+1],o);return o&&Oo(o,o.next)&&(Xo(o),o=o.next),o}function So(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!Oo(n,n.next)&&0!==Do(n.prev,n,n.next))n=n.next;else{if(Xo(n),(n=e=n.prev)===n.next)break;r=!0;}}while(r||n!==e);return e}function ko(t,e,r,n,i,a,o){if(t){!o&&a&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=Po(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,a,o,s,u,l=1;do{for(r=t,t=null,a=null,o=0;r;){for(o++,n=r,s=0,e=0;e<l&&(s++,n=n.nextZ);e++);for(u=l;s>0||u>0&&n;)0!==s&&(0===u||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,u--),a?a.nextZ=i:t=i,i.prevZ=a,a=i;r=n;}a.nextZ=null,l*=2;}while(o>1)}(i);}(t,n,i,a);for(var s,u,l=t;t.prev!==t.next;)if(s=t.prev,u=t.next,a?zo(t,n,i,a):Io(t))e.push(s.i/r),e.push(t.i/r),e.push(u.i/r),Xo(t),t=u.next,l=u.next;else if((t=u)===l){o?1===o?ko(t=Co(So(t),e,r),e,r,n,i,a,2):2===o&&To(t,e,r,n,i,a):ko(So(t),e,r,n,i,a,1);break}}}function Io(t){var e=t.prev,r=t,n=t.next;if(Do(e,r,n)>=0)return !1;for(var i=t.next.next;i!==t.prev;){if(Fo(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&Do(i.prev,i,i.next)>=0)return !1;i=i.next;}return !0}function zo(t,e,r,n){var i=t.prev,a=t,o=t.next;if(Do(i,a,o)>=0)return !1;for(var s=i.x<a.x?i.x<o.x?i.x:o.x:a.x<o.x?a.x:o.x,u=i.y<a.y?i.y<o.y?i.y:o.y:a.y<o.y?a.y:o.y,l=i.x>a.x?i.x>o.x?i.x:o.x:a.x>o.x?a.x:o.x,p=i.y>a.y?i.y>o.y?i.y:o.y:a.y>o.y?a.y:o.y,c=Po(s,u,e,r,n),h=Po(l,p,e,r,n),f=t.prevZ,y=t.nextZ;f&&f.z>=c&&y&&y.z<=h;){if(f!==t.prev&&f!==t.next&&Fo(i.x,i.y,a.x,a.y,o.x,o.y,f.x,f.y)&&Do(f.prev,f,f.next)>=0)return !1;if(f=f.prevZ,y!==t.prev&&y!==t.next&&Fo(i.x,i.y,a.x,a.y,o.x,o.y,y.x,y.y)&&Do(y.prev,y,y.next)>=0)return !1;y=y.nextZ;}for(;f&&f.z>=c;){if(f!==t.prev&&f!==t.next&&Fo(i.x,i.y,a.x,a.y,o.x,o.y,f.x,f.y)&&Do(f.prev,f,f.next)>=0)return !1;f=f.prevZ;}for(;y&&y.z<=h;){if(y!==t.prev&&y!==t.next&&Fo(i.x,i.y,a.x,a.y,o.x,o.y,y.x,y.y)&&Do(y.prev,y,y.next)>=0)return !1;y=y.nextZ;}return !0}function Co(t,e,r){var n=t;do{var i=n.prev,a=n.next.next;!Oo(i,a)&&Ro(i,n,n.next,a)&&qo(i,a)&&qo(a,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(a.i/r),Xo(n),Xo(n.next),n=t=a),n=n.next;}while(n!==t);return So(n)}function To(t,e,r,n,i,a){var o=t;do{for(var s=o.next.next;s!==o.prev;){if(o.i!==s.i&&Lo(o,s)){var u=No(o,s);return o=So(o,o.next),u=So(u,u.next),ko(o,e,r,n,i,a),void ko(u,e,r,n,i,a)}s=s.next;}o=o.next;}while(o!==t)}function Eo(t,e){return t.x-e.x}function Mo(t,e){if(e=function(t,e){var r,n=e,i=t.x,a=t.y,o=-1/0;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){var s=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>o){if(o=s,s===i){if(a===n.y)return n;if(a===n.next.y)return n.next}r=n.x<n.next.x?n:n.next;}}n=n.next;}while(n!==e);if(!r)return null;if(i===o)return r;var u,l=r,p=r.x,c=r.y,h=1/0;n=r;do{i>=n.x&&n.x>=p&&i!==n.x&&Fo(a<c?i:o,a,p,c,a<c?o:i,a,n.x,n.y)&&(u=Math.abs(a-n.y)/(i-n.x),qo(n,t)&&(u<h||u===h&&(n.x>r.x||n.x===r.x&&Bo(r,n)))&&(r=n,h=u)),n=n.next;}while(n!==l);return r}(t,e)){var r=No(e,t);So(e,e.next),So(r,r.next);}}function Bo(t,e){return Do(t.prev,t,e.prev)<0&&Do(e.next,t,t.next)<0}function Po(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Vo(t){var e=t,r=t;do{(e.x<r.x||e.x===r.x&&e.y<r.y)&&(r=e),e=e.next;}while(e!==t);return r}function Fo(t,e,r,n,i,a,o,s){return (i-o)*(e-s)-(t-o)*(a-s)>=0&&(t-o)*(n-s)-(r-o)*(e-s)>=0&&(r-o)*(a-s)-(i-o)*(n-s)>=0}function Lo(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&Ro(r,r.next,t,e))return !0;r=r.next;}while(r!==t);return !1}(t,e)&&(qo(t,e)&&qo(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(Do(t.prev,t,e.prev)||Do(t,e.prev,e))||Oo(t,e)&&Do(t.prev,t,t.next)>0&&Do(e.prev,e,e.next)>0)}function Do(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Oo(t,e){return t.x===e.x&&t.y===e.y}function Ro(t,e,r,n){var i=jo(Do(t,e,r)),a=jo(Do(t,e,n)),o=jo(Do(r,n,t)),s=jo(Do(r,n,e));return i!==a&&o!==s||(!(0!==i||!Uo(t,r,e))||(!(0!==a||!Uo(t,n,e))||(!(0!==o||!Uo(r,t,n))||!(0!==s||!Uo(r,e,n)))))}function Uo(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function jo(t){return t>0?1:t<0?-1:0}function qo(t,e){return Do(t.prev,t,t.next)<0?Do(t,e,t.next)>=0&&Do(t,t.prev,e)>=0:Do(t,e,t.prev)<0||Do(t,t.next,e)<0}function No(t,e){var r=new Zo(t.i,t.x,t.y),n=new Zo(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function Ko(t,e,r,n){var i=new Zo(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Xo(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ);}function Zo(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1;}function Go(t,e,r,n){for(var i=0,a=e,o=r-n;a<r;a+=n)i+=(t[o]-t[a])*(t[a+1]+t[o+1]),o=a;return i}function Jo(t,e,r,n,i){!function t(e,r,n,i,a){for(;i>n;){if(i-n>600){var o=i-n+1,s=r-n+1,u=Math.log(o),l=.5*Math.exp(2*u/3),p=.5*Math.sqrt(u*l*(o-l)/o)*(s-o/2<0?-1:1),c=Math.max(n,Math.floor(r-s*l/o+p)),h=Math.min(i,Math.floor(r+(o-s)*l/o+p));t(e,r,c,h,a);}var f=e[r],y=n,d=i;for(Yo(e,n,r),a(e[i],f)>0&&Yo(e,n,i);y<d;){for(Yo(e,y,d),y++,d--;a(e[y],f)<0;)y++;for(;a(e[d],f)>0;)d--;}0===a(e[n],f)?Yo(e,n,d):Yo(e,++d,i),d<=r&&(n=d+1),r<=d&&(i=d-1);}}(t,e,r||0,n||t.length-1,i||Ho);}function Yo(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}function Ho(t,e){return t<e?-1:t>e?1:0}function $o(t,e){var r=t.length;if(r<=1)return [t];for(var n,i,a=[],o=0;o<r;o++){var s=A(t[o]);0!==s&&(t[o].area=Math.abs(s),void 0===i&&(i=s<0),i===s<0?(n&&a.push(n),n=[t[o]]):n.push(t[o]));}if(n&&a.push(n),e>1)for(var u=0;u<a.length;u++)a[u].length<=e||(Jo(a[u],e,1,a[u].length-1,Wo),a[u]=a[u].slice(0,e));return a}function Wo(t,e){return e.area-t.area}function Qo(t,e,r){for(var n=r.patternDependencies,i=!1,a=0,o=e;a<o.length;a+=1){var s=o[a].paint.get(t+"-pattern");s.isConstant()||(i=!0);var u=s.constantOr(null);u&&(i=!0,n[u.to]=!0,n[u.from]=!0);}return i}function ts(t,e,r,n,i){for(var a=i.patternDependencies,o=0,s=e;o<s.length;o+=1){var u=s[o],l=u.paint.get(t+"-pattern").value;if("constant"!==l.kind){var p=l.evaluate({zoom:n-1},r,{},i.availableImages),c=l.evaluate({zoom:n},r,{},i.availableImages),h=l.evaluate({zoom:n+1},r,{},i.availableImages);p=p&&p.name?p.name:p,c=c&&c.name?c.name:c,h=h&&h.name?h.name:h,a[p]=!0,a[c]=!0,a[h]=!0,r.patterns[u.id]={min:p,mid:c,max:h};}}return r}wo.deviation=function(t,e,r,n){var i=e&&e.length,a=i?e[0]*r:t.length,o=Math.abs(Go(t,0,a,r));if(i)for(var s=0,u=e.length;s<u;s++){var l=e[s]*r,p=s<u-1?e[s+1]*r:t.length;o-=Math.abs(Go(t,l,p,r));}var c=0;for(s=0;s<n.length;s+=3){var h=n[s]*r,f=n[s+1]*r,y=n[s+2]*r;c+=Math.abs((t[h]-t[y])*(t[f+1]-t[h+1])-(t[h]-t[f])*(t[y+1]-t[h+1]));}return 0===o&&0===c?0:Math.abs((c-o)/o)},wo.flatten=function(t){for(var e=t[0][0].length,r={vertices:[],holes:[],dimensions:e},n=0,i=0;i<t.length;i++){for(var a=0;a<t[i].length;a++)for(var o=0;o<e;o++)r.vertices.push(t[i][a][o]);i>0&&(n+=t[i-1].length,r.holes.push(n));}return r},bo.default=_o;var es=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new _i,this.indexArray=new Di,this.indexArray2=new Oi,this.programConfigurations=new Ca(xo,t.layers,t.zoom),this.segments=new ea,this.segments2=new ea,this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};es.prototype.populate=function(t,e){this.hasPattern=Qo("fill",this.layers,e);for(var r=this.layers[0].layout.get("fill-sort-key"),n=[],i=0,a=t;i<a.length;i+=1){var o=a[i],s=o.feature,u=o.id,l=o.index,p=o.sourceLayerIndex;if(this.layers[0]._featureFilter(new ti(this.zoom),s)){var c=Va(s),h=r?r.evaluate(s,{},e.availableImages):void 0,f={id:u,properties:s.properties,type:s.type,sourceLayerIndex:p,index:l,geometry:c,patterns:{},sortKey:h};n.push(f);}}r&&n.sort((function(t,e){return t.sortKey-e.sortKey}));for(var y=0,d=n;y<d.length;y+=1){var m=d[y],v=m,g=v.geometry,x=v.index,b=v.sourceLayerIndex;if(this.hasPattern){var _=ts("fill",this.layers,m,this.zoom,e);this.patternFeatures.push(_);}else this.addFeature(m,g,x,{});var w=t[x].feature;e.featureIndex.insert(w,g,x,b,this.index);}},es.prototype.update=function(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);},es.prototype.addFeatures=function(t,e){for(var r=0,n=this.patternFeatures;r<n.length;r+=1){var i=n[r];this.addFeature(i,i.geometry,i.index,e);}},es.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},es.prototype.uploadPending=function(){return !this.uploaded||this.programConfigurations.needsUpload},es.prototype.upload=function(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,xo),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0;},es.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());},es.prototype.addFeature=function(t,e,r,n){for(var i=0,a=$o(e,500);i<a.length;i+=1){for(var o=a[i],s=0,u=0,l=o;u<l.length;u+=1){s+=l[u].length;}for(var p=this.segments.prepareSegment(s,this.layoutVertexArray,this.indexArray),c=p.vertexLength,h=[],f=[],y=0,d=o;y<d.length;y+=1){var m=d[y];if(0!==m.length){m!==o[0]&&f.push(h.length/2);var v=this.segments2.prepareSegment(m.length,this.layoutVertexArray,this.indexArray2),g=v.vertexLength;this.layoutVertexArray.emplaceBack(m[0].x,m[0].y),this.indexArray2.emplaceBack(g+m.length-1,g),h.push(m[0].x),h.push(m[0].y);for(var x=1;x<m.length;x++)this.layoutVertexArray.emplaceBack(m[x].x,m[x].y),this.indexArray2.emplaceBack(g+x-1,g+x),h.push(m[x].x),h.push(m[x].y);v.vertexLength+=m.length,v.primitiveLength+=m.length;}}for(var b=bo(h,f),_=0;_<b.length;_+=3)this.indexArray.emplaceBack(c+b[_],c+b[_+1],c+b[_+2]);p.vertexLength+=s,p.primitiveLength+=b.length/3;}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,n);},zn("FillBucket",es,{omit:["layers","patternFeatures"]});var rs=new yi({"fill-sort-key":new pi(Bt.layout_fill["fill-sort-key"])}),ns={paint:new yi({"fill-antialias":new li(Bt.paint_fill["fill-antialias"]),"fill-opacity":new pi(Bt.paint_fill["fill-opacity"]),"fill-color":new pi(Bt.paint_fill["fill-color"]),"fill-outline-color":new pi(Bt.paint_fill["fill-outline-color"]),"fill-translate":new li(Bt.paint_fill["fill-translate"]),"fill-translate-anchor":new li(Bt.paint_fill["fill-translate-anchor"]),"fill-pattern":new ci(Bt.paint_fill["fill-pattern"])}),layout:rs},is=function(t){function e(e){t.call(this,e,ns);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(e,r){t.prototype.recalculate.call(this,e,r);var n=this.paint._values["fill-outline-color"];"constant"===n.value.kind&&void 0===n.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);},e.prototype.createBucket=function(t){return new es(t)},e.prototype.queryRadius=function(){return Ya(this.paint.get("fill-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,a,o){return Ra(Ha(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),a.angle,o),n)},e.prototype.isTileClipped=function(){return !0},e}(di),as=xi([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4).members,os=ss;function ss(t,e,r,n,i){this.properties={},this.extent=r,this.type=0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=i,t.readFields(us,this,e);}function us(t,e,r){1==t?e.id=r.readVarint():2==t?function(t,e){var r=t.readVarint()+t.pos;for(;t.pos<r;){var n=e._keys[t.readVarint()],i=e._values[t.readVarint()];e.properties[n]=i;}}(r,e):3==t?e.type=r.readVarint():4==t&&(e._geometry=r.pos);}function ls(t){for(var e,r,n=0,i=0,a=t.length,o=a-1;i<a;o=i++)e=t[i],n+=((r=t[o]).x-e.x)*(e.y+r.y);return n}ss.types=["Unknown","Point","LineString","Polygon"],ss.prototype.loadGeometry=function(){var t=this._pbf;t.pos=this._geometry;for(var e,r=t.readVarint()+t.pos,n=1,a=0,o=0,s=0,u=[];t.pos<r;){if(a<=0){var l=t.readVarint();n=7&l,a=l>>3;}if(a--,1===n||2===n)o+=t.readSVarint(),s+=t.readSVarint(),1===n&&(e&&u.push(e),e=[]),e.push(new i(o,s));else{if(7!==n)throw new Error("unknown command "+n);e&&e.push(e[0].clone());}}return e&&u.push(e),u},ss.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,a=0,o=1/0,s=-1/0,u=1/0,l=-1/0;t.pos<e;){if(n<=0){var p=t.readVarint();r=7&p,n=p>>3;}if(n--,1===r||2===r)(i+=t.readSVarint())<o&&(o=i),i>s&&(s=i),(a+=t.readSVarint())<u&&(u=a),a>l&&(l=a);else if(7!==r)throw new Error("unknown command "+r)}return [o,u,s,l]},ss.prototype.toGeoJSON=function(t,e,r){var n,i,a=this.extent*Math.pow(2,r),o=this.extent*t,s=this.extent*e,u=this.loadGeometry(),l=ss.types[this.type];function p(t){for(var e=0;e<t.length;e++){var r=t[e],n=180-360*(r.y+s)/a;t[e]=[360*(r.x+o)/a-180,360/Math.PI*Math.atan(Math.exp(n*Math.PI/180))-90];}}switch(this.type){case 1:var c=[];for(n=0;n<u.length;n++)c[n]=u[n][0];p(u=c);break;case 2:for(n=0;n<u.length;n++)p(u[n]);break;case 3:for(u=function(t){var e=t.length;if(e<=1)return [t];for(var r,n,i=[],a=0;a<e;a++){var o=ls(t[a]);0!==o&&(void 0===n&&(n=o<0),n===o<0?(r&&i.push(r),r=[t[a]]):r.push(t[a]));}r&&i.push(r);return i}(u),n=0;n<u.length;n++)for(i=0;i<u[n].length;i++)p(u[n][i]);}1===u.length?u=u[0]:l="Multi"+l;var h={type:"Feature",geometry:{type:l,coordinates:u},properties:this.properties};return "id"in this&&(h.id=this.id),h};var ps=cs;function cs(t,e){this.version=1,this.name=null,this.extent=4096,this.length=0,this._pbf=t,this._keys=[],this._values=[],this._features=[],t.readFields(hs,this,e),this.length=this._features.length;}function hs(t,e,r){15===t?e.version=r.readVarint():1===t?e.name=r.readString():5===t?e.extent=r.readVarint():2===t?e._features.push(r.pos):3===t?e._keys.push(r.readString()):4===t&&e._values.push(function(t){var e=null,r=t.readVarint()+t.pos;for(;t.pos<r;){var n=t.readVarint()>>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null;}return e}(r));}function fs(t,e,r){if(3===t){var n=new ps(r,r.readVarint()+r.pos);n.length&&(e[n.name]=n);}}cs.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new os(this._pbf,e,this.extent,this._keys,this._values)};var ys={VectorTile:function(t,e){this.layers=t.readFields(fs,{},e);},VectorTileFeature:os,VectorTileLayer:ps},ds=ys.VectorTileFeature.types,ms=Math.pow(2,13);function vs(t,e,r,n,i,a,o,s){t.emplaceBack(e,r,2*Math.floor(n*ms)+o,i*ms*2,a*ms*2,Math.round(s));}var gs=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new Ai,this.indexArray=new Di,this.programConfigurations=new Ca(as,t.layers,t.zoom),this.segments=new ea,this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};function xs(t,e){return t.x===e.x&&(t.x<0||t.x>Ma)||t.y===e.y&&(t.y<0||t.y>Ma)}function bs(t){return t.every((function(t){return t.x<0}))||t.every((function(t){return t.x>Ma}))||t.every((function(t){return t.y<0}))||t.every((function(t){return t.y>Ma}))}gs.prototype.populate=function(t,e){this.features=[],this.hasPattern=Qo("fill-extrusion",this.layers,e);for(var r=0,n=t;r<n.length;r+=1){var i=n[r],a=i.feature,o=i.id,s=i.index,u=i.sourceLayerIndex;if(this.layers[0]._featureFilter(new ti(this.zoom),a)){var l=Va(a),p={id:o,sourceLayerIndex:u,index:s,geometry:l,properties:a.properties,type:a.type,patterns:{}};void 0!==a.id&&(p.id=a.id),this.hasPattern?this.features.push(ts("fill-extrusion",this.layers,p,this.zoom,e)):this.addFeature(p,l,s,{}),e.featureIndex.insert(a,l,s,u,this.index,!0);}}},gs.prototype.addFeatures=function(t,e){for(var r=0,n=this.features;r<n.length;r+=1){var i=n[r],a=i.geometry;this.addFeature(i,a,i.index,e);}},gs.prototype.update=function(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);},gs.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},gs.prototype.uploadPending=function(){return !this.uploaded||this.programConfigurations.needsUpload},gs.prototype.upload=function(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,as),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;},gs.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());},gs.prototype.addFeature=function(t,e,r,n){for(var i=0,a=$o(e,500);i<a.length;i+=1){for(var o=a[i],s=0,u=0,l=o;u<l.length;u+=1){s+=l[u].length;}for(var p=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray),c=0,h=o;c<h.length;c+=1){var f=h[c];if(0!==f.length&&!bs(f))for(var y=0,d=0;d<f.length;d++){var m=f[d];if(d>=1){var v=f[d-1];if(!xs(m,v)){p.vertexLength+4>ea.MAX_VERTEX_ARRAY_LENGTH&&(p=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));var g=m.sub(v)._perp()._unit(),x=v.dist(m);y+x>32768&&(y=0),vs(this.layoutVertexArray,m.x,m.y,g.x,g.y,0,0,y),vs(this.layoutVertexArray,m.x,m.y,g.x,g.y,0,1,y),y+=x,vs(this.layoutVertexArray,v.x,v.y,g.x,g.y,0,0,y),vs(this.layoutVertexArray,v.x,v.y,g.x,g.y,0,1,y);var b=p.vertexLength;this.indexArray.emplaceBack(b,b+2,b+1),this.indexArray.emplaceBack(b+1,b+2,b+3),p.vertexLength+=4,p.primitiveLength+=2;}}}}if(p.vertexLength+s>ea.MAX_VERTEX_ARRAY_LENGTH&&(p=this.segments.prepareSegment(s,this.layoutVertexArray,this.indexArray)),"Polygon"===ds[t.type]){for(var _=[],w=[],A=p.vertexLength,S=0,k=o;S<k.length;S+=1){var I=k[S];if(0!==I.length){I!==o[0]&&w.push(_.length/2);for(var z=0;z<I.length;z++){var C=I[z];vs(this.layoutVertexArray,C.x,C.y,0,0,1,1,0),_.push(C.x),_.push(C.y);}}}for(var T=bo(_,w),E=0;E<T.length;E+=3)this.indexArray.emplaceBack(A+T[E],A+T[E+2],A+T[E+1]);p.primitiveLength+=T.length/3,p.vertexLength+=s;}}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,n);},zn("FillExtrusionBucket",gs,{omit:["layers","features"]});var _s={paint:new yi({"fill-extrusion-opacity":new li(Bt["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new pi(Bt["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new li(Bt["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new li(Bt["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new ci(Bt["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new pi(Bt["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new pi(Bt["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new li(Bt["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})},ws=function(t){function e(e){t.call(this,e,_s);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new gs(t)},e.prototype.queryRadius=function(){return Ya(this.paint.get("fill-extrusion-translate"))},e.prototype.is3D=function(){return !0},e.prototype.queryIntersectsFeature=function(t,e,r,n,a,o,s,u){var l=Ha(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),o.angle,s),p=this.paint.get("fill-extrusion-height").evaluate(e,r),c=this.paint.get("fill-extrusion-base").evaluate(e,r),h=function(t,e,r,n){for(var a=[],o=0,s=t;o<s.length;o+=1){var u=s[o],l=[u.x,u.y,n,1];no(l,l,e),a.push(new i(l[0]/l[3],l[1]/l[3]));}return a}(l,u,0,0),f=function(t,e,r,n){for(var a=[],o=[],s=n[8]*e,u=n[9]*e,l=n[10]*e,p=n[11]*e,c=n[8]*r,h=n[9]*r,f=n[10]*r,y=n[11]*r,d=0,m=t;d<m.length;d+=1){for(var v=m[d],g=[],x=[],b=0,_=v;b<_.length;b+=1){var w=_[b],A=w.x,S=w.y,k=n[0]*A+n[4]*S+n[12],I=n[1]*A+n[5]*S+n[13],z=n[2]*A+n[6]*S+n[14],C=n[3]*A+n[7]*S+n[15],T=z+l,E=C+p,M=k+c,B=I+h,P=z+f,V=C+y,F=new i((k+s)/E,(I+u)/E);F.z=T/E,g.push(F);var L=new i(M/V,B/V);L.z=P/V,x.push(L);}a.push(g),o.push(x);}return [a,o]}(n,c,p,u);return function(t,e,r){var n=1/0;Ra(r,e)&&(n=Ss(r,e[0]));for(var i=0;i<e.length;i++)for(var a=e[i],o=t[i],s=0;s<a.length-1;s++){var u=a[s],l=a[s+1],p=o[s],c=o[s+1],h=[u,l,c,p,u];Da(r,h)&&(n=Math.min(n,Ss(r,h)));}return n!==1/0&&n}(f[0],f[1],h)},e}(di);function As(t,e){return t.x*e.x+t.y*e.y}function Ss(t,e){if(1===t.length){for(var r,n,i=0,a=e[i++];!r||a.equals(r);)if(!(r=e[i++]))return 1/0;for(;!n||a.equals(n)||r.equals(n);)if(!(n=e[i++]))return 1/0;var o=t[0],s=r.sub(a),u=n.sub(a),l=o.sub(a),p=As(s,s),c=As(s,u),h=As(u,u),f=As(l,s),y=As(l,u),d=p*h-c*c,m=(h*f-c*y)/d,v=(p*y-c*f)/d,g=1-m-v;return a.z*g+r.z*m+n.z*v}for(var x=1/0,b=0,_=e;b<_.length;b+=1){var w=_[b];x=Math.min(x,w.z);}return x}var ks=xi([{name:"a_pos_normal",components:2,type:"Int16"},{name:"a_data",components:4,type:"Uint8"}],4).members,Is=ys.VectorTileFeature.types,zs=Math.cos(Math.PI/180*37.5),Cs=Math.pow(2,14)/.5,Ts=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new Si,this.indexArray=new Di,this.programConfigurations=new Ca(ks,t.layers,t.zoom),this.segments=new ea,this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};Ts.prototype.populate=function(t,e){this.hasPattern=Qo("line",this.layers,e);for(var r=this.layers[0].layout.get("line-sort-key"),n=[],i=0,a=t;i<a.length;i+=1){var o=a[i],s=o.feature,u=o.id,l=o.index,p=o.sourceLayerIndex;if(this.layers[0]._featureFilter(new ti(this.zoom),s)){var c=Va(s),h=r?r.evaluate(s,{}):void 0,f={id:u,properties:s.properties,type:s.type,sourceLayerIndex:p,index:l,geometry:c,patterns:{},sortKey:h};n.push(f);}}r&&n.sort((function(t,e){return t.sortKey-e.sortKey}));for(var y=0,d=n;y<d.length;y+=1){var m=d[y],v=m,g=v.geometry,x=v.index,b=v.sourceLayerIndex;if(this.hasPattern){var _=ts("line",this.layers,m,this.zoom,e);this.patternFeatures.push(_);}else this.addFeature(m,g,x,{});var w=t[x].feature;e.featureIndex.insert(w,g,x,b,this.index);}},Ts.prototype.update=function(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);},Ts.prototype.addFeatures=function(t,e){for(var r=0,n=this.patternFeatures;r<n.length;r+=1){var i=n[r];this.addFeature(i,i.geometry,i.index,e);}},Ts.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},Ts.prototype.uploadPending=function(){return !this.uploaded||this.programConfigurations.needsUpload},Ts.prototype.upload=function(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,ks),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;},Ts.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());},Ts.prototype.addFeature=function(t,e,r,n){for(var i=this.layers[0].layout,a=i.get("line-join").evaluate(t,{}),o=i.get("line-cap"),s=i.get("line-miter-limit"),u=i.get("line-round-limit"),l=0,p=e;l<p.length;l+=1){var c=p[l];this.addLine(c,t,a,o,s,u,r,n);}},Ts.prototype.addLine=function(t,e,r,n,i,a,o,s){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,e.properties&&e.properties.hasOwnProperty("mapbox_clip_start")&&e.properties.hasOwnProperty("mapbox_clip_end")){this.clipStart=+e.properties.mapbox_clip_start,this.clipEnd=+e.properties.mapbox_clip_end;for(var u=0;u<t.length-1;u++)this.totalDistance+=t[u].dist(t[u+1]);this.updateScaledDistance();}for(var l="Polygon"===Is[e.type],p=t.length;p>=2&&t[p-1].equals(t[p-2]);)p--;for(var c=0;c<p-1&&t[c].equals(t[c+1]);)c++;if(!(p<(l?3:2))){"bevel"===r&&(i=1.05);var h,f=this.overscaling<=16?15*Ma/(512*this.overscaling):0,y=this.segments.prepareSegment(10*p,this.layoutVertexArray,this.indexArray),d=void 0,m=void 0,v=void 0,g=void 0;this.e1=this.e2=-1,l&&(h=t[p-2],g=t[c].sub(h)._unit()._perp());for(var x=c;x<p;x++)if(!(m=x===p-1?l?t[c+1]:void 0:t[x+1])||!t[x].equals(m)){g&&(v=g),h&&(d=h),h=t[x],g=m?m.sub(h)._unit()._perp():v;var b=(v=v||g).add(g);0===b.x&&0===b.y||b._unit();var _=v.x*g.x+v.y*g.y,w=b.x*g.x+b.y*g.y,A=0!==w?1/w:1/0,S=2*Math.sqrt(2-2*w),k=w<zs&&d&&m,I=v.x*g.y-v.y*g.x>0;if(k&&x>c){var z=h.dist(d);if(z>2*f){var C=h.sub(h.sub(d)._mult(f/z)._round());this.updateDistance(d,C),this.addCurrentVertex(C,v,0,0,y),d=C;}}var T=d&&m,E=T?r:l?"butt":n;if(T&&"round"===E&&(A<a?E="miter":A<=2&&(E="fakeround")),"miter"===E&&A>i&&(E="bevel"),"bevel"===E&&(A>2&&(E="flipbevel"),A<i&&(E="miter")),d&&this.updateDistance(d,h),"miter"===E)b._mult(A),this.addCurrentVertex(h,b,0,0,y);else if("flipbevel"===E){if(A>100)b=g.mult(-1);else{var M=A*v.add(g).mag()/v.sub(g).mag();b._perp()._mult(M*(I?-1:1));}this.addCurrentVertex(h,b,0,0,y),this.addCurrentVertex(h,b.mult(-1),0,0,y);}else if("bevel"===E||"fakeround"===E){var B=-Math.sqrt(A*A-1),P=I?B:0,V=I?0:B;if(d&&this.addCurrentVertex(h,v,P,V,y),"fakeround"===E)for(var F=Math.round(180*S/Math.PI/20),L=1;L<F;L++){var D=L/F;if(.5!==D){var O=D-.5;D+=D*O*(D-1)*((1.0904+_*(_*(3.55645-1.43519*_)-3.2452))*O*O+(.848013+_*(.215638*_-1.06021)));}var R=g.sub(v)._mult(D)._add(v)._unit()._mult(I?-1:1);this.addHalfVertex(h,R.x,R.y,!1,I,0,y);}m&&this.addCurrentVertex(h,g,-P,-V,y);}else if("butt"===E)this.addCurrentVertex(h,b,0,0,y);else if("square"===E){var U=d?1:-1;this.addCurrentVertex(h,b,U,U,y);}else"round"===E&&(d&&(this.addCurrentVertex(h,v,0,0,y),this.addCurrentVertex(h,v,1,1,y,!0)),m&&(this.addCurrentVertex(h,g,-1,-1,y,!0),this.addCurrentVertex(h,g,0,0,y)));if(k&&x<p-1){var j=h.dist(m);if(j>2*f){var q=h.add(m.sub(h)._mult(f/j)._round());this.updateDistance(h,q),this.addCurrentVertex(q,g,0,0,y),h=q;}}}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,e,o,s);}},Ts.prototype.addCurrentVertex=function(t,e,r,n,i,a){void 0===a&&(a=!1);var o=e.x+e.y*r,s=e.y-e.x*r,u=-e.x+e.y*n,l=-e.y-e.x*n;this.addHalfVertex(t,o,s,a,!1,r,i),this.addHalfVertex(t,u,l,a,!0,-n,i),this.distance>Cs/2&&0===this.totalDistance&&(this.distance=0,this.addCurrentVertex(t,e,r,n,i,a));},Ts.prototype.addHalfVertex=function(t,e,r,n,i,a,o){var s=t.x,u=t.y,l=.5*this.scaledDistance;this.layoutVertexArray.emplaceBack((s<<1)+(n?1:0),(u<<1)+(i?1:0),Math.round(63*e)+128,Math.round(63*r)+128,1+(0===a?0:a<0?-1:1)|(63&l)<<2,l>>6);var p=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,p),o.primitiveLength++),i?this.e2=p:this.e1=p;},Ts.prototype.updateScaledDistance=function(){this.scaledDistance=this.totalDistance>0?(this.clipStart+(this.clipEnd-this.clipStart)*this.distance/this.totalDistance)*(Cs-1):this.distance;},Ts.prototype.updateDistance=function(t,e){this.distance+=t.dist(e),this.updateScaledDistance();},zn("LineBucket",Ts,{omit:["layers","patternFeatures"]});var Es=new yi({"line-cap":new li(Bt.layout_line["line-cap"]),"line-join":new pi(Bt.layout_line["line-join"]),"line-miter-limit":new li(Bt.layout_line["line-miter-limit"]),"line-round-limit":new li(Bt.layout_line["line-round-limit"]),"line-sort-key":new pi(Bt.layout_line["line-sort-key"])}),Ms={paint:new yi({"line-opacity":new pi(Bt.paint_line["line-opacity"]),"line-color":new pi(Bt.paint_line["line-color"]),"line-translate":new li(Bt.paint_line["line-translate"]),"line-translate-anchor":new li(Bt.paint_line["line-translate-anchor"]),"line-width":new pi(Bt.paint_line["line-width"]),"line-gap-width":new pi(Bt.paint_line["line-gap-width"]),"line-offset":new pi(Bt.paint_line["line-offset"]),"line-blur":new pi(Bt.paint_line["line-blur"]),"line-dasharray":new hi(Bt.paint_line["line-dasharray"]),"line-pattern":new ci(Bt.paint_line["line-pattern"]),"line-gradient":new fi(Bt.paint_line["line-gradient"])}),layout:Es},Bs=new(function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.possiblyEvaluate=function(e,r){return r=new ti(Math.floor(r.zoom),{now:r.now,fadeDuration:r.fadeDuration,zoomHistory:r.zoomHistory,transition:r.transition}),t.prototype.possiblyEvaluate.call(this,e,r)},e.prototype.evaluate=function(e,r,n,i){return r=p({},r,{zoom:Math.floor(r.zoom)}),t.prototype.evaluate.call(this,e,r,n,i)},e}(pi))(Ms.paint.properties["line-width"].specification);Bs.useIntegerZoom=!0;var Ps=function(t){function e(e){t.call(this,e,Ms);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype._handleSpecialPaintPropertyUpdate=function(t){"line-gradient"===t&&this._updateGradient();},e.prototype._updateGradient=function(){var t=this._transitionablePaint._values["line-gradient"].value.expression;this.gradient=yo(t,"lineProgress"),this.gradientTexture=null;},e.prototype.recalculate=function(e,r){t.prototype.recalculate.call(this,e,r),this.paint._values["line-floorwidth"]=Bs.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,e);},e.prototype.createBucket=function(t){return new Ts(t)},e.prototype.queryRadius=function(t){var e=t,r=Vs(Ja("line-width",this,e),Ja("line-gap-width",this,e)),n=Ja("line-offset",this,e);return r/2+Math.abs(n)+Ya(this.paint.get("line-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,a,o,s){var u=Ha(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),o.angle,s),l=s/2*Vs(this.paint.get("line-width").evaluate(e,r),this.paint.get("line-gap-width").evaluate(e,r)),p=this.paint.get("line-offset").evaluate(e,r);return p&&(n=function(t,e){for(var r=[],n=new i(0,0),a=0;a<t.length;a++){for(var o=t[a],s=[],u=0;u<o.length;u++){var l=o[u-1],p=o[u],c=o[u+1],h=0===u?n:p.sub(l)._unit()._perp(),f=u===o.length-1?n:c.sub(p)._unit()._perp(),y=h._add(f)._unit(),d=y.x*f.x+y.y*f.y;y._mult(1/d),s.push(y._mult(e)._add(p));}r.push(s);}return r}(n,p*s)),function(t,e,r){for(var n=0;n<e.length;n++){var i=e[n];if(t.length>=3)for(var a=0;a<i.length;a++)if(Za(t,i[a]))return !0;if(Ua(t,i,r))return !0}return !1}(u,n,l)},e.prototype.isTileClipped=function(){return !0},e}(di);function Vs(t,e){return e>0?e+2*t:t}var Fs=xi([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Ls=xi([{name:"a_projected_pos",components:3,type:"Float32"}],4),Ds=(xi([{name:"a_fade_opacity",components:1,type:"Uint32"}],4),xi([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"}])),Os=(xi([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"},{type:"Int16",name:"radius"},{type:"Int16",name:"signedDistanceFromAnchor"}]),xi([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4)),Rs=xi([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4);xi([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),xi([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",components:2,name:"textOffset"}]),xi([{type:"Float32",name:"offsetX"}]),xi([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]);function Us(t,e,r){return t.sections.forEach((function(t){t.text=function(t,e,r){var n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),Qn.applyArabicShaping&&(t=Qn.applyArabicShaping(t)),t}(t.text,e,r);})),t}var js={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var qs=24,Ns=function(t,e,r,n,i){var a,o,s=8*i-n-1,u=(1<<s)-1,l=u>>1,p=-7,c=r?i-1:0,h=r?-1:1,f=t[e+c];for(c+=h,a=f&(1<<-p)-1,f>>=-p,p+=s;p>0;a=256*a+t[e+c],c+=h,p-=8);for(o=a&(1<<-p)-1,a>>=-p,p+=n;p>0;o=256*o+t[e+c],c+=h,p-=8);if(0===a)a=1-l;else{if(a===u)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,n),a-=l;}return (f?-1:1)*o*Math.pow(2,a-n)},Ks=function(t,e,r,n,i,a){var o,s,u,l=8*a-i-1,p=(1<<l)-1,c=p>>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:a-1,y=n?1:-1,d=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=p):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),(e+=o+c>=1?h/u:h*Math.pow(2,1-c))*u>=2&&(o++,u/=2),o+c>=p?(s=0,o=p):o+c>=1?(s=(e*u-1)*Math.pow(2,i),o+=c):(s=e*Math.pow(2,c-1)*Math.pow(2,i),o=0));i>=8;t[r+f]=255&s,f+=y,s/=256,i-=8);for(o=o<<i|s,l+=i;l>0;t[r+f]=255&o,f+=y,o/=256,l-=8);t[r+f-y]|=128*d;},Xs=Zs;function Zs(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length;}Zs.Varint=0,Zs.Fixed64=1,Zs.Bytes=2,Zs.Fixed32=5;var Gs="undefined"==typeof TextDecoder?null:new TextDecoder("utf8");function Js(t){return t.type===Zs.Bytes?t.readVarint()+t.pos:t.pos+1}function Ys(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function Hs(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i];}function $s(t,e){for(var r=0;r<t.length;r++)e.writeVarint(t[r]);}function Ws(t,e){for(var r=0;r<t.length;r++)e.writeSVarint(t[r]);}function Qs(t,e){for(var r=0;r<t.length;r++)e.writeFloat(t[r]);}function tu(t,e){for(var r=0;r<t.length;r++)e.writeDouble(t[r]);}function eu(t,e){for(var r=0;r<t.length;r++)e.writeBoolean(t[r]);}function ru(t,e){for(var r=0;r<t.length;r++)e.writeFixed32(t[r]);}function nu(t,e){for(var r=0;r<t.length;r++)e.writeSFixed32(t[r]);}function iu(t,e){for(var r=0;r<t.length;r++)e.writeFixed64(t[r]);}function au(t,e){for(var r=0;r<t.length;r++)e.writeSFixed64(t[r]);}function ou(t,e){return (t[e]|t[e+1]<<8|t[e+2]<<16)+16777216*t[e+3]}function su(t,e,r){t[r]=e,t[r+1]=e>>>8,t[r+2]=e>>>16,t[r+3]=e>>>24;}function uu(t,e){return (t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}Zs.prototype={destroy:function(){this.buf=null;},readFields:function(t,e,r){for(r=r||this.length;this.pos<r;){var n=this.readVarint(),i=n>>3,a=this.pos;this.type=7&n,t(i,e,this),this.pos===a&&this.skip(n);}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=ou(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=uu(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=ou(this.buf,this.pos)+4294967296*ou(this.buf,this.pos+4);return this.pos+=8,t},readSFixed64:function(){var t=ou(this.buf,this.pos)+4294967296*uu(this.buf,this.pos+4);return this.pos+=8,t},readFloat:function(){var t=Ns(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=Ns(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,a=r.buf;if(i=a[r.pos++],n=(112&i)>>4,i<128)return Ys(t,n,e);if(i=a[r.pos++],n|=(127&i)<<3,i<128)return Ys(t,n,e);if(i=a[r.pos++],n|=(127&i)<<10,i<128)return Ys(t,n,e);if(i=a[r.pos++],n|=(127&i)<<17,i<128)return Ys(t,n,e);if(i=a[r.pos++],n|=(127&i)<<24,i<128)return Ys(t,n,e);if(i=a[r.pos++],n|=(1&i)<<31,i<128)return Ys(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&Gs?function(t,e,r){return Gs.decode(t.subarray(e,r))}(this.buf,e,t):function(t,e,r){var n="",i=e;for(;i<r;){var a,o,s,u=t[i],l=null,p=u>239?4:u>223?3:u>191?2:1;if(i+p>r)break;1===p?u<128&&(l=u):2===p?128==(192&(a=t[i+1]))&&(l=(31&u)<<6|63&a)<=127&&(l=null):3===p?(a=t[i+1],o=t[i+2],128==(192&a)&&128==(192&o)&&((l=(15&u)<<12|(63&a)<<6|63&o)<=2047||l>=55296&&l<=57343)&&(l=null)):4===p&&(a=t[i+1],o=t[i+2],s=t[i+3],128==(192&a)&&128==(192&o)&&128==(192&s)&&((l=(15&u)<<18|(63&a)<<12|(63&o)<<6|63&s)<=65535||l>=1114112)&&(l=null)),null===l?(l=65533,p=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=p;}return n}(this.buf,e,t)},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){if(this.type!==Zs.Bytes)return t.push(this.readVarint(e));var r=Js(this);for(t=t||[];this.pos<r;)t.push(this.readVarint(e));return t},readPackedSVarint:function(t){if(this.type!==Zs.Bytes)return t.push(this.readSVarint());var e=Js(this);for(t=t||[];this.pos<e;)t.push(this.readSVarint());return t},readPackedBoolean:function(t){if(this.type!==Zs.Bytes)return t.push(this.readBoolean());var e=Js(this);for(t=t||[];this.pos<e;)t.push(this.readBoolean());return t},readPackedFloat:function(t){if(this.type!==Zs.Bytes)return t.push(this.readFloat());var e=Js(this);for(t=t||[];this.pos<e;)t.push(this.readFloat());return t},readPackedDouble:function(t){if(this.type!==Zs.Bytes)return t.push(this.readDouble());var e=Js(this);for(t=t||[];this.pos<e;)t.push(this.readDouble());return t},readPackedFixed32:function(t){if(this.type!==Zs.Bytes)return t.push(this.readFixed32());var e=Js(this);for(t=t||[];this.pos<e;)t.push(this.readFixed32());return t},readPackedSFixed32:function(t){if(this.type!==Zs.Bytes)return t.push(this.readSFixed32());var e=Js(this);for(t=t||[];this.pos<e;)t.push(this.readSFixed32());return t},readPackedFixed64:function(t){if(this.type!==Zs.Bytes)return t.push(this.readFixed64());var e=Js(this);for(t=t||[];this.pos<e;)t.push(this.readFixed64());return t},readPackedSFixed64:function(t){if(this.type!==Zs.Bytes)return t.push(this.readSFixed64());var e=Js(this);for(t=t||[];this.pos<e;)t.push(this.readSFixed64());return t},skip:function(t){var e=7&t;if(e===Zs.Varint)for(;this.buf[this.pos++]>127;);else if(e===Zs.Bytes)this.pos=this.readVarint()+this.pos;else if(e===Zs.Fixed32)this.pos+=4;else{if(e!==Zs.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8;}},writeTag:function(t,e){this.writeVarint(t<<3|e);},realloc:function(t){for(var e=this.length||16;e<this.pos+t;)e*=2;if(e!==this.length){var r=new Uint8Array(e);r.set(this.buf),this.buf=r,this.length=e;}},finish:function(){return this.length=this.pos,this.pos=0,this.buf.subarray(0,this.length)},writeFixed32:function(t){this.realloc(4),su(this.buf,t,this.pos),this.pos+=4;},writeSFixed32:function(t){this.realloc(4),su(this.buf,t,this.pos),this.pos+=4;},writeFixed64:function(t){this.realloc(8),su(this.buf,-1&t,this.pos),su(this.buf,Math.floor(t*(1/4294967296)),this.pos+4),this.pos+=8;},writeSFixed64:function(t){this.realloc(8),su(this.buf,-1&t,this.pos),su(this.buf,Math.floor(t*(1/4294967296)),this.pos+4),this.pos+=8;},writeVarint:function(t){(t=+t||0)>268435455||t<0?function(t,e){var r,n;t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0));if(t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos]=127&t;}(r,0,e),function(t,e){var r=(7&t)<<4;if(e.buf[e.pos++]|=r|((t>>>=3)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;e.buf[e.pos++]=127&t;}(n,e);}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))));},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t);},writeBoolean:function(t){this.writeVarint(Boolean(t));},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,a=0;a<e.length;a++){if((n=e.charCodeAt(a))>55295&&n<57344){if(!i){n>56319||a+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&Hs(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;},writeFloat:function(t){this.realloc(4),Ks(this.buf,t,this.pos,!0,23,4),this.pos+=4;},writeDouble:function(t){this.realloc(8),Ks(this.buf,t,this.pos,!0,52,8),this.pos+=8;},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r<e;r++)this.buf[this.pos++]=t[r];},writeRawMessage:function(t,e){this.pos++;var r=this.pos;t(e,this);var n=this.pos-r;n>=128&&Hs(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;},writeMessage:function(t,e,r){this.writeTag(t,Zs.Bytes),this.writeRawMessage(e,r);},writePackedVarint:function(t,e){e.length&&this.writeMessage(t,$s,e);},writePackedSVarint:function(t,e){e.length&&this.writeMessage(t,Ws,e);},writePackedBoolean:function(t,e){e.length&&this.writeMessage(t,eu,e);},writePackedFloat:function(t,e){e.length&&this.writeMessage(t,Qs,e);},writePackedDouble:function(t,e){e.length&&this.writeMessage(t,tu,e);},writePackedFixed32:function(t,e){e.length&&this.writeMessage(t,ru,e);},writePackedSFixed32:function(t,e){e.length&&this.writeMessage(t,nu,e);},writePackedFixed64:function(t,e){e.length&&this.writeMessage(t,iu,e);},writePackedSFixed64:function(t,e){e.length&&this.writeMessage(t,au,e);},writeBytesField:function(t,e){this.writeTag(t,Zs.Bytes),this.writeBytes(e);},writeFixed32Field:function(t,e){this.writeTag(t,Zs.Fixed32),this.writeFixed32(e);},writeSFixed32Field:function(t,e){this.writeTag(t,Zs.Fixed32),this.writeSFixed32(e);},writeFixed64Field:function(t,e){this.writeTag(t,Zs.Fixed64),this.writeFixed64(e);},writeSFixed64Field:function(t,e){this.writeTag(t,Zs.Fixed64),this.writeSFixed64(e);},writeVarintField:function(t,e){this.writeTag(t,Zs.Varint),this.writeVarint(e);},writeSVarintField:function(t,e){this.writeTag(t,Zs.Varint),this.writeSVarint(e);},writeStringField:function(t,e){this.writeTag(t,Zs.Bytes),this.writeString(e);},writeFloatField:function(t,e){this.writeTag(t,Zs.Fixed32),this.writeFloat(e);},writeDoubleField:function(t,e){this.writeTag(t,Zs.Fixed64),this.writeDouble(e);},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e));}};var lu=3;function pu(t,e,r){1===t&&r.readMessage(cu,e);}function cu(t,e,r){if(3===t){var n=r.readMessage(hu,{}),i=n.id,a=n.bitmap,o=n.width,s=n.height,u=n.left,l=n.top,p=n.advance;e.push({id:i,bitmap:new co({width:o+2*lu,height:s+2*lu},a),metrics:{width:o,height:s,left:u,top:l,advance:p}});}}function hu(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint());}var fu=lu;function yu(t){for(var e=0,r=0,n=0,i=t;n<i.length;n+=1){var a=i[n];e+=a.w*a.h,r=Math.max(r,a.w);}t.sort((function(t,e){return e.h-t.h}));for(var o=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}],s=0,u=0,l=0,p=t;l<p.length;l+=1)for(var c=p[l],h=o.length-1;h>=0;h--){var f=o[h];if(!(c.w>f.w||c.h>f.h)){if(c.x=f.x,c.y=f.y,u=Math.max(u,c.y+c.h),s=Math.max(s,c.x+c.w),c.w===f.w&&c.h===f.h){var y=o.pop();h<o.length&&(o[h]=y);}else c.h===f.h?(f.x+=c.w,f.w-=c.w):c.w===f.w?(f.y+=c.h,f.h-=c.h):(o.push({x:f.x+c.w,y:f.y,w:f.w-c.w,h:c.h}),f.y+=c.h,f.h-=c.h);break}}return {w:s,h:u,fill:e/(s*u)||0}}var du=1,mu=function(t,e){var r=e.pixelRatio,n=e.version,i=e.stretchX,a=e.stretchY,o=e.content;this.paddedRect=t,this.pixelRatio=r,this.stretchX=i,this.stretchY=a,this.content=o,this.version=n;},vu={tl:{configurable:!0},br:{configurable:!0},tlbr:{configurable:!0},displaySize:{configurable:!0}};vu.tl.get=function(){return [this.paddedRect.x+du,this.paddedRect.y+du]},vu.br.get=function(){return [this.paddedRect.x+this.paddedRect.w-du,this.paddedRect.y+this.paddedRect.h-du]},vu.tlbr.get=function(){return this.tl.concat(this.br)},vu.displaySize.get=function(){return [(this.paddedRect.w-2*du)/this.pixelRatio,(this.paddedRect.h-2*du)/this.pixelRatio]},Object.defineProperties(mu.prototype,vu);var gu=function(t,e){var r={},n={};this.haveRenderCallbacks=[];var i=[];this.addImages(t,r,i),this.addImages(e,n,i);var a=yu(i),o=a.w,s=a.h,u=new ho({width:o||1,height:s||1});for(var l in t){var p=t[l],c=r[l].paddedRect;ho.copy(p.data,u,{x:0,y:0},{x:c.x+du,y:c.y+du},p.data);}for(var h in e){var f=e[h],y=n[h].paddedRect,d=y.x+du,m=y.y+du,v=f.data.width,g=f.data.height;ho.copy(f.data,u,{x:0,y:0},{x:d,y:m},f.data),ho.copy(f.data,u,{x:0,y:g-1},{x:d,y:m-1},{width:v,height:1}),ho.copy(f.data,u,{x:0,y:0},{x:d,y:m+g},{width:v,height:1}),ho.copy(f.data,u,{x:v-1,y:0},{x:d-1,y:m},{width:1,height:g}),ho.copy(f.data,u,{x:0,y:0},{x:d+v,y:m},{width:1,height:g});}this.image=u,this.iconPositions=r,this.patternPositions=n;};gu.prototype.addImages=function(t,e,r){for(var n in t){var i=t[n],a={x:0,y:0,w:i.data.width+2*du,h:i.data.height+2*du};r.push(a),e[n]=new mu(a,i),i.hasRenderCallback&&this.haveRenderCallbacks.push(n);}},gu.prototype.patchUpdatedImages=function(t,e){for(var r in t.dispatchRenderCallbacks(this.haveRenderCallbacks),t.updatedImages)this.patchUpdatedImage(this.iconPositions[r],t.getImage(r),e),this.patchUpdatedImage(this.patternPositions[r],t.getImage(r),e);},gu.prototype.patchUpdatedImage=function(t,e,r){if(t&&e&&t.version!==e.version){t.version=e.version;var n=t.tl,i=n[0],a=n[1];r.update(e.data,void 0,{x:i,y:a});}},zn("ImagePosition",mu),zn("ImageAtlas",gu);var xu={horizontal:1,vertical:2,horizontalOnly:3},bu=-17;var _u=function(){this.scale=1,this.fontStack="",this.imageName=null;};_u.forText=function(t,e){var r=new _u;return r.scale=t||1,r.fontStack=e,r},_u.forImage=function(t){var e=new _u;return e.imageName=t,e};var wu=function(){this.text="",this.sectionIndex=[],this.sections=[],this.imageSectionID=null;};function Au(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d){var m,v=wu.fromFeature(t,i);c===xu.vertical&&v.verticalizePunctuation();var g=Qn.processBidirectionalText,x=Qn.processStyledBidirectionalText;if(g&&1===v.sections.length){m=[];for(var b=0,_=g(v.toString(),Eu(v,l,a,e,n,f,y));b<_.length;b+=1){var w=_[b],A=new wu;A.text=w,A.sections=v.sections;for(var S=0;S<w.length;S++)A.sectionIndex.push(0);m.push(A);}}else if(x){m=[];for(var k=0,I=x(v.text,v.sectionIndex,Eu(v,l,a,e,n,f,y));k<I.length;k+=1){var z=I[k],C=new wu;C.text=z[0],C.sectionIndex=z[1],C.sections=v.sections,m.push(C);}}else m=function(t,e){for(var r=[],n=t.text,i=0,a=0,o=e;a<o.length;a+=1){var s=o[a];r.push(t.substring(i,s)),i=s;}return i<n.length&&r.push(t.substring(i,n.length)),r}(v,Eu(v,l,a,e,n,f,y));var T=[],E={positionedLines:T,text:v.toString(),top:p[1],bottom:p[1],left:p[0],right:p[0],writingMode:c,iconsInText:!1,verticalizable:!1};return function(t,e,r,n,i,a,o,s,u,l,p,c){for(var h=0,f=bu,y=0,d=0,m="right"===s?1:"left"===s?0:.5,v=0,g=0,x=i;g<x.length;g+=1){var b=x[g];b.trim();var _=b.getMaxScale(),w=(_-1)*qs,A={positionedGlyphs:[],lineOffset:0};t.positionedLines[v]=A;var S=A.positionedGlyphs,k=0;if(b.length()){for(var I=0;I<b.length();I++){var z=b.getSection(I),C=b.getSectionIndex(I),T=b.getCharCode(I),E=0,M=null,B=null,P=null,V=qs,F=!(u===xu.horizontal||!p&&!Dn(T)||p&&(Su[T]||(Z=T,Vn.Arabic(Z)||Vn["Arabic Supplement"](Z)||Vn["Arabic Extended-A"](Z)||Vn["Arabic Presentation Forms-A"](Z)||Vn["Arabic Presentation Forms-B"](Z))));if(z.imageName){var L=n[z.imageName];if(!L)continue;P=z.imageName,t.iconsInText=t.iconsInText||!0,B=L.paddedRect;var D=L.displaySize;z.scale=z.scale*qs/c,M={width:D[0],height:D[1],left:du,top:-fu,advance:F?D[1]:D[0]};var O=qs-D[1]*z.scale;E=w+O,V=M.advance;var R=F?D[0]*z.scale-qs*_:D[1]*z.scale-qs*_;R>0&&R>k&&(k=R);}else{var U=r[z.fontStack],j=U&&U[T];if(j&&j.rect)B=j.rect,M=j.metrics;else{var q=e[z.fontStack],N=q&&q[T];if(!N)continue;M=N.metrics;}E=(_-z.scale)*qs;}F?(t.verticalizable=!0,S.push({glyph:T,imageName:P,x:h,y:f+E,vertical:F,scale:z.scale,fontStack:z.fontStack,sectionIndex:C,metrics:M,rect:B}),h+=V*z.scale+l):(S.push({glyph:T,imageName:P,x:h,y:f+E,vertical:F,scale:z.scale,fontStack:z.fontStack,sectionIndex:C,metrics:M,rect:B}),h+=M.advance*z.scale+l);}if(0!==S.length){var K=h-l;y=Math.max(K,y),Bu(S,0,S.length-1,m,k);}h=0;var X=a*_+k;A.lineOffset=Math.max(k,w),f+=X,d=Math.max(X,d),++v;}else f+=a,++v;}var Z;var G=f-bu,J=Mu(o),Y=J.horizontalAlign,H=J.verticalAlign;(function(t,e,r,n,i,a,o,s,u){var l=(e-r)*i,p=0;p=a!==o?-s*n-bu:(-n*u+.5)*o;for(var c=0,h=t;c<h.length;c+=1)for(var f=h[c],y=0,d=f.positionedGlyphs;y<d.length;y+=1){var m=d[y];m.x+=l,m.y+=p;}})(t.positionedLines,m,Y,H,y,d,a,G,i.length),t.top+=-H*G,t.bottom=t.top+G,t.left+=-Y*y,t.right=t.left+y;}(E,e,r,n,m,o,s,u,c,l,h,d),!function(t){for(var e=0,r=t;e<r.length;e+=1){if(0!==r[e].positionedGlyphs.length)return !1}return !0}(T)&&E}wu.fromFeature=function(t,e){for(var r=new wu,n=0;n<t.sections.length;n++){var i=t.sections[n];i.image?r.addImageSection(i):r.addTextSection(i,e);}return r},wu.prototype.length=function(){return this.text.length},wu.prototype.getSection=function(t){return this.sections[this.sectionIndex[t]]},wu.prototype.getSectionIndex=function(t){return this.sectionIndex[t]},wu.prototype.getCharCode=function(t){return this.text.charCodeAt(t)},wu.prototype.verticalizePunctuation=function(){this.text=function(t){for(var e="",r=0;r<t.length;r++){var n=t.charCodeAt(r+1)||null,i=t.charCodeAt(r-1)||null;(!n||!On(n)||js[t[r+1]])&&(!i||!On(i)||js[t[r-1]])&&js[t[r]]?e+=js[t[r]]:e+=t[r];}return e}(this.text);},wu.prototype.trim=function(){for(var t=0,e=0;e<this.text.length&&Su[this.text.charCodeAt(e)];e++)t++;for(var r=this.text.length,n=this.text.length-1;n>=0&&n>=t&&Su[this.text.charCodeAt(n)];n--)r--;this.text=this.text.substring(t,r),this.sectionIndex=this.sectionIndex.slice(t,r);},wu.prototype.substring=function(t,e){var r=new wu;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r},wu.prototype.toString=function(){return this.text},wu.prototype.getMaxScale=function(){var t=this;return this.sectionIndex.reduce((function(e,r){return Math.max(e,t.sections[r].scale)}),0)},wu.prototype.addTextSection=function(t,e){this.text+=t.text,this.sections.push(_u.forText(t.scale,t.fontStack||e));for(var r=this.sections.length-1,n=0;n<t.text.length;++n)this.sectionIndex.push(r);},wu.prototype.addImageSection=function(t){var e=t.image?t.image.name:"";if(0!==e.length){var r=this.getNextImageSectionCharCode();r?(this.text+=String.fromCharCode(r),this.sections.push(_u.forImage(e)),this.sectionIndex.push(this.sections.length-1)):_("Reached maximum number of images 6401");}else _("Can't add FormattedSection with an empty image.");},wu.prototype.getNextImageSectionCharCode=function(){return this.imageSectionID?this.imageSectionID>=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)};var Su={9:!0,10:!0,11:!0,12:!0,13:!0,32:!0},ku={};function Iu(t,e,r,n,i,a){if(e.imageName){var o=n[e.imageName];return o?o.displaySize[0]*e.scale*qs/a+i:0}var s=r[e.fontStack],u=s&&s[t];return u?u.metrics.advance*e.scale+i:0}function zu(t,e,r,n){var i=Math.pow(t-e,2);return n?t<e?i/2:2*i:i+Math.abs(r)*r}function Cu(t,e,r){var n=0;return 10===t&&(n-=1e4),r&&(n+=150),40!==t&&65288!==t||(n+=50),41!==e&&65289!==e||(n+=50),n}function Tu(t,e,r,n,i,a){for(var o=null,s=zu(e,r,i,a),u=0,l=n;u<l.length;u+=1){var p=l[u],c=zu(e-p.x,r,i,a)+p.badness;c<=s&&(o=p,s=c);}return {index:t,x:e,priorBreak:o,badness:s}}function Eu(t,e,r,n,i,a,o){if("point"!==a)return [];if(!t)return [];for(var s,u=[],l=function(t,e,r,n,i,a){for(var o=0,s=0;s<t.length();s++){var u=t.getSection(s);o+=Iu(t.getCharCode(s),u,n,i,e,a);}return o/Math.max(1,Math.ceil(o/r))}(t,e,r,n,i,o),p=t.text.indexOf("")>=0,c=0,h=0;h<t.length();h++){var f=t.getSection(h),y=t.getCharCode(h);if(Su[y]||(c+=Iu(y,f,n,i,e,o)),h<t.length()-1){var d=!!(!((s=y)<11904)&&(Vn["Bopomofo Extended"](s)||Vn.Bopomofo(s)||Vn["CJK Compatibility Forms"](s)||Vn["CJK Compatibility Ideographs"](s)||Vn["CJK Compatibility"](s)||Vn["CJK Radicals Supplement"](s)||Vn["CJK Strokes"](s)||Vn["CJK Symbols and Punctuation"](s)||Vn["CJK Unified Ideographs Extension A"](s)||Vn["CJK Unified Ideographs"](s)||Vn["Enclosed CJK Letters and Months"](s)||Vn["Halfwidth and Fullwidth Forms"](s)||Vn.Hiragana(s)||Vn["Ideographic Description Characters"](s)||Vn["Kangxi Radicals"](s)||Vn["Katakana Phonetic Extensions"](s)||Vn.Katakana(s)||Vn["Vertical Forms"](s)||Vn["Yi Radicals"](s)||Vn["Yi Syllables"](s)));(ku[y]||d||f.imageName)&&u.push(Tu(h+1,c,l,u,Cu(y,t.getCharCode(h+1),d&&p),!1));}}return function t(e){return e?t(e.priorBreak).concat(e.index):[]}(Tu(t.length(),c,l,u,0,!0))}function Mu(t){var e=.5,r=.5;switch(t){case"right":case"top-right":case"bottom-right":e=1;break;case"left":case"top-left":case"bottom-left":e=0;}switch(t){case"bottom":case"bottom-right":case"bottom-left":r=1;break;case"top":case"top-right":case"top-left":r=0;}return {horizontalAlign:e,verticalAlign:r}}function Bu(t,e,r,n,i){if(n||i)for(var a=t[r],o=a.metrics.advance*a.scale,s=(t[r].x+o)*n,u=e;u<=r;u++)t[u].x-=s,t[u].y+=i;}function Pu(t,e,r,n,i,a){var o,s=t.image;if(s.content){var u=s.content,l=s.pixelRatio||1;o=[u[0]/l,u[1]/l,s.displaySize[0]-u[2]/l,s.displaySize[1]-u[3]/l];}var p,c,h,f,y=e.left*a,d=e.right*a;"width"===r||"both"===r?(f=i[0]+y-n[3],c=i[0]+d+n[1]):c=(f=i[0]+(y+d-s.displaySize[0])/2)+s.displaySize[0];var m=e.top*a,v=e.bottom*a;return "height"===r||"both"===r?(p=i[1]+m-n[0],h=i[1]+v+n[2]):h=(p=i[1]+(m+v-s.displaySize[1])/2)+s.displaySize[1],{image:s,top:p,right:c,bottom:h,left:f,collisionPadding:o}}ku[10]=!0,ku[32]=!0,ku[38]=!0,ku[40]=!0,ku[41]=!0,ku[43]=!0,ku[45]=!0,ku[47]=!0,ku[173]=!0,ku[183]=!0,ku[8203]=!0,ku[8208]=!0,ku[8211]=!0,ku[8231]=!0;var Vu=function(t){function e(e,r,n,i){t.call(this,e,r),this.angle=n,void 0!==i&&(this.segment=i);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.clone=function(){return new e(this.x,this.y,this.angle,this.segment)},e}(i);zn("Anchor",Vu);var Fu=128;function Lu(t,e){var r=e.expression;if("constant"===r.kind)return {kind:"constant",layoutSize:r.evaluate(new ti(t+1))};if("source"===r.kind)return {kind:"source"};for(var n=r.zoomStops,i=r.interpolationType,a=0;a<n.length&&n[a]<=t;)a++;for(var o=a=Math.max(0,a-1);o<n.length&&n[o]<t+1;)o++;o=Math.min(n.length-1,o);var s=n[a],u=n[o];return "composite"===r.kind?{kind:"composite",minZoom:s,maxZoom:u,interpolationType:i}:{kind:"camera",minZoom:s,maxZoom:u,minSize:r.evaluate(new ti(s)),maxSize:r.evaluate(new ti(u)),interpolationType:i}}function Du(t,e,r){var n=e.uSize,i=e.uSizeT,a=r.lowerSize,o=r.upperSize;return "source"===t.kind?a/Fu:"composite"===t.kind?Ce(a/Fu,o/Fu,i):n}function Ou(t,e){var r=0,n=0;if("constant"===t.kind)n=t.layoutSize;else if("source"!==t.kind){var i=t.interpolationType,a=t.minZoom,o=t.maxZoom,s=i?u(Ye.interpolationFactor(i,e,a,o),0,1):0;"camera"===t.kind?n=Ce(t.minSize,t.maxSize,s):r=s;}return {uSizeT:r,uSize:n}}var Ru=Object.freeze({__proto__:null,getSizeData:Lu,evaluateSizeForFeature:Du,evaluateSizeForZoom:Ou,SIZE_PACK_FACTOR:Fu});function Uu(t,e,r,n,i){if(void 0===e.segment)return !0;for(var a=e,o=e.segment+1,s=0;s>-r/2;){if(--o<0)return !1;s-=t[o].dist(a),a=t[o];}s+=t[o].dist(t[o+1]),o++;for(var u=[],l=0;s<r/2;){var p=t[o-1],c=t[o],h=t[o+1];if(!h)return !1;var f=p.angleTo(c)-c.angleTo(h);for(f=Math.abs((f+3*Math.PI)%(2*Math.PI)-Math.PI),u.push({distance:s,angleDelta:f}),l+=f;s-u[0].distance>n;)l-=u.shift().angleDelta;if(l>i)return !1;o++,s+=c.dist(h);}return !0}function ju(t){for(var e=0,r=0;r<t.length-1;r++)e+=t[r].dist(t[r+1]);return e}function qu(t,e,r){return t?.6*e*r:0}function Nu(t,e){return Math.max(t?t.right-t.left:0,e?e.right-e.left:0)}function Ku(t,e,r,n,i,a){for(var o=qu(r,i,a),s=Nu(r,n)*a,u=0,l=ju(t)/2,p=0;p<t.length-1;p++){var c=t[p],h=t[p+1],f=c.dist(h);if(u+f>l){var y=(l-u)/f,d=Ce(c.x,h.x,y),m=Ce(c.y,h.y,y),v=new Vu(d,m,h.angleTo(c),p);return v._round(),!o||Uu(t,v,s,o,e)?v:void 0}u+=f;}}function Xu(t,e,r,n,i,a,o,s,u){var l=qu(n,a,o),p=Nu(n,i),c=p*o,h=0===t[0].x||t[0].x===u||0===t[0].y||t[0].y===u;return e-c<e/4&&(e=c+e/4),function t(e,r,n,i,a,o,s,u,l){var p=o/2;var c=ju(e);var h=0,f=r-n;var y=[];for(var d=0;d<e.length-1;d++){for(var m=e[d],v=e[d+1],g=m.dist(v),x=v.angleTo(m);f+n<h+g;){var b=((f+=n)-h)/g,_=Ce(m.x,v.x,b),w=Ce(m.y,v.y,b);if(_>=0&&_<l&&w>=0&&w<l&&f-p>=0&&f+p<=c){var A=new Vu(_,w,x,d);A._round(),i&&!Uu(e,A,o,i,a)||y.push(A);}}h+=g;}u||y.length||s||(y=t(e,h/2,n,i,a,o,s,!0,l));return y}(t,h?e/2*s%e:(p/2+2*a)*o*s%e,e,l,r,c,h,!1,u)}var Zu=du;function Gu(t,e,r,n){var a=[],o=t.image,s=o.pixelRatio,u=o.paddedRect.w-2*Zu,l=o.paddedRect.h-2*Zu,p=t.right-t.left,c=t.bottom-t.top,h=o.stretchX||[[0,u]],f=o.stretchY||[[0,l]],y=function(t,e){return t+e[1]-e[0]},d=h.reduce(y,0),m=f.reduce(y,0),v=u-d,g=l-m,x=0,b=d,_=0,w=m,A=0,S=v,k=0,I=g;if(o.content&&n){var z=o.content;x=Ju(h,0,z[0]),_=Ju(f,0,z[1]),b=Ju(h,z[0],z[2]),w=Ju(f,z[1],z[3]),A=z[0]-x,k=z[1]-_,S=z[2]-z[0]-b,I=z[3]-z[1]-w;}var C=function(n,a,u,l){var h=Hu(n.stretch-x,b,p,t.left),f=$u(n.fixed-A,S,n.stretch,d),y=Hu(a.stretch-_,w,c,t.top),v=$u(a.fixed-k,I,a.stretch,m),g=Hu(u.stretch-x,b,p,t.left),z=$u(u.fixed-A,S,u.stretch,d),C=Hu(l.stretch-_,w,c,t.top),T=$u(l.fixed-k,I,l.stretch,m),E=new i(h,y),M=new i(g,y),B=new i(g,C),P=new i(h,C),V=new i(f/s,v/s),F=new i(z/s,T/s),L=e*Math.PI/180;if(L){var D=Math.sin(L),O=Math.cos(L),R=[O,-D,D,O];E._matMult(R),M._matMult(R),P._matMult(R),B._matMult(R);}var U=n.stretch+n.fixed,j=u.stretch+u.fixed,q=a.stretch+a.fixed,N=l.stretch+l.fixed;return {tl:E,tr:M,bl:P,br:B,tex:{x:o.paddedRect.x+Zu+U,y:o.paddedRect.y+Zu+q,w:j-U,h:N-q},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:V,pixelOffsetBR:F,minFontScaleX:S/s/p,minFontScaleY:I/s/c,isSDF:r}};if(n&&(o.stretchX||o.stretchY))for(var T=Yu(h,v,d),E=Yu(f,g,m),M=0;M<T.length-1;M++)for(var B=T[M],P=T[M+1],V=0;V<E.length-1;V++){var F=E[V],L=E[V+1];a.push(C(B,F,P,L));}else a.push(C({fixed:0,stretch:-1},{fixed:0,stretch:-1},{fixed:0,stretch:u+1},{fixed:0,stretch:l+1}));return a}function Ju(t,e,r){for(var n=0,i=0,a=t;i<a.length;i+=1){var o=a[i];n+=Math.max(e,Math.min(r,o[1]))-Math.max(e,Math.min(r,o[0]));}return n}function Yu(t,e,r){for(var n=[{fixed:-Zu,stretch:0}],i=0,a=t;i<a.length;i+=1){var o=a[i],s=o[0],u=o[1],l=n[n.length-1];n.push({fixed:s-l.stretch,stretch:l.stretch}),n.push({fixed:s-l.stretch,stretch:l.stretch+(u-s)});}return n.push({fixed:e+Zu,stretch:r}),n}function Hu(t,e,r,n){return t/e*r+n}function $u(t,e,r,n){return t-e*r/n}var Wu=function(t,e,r,n,a,o,s,u,l,p,c,h){var f=s.top*u-l,y=s.bottom*u+l,d=s.left*u-l,m=s.right*u+l,v=s.collisionPadding;if(v&&(d-=v[0]*u,f-=v[1]*u,m+=v[2]*u,y+=v[3]*u),this.boxStartIndex=t.length,p){var g=y-f,x=m-d;g>0&&(g=Math.max(10*u,g),this._addLineCollisionCircles(t,e,r,r.segment,x,g,n,a,o,c));}else{if(h){var b=new i(d,f),_=new i(m,f),w=new i(d,y),A=new i(m,y),S=h*Math.PI/180;b._rotate(S),_._rotate(S),w._rotate(S),A._rotate(S),d=Math.min(b.x,_.x,w.x,A.x),m=Math.max(b.x,_.x,w.x,A.x),f=Math.min(b.y,_.y,w.y,A.y),y=Math.max(b.y,_.y,w.y,A.y);}t.emplaceBack(r.x,r.y,d,f,m,y,n,a,o,0,0);}this.boxEndIndex=t.length;};Wu.prototype._addLineCollisionCircles=function(t,e,r,n,i,a,o,s,u,l){var p=a/2,c=Math.floor(i/p)||1,h=1+.4*Math.log(l)/Math.LN2,f=Math.floor(c*h/2),y=-a/2,d=r,m=n+1,v=y,g=-i/2,x=g-i/4;do{if(--m<0){if(v>g)return;m=0;break}v-=e[m].dist(d),d=e[m];}while(v>x);for(var b=e[m].dist(e[m+1]),_=-f;_<c+f;_++){var w=_*p,A=g+w;if(w<0&&(A+=w),w>i&&(A+=w-i),!(A<v)){for(;v+b<A;){if(v+=b,++m+1>=e.length)return;b=e[m].dist(e[m+1]);}var S=A-v,k=e[m],I=e[m+1].sub(k)._unit()._mult(S)._add(k)._round(),z=Math.abs(A-y)<p?0:.8*(A-y);t.emplaceBack(I.x,I.y,-a/2,-a/2,a/2,a/2,o,s,u,a/2,z);}}};var Qu=function(t,e){if(void 0===t&&(t=[]),void 0===e&&(e=tl),this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r);};function tl(t,e){return t<e?-1:t>e?1:0}function el(t,e,r){void 0===e&&(e=1),void 0===r&&(r=!1);for(var n=1/0,a=1/0,o=-1/0,s=-1/0,u=t[0],l=0;l<u.length;l++){var p=u[l];(!l||p.x<n)&&(n=p.x),(!l||p.y<a)&&(a=p.y),(!l||p.x>o)&&(o=p.x),(!l||p.y>s)&&(s=p.y);}var c=o-n,h=s-a,f=Math.min(c,h),y=f/2,d=new Qu([],rl);if(0===f)return new i(n,a);for(var m=n;m<o;m+=f)for(var v=a;v<s;v+=f)d.push(new nl(m+y,v+y,y,t));for(var g=function(t){for(var e=0,r=0,n=0,i=t[0],a=0,o=i.length,s=o-1;a<o;s=a++){var u=i[a],l=i[s],p=u.x*l.y-l.x*u.y;r+=(u.x+l.x)*p,n+=(u.y+l.y)*p,e+=3*p;}return new nl(r/e,n/e,0,t)}(t),x=d.length;d.length;){var b=d.pop();(b.d>g.d||!g.d)&&(g=b,r&&console.log("found best %d after %d probes",Math.round(1e4*b.d)/1e4,x)),b.max-g.d<=e||(y=b.h/2,d.push(new nl(b.p.x-y,b.p.y-y,y,t)),d.push(new nl(b.p.x+y,b.p.y-y,y,t)),d.push(new nl(b.p.x-y,b.p.y+y,y,t)),d.push(new nl(b.p.x+y,b.p.y+y,y,t)),x+=4);}return r&&(console.log("num probes: "+x),console.log("best distance: "+g.d)),g.p}function rl(t,e){return e.max-t.max}function nl(t,e,r,n){this.p=new i(t,e),this.h=r,this.d=function(t,e){for(var r=!1,n=1/0,i=0;i<e.length;i++)for(var a=e[i],o=0,s=a.length,u=s-1;o<s;u=o++){var l=a[o],p=a[u];l.y>t.y!=p.y>t.y&&t.x<(p.x-l.x)*(t.y-l.y)/(p.y-l.y)+l.x&&(r=!r),n=Math.min(n,Ka(t,l,p));}return (r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2;}Qu.prototype.push=function(t){this.data.push(t),this.length++,this._up(this.length-1);},Qu.prototype.pop=function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}},Qu.prototype.peek=function(){return this.data[0]},Qu.prototype._up=function(t){for(var e=this.data,r=this.compare,n=e[t];t>0;){var i=t-1>>1,a=e[i];if(r(n,a)>=0)break;e[t]=a,t=i;}e[t]=n;},Qu.prototype._down=function(t){for(var e=this.data,r=this.compare,n=this.length>>1,i=e[t];t<n;){var a=1+(t<<1),o=e[a],s=a+1;if(s<this.length&&r(e[s],o)<0&&(a=s,o=e[s]),r(o,i)>=0)break;e[t]=o,t=a;}e[t]=i;};var il=7,al=Number.POSITIVE_INFINITY;function ol(t,e){return e[1]!==al?function(t,e,r){var n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case"top-right":case"top-left":case"top":i=r-il;break;case"bottom-right":case"bottom-left":case"bottom":i=-r+il;}switch(t){case"top-right":case"bottom-right":case"right":n=-e;break;case"top-left":case"bottom-left":case"left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){var r=0,n=0;e<0&&(e=0);var i=e/Math.sqrt(2);switch(t){case"top-right":case"top-left":n=i-il;break;case"bottom-right":case"bottom-left":n=-i+il;break;case"bottom":n=-e+il;break;case"top":n=e-il;}switch(t){case"top-right":case"bottom-right":r=-i;break;case"top-left":case"bottom-left":r=i;break;case"left":r=e;break;case"right":r=-e;}return [r,n]}(t,e[0])}function sl(t){switch(t){case"right":case"top-right":case"bottom-right":return "right";case"left":case"top-left":case"bottom-left":return "left"}return "center"}var ul=255,ll=ul*Fu;function pl(t,e,r,n,a,o,s,u,l,p,c,h,f,y){var d=function(t,e,r,n,a,o,s,u){for(var l=n.layout.get("text-rotate").evaluate(o,{})*Math.PI/180,p=[],c=0,h=e.positionedLines;c<h.length;c+=1)for(var f=h[c],y=0,d=f.positionedGlyphs;y<d.length;y+=1){var m=d[y];if(m.rect){var v=m.rect||{},g=fu+1,x=!0,b=1,_=0,w=(a||u)&&m.vertical,A=m.metrics.advance*m.scale/2;if(u&&e.verticalizable){var S=(m.scale-1)*qs,k=(qs-m.metrics.width*m.scale)/2;_=f.lineOffset/2-(m.imageName?-k:S);}if(m.imageName){var I=s[m.imageName];x=I.sdf,b=I.pixelRatio,g=du/b;}var z=a?[m.x+A,m.y]:[0,0],C=a?[0,0]:[m.x+A+r[0],m.y+r[1]-_],T=[0,0];w&&(T=C,C=[0,0]);var E=(m.metrics.left-g)*m.scale-A+C[0],M=(-m.metrics.top-g)*m.scale+C[1],B=E+v.w*m.scale/b,P=M+v.h*m.scale/b,V=new i(E,M),F=new i(B,M),L=new i(E,P),D=new i(B,P);if(w){var O=new i(-A,A-bu),R=-Math.PI/2,U=qs/2-A,j=m.imageName?U:0,q=new i(5-bu-U,-j),N=new(Function.prototype.bind.apply(i,[null].concat(T)));V._rotateAround(R,O)._add(q)._add(N),F._rotateAround(R,O)._add(q)._add(N),L._rotateAround(R,O)._add(q)._add(N),D._rotateAround(R,O)._add(q)._add(N);}if(l){var K=Math.sin(l),X=Math.cos(l),Z=[X,-K,K,X];V._matMult(Z),F._matMult(Z),L._matMult(Z),D._matMult(Z);}var G=new i(0,0),J=new i(0,0);p.push({tl:V,tr:F,bl:L,br:D,tex:v,writingMode:e.writingMode,glyphOffset:z,sectionIndex:m.sectionIndex,isSDF:x,pixelOffsetTL:G,pixelOffsetBR:J,minFontScaleX:0,minFontScaleY:0});}}return p}(0,r,u,a,o,s,n,t.allowVerticalPlacement),m=t.textSizeData,v=null;"source"===m.kind?(v=[Fu*a.layout.get("text-size").evaluate(s,{})])[0]>ll&&_(t.layerIds[0]+': Value for "text-size" is >= '+ul+'. Reduce your "text-size".'):"composite"===m.kind&&((v=[Fu*y.compositeTextSizes[0].evaluate(s,{}),Fu*y.compositeTextSizes[1].evaluate(s,{})])[0]>ll||v[1]>ll)&&_(t.layerIds[0]+': Value for "text-size" is >= '+ul+'. Reduce your "text-size".'),t.addSymbols(t.text,d,v,u,o,s,p,e,l.lineStartIndex,l.lineLength,f);for(var g=0,x=c;g<x.length;g+=1){h[x[g]]=t.text.placedSymbolArray.length-1;}return 4*d.length}function cl(t){for(var e in t)return t[e];return null}function hl(t,e,r,n){var i=t.compareText;if(e in i){for(var a=i[e],o=a.length-1;o>=0;o--)if(n.dist(a[o])<r)return !0}else i[e]=[];return i[e].push(n),!1}var fl=ys.VectorTileFeature.types,yl=[{name:"a_fade_opacity",components:1,type:"Uint8",offset:0}];function dl(t,e,r,n,i,a,o,s,u,l,p,c,h){var f=s?Math.min(ll,Math.round(s[0])):0,y=s?Math.min(ll,Math.round(s[1])):0;t.emplaceBack(e,r,Math.round(32*n),Math.round(32*i),a,o,(f<<1)+(u?1:0),y,16*l,16*p,256*c,256*h);}function ml(t,e,r){t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r);}function vl(t){for(var e=0,r=t.sections;e<r.length;e+=1){if(jn(r[e].text))return !0}return !1}var gl=function(t){this.layoutVertexArray=new Ii,this.indexArray=new Di,this.programConfigurations=t,this.segments=new ea,this.dynamicLayoutVertexArray=new zi,this.opacityVertexArray=new Ci,this.placedSymbolArray=new Xi;};gl.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length&&0===this.indexArray.length&&0===this.dynamicLayoutVertexArray.length&&0===this.opacityVertexArray.length},gl.prototype.upload=function(t,e,r,n){this.isEmpty()||(r&&(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Fs.members),this.indexBuffer=t.createIndexBuffer(this.indexArray,e),this.dynamicLayoutVertexBuffer=t.createVertexBuffer(this.dynamicLayoutVertexArray,Ls.members,!0),this.opacityVertexBuffer=t.createVertexBuffer(this.opacityVertexArray,yl,!0),this.opacityVertexBuffer.itemSize=1),(r||n)&&this.programConfigurations.upload(t));},gl.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy());},zn("SymbolBuffers",gl);var xl=function(t,e,r){this.layoutVertexArray=new t,this.layoutAttributes=e,this.indexArray=new r,this.segments=new ea,this.collisionVertexArray=new Mi;};xl.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=t.createVertexBuffer(this.collisionVertexArray,Ds.members,!0);},xl.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy());},zn("CollisionBuffers",xl);var bl=function(t){this.collisionBoxArray=t.collisionBoxArray,this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.pixelRatio=t.pixelRatio,this.sourceLayerIndex=t.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[];var e=this.layers[0]._unevaluatedLayout._values;this.textSizeData=Lu(this.zoom,e["text-size"]),this.iconSizeData=Lu(this.zoom,e["icon-size"]);var r=this.layers[0].layout,n=r.get("symbol-sort-key"),i=r.get("symbol-z-order");this.sortFeaturesByKey="viewport-y"!==i&&void 0!==n.constantOr(1);var a="viewport-y"===i||"auto"===i&&!this.sortFeaturesByKey;this.sortFeaturesByY=a&&(r.get("text-allow-overlap")||r.get("icon-allow-overlap")||r.get("text-ignore-placement")||r.get("icon-ignore-placement")),"point"===r.get("symbol-placement")&&(this.writingModes=r.get("text-writing-mode").map((function(t){return xu[t]}))),this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id})),this.sourceID=t.sourceID;};bl.prototype.createArrays=function(){this.text=new gl(new Ca(Fs.members,this.layers,this.zoom,(function(t){return /^text/.test(t)}))),this.icon=new gl(new Ca(Fs.members,this.layers,this.zoom,(function(t){return /^icon/.test(t)}))),this.glyphOffsetArray=new Yi,this.lineVertexArray=new $i,this.symbolInstances=new Gi;},bl.prototype.calculateGlyphDependencies=function(t,e,r,n,i){for(var a=0;a<t.length;a++)if(e[t.charCodeAt(a)]=!0,(r||n)&&i){var o=js[t.charAt(a)];o&&(e[o.charCodeAt(0)]=!0);}},bl.prototype.populate=function(t,e){var r=this.layers[0],n=r.layout,i=n.get("text-font"),a=n.get("text-field"),o=n.get("icon-image"),s=("constant"!==a.value.kind||a.value.value instanceof ie&&!a.value.value.isEmpty()||a.value.value.toString().length>0)&&("constant"!==i.value.kind||i.value.value.length>0),u=("constant"!==o.value.kind||!!o.value.value)&&Object.keys(o.parameters).length>0,l=n.get("symbol-sort-key");if(this.features=[],s||u){for(var p=e.iconDependencies,c=e.glyphDependencies,h=e.availableImages,f=new ti(this.zoom),y=0,d=t;y<d.length;y+=1){var m=d[y],v=m.feature,g=m.id,x=m.index,b=m.sourceLayerIndex;if(r._featureFilter(f,v)){var _=void 0;if(s){var w=r.getValueAndResolveTokens("text-field",v,h),A=ie.factory(w);vl(A)&&(this.hasRTLText=!0),(!this.hasRTLText||"unavailable"===$n()||this.hasRTLText&&Qn.isParsed())&&(_=Us(A,r,v));}var S=void 0;if(u){var k=r.getValueAndResolveTokens("icon-image",v,h);S=k instanceof ae?k:ae.fromString(k);}if(_||S){var I=this.sortFeaturesByKey?l.evaluate(v,{}):void 0,z={id:g,text:_,icon:S,index:x,sourceLayerIndex:b,geometry:Va(v),properties:v.properties,type:fl[v.type],sortKey:I};if(this.features.push(z),S&&(p[S.name]=!0),_){var C=i.evaluate(v,{}).join(","),T="map"===n.get("text-rotation-alignment")&&"point"!==n.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(xu.vertical)>=0;for(var E=0,M=_.sections;E<M.length;E+=1){var B=M[E];if(B.image)p[B.image.name]=!0;else{var P=Fn(_.toString()),V=B.fontStack||C,F=c[V]=c[V]||{};this.calculateGlyphDependencies(B.text,F,T,this.allowVerticalPlacement,P);}}}}}}"line"===n.get("symbol-placement")&&(this.features=function(t){var e={},r={},n=[],i=0;function a(e){n.push(t[e]),i++;}function o(t,e,i){var a=r[t];return delete r[t],r[e]=a,n[a].geometry[0].pop(),n[a].geometry[0]=n[a].geometry[0].concat(i[0]),a}function s(t,r,i){var a=e[r];return delete e[r],e[t]=a,n[a].geometry[0].shift(),n[a].geometry[0]=i[0].concat(n[a].geometry[0]),a}function u(t,e,r){var n=r?e[0][e[0].length-1]:e[0][0];return t+":"+n.x+":"+n.y}for(var l=0;l<t.length;l++){var p=t[l],c=p.geometry,h=p.text?p.text.toString():null;if(h){var f=u(h,c),y=u(h,c,!0);if(f in r&&y in e&&r[f]!==e[y]){var d=s(f,y,c),m=o(f,y,n[d].geometry);delete e[f],delete r[y],r[u(h,n[m].geometry,!0)]=m,n[d].geometry=null;}else f in r?o(f,y,c):y in e?s(f,y,c):(a(l),e[f]=i-1,r[y]=i-1);}else a(l);}return n.filter((function(t){return t.geometry}))}(this.features)),this.sortFeaturesByKey&&this.features.sort((function(t,e){return t.sortKey-e.sortKey}));}},bl.prototype.update=function(t,e,r){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,r),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,r));},bl.prototype.isEmpty=function(){return 0===this.symbolInstances.length&&!this.hasRTLText},bl.prototype.uploadPending=function(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload},bl.prototype.upload=function(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t),this.textCollisionCircle.upload(t),this.iconCollisionCircle.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0;},bl.prototype.destroyDebugData=function(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy(),this.textCollisionCircle.destroy(),this.iconCollisionCircle.destroy();},bl.prototype.destroy=function(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();},bl.prototype.addToLineVertexArray=function(t,e){var r=this.lineVertexArray.length;if(void 0!==t.segment){for(var n=t.dist(e[t.segment+1]),i=t.dist(e[t.segment]),a={},o=t.segment+1;o<e.length;o++)a[o]={x:e[o].x,y:e[o].y,tileUnitDistanceFromAnchor:n},o<e.length-1&&(n+=e[o+1].dist(e[o]));for(var s=t.segment||0;s>=0;s--)a[s]={x:e[s].x,y:e[s].y,tileUnitDistanceFromAnchor:i},s>0&&(i+=e[s-1].dist(e[s]));for(var u=0;u<e.length;u++){var l=a[u];this.lineVertexArray.emplaceBack(l.x,l.y,l.tileUnitDistanceFromAnchor);}}return {lineStartIndex:r,lineLength:this.lineVertexArray.length-r}},bl.prototype.addSymbols=function(t,e,r,n,i,a,o,s,u,l,p){for(var c=t.indexArray,h=t.layoutVertexArray,f=t.segments.prepareSegment(4*e.length,h,c,a.sortKey),y=this.glyphOffsetArray.length,d=f.vertexLength,m=this.allowVerticalPlacement&&o===xu.vertical?Math.PI/2:0,v=a.text&&a.text.sections,g=0;g<e.length;g++){var x=e[g],b=x.tl,_=x.tr,w=x.bl,A=x.br,S=x.tex,k=x.pixelOffsetTL,I=x.pixelOffsetBR,z=x.minFontScaleX,C=x.minFontScaleY,T=x.glyphOffset,E=x.isSDF,M=x.sectionIndex,B=f.vertexLength,P=T[1];dl(h,s.x,s.y,b.x,P+b.y,S.x,S.y,r,E,k.x,k.y,z,C),dl(h,s.x,s.y,_.x,P+_.y,S.x+S.w,S.y,r,E,I.x,k.y,z,C),dl(h,s.x,s.y,w.x,P+w.y,S.x,S.y+S.h,r,E,k.x,I.y,z,C),dl(h,s.x,s.y,A.x,P+A.y,S.x+S.w,S.y+S.h,r,E,I.x,I.y,z,C),ml(t.dynamicLayoutVertexArray,s,m),c.emplaceBack(B,B+1,B+2),c.emplaceBack(B+1,B+2,B+3),f.vertexLength+=4,f.primitiveLength+=2,this.glyphOffsetArray.emplaceBack(T[0]),g!==e.length-1&&M===e[g+1].sectionIndex||t.programConfigurations.populatePaintArrays(h.length,a,a.index,{},v&&v[M]);}t.placedSymbolArray.emplaceBack(s.x,s.y,y,this.glyphOffsetArray.length-y,d,u,l,s.segment,r?r[0]:0,r?r[1]:0,n[0],n[1],o,0,!1,0,p);},bl.prototype._addCollisionDebugVertex=function(t,e,r,n,i,a){return e.emplaceBack(0,0),t.emplaceBack(r.x,r.y,n,i,Math.round(a.x),Math.round(a.y))},bl.prototype.addCollisionDebugVertices=function(t,e,r,n,a,o,s,u){var l=a.segments.prepareSegment(4,a.layoutVertexArray,a.indexArray),p=l.vertexLength,c=a.layoutVertexArray,h=a.collisionVertexArray,f=s.anchorX,y=s.anchorY;if(this._addCollisionDebugVertex(c,h,o,f,y,new i(t,e)),this._addCollisionDebugVertex(c,h,o,f,y,new i(r,e)),this._addCollisionDebugVertex(c,h,o,f,y,new i(r,n)),this._addCollisionDebugVertex(c,h,o,f,y,new i(t,n)),l.vertexLength+=4,u){var d=a.indexArray;d.emplaceBack(p,p+1,p+2),d.emplaceBack(p,p+2,p+3),l.primitiveLength+=2;}else{var m=a.indexArray;m.emplaceBack(p,p+1),m.emplaceBack(p+1,p+2),m.emplaceBack(p+2,p+3),m.emplaceBack(p+3,p),l.primitiveLength+=4;}},bl.prototype.addDebugCollisionBoxes=function(t,e,r,n){for(var i=t;i<e;i++){var a=this.collisionBoxArray.get(i),o=a.x1,s=a.y1,u=a.x2,l=a.y2,p=a.radius>0;this.addCollisionDebugVertices(o,s,u,l,p?n?this.textCollisionCircle:this.iconCollisionCircle:n?this.textCollisionBox:this.iconCollisionBox,a.anchorPoint,r,p);}},bl.prototype.generateCollisionDebugBuffers=function(){this.hasDebugData()&&this.destroyDebugData(),this.textCollisionBox=new xl(Ei,Os.members,Oi),this.iconCollisionBox=new xl(Ei,Os.members,Oi),this.textCollisionCircle=new xl(Ei,Rs.members,Di),this.iconCollisionCircle=new xl(Ei,Rs.members,Di);for(var t=0;t<this.symbolInstances.length;t++){var e=this.symbolInstances.get(t);this.addDebugCollisionBoxes(e.textBoxStartIndex,e.textBoxEndIndex,e,!0),this.addDebugCollisionBoxes(e.verticalTextBoxStartIndex,e.verticalTextBoxEndIndex,e,!0),this.addDebugCollisionBoxes(e.iconBoxStartIndex,e.iconBoxEndIndex,e,!1),this.addDebugCollisionBoxes(e.verticalIconBoxStartIndex,e.verticalIconBoxEndIndex,e,!1);}},bl.prototype._deserializeCollisionBoxesForSymbol=function(t,e,r,n,i,a,o,s,u){for(var l={},p=e;p<r;p++){var c=t.get(p);if(0===c.radius){l.textBox={x1:c.x1,y1:c.y1,x2:c.x2,y2:c.y2,anchorPointX:c.anchorPointX,anchorPointY:c.anchorPointY},l.textFeatureIndex=c.featureIndex;break}l.textCircles||(l.textCircles=[],l.textFeatureIndex=c.featureIndex);l.textCircles.push(c.anchorPointX,c.anchorPointY,c.radius,c.signedDistanceFromAnchor,1);}for(var h=n;h<i;h++){var f=t.get(h);if(0===f.radius){l.verticalTextBox={x1:f.x1,y1:f.y1,x2:f.x2,y2:f.y2,anchorPointX:f.anchorPointX,anchorPointY:f.anchorPointY},l.verticalTextFeatureIndex=f.featureIndex;break}}for(var y=a;y<o;y++){var d=t.get(y);if(0===d.radius){l.iconBox={x1:d.x1,y1:d.y1,x2:d.x2,y2:d.y2,anchorPointX:d.anchorPointX,anchorPointY:d.anchorPointY},l.iconFeatureIndex=d.featureIndex;break}}for(var m=s;m<u;m++){var v=t.get(m);if(0===v.radius){l.verticalIconBox={x1:v.x1,y1:v.y1,x2:v.x2,y2:v.y2,anchorPointX:v.anchorPointX,anchorPointY:v.anchorPointY},l.verticalIconFeatureIndex=v.featureIndex;break}}return l},bl.prototype.deserializeCollisionBoxes=function(t){this.collisionArrays=[];for(var e=0;e<this.symbolInstances.length;e++){var r=this.symbolInstances.get(e);this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol(t,r.textBoxStartIndex,r.textBoxEndIndex,r.verticalTextBoxStartIndex,r.verticalTextBoxEndIndex,r.iconBoxStartIndex,r.iconBoxEndIndex,r.verticalIconBoxStartIndex,r.verticalIconBoxEndIndex));}},bl.prototype.hasTextData=function(){return this.text.segments.get().length>0},bl.prototype.hasIconData=function(){return this.icon.segments.get().length>0},bl.prototype.hasDebugData=function(){return this.textCollisionBox&&this.iconCollisionBox&&this.textCollisionCircle&&this.iconCollisionCircle},bl.prototype.hasTextCollisionBoxData=function(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0},bl.prototype.hasIconCollisionBoxData=function(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0},bl.prototype.hasTextCollisionCircleData=function(){return this.hasDebugData()&&this.textCollisionCircle.segments.get().length>0},bl.prototype.hasIconCollisionCircleData=function(){return this.hasDebugData()&&this.iconCollisionCircle.segments.get().length>0},bl.prototype.addIndicesForPlacedSymbol=function(t,e){for(var r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs,i=r.vertexStartIndex;i<n;i+=4)t.indexArray.emplaceBack(i,i+1,i+2),t.indexArray.emplaceBack(i+1,i+2,i+3);},bl.prototype.getSortedSymbolIndexes=function(t){if(this.sortedAngle===t&&void 0!==this.symbolInstanceIndexes)return this.symbolInstanceIndexes;for(var e=Math.sin(t),r=Math.cos(t),n=[],i=[],a=[],o=0;o<this.symbolInstances.length;++o){a.push(o);var s=this.symbolInstances.get(o);n.push(0|Math.round(e*s.anchorX+r*s.anchorY)),i.push(s.featureIndex);}return a.sort((function(t,e){return n[t]-n[e]||i[e]-i[t]})),a},bl.prototype.addToSortKeyRanges=function(t,e){var r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});},bl.prototype.sortFeatures=function(t){var e=this;if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(var r=0,n=this.symbolInstanceIndexes;r<n.length;r+=1){var i=n[r],a=this.symbolInstances.get(i);this.featureSortOrder.push(a.featureIndex),[a.rightJustifiedTextSymbolIndex,a.centerJustifiedTextSymbolIndex,a.leftJustifiedTextSymbolIndex].forEach((function(t,r,n){t>=0&&n.indexOf(t)===r&&e.addIndicesForPlacedSymbol(e.text,t);})),a.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,a.verticalPlacedTextSymbolIndex),a.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,a.placedIconSymbolIndex),a.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,a.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}},zn("SymbolBucket",bl,{omit:["layers","collisionBoxArray","features","compareText"]}),bl.MAX_GLYPHS=65535,bl.addDynamicAttributes=ml;var _l=new yi({"symbol-placement":new li(Bt.layout_symbol["symbol-placement"]),"symbol-spacing":new li(Bt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new li(Bt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new pi(Bt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new li(Bt.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new li(Bt.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new li(Bt.layout_symbol["icon-ignore-placement"]),"icon-optional":new li(Bt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new li(Bt.layout_symbol["icon-rotation-alignment"]),"icon-size":new pi(Bt.layout_symbol["icon-size"]),"icon-text-fit":new li(Bt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new li(Bt.layout_symbol["icon-text-fit-padding"]),"icon-image":new pi(Bt.layout_symbol["icon-image"]),"icon-rotate":new pi(Bt.layout_symbol["icon-rotate"]),"icon-padding":new li(Bt.layout_symbol["icon-padding"]),"icon-keep-upright":new li(Bt.layout_symbol["icon-keep-upright"]),"icon-offset":new pi(Bt.layout_symbol["icon-offset"]),"icon-anchor":new pi(Bt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new li(Bt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new li(Bt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new li(Bt.layout_symbol["text-rotation-alignment"]),"text-field":new pi(Bt.layout_symbol["text-field"]),"text-font":new pi(Bt.layout_symbol["text-font"]),"text-size":new pi(Bt.layout_symbol["text-size"]),"text-max-width":new pi(Bt.layout_symbol["text-max-width"]),"text-line-height":new li(Bt.layout_symbol["text-line-height"]),"text-letter-spacing":new pi(Bt.layout_symbol["text-letter-spacing"]),"text-justify":new pi(Bt.layout_symbol["text-justify"]),"text-radial-offset":new pi(Bt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new li(Bt.layout_symbol["text-variable-anchor"]),"text-anchor":new pi(Bt.layout_symbol["text-anchor"]),"text-max-angle":new li(Bt.layout_symbol["text-max-angle"]),"text-writing-mode":new li(Bt.layout_symbol["text-writing-mode"]),"text-rotate":new pi(Bt.layout_symbol["text-rotate"]),"text-padding":new li(Bt.layout_symbol["text-padding"]),"text-keep-upright":new li(Bt.layout_symbol["text-keep-upright"]),"text-transform":new pi(Bt.layout_symbol["text-transform"]),"text-offset":new pi(Bt.layout_symbol["text-offset"]),"text-allow-overlap":new li(Bt.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new li(Bt.layout_symbol["text-ignore-placement"]),"text-optional":new li(Bt.layout_symbol["text-optional"])}),wl={paint:new yi({"icon-opacity":new pi(Bt.paint_symbol["icon-opacity"]),"icon-color":new pi(Bt.paint_symbol["icon-color"]),"icon-halo-color":new pi(Bt.paint_symbol["icon-halo-color"]),"icon-halo-width":new pi(Bt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new pi(Bt.paint_symbol["icon-halo-blur"]),"icon-translate":new li(Bt.paint_symbol["icon-translate"]),"icon-translate-anchor":new li(Bt.paint_symbol["icon-translate-anchor"]),"text-opacity":new pi(Bt.paint_symbol["text-opacity"]),"text-color":new pi(Bt.paint_symbol["text-color"],{runtimeType:Kt,getOverride:function(t){return t.textColor},hasOverride:function(t){return !!t.textColor}}),"text-halo-color":new pi(Bt.paint_symbol["text-halo-color"]),"text-halo-width":new pi(Bt.paint_symbol["text-halo-width"]),"text-halo-blur":new pi(Bt.paint_symbol["text-halo-blur"]),"text-translate":new li(Bt.paint_symbol["text-translate"]),"text-translate-anchor":new li(Bt.paint_symbol["text-translate-anchor"])}),layout:_l},Al=function(t){this.type=t.property.overrides?t.property.overrides.runtimeType:Ut,this.defaultValue=t;};Al.prototype.evaluate=function(t){if(t.formattedSection){var e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default},Al.prototype.eachChild=function(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);},Al.prototype.possibleOutputs=function(){return [void 0]},Al.prototype.serialize=function(){return null},zn("FormatSectionOverride",Al,{omit:["defaultValue"]});var Sl=function(t){function e(e){t.call(this,e,wl);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(e,r){if(t.prototype.recalculate.call(this,e,r),"auto"===this.layout.get("icon-rotation-alignment")&&("point"!==this.layout.get("symbol-placement")?this.layout._values["icon-rotation-alignment"]="map":this.layout._values["icon-rotation-alignment"]="viewport"),"auto"===this.layout.get("text-rotation-alignment")&&("point"!==this.layout.get("symbol-placement")?this.layout._values["text-rotation-alignment"]="map":this.layout._values["text-rotation-alignment"]="viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){var n=this.layout.get("text-writing-mode");if(n){for(var i=[],a=0,o=n;a<o.length;a+=1){var s=o[a];i.indexOf(s)<0&&i.push(s);}this.layout._values["text-writing-mode"]=i;}else this.layout._values["text-writing-mode"]=["horizontal"];}this._setPaintOverrides();},e.prototype.getValueAndResolveTokens=function(t,e,r){var n=this.layout.get(t).evaluate(e,{},r),i=this._unevaluatedLayout._values[t];return i.isDataDriven()||Pr(i.value)||!n?n:function(t,e){return e.replace(/{([^{}]+)}/g,(function(e,r){return r in t?String(t[r]):""}))}(e.properties,n)},e.prototype.createBucket=function(t){return new bl(t)},e.prototype.queryRadius=function(){return 0},e.prototype.queryIntersectsFeature=function(){return !1},e.prototype._setPaintOverrides=function(){for(var t=0,r=wl.paint.overridableProperties;t<r.length;t+=1){var n=r[t];if(e.hasPaintOverride(this.layout,n)){var i=this.paint.get(n),a=new Al(i),o=new Br(a,i.property.specification),s=null;s="constant"===i.value.kind||"source"===i.value.kind?new Fr("source",o):new Lr("composite",o,i.value.zoomStops,i.value._interpolationType),this.paint._values[n]=new si(i.property,s,i.parameters);}}},e.prototype._handleOverridablePaintPropertyUpdate=function(t,r,n){return !(!this.layout||r.isDataDriven()||n.isDataDriven())&&e.hasPaintOverride(this.layout,t)},e.hasPaintOverride=function(t,e){var r=t.get("text-field"),n=wl.paint.properties[e],i=!1,a=function(t){for(var e=0,r=t;e<r.length;e+=1){var a=r[e];if(n.overrides&&n.overrides.hasOverride(a))return void(i=!0)}};if("constant"===r.value.kind&&r.value.value instanceof ie)a(r.value.value.sections);else if("source"===r.value.kind){var o=function(t){if(!i)if(t instanceof le&&se(t.value)===Jt){var e=t.value;a(e.sections);}else t instanceof fe?a(t.sections):t.eachChild(o);},s=r.value;s._styleExpression&&o(s._styleExpression.expression);}return i},e}(di),kl={paint:new yi({"background-color":new li(Bt.paint_background["background-color"]),"background-pattern":new hi(Bt.paint_background["background-pattern"]),"background-opacity":new li(Bt.paint_background["background-opacity"])})},Il=function(t){function e(e){t.call(this,e,kl);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(di),zl={paint:new yi({"raster-opacity":new li(Bt.paint_raster["raster-opacity"]),"raster-hue-rotate":new li(Bt.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new li(Bt.paint_raster["raster-brightness-min"]),"raster-brightness-max":new li(Bt.paint_raster["raster-brightness-max"]),"raster-saturation":new li(Bt.paint_raster["raster-saturation"]),"raster-contrast":new li(Bt.paint_raster["raster-contrast"]),"raster-resampling":new li(Bt.paint_raster["raster-resampling"]),"raster-fade-duration":new li(Bt.paint_raster["raster-fade-duration"])})},Cl=function(t){function e(e){t.call(this,e,zl);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(di);var Tl=function(t){function e(e){t.call(this,e,{}),this.implementation=e;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.is3D=function(){return "3d"===this.implementation.renderingMode},e.prototype.hasOffscreenPass=function(){return void 0!==this.implementation.prerender},e.prototype.recalculate=function(){},e.prototype.updateTransitions=function(){},e.prototype.hasTransition=function(){},e.prototype.serialize=function(){},e.prototype.onAdd=function(t){this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl);},e.prototype.onRemove=function(t){this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl);},e}(di),El={circle:ao,heatmap:mo,hillshade:go,fill:is,"fill-extrusion":ws,line:Ps,symbol:Sl,background:Il,raster:Cl};var Ml=self.HTMLImageElement,Bl=self.HTMLCanvasElement,Pl=self.HTMLVideoElement,Vl=self.ImageData,Fl=self.ImageBitmap,Ll=function(t,e,r,n){this.context=t,this.format=r,this.texture=t.gl.createTexture(),this.update(e,n);};Ll.prototype.update=function(t,e,r){var n=t.width,i=t.height,a=!(this.size&&this.size[0]===n&&this.size[1]===i||r),o=this.context,s=o.gl;if(this.useMipmap=Boolean(e&&e.useMipmap),s.bindTexture(s.TEXTURE_2D,this.texture),o.pixelStoreUnpackFlipY.set(!1),o.pixelStoreUnpack.set(1),o.pixelStoreUnpackPremultiplyAlpha.set(this.format===s.RGBA&&(!e||!1!==e.premultiply)),a)this.size=[n,i],t instanceof Ml||t instanceof Bl||t instanceof Pl||t instanceof Vl||Fl&&t instanceof Fl?s.texImage2D(s.TEXTURE_2D,0,this.format,this.format,s.UNSIGNED_BYTE,t):s.texImage2D(s.TEXTURE_2D,0,this.format,n,i,0,this.format,s.UNSIGNED_BYTE,t.data);else{var u=r||{x:0,y:0},l=u.x,p=u.y;t instanceof Ml||t instanceof Bl||t instanceof Pl||t instanceof Vl||Fl&&t instanceof Fl?s.texSubImage2D(s.TEXTURE_2D,0,l,p,s.RGBA,s.UNSIGNED_BYTE,t):s.texSubImage2D(s.TEXTURE_2D,0,l,p,n,i,s.RGBA,s.UNSIGNED_BYTE,t.data);}this.useMipmap&&this.isSizePowerOfTwo()&&s.generateMipmap(s.TEXTURE_2D);},Ll.prototype.bind=function(t,e,r){var n=this.context.gl;n.bindTexture(n.TEXTURE_2D,this.texture),r!==n.LINEAR_MIPMAP_NEAREST||this.isSizePowerOfTwo()||(r=n.LINEAR),t!==this.filter&&(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,t),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,r||t),this.filter=t),e!==this.wrap&&(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,e),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,e),this.wrap=e);},Ll.prototype.isSizePowerOfTwo=function(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1==0},Ll.prototype.destroy=function(){this.context.gl.deleteTexture(this.texture),this.texture=null;};var Dl=function(t){var e=this;this._callback=t,this._triggered=!1,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=function(){e._triggered=!1,e._callback();});};Dl.prototype.trigger=function(){var t=this;this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((function(){t._triggered=!1,t._callback();}),0));},Dl.prototype.remove=function(){delete this._channel,this._callback=function(){};};var Ol=function(t,e,r){this.target=t,this.parent=e,this.mapId=r,this.callbacks={},this.tasks={},this.taskQueue=[],this.cancelCallbacks={},d(["receive","process"],this),this.invoker=new Dl(this.process),this.target.addEventListener("message",this.receive,!1),this.globalScope=S()?t:self;};function Rl(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return [t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}Ol.prototype.send=function(t,e,r,n,i){var a=this;void 0===i&&(i=!1);var o=Math.round(1e18*Math.random()).toString(36).substring(0,10);r&&(this.callbacks[o]=r);var s=z(this.globalScope)?void 0:[];return this.target.postMessage({id:o,type:t,hasCallback:!!r,targetMapId:n,mustQueue:i,sourceMapId:this.mapId,data:Mn(e,s)},s),{cancel:function(){r&&delete a.callbacks[o],a.target.postMessage({id:o,type:"<cancel>",targetMapId:n,sourceMapId:a.mapId});}}},Ol.prototype.receive=function(t){var e=t.data,r=e.id;if(r&&(!e.targetMapId||this.mapId===e.targetMapId))if("<cancel>"===e.type){delete this.tasks[r];var n=this.cancelCallbacks[r];delete this.cancelCallbacks[r],n&&n();}else S()||e.mustQueue?(this.tasks[r]=e,this.taskQueue.push(r),this.invoker.trigger()):this.processTask(r,e);},Ol.prototype.process=function(){if(this.taskQueue.length){var t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length&&this.invoker.trigger(),e&&this.processTask(t,e);}},Ol.prototype.processTask=function(t,e){var r=this;if("<response>"===e.type){var n=this.callbacks[t];delete this.callbacks[t],n&&(e.error?n(Bn(e.error)):n(null,Bn(e.data)));}else{var i=!1,a=z(this.globalScope)?void 0:[],o=e.hasCallback?function(e,n){i=!0,delete r.cancelCallbacks[t],r.target.postMessage({id:t,type:"<response>",sourceMapId:r.mapId,error:e?Mn(e):null,data:Mn(n,a)},a);}:function(t){i=!0;},s=null,u=Bn(e.data);if(this.parent[e.type])s=this.parent[e.type](e.sourceMapId,u,o);else if(this.parent.getWorkerSource){var l=e.type.split(".");s=this.parent.getWorkerSource(e.sourceMapId,l[0],u.source)[l[1]](u,o);}else o(new Error("Could not find function "+e.type));!i&&s&&s.cancel&&(this.cancelCallbacks[t]=s.cancel);}},Ol.prototype.remove=function(){this.invoker.remove(),this.target.removeEventListener("message",this.receive,!1);};var Ul=function(t,e){t&&(e?this.setSouthWest(t).setNorthEast(e):4===t.length?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1]));};Ul.prototype.setNorthEast=function(t){return this._ne=t instanceof jl?new jl(t.lng,t.lat):jl.convert(t),this},Ul.prototype.setSouthWest=function(t){return this._sw=t instanceof jl?new jl(t.lng,t.lat):jl.convert(t),this},Ul.prototype.extend=function(t){var e,r,n=this._sw,i=this._ne;if(t instanceof jl)e=t,r=t;else{if(!(t instanceof Ul))return Array.isArray(t)?t.every(Array.isArray)?this.extend(Ul.convert(t)):this.extend(jl.convert(t)):this;if(e=t._sw,r=t._ne,!e||!r)return this}return n||i?(n.lng=Math.min(e.lng,n.lng),n.lat=Math.min(e.lat,n.lat),i.lng=Math.max(r.lng,i.lng),i.lat=Math.max(r.lat,i.lat)):(this._sw=new jl(e.lng,e.lat),this._ne=new jl(r.lng,r.lat)),this},Ul.prototype.getCenter=function(){return new jl((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)},Ul.prototype.getSouthWest=function(){return this._sw},Ul.prototype.getNorthEast=function(){return this._ne},Ul.prototype.getNorthWest=function(){return new jl(this.getWest(),this.getNorth())},Ul.prototype.getSouthEast=function(){return new jl(this.getEast(),this.getSouth())},Ul.prototype.getWest=function(){return this._sw.lng},Ul.prototype.getSouth=function(){return this._sw.lat},Ul.prototype.getEast=function(){return this._ne.lng},Ul.prototype.getNorth=function(){return this._ne.lat},Ul.prototype.toArray=function(){return [this._sw.toArray(),this._ne.toArray()]},Ul.prototype.toString=function(){return "LngLatBounds("+this._sw.toString()+", "+this._ne.toString()+")"},Ul.prototype.isEmpty=function(){return !(this._sw&&this._ne)},Ul.prototype.contains=function(t){var e=jl.convert(t),r=e.lng,n=e.lat,i=this._sw.lat<=n&&n<=this._ne.lat,a=this._sw.lng<=r&&r<=this._ne.lng;return this._sw.lng>this._ne.lng&&(a=this._sw.lng>=r&&r>=this._ne.lng),i&&a},Ul.convert=function(t){return !t||t instanceof Ul?t:new Ul(t)};var jl=function(t,e){if(isNaN(t)||isNaN(e))throw new Error("Invalid LngLat object: ("+t+", "+e+")");if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")};jl.prototype.wrap=function(){return new jl(l(this.lng,-180,180),this.lat)},jl.prototype.toArray=function(){return [this.lng,this.lat]},jl.prototype.toString=function(){return "LngLat("+this.lng+", "+this.lat+")"},jl.prototype.distanceTo=function(t){var e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return 6371008.8*Math.acos(Math.min(i,1))},jl.prototype.toBounds=function(t){void 0===t&&(t=0);var e=360*t/40075017,r=e/Math.cos(Math.PI/180*this.lat);return new Ul(new jl(this.lng-r,this.lat-e),new jl(this.lng+r,this.lat+e))},jl.convert=function(t){if(t instanceof jl)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new jl(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new jl(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, an object {lon: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]")};var ql=2*Math.PI*6371008.8;function Nl(t){return ql*Math.cos(t*Math.PI/180)}function Kl(t){return (180+t)/360}function Xl(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function Zl(t,e){return t/Nl(e)}function Gl(t){var e=180-360*t;return 360/Math.PI*Math.atan(Math.exp(e*Math.PI/180))-90}var Jl=function(t,e,r){void 0===r&&(r=0),this.x=+t,this.y=+e,this.z=+r;};Jl.fromLngLat=function(t,e){void 0===e&&(e=0);var r=jl.convert(t);return new Jl(Kl(r.lng),Xl(r.lat),Zl(e,r.lat))},Jl.prototype.toLngLat=function(){return new jl(360*this.x-180,Gl(this.y))},Jl.prototype.toAltitude=function(){return t=this.z,e=this.y,t*Nl(Gl(e));var t,e;},Jl.prototype.meterInMercatorCoordinateUnits=function(){return 1/ql*(t=Gl(this.y),1/Math.cos(t*Math.PI/180));var t;};var Yl=function(t,e,r){this.z=t,this.x=e,this.y=r,this.key=Wl(0,t,t,e,r);};Yl.prototype.equals=function(t){return this.z===t.z&&this.x===t.x&&this.y===t.y},Yl.prototype.url=function(t,e){var r,n,i,a,o,s=(r=this.x,n=this.y,i=this.z,a=Rl(256*r,256*(n=Math.pow(2,i)-n-1),i),o=Rl(256*(r+1),256*(n+1),i),a[0]+","+a[1]+","+o[0]+","+o[1]),u=function(t,e,r){for(var n,i="",a=t;a>0;a--)i+=(e&(n=1<<a-1)?1:0)+(r&n?2:0);return i}(this.z,this.x,this.y);return t[(this.x+this.y)%t.length].replace("{prefix}",(this.x%16).toString(16)+(this.y%16).toString(16)).replace("{z}",String(this.z)).replace("{x}",String(this.x)).replace("{y}",String("tms"===e?Math.pow(2,this.z)-this.y-1:this.y)).replace("{quadkey}",u).replace("{bbox-epsg-3395}",s)},Yl.prototype.getTilePoint=function(t){var e=Math.pow(2,this.z);return new i((t.x*e-this.x)*Ma,(t.y*e-this.y)*Ma)},Yl.prototype.toString=function(){return this.z+"/"+this.x+"/"+this.y};var Hl=function(t,e){this.wrap=t,this.canonical=e,this.key=Wl(t,e.z,e.z,e.x,e.y);},$l=function(t,e,r,n,i){this.overscaledZ=t,this.wrap=e,this.canonical=new Yl(r,+n,+i),this.key=Wl(e,t,r,n,i);};function Wl(t,e,r,n,i){(t*=2)<0&&(t=-1*t-1);var a=1<<r;return (a*a*t+a*i+n).toString(36)+r.toString(36)+e.toString(36)}$l.prototype.equals=function(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)},$l.prototype.scaledTo=function(t){var e=this.canonical.z-t;return t>this.canonical.z?new $l(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new $l(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)},$l.prototype.calculateScaledKey=function(t,e){var r=this.canonical.z-t;return t>this.canonical.z?Wl(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Wl(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)},$l.prototype.isChildOf=function(t){if(t.wrap!==this.wrap)return !1;var e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ<this.overscaledZ&&t.canonical.x===this.canonical.x>>e&&t.canonical.y===this.canonical.y>>e},$l.prototype.children=function(t){if(this.overscaledZ>=t)return [new $l(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];var e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new $l(e,this.wrap,e,r,n),new $l(e,this.wrap,e,r+1,n),new $l(e,this.wrap,e,r,n+1),new $l(e,this.wrap,e,r+1,n+1)]},$l.prototype.isLessThan=function(t){return this.wrap<t.wrap||!(this.wrap>t.wrap)&&(this.overscaledZ<t.overscaledZ||!(this.overscaledZ>t.overscaledZ)&&(this.canonical.x<t.canonical.x||!(this.canonical.x>t.canonical.x)&&this.canonical.y<t.canonical.y))},$l.prototype.wrapped=function(){return new $l(this.overscaledZ,0,this.canonical.z,this.canonical.x,this.canonical.y)},$l.prototype.unwrapTo=function(t){return new $l(this.overscaledZ,t,this.canonical.z,this.canonical.x,this.canonical.y)},$l.prototype.overscaleFactor=function(){return Math.pow(2,this.overscaledZ-this.canonical.z)},$l.prototype.toUnwrapped=function(){return new Hl(this.wrap,this.canonical)},$l.prototype.toString=function(){return this.overscaledZ+"/"+this.canonical.x+"/"+this.canonical.y},$l.prototype.getTilePoint=function(t){return this.canonical.getTilePoint(new Jl(t.x-this.wrap,t.y))},zn("CanonicalTileID",Yl),zn("OverscaledTileID",$l,{omit:["posMatrix"]});var Ql=function(t,e,r){if(this.uid=t,e.height!==e.width)throw new RangeError("DEM tiles must be square");if(r&&"mapbox"!==r&&"terrarium"!==r)return _('"'+r+'" is not a valid encoding type. Valid types include "mapbox" and "terrarium".');this.stride=e.height;var n=this.dim=e.height-2;this.data=new Uint32Array(e.data.buffer),this.encoding=r||"mapbox";for(var i=0;i<n;i++)this.data[this._idx(-1,i)]=this.data[this._idx(0,i)],this.data[this._idx(n,i)]=this.data[this._idx(n-1,i)],this.data[this._idx(i,-1)]=this.data[this._idx(i,0)],this.data[this._idx(i,n)]=this.data[this._idx(i,n-1)];this.data[this._idx(-1,-1)]=this.data[this._idx(0,0)],this.data[this._idx(n,-1)]=this.data[this._idx(n-1,0)],this.data[this._idx(-1,n)]=this.data[this._idx(0,n-1)],this.data[this._idx(n,n)]=this.data[this._idx(n-1,n-1)];};Ql.prototype.get=function(t,e){var r=new Uint8Array(this.data.buffer),n=4*this._idx(t,e);return ("terrarium"===this.encoding?this._unpackTerrarium:this._unpackMapbox)(r[n],r[n+1],r[n+2])},Ql.prototype.getUnpackVector=function(){return "terrarium"===this.encoding?[256,1,1/256,32768]:[6553.6,25.6,.1,1e4]},Ql.prototype._idx=function(t,e){if(t<-1||t>=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)},Ql.prototype._unpackMapbox=function(t,e,r){return (256*t*256+256*e+r)/10-1e4},Ql.prototype._unpackTerrarium=function(t,e,r){return 256*t+e+r/256-32768},Ql.prototype.getPixels=function(){return new ho({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))},Ql.prototype.backfillBorder=function(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");var n=e*this.dim,i=e*this.dim+this.dim,a=r*this.dim,o=r*this.dim+this.dim;switch(e){case-1:n=i-1;break;case 1:i=n+1;}switch(r){case-1:a=o-1;break;case 1:o=a+1;}for(var s=-e*this.dim,u=-r*this.dim,l=a;l<o;l++)for(var p=n;p<i;p++)this.data[this._idx(p,l)]=t.data[this._idx(p+s,l+u)];},zn("DEMData",Ql);var tp=function(t){this._stringToNumber={},this._numberToString=[];for(var e=0;e<t.length;e++){var r=t[e];this._stringToNumber[r]=e,this._numberToString[e]=r;}};tp.prototype.encode=function(t){return this._stringToNumber[t]},tp.prototype.decode=function(t){return this._numberToString[t]};var ep=function(t,e,r,n,i){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,this.id=i;},rp={geometry:{configurable:!0}};rp.geometry.get=function(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry},rp.geometry.set=function(t){this._geometry=t;},ep.prototype.toJSON=function(){var t={geometry:this.geometry};for(var e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t},Object.defineProperties(ep.prototype,rp);var np=function(){this.state={},this.stateChanges={},this.deletedStates={};};np.prototype.updateState=function(t,e,r){var n=String(e);if(this.stateChanges[t]=this.stateChanges[t]||{},this.stateChanges[t][n]=this.stateChanges[t][n]||{},p(this.stateChanges[t][n],r),null===this.deletedStates[t])for(var i in this.deletedStates[t]={},this.state[t])i!==n&&(this.deletedStates[t][i]=null);else if(this.deletedStates[t]&&null===this.deletedStates[t][n])for(var a in this.deletedStates[t][n]={},this.state[t][n])r[a]||(this.deletedStates[t][n][a]=null);else for(var o in r){this.deletedStates[t]&&this.deletedStates[t][n]&&null===this.deletedStates[t][n][o]&&delete this.deletedStates[t][n][o];}},np.prototype.removeFeatureState=function(t,e,r){if(!(null===this.deletedStates[t])){var n=String(e);if(this.deletedStates[t]=this.deletedStates[t]||{},r&&void 0!==e)null!==this.deletedStates[t][n]&&(this.deletedStates[t][n]=this.deletedStates[t][n]||{},this.deletedStates[t][n][r]=null);else if(void 0!==e){if(this.stateChanges[t]&&this.stateChanges[t][n])for(r in this.deletedStates[t][n]={},this.stateChanges[t][n])this.deletedStates[t][n][r]=null;else this.deletedStates[t][n]=null;}else this.deletedStates[t]=null;}},np.prototype.getState=function(t,e){var r=String(e),n=this.state[t]||{},i=this.stateChanges[t]||{},a=p({},n[r],i[r]);if(null===this.deletedStates[t])return {};if(this.deletedStates[t]){var o=this.deletedStates[t][e];if(null===o)return {};for(var s in o)delete a[s];}return a},np.prototype.initializeTileState=function(t,e){t.setFeatureState(this.state,e);},np.prototype.coalesceChanges=function(t,e){var r={};for(var n in this.stateChanges){this.state[n]=this.state[n]||{};var i={};for(var a in this.stateChanges[n])this.state[n][a]||(this.state[n][a]={}),p(this.state[n][a],this.stateChanges[n][a]),i[a]=this.state[n][a];r[n]=i;}for(var o in this.deletedStates){this.state[o]=this.state[o]||{};var s={};if(null===this.deletedStates[o])for(var u in this.state[o])s[u]={},this.state[o][u]={};else for(var l in this.deletedStates[o]){if(null===this.deletedStates[o][l])this.state[o][l]={};else for(var c=0,h=Object.keys(this.deletedStates[o][l]);c<h.length;c+=1){var f=h[c];delete this.state[o][l][f];}s[l]=this.state[o][l];}r[o]=r[o]||{},p(r[o],s);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(r).length)for(var y in t){t[y].setFeatureState(r,e);}};var ip=function(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new _n(Ma,16,0),this.grid3D=new _n(Ma,16,0),this.featureIndexArray=new Qi,this.promoteId=e;};function ap(t){for(var e=1/0,r=1/0,n=-1/0,i=-1/0,a=0,o=t;a<o.length;a+=1){var s=o[a];e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);}return {minX:e,minY:r,maxX:n,maxY:i}}function op(t,e){return e-t}ip.prototype.insert=function(t,e,r,n,i,a){var o=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);for(var s=a?this.grid3D:this.grid,u=0;u<e.length;u++){for(var l=e[u],p=[1/0,1/0,-1/0,-1/0],c=0;c<l.length;c++){var h=l[c];p[0]=Math.min(p[0],h.x),p[1]=Math.min(p[1],h.y),p[2]=Math.max(p[2],h.x),p[3]=Math.max(p[3],h.y);}p[0]<Ma&&p[1]<Ma&&p[2]>=0&&p[3]>=0&&s.insert(o,p[0],p[1],p[2],p[3]);}},ip.prototype.loadVTLayers=function(){return this.vtLayers||(this.vtLayers=new ys.VectorTile(new Xs(this.rawTileData)).layers,this.sourceLayerCoder=new tp(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers},ip.prototype.query=function(t,e,r){var n=this;this.loadVTLayers();for(var a=t.params||{},o=Ma/t.tileSize/t.scale,s=Gr(a.filter),u=t.queryGeometry,l=t.queryPadding*o,p=ap(u),c=this.grid.query(p.minX-l,p.minY-l,p.maxX+l,p.maxY+l),h=ap(t.cameraQueryGeometry),f=this.grid3D.query(h.minX-l,h.minY-l,h.maxX+l,h.maxY+l,(function(e,r,n,a){return function(t,e,r,n,a){for(var o=0,s=t;o<s.length;o+=1){var u=s[o];if(e<=u.x&&r<=u.y&&n>=u.x&&a>=u.y)return !0}var l=[new i(e,r),new i(e,a),new i(n,a),new i(n,r)];if(t.length>2)for(var p=0,c=l;p<c.length;p+=1){if(Za(t,c[p]))return !0}for(var h=0;h<t.length-1;h++){if(Ga(t[h],t[h+1],l))return !0}return !1}(t.cameraQueryGeometry,e-l,r-l,n+l,a+l)})),y=0,d=f;y<d.length;y+=1){var m=d[y];c.push(m);}c.sort(op);for(var v,g={},x=function(i){var l=c[i];if(l!==v){v=l;var p=n.featureIndexArray.get(l),h=null;n.loadMatchingFeature(g,p.bucketIndex,p.sourceLayerIndex,p.featureIndex,s,a.layers,e,(function(e,i,a){h||(h=Va(e));var s={};return void 0!==a&&(s=r.getState(i.sourceLayer||"_geojsonTileLayer",a)),i.queryIntersectsFeature(u,e,s,h,n.z,t.transform,o,t.pixelPosMatrix)}));}},b=0;b<c.length;b++)x(b);return g},ip.prototype.loadMatchingFeature=function(t,e,r,n,i,a,o,s){var u=this.bucketLayerIDs[e];if(!a||function(t,e){for(var r=0;r<t.length;r++)if(e.indexOf(t[r])>=0)return !0;return !1}(a,u)){var l=this.sourceLayerCoder.decode(r),p=this.vtLayers[l].feature(n);if(i(new ti(this.tileID.overscaledZ),p))for(var c=this.getId(p,l),h=0;h<u.length;h++){var f=u[h];if(!(a&&a.indexOf(f)<0)){var y=o[f];if(y){var d=!s||s(p,y,c);if(d){var m=new ep(p,this.z,this.x,this.y,c);m.layer=y.serialize();var v=t[f];void 0===v&&(v=t[f]=[]),v.push({featureIndex:n,feature:m,intersectionZ:d});}}}}}},ip.prototype.lookupSymbolFeatures=function(t,e,r,n,i,a){var o={};this.loadVTLayers();for(var s=Gr(n),u=0,l=t;u<l.length;u+=1){var p=l[u];this.loadMatchingFeature(o,e,r,p,s,i,a);}return o},ip.prototype.hasLayer=function(t){for(var e=0,r=this.bucketLayerIDs;e<r.length;e+=1)for(var n=0,i=r[e];n<i.length;n+=1){if(t===i[n])return !0}return !1},ip.prototype.getId=function(t,e){var r=t.id;if(this.promoteId){var n="string"==typeof this.promoteId?this.promoteId:this.promoteId[e];"boolean"==typeof(r=t.properties[n])&&(r=Number(r));}return r},zn("FeatureIndex",ip,{omit:["rawTileData","sourceLayerCoder"]});var sp=function(t,e){this.tileID=t,this.uid=h(),this.uses=0,this.tileSize=e,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.expiredRequestCount=0,this.state="loading";};sp.prototype.registerFadeDuration=function(t){var e=t+this.timeAdded;e<L.now()||this.fadeEndTime&&e<this.fadeEndTime||(this.fadeEndTime=e);},sp.prototype.wasRequested=function(){return "errored"===this.state||"loaded"===this.state||"reloading"===this.state},sp.prototype.loadVectorData=function(t,e,r){if(this.hasData()&&this.unloadVectorData(),this.state="loaded",t){for(var n in t.featureIndex&&(this.latestFeatureIndex=t.featureIndex,t.rawTileData?(this.latestRawTileData=t.rawTileData,this.latestFeatureIndex.rawTileData=t.rawTileData):this.latestRawTileData&&(this.latestFeatureIndex.rawTileData=this.latestRawTileData)),this.collisionBoxArray=t.collisionBoxArray,this.buckets=function(t,e){var r={};if(!e)return r;for(var n=function(){var t=a[i],n=t.layerIds.map((function(t){return e.getLayer(t)})).filter(Boolean);if(0!==n.length){t.layers=n,t.stateDependentLayerIds&&(t.stateDependentLayers=t.stateDependentLayerIds.map((function(t){return n.filter((function(e){return e.id===t}))[0]})));for(var o=0,s=n;o<s.length;o+=1){var u=s[o];r[u.id]=t;}}},i=0,a=t;i<a.length;i+=1)n();return r}(t.buckets,e.style),this.hasSymbolBuckets=!1,this.buckets){var i=this.buckets[n];if(i instanceof bl){if(this.hasSymbolBuckets=!0,!r)break;i.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(var a in this.buckets){var o=this.buckets[a];if(o instanceof bl&&o.hasRTLText){this.hasRTLText=!0,Qn.isLoading()||Qn.isLoaded()||"deferred"!==$n()||Wn();break}}for(var s in this.queryPadding=0,this.buckets){var u=this.buckets[s];this.queryPadding=Math.max(this.queryPadding,e.style.getLayer(s).queryRadius(u));}t.imageAtlas&&(this.imageAtlas=t.imageAtlas),t.glyphAtlasImage&&(this.glyphAtlasImage=t.glyphAtlasImage);}else this.collisionBoxArray=new Ni;},sp.prototype.unloadVectorData=function(){for(var t in this.buckets)this.buckets[t].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";},sp.prototype.getBucket=function(t){return this.buckets[t.id]},sp.prototype.upload=function(t){for(var e in this.buckets){var r=this.buckets[e];r.uploadPending()&&r.upload(t);}var n=t.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new Ll(t,this.imageAtlas.image,n.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new Ll(t,this.glyphAtlasImage,n.ALPHA),this.glyphAtlasImage=null);},sp.prototype.prepare=function(t){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(t,this.imageAtlasTexture);},sp.prototype.queryRenderedFeatures=function(t,e,r,n,i,a,o,s,u){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:r,cameraQueryGeometry:n,scale:i,tileSize:this.tileSize,pixelPosMatrix:u,transform:o,params:a,queryPadding:this.queryPadding*s},t,e):{}},sp.prototype.querySourceFeatures=function(t,e){var r=this.latestFeatureIndex;if(r&&r.rawTileData){var n=r.loadVTLayers(),i=e?e.sourceLayer:"",a=n._geojsonTileLayer||n[i];if(a)for(var o=Gr(e&&e.filter),s=this.tileID.canonical,u=s.z,l=s.x,p=s.y,c={z:u,x:l,y:p},h=0;h<a.length;h++){var f=a.feature(h);if(o(new ti(this.tileID.overscaledZ),f)){var y=r.getId(f,i),d=new ep(f,u,l,p,y);d.tile=c,t.push(d);}}}},sp.prototype.hasData=function(){return "loaded"===this.state||"reloading"===this.state||"expired"===this.state},sp.prototype.patternsLoaded=function(){return this.imageAtlas&&!!Object.keys(this.imageAtlas.patternPositions).length},sp.prototype.setExpiryData=function(t){var e=this.expirationTime;if(t.cacheControl){var r=k(t.cacheControl);r["max-age"]&&(this.expirationTime=Date.now()+1e3*r["max-age"]);}else t.expires&&(this.expirationTime=new Date(t.expires).getTime());if(this.expirationTime){var n=Date.now(),i=!1;if(this.expirationTime>n)i=!1;else if(e)if(this.expirationTime<e)i=!0;else{var a=this.expirationTime-e;a?this.expirationTime=n+Math.max(a,3e4):i=!0;}else i=!0;i?(this.expiredRequestCount++,this.state="expired"):this.expiredRequestCount=0;}},sp.prototype.getExpiryTimeout=function(){if(this.expirationTime)return this.expiredRequestCount?1e3*(1<<Math.min(this.expiredRequestCount-1,31)):Math.min(this.expirationTime-(new Date).getTime(),Math.pow(2,31)-1)},sp.prototype.setFeatureState=function(t,e){if(this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData&&0!==Object.keys(t).length){var r=this.latestFeatureIndex.loadVTLayers();for(var n in this.buckets){var i=this.buckets[n],a=i.layers[0].sourceLayer||"_geojsonTileLayer",o=r[a],s=t[a];o&&s&&0!==Object.keys(s).length&&(i.update(s,o,this.imageAtlas&&this.imageAtlas.patternPositions||{}),e&&e.style&&(this.queryPadding=Math.max(this.queryPadding,e.style.getLayer(n).queryRadius(i))));}}},sp.prototype.holdingForFade=function(){return void 0!==this.symbolFadeHoldUntil},sp.prototype.symbolFadeFinished=function(){return !this.symbolFadeHoldUntil||this.symbolFadeHoldUntil<L.now()},sp.prototype.clearFadeHold=function(){this.symbolFadeHoldUntil=void 0;},sp.prototype.setHoldDuration=function(t){this.symbolFadeHoldUntil=L.now()+t;},sp.prototype.setDependencies=function(t,e){for(var r={},n=0,i=e;n<i.length;n+=1){r[i[n]]=!0;}this.dependencies[t]=r;},sp.prototype.hasDependency=function(t,e){for(var r=0,n=t;r<n.length;r+=1){var i=n[r],a=this.dependencies[i];if(a)for(var o=0,s=e;o<s.length;o+=1){if(a[s[o]])return !0}}return !1};var up=self.performance,lp=function(t){this._marks={start:[t.url,"start"].join("#"),end:[t.url,"end"].join("#"),measure:t.url.toString()},up.mark(this._marks.start);};lp.prototype.finish=function(){up.mark(this._marks.end);var t=up.getEntriesByName(this._marks.measure);return 0===t.length&&(up.measure(this._marks.measure,this._marks.start,this._marks.end),t=up.getEntriesByName(this._marks.measure),up.clearMarks(this._marks.start),up.clearMarks(this._marks.end),up.clearMeasures(this._marks.measure)),t},t.Actor=Ol,t.AlphaImage=co,t.CanonicalTileID=Yl,t.CollisionBoxArray=Ni,t.Color=ee,t.DEMData=Ql,t.DataConstantProperty=li,t.DictionaryCoder=tp,t.EXTENT=Ma,t.ErrorEvent=Et,t.EvaluationParameters=ti,t.Event=Tt,t.Evented=Mt,t.FeatureIndex=ip,t.FillBucket=es,t.FillExtrusionBucket=gs,t.ImageAtlas=gu,t.ImagePosition=mu,t.LineBucket=Ts,t.LngLat=jl,t.LngLatBounds=Ul,t.MercatorCoordinate=Jl,t.ONE_EM=qs,t.OverscaledTileID=$l,t.Point=i,t.Point$1=i,t.Properties=yi,t.Protobuf=Xs,t.RGBAImage=ho,t.RequestManager=N,t.RequestPerformance=lp,t.ResourceType=mt,t.SegmentVector=ea,t.SourceFeatureState=np,t.StructArrayLayout1ui2=Ri,t.StructArrayLayout2i4=_i,t.StructArrayLayout2ui4=Oi,t.StructArrayLayout3ui6=Di,t.StructArrayLayout4i8=wi,t.SymbolBucket=bl,t.Texture=Ll,t.Tile=sp,t.Transitionable=ni,t.Uniform1f=ya,t.Uniform1i=fa,t.Uniform2f=da,t.Uniform3f=ma,t.Uniform4f=va,t.UniformColor=ga,t.UniformMatrix4f=ba,t.UnwrappedTileID=Hl,t.ValidationError=Pt,t.WritingMode=xu,t.ZoomHistory=Pn,t.add=function(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t},t.addDynamicAttributes=ml,t.asyncAll=function(t,e,r){if(!t.length)return r(null,[]);var n=t.length,i=new Array(t.length),a=null;t.forEach((function(t,o){e(t,(function(t,e){t&&(a=t),i[o]=e,0==--n&&r(a,i);}));}));},t.bezier=o,t.bindAll=d,t.browser=L,t.cacheEntryPossiblyAdded=function(t){++yt>st&&(t.getActor().send("enforceCacheSizeLimit",ot),yt=0);},t.clamp=u,t.clearTileCache=function(t){var e=self.caches.delete(at);t&&e.catch(t).then((function(){return t()}));},t.clone=function(t){var e=new Qa(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.clone$1=x,t.clone$2=function(t){var e=new Qa(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},t.config=D,t.create=function(){var t=new Qa(16);return Qa!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.create$1=function(){var t=new Qa(9);return Qa!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1,t},t.create$2=function(){var t=new Qa(4);return Qa!=Float32Array&&(t[1]=0,t[2]=0),t[0]=1,t[3]=1,t},t.createCommonjsModule=e,t.createExpression=Vr,t.createLayout=xi,t.createStyleLayer=function(t){return "custom"===t.type?new Tl(t):new El[t.type](t)},t.cross=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],u=r[2];return t[0]=i*u-a*s,t[1]=a*o-n*u,t[2]=n*s-i*o,t},t.deepEqual=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return !1;for(var n=0;n<e.length;n++)if(!t(e[n],r[n]))return !1;return !0}if("object"==typeof e&&null!==e&&null!==r){if("object"!=typeof r)return !1;if(Object.keys(e).length!==Object.keys(r).length)return !1;for(var i in e)if(!t(e[i],r[i]))return !1;return !0}return e===r},t.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]},t.dot$1=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]},t.ease=s,t.emitValidationErrors=bn,t.endsWith=m,t.enforceCacheSizeLimit=function(t){lt(),W&&W.then((function(e){e.keys().then((function(r){for(var n=0;n<r.length-t;n++)e.delete(r[n]);}));}));},t.evaluateSizeForFeature=Du,t.evaluateSizeForZoom=Ou,t.evaluateVariableOffset=ol,t.evented=Hn,t.extend=p,t.featureFilter=Gr,t.filterObject=g,t.fromRotation=function(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=0,t[3]=-r,t[4]=n,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t},t.getAnchorAlignment=Mu,t.getAnchorJustification=sl,t.getArrayBuffer=_t,t.getImage=It,t.getJSON=function(t,e){return bt(p(t,{type:"json"}),e)},t.getRTLTextPluginStatus=$n,t.getReferrer=gt,t.getVideo=function(t,e){var r,n,i=self.document.createElement("video");i.muted=!0,i.onloadstart=function(){e(null,i);};for(var a=0;a<t.length;a++){var o=self.document.createElement("source");r=t[a],n=void 0,(n=self.document.createElement("a")).href=r,(n.protocol!==self.document.location.protocol||n.host!==self.document.location.host)&&(i.crossOrigin="Anonymous"),o.src=t[a],i.appendChild(o);}return {cancel:function(){}}},t.identity=function(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},t.invert=function(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],u=e[6],l=e[7],p=e[8],c=e[9],h=e[10],f=e[11],y=e[12],d=e[13],m=e[14],v=e[15],g=r*s-n*o,x=r*u-i*o,b=r*l-a*o,_=n*u-i*s,w=n*l-a*s,A=i*l-a*u,S=p*d-c*y,k=p*m-h*y,I=p*v-f*y,z=c*m-h*d,C=c*v-f*d,T=h*v-f*m,E=g*T-x*C+b*z+_*I-w*k+A*S;return E?(E=1/E,t[0]=(s*T-u*C+l*z)*E,t[1]=(i*C-n*T-a*z)*E,t[2]=(d*A-m*w+v*_)*E,t[3]=(h*w-c*A-f*_)*E,t[4]=(u*I-o*T-l*k)*E,t[5]=(r*T-i*I+a*k)*E,t[6]=(m*b-y*A-v*x)*E,t[7]=(p*A-h*b+f*x)*E,t[8]=(o*C-s*I+l*S)*E,t[9]=(n*I-r*C-a*S)*E,t[10]=(y*w-d*b+v*g)*E,t[11]=(c*b-p*w-f*g)*E,t[12]=(s*k-o*z-u*S)*E,t[13]=(r*z-n*k+i*S)*E,t[14]=(d*x-y*_-m*g)*E,t[15]=(p*_-c*x+h*g)*E,t):null},t.isChar=Vn,t.isMapboxURL=K,t.keysDifference=function(t,e){var r=[];for(var n in t)n in e||r.push(n);return r},t.makeRequest=bt,t.mapObject=v,t.mercatorXfromLng=Kl,t.mercatorYfromLat=Xl,t.mercatorZfromAltitude=Zl,t.multiply=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],u=e[5],l=e[6],p=e[7],c=e[8],h=e[9],f=e[10],y=e[11],d=e[12],m=e[13],v=e[14],g=e[15],x=r[0],b=r[1],_=r[2],w=r[3];return t[0]=x*n+b*s+_*c+w*d,t[1]=x*i+b*u+_*h+w*m,t[2]=x*a+b*l+_*f+w*v,t[3]=x*o+b*p+_*y+w*g,x=r[4],b=r[5],_=r[6],w=r[7],t[4]=x*n+b*s+_*c+w*d,t[5]=x*i+b*u+_*h+w*m,t[6]=x*a+b*l+_*f+w*v,t[7]=x*o+b*p+_*y+w*g,x=r[8],b=r[9],_=r[10],w=r[11],t[8]=x*n+b*s+_*c+w*d,t[9]=x*i+b*u+_*h+w*m,t[10]=x*a+b*l+_*f+w*v,t[11]=x*o+b*p+_*y+w*g,x=r[12],b=r[13],_=r[14],w=r[15],t[12]=x*n+b*s+_*c+w*d,t[13]=x*i+b*u+_*h+w*m,t[14]=x*a+b*l+_*f+w*v,t[15]=x*o+b*p+_*y+w*g,t},t.mvt=ys,t.normalize=function(t,e){var r=e[0],n=e[1],i=e[2],a=r*r+n*n+i*i;return a>0&&(a=1/Math.sqrt(a)),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a,t},t.number=Ce,t.offscreenCanvasSupported=dt,t.ortho=function(t,e,r,n,i,a,o){var s=1/(e-r),u=1/(n-i),l=1/(a-o);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*u,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*u,t[14]=(o+a)*l,t[15]=1,t},t.parseGlyphPBF=function(t){return new Xs(t).readFields(pu,[])},t.pbf=Xs,t.performSymbolLayout=function(t,e,r,n,a,o){t.createArrays();var s=512*t.overscaling;t.tilePixelRatio=Ma/s,t.compareText={},t.iconsNeedLinear=!1;var u=t.layers[0].layout,l=t.layers[0]._unevaluatedLayout._values,p={};if("composite"===t.textSizeData.kind){var c=t.textSizeData,h=c.minZoom,f=c.maxZoom;p.compositeTextSizes=[l["text-size"].possiblyEvaluate(new ti(h)),l["text-size"].possiblyEvaluate(new ti(f))];}if("composite"===t.iconSizeData.kind){var y=t.iconSizeData,d=y.minZoom,m=y.maxZoom;p.compositeIconSizes=[l["icon-size"].possiblyEvaluate(new ti(d)),l["icon-size"].possiblyEvaluate(new ti(m))];}p.layoutTextSize=l["text-size"].possiblyEvaluate(new ti(t.zoom+1)),p.layoutIconSize=l["icon-size"].possiblyEvaluate(new ti(t.zoom+1)),p.textMaxSize=l["text-size"].possiblyEvaluate(new ti(18));for(var v=u.get("text-line-height")*qs,g="map"===u.get("text-rotation-alignment")&&"point"!==u.get("symbol-placement"),x=u.get("text-keep-upright"),b=u.get("text-size"),w=function(){var o=S[A],s=u.get("text-font").evaluate(o,{}).join(","),l=b.evaluate(o,{}),c=p.layoutTextSize.evaluate(o,{}),h=p.layoutIconSize.evaluate(o,{}),f={horizontal:{},vertical:void 0},y=o.text,d=[0,0];if(y){var m=y.toString(),w=u.get("text-letter-spacing").evaluate(o,{})*qs,k=function(t){for(var e=0,r=t;e<r.length;e+=1){if(!Ln(r[e].charCodeAt(0)))return !1}return !0}(m)?w:0,I=u.get("text-anchor").evaluate(o,{}),z=u.get("text-variable-anchor");if(!z){var C=u.get("text-radial-offset").evaluate(o,{});d=C?ol(I,[C*qs,al]):u.get("text-offset").evaluate(o,{}).map((function(t){return t*qs}));}var T=g?"center":u.get("text-justify").evaluate(o,{}),E=u.get("symbol-placement"),M="point"===E?u.get("text-max-width").evaluate(o,{})*qs:0,B=function(){t.allowVerticalPlacement&&Fn(m)&&(f.vertical=Au(y,e,r,a,s,M,v,I,"left",k,d,xu.vertical,!0,E,c,l));};if(!g&&z){for(var P="auto"===T?z.map((function(t){return sl(t)})):[T],V=!1,F=0;F<P.length;F++){var L=P[F];if(!f.horizontal[L])if(V)f.horizontal[L]=f.horizontal[0];else{var D=Au(y,e,r,a,s,M,v,"center",L,k,d,xu.horizontal,!1,E,c,l);D&&(f.horizontal[L]=D,V=1===D.positionedLines.length);}}B();}else{"auto"===T&&(T=sl(I));var O=Au(y,e,r,a,s,M,v,I,T,k,d,xu.horizontal,!1,E,c,l);O&&(f.horizontal[T]=O),B(),Fn(m)&&g&&x&&(f.vertical=Au(y,e,r,a,s,M,v,I,T,k,d,xu.vertical,!1,E,c,l));}}var R=void 0,U=!1;if(o.icon&&o.icon.name){var j=n[o.icon.name];j&&(R=function(t,e,r){var n=Mu(r),i=n.horizontalAlign,a=n.verticalAlign,o=e[0],s=e[1],u=o-t.displaySize[0]*i,l=u+t.displaySize[0],p=s-t.displaySize[1]*a;return {image:t,top:p,bottom:p+t.displaySize[1],left:u,right:l}}(a[o.icon.name],u.get("icon-offset").evaluate(o,{}),u.get("icon-anchor").evaluate(o,{})),U=j.sdf,void 0===t.sdfIcons?t.sdfIcons=j.sdf:t.sdfIcons!==j.sdf&&_("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),j.pixelRatio!==t.pixelRatio?t.iconsNeedLinear=!0:0!==u.get("icon-rotate").constantOr(1)&&(t.iconsNeedLinear=!0));}var q=cl(f.horizontal)||f.vertical;t.iconsInText=!!q&&q.iconsInText,(q||R)&&function(t,e,r,n,a,o,s,u,l,p){var c=o.textMaxSize.evaluate(e,{});void 0===c&&(c=s);var h,f=t.layers[0].layout,y=f.get("icon-offset").evaluate(e,{}),d=cl(r.horizontal),m=s/24,v=t.tilePixelRatio*m,g=t.tilePixelRatio*c/24,x=t.tilePixelRatio*u,b=t.tilePixelRatio*f.get("symbol-spacing"),w=f.get("text-padding")*t.tilePixelRatio,A=f.get("icon-padding")*t.tilePixelRatio,S=f.get("text-max-angle")/180*Math.PI,k="map"===f.get("text-rotation-alignment")&&"point"!==f.get("symbol-placement"),I="map"===f.get("icon-rotation-alignment")&&"point"!==f.get("symbol-placement"),z=f.get("symbol-placement"),C=b/2,T=f.get("icon-text-fit");n&&"none"!==T&&(t.allowVerticalPlacement&&r.vertical&&(h=Pu(n,r.vertical,T,f.get("icon-text-fit-padding"),y,m)),d&&(n=Pu(n,d,T,f.get("icon-text-fit-padding"),y,m)));var E=function(i,s){s.x<0||s.x>=Ma||s.y<0||s.y>=Ma||function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,w,A){var S,k,I,z,C,T=t.addToLineVertexArray(e,r),E=0,M=0,B=0,P=0,V=-1,F=-1,L={},D=aa(""),O=0,R=0;void 0===s._unevaluatedLayout.getValue("text-radial-offset")?(S=s.layout.get("text-offset").evaluate(b,{}).map((function(t){return t*qs})),O=S[0],R=S[1]):(O=s.layout.get("text-radial-offset").evaluate(b,{})*qs,R=al);if(t.allowVerticalPlacement&&n.vertical){var U=s.layout.get("text-rotate").evaluate(b,{})+90,j=n.vertical;z=new Wu(u,r,e,l,p,c,j,h,f,y,t.overscaling,U),o&&(C=new Wu(u,r,e,l,p,c,o,m,v,y,t.overscaling,U));}if(i){var q=s.layout.get("icon-rotate").evaluate(b,{}),N="none"!==s.layout.get("icon-text-fit"),K=Gu(i,q,A,N),X=o?Gu(o,q,A,N):void 0;I=new Wu(u,r,e,l,p,c,i,m,v,!1,t.overscaling,q),E=4*K.length;var Z=t.iconSizeData,G=null;"source"===Z.kind?(G=[Fu*s.layout.get("icon-size").evaluate(b,{})])[0]>ll&&_(t.layerIds[0]+': Value for "icon-size" is >= '+ul+'. Reduce your "icon-size".'):"composite"===Z.kind&&((G=[Fu*w.compositeIconSizes[0].evaluate(b,{}),Fu*w.compositeIconSizes[1].evaluate(b,{})])[0]>ll||G[1]>ll)&&_(t.layerIds[0]+': Value for "icon-size" is >= '+ul+'. Reduce your "icon-size".'),t.addSymbols(t.icon,K,G,x,g,b,!1,e,T.lineStartIndex,T.lineLength,-1),V=t.icon.placedSymbolArray.length-1,X&&(M=4*X.length,t.addSymbols(t.icon,X,G,x,g,b,xu.vertical,e,T.lineStartIndex,T.lineLength,-1),F=t.icon.placedSymbolArray.length-1);}for(var J in n.horizontal){var Y=n.horizontal[J];if(!k){D=aa(Y.text);var H=s.layout.get("text-rotate").evaluate(b,{});k=new Wu(u,r,e,l,p,c,Y,h,f,y,t.overscaling,H);}var $=1===Y.positionedLines.length;if(B+=pl(t,e,Y,a,s,y,b,d,T,n.vertical?xu.horizontal:xu.horizontalOnly,$?Object.keys(n.horizontal):[J],L,V,w),$)break}n.vertical&&(P+=pl(t,e,n.vertical,a,s,y,b,d,T,xu.vertical,["vertical"],L,F,w));var W=k?k.boxStartIndex:t.collisionBoxArray.length,Q=k?k.boxEndIndex:t.collisionBoxArray.length,tt=z?z.boxStartIndex:t.collisionBoxArray.length,et=z?z.boxEndIndex:t.collisionBoxArray.length,rt=I?I.boxStartIndex:t.collisionBoxArray.length,nt=I?I.boxEndIndex:t.collisionBoxArray.length,it=C?C.boxStartIndex:t.collisionBoxArray.length,at=C?C.boxEndIndex:t.collisionBoxArray.length;t.glyphOffsetArray.length>=bl.MAX_GLYPHS&&_("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907");void 0!==b.sortKey&&t.addToSortKeyRanges(t.symbolInstances.length,b.sortKey);t.symbolInstances.emplaceBack(e.x,e.y,L.right>=0?L.right:-1,L.center>=0?L.center:-1,L.left>=0?L.left:-1,L.vertical||-1,V,F,D,W,Q,tt,et,rt,nt,it,at,l,B,P,E,M,0,h,O,R);}(t,s,i,r,n,a,h,t.layers[0],t.collisionBoxArray,e.index,e.sourceLayerIndex,t.index,v,w,k,l,x,A,I,y,e,o,p);};if("line"===z)for(var M=0,B=function(t,e,r,n,a){for(var o=[],s=0;s<t.length;s++)for(var u=t[s],l=void 0,p=0;p<u.length-1;p++){var c=u[p],h=u[p+1];c.x<e&&h.x<e||(c.x<e?c=new i(e,c.y+(h.y-c.y)*((e-c.x)/(h.x-c.x)))._round():h.x<e&&(h=new i(e,c.y+(h.y-c.y)*((e-c.x)/(h.x-c.x)))._round()),c.y<r&&h.y<r||(c.y<r?c=new i(c.x+(h.x-c.x)*((r-c.y)/(h.y-c.y)),r)._round():h.y<r&&(h=new i(c.x+(h.x-c.x)*((r-c.y)/(h.y-c.y)),r)._round()),c.x>=n&&h.x>=n||(c.x>=n?c=new i(n,c.y+(h.y-c.y)*((n-c.x)/(h.x-c.x)))._round():h.x>=n&&(h=new i(n,c.y+(h.y-c.y)*((n-c.x)/(h.x-c.x)))._round()),c.y>=a&&h.y>=a||(c.y>=a?c=new i(c.x+(h.x-c.x)*((a-c.y)/(h.y-c.y)),a)._round():h.y>=a&&(h=new i(c.x+(h.x-c.x)*((a-c.y)/(h.y-c.y)),a)._round()),l&&c.equals(l[l.length-1])||(l=[c],o.push(l)),l.push(h)))));}return o}(e.geometry,0,0,Ma,Ma);M<B.length;M+=1)for(var P=B[M],V=Xu(P,b,S,r.vertical||d,n,24,g,t.overscaling,Ma),F=0,L=V;F<L.length;F+=1){var D=L[F],O=d;O&&hl(t,O.text,C,D)||E(P,D);}else if("line-center"===z)for(var R=0,U=e.geometry;R<U.length;R+=1){var j=U[R];if(j.length>1){var q=Ku(j,S,r.vertical||d,n,24,g);q&&E(j,q);}}else if("Polygon"===e.type)for(var N=0,K=$o(e.geometry,0);N<K.length;N+=1){var X=K[N],Z=el(X,16);E(X[0],new Vu(Z.x,Z.y,0));}else if("LineString"===e.type)for(var G=0,J=e.geometry;G<J.length;G+=1){var Y=J[G];E(Y,new Vu(Y[0].x,Y[0].y,0));}else if("Point"===e.type)for(var H=0,$=e.geometry;H<$.length;H+=1)for(var W=$[H],Q=0,tt=W;Q<tt.length;Q+=1){var et=tt[Q];E([et],new Vu(et.x,et.y,0));}}(t,o,f,R,n,p,c,h,d,U);},A=0,S=t.features;A<S.length;A+=1)w();o&&t.generateCollisionDebugBuffers();},t.perspective=function(t,e,r,n,i){var a,o=1/Math.tan(e/2);return t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=i&&i!==1/0?(a=1/(n-i),t[10]=(i+n)*a,t[14]=2*i*n*a):(t[10]=-1,t[14]=-2*n),t},t.pick=function(t,e){for(var r={},n=0;n<e.length;n++){var i=e[n];i in t&&(r[i]=t[i]);}return r},t.plugin=Qn,t.polygonIntersectsPolygon=Da,t.postMapLoadEvent=it,t.postTurnstileEvent=rt,t.potpack=yu,t.refProperties=["type","source","source-layer","minzoom","maxzoom","filter","layout"],t.register=zn,t.registerForPluginStateChange=function(t){return t({pluginStatus:Zn,pluginURL:Gn}),Hn.on("pluginStateChange",t),t},t.rotate=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=Math.sin(r),u=Math.cos(r);return t[0]=n*u+a*s,t[1]=i*u+o*s,t[2]=n*-s+a*u,t[3]=i*-s+o*u,t},t.rotateX=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[4],o=e[5],s=e[6],u=e[7],l=e[8],p=e[9],c=e[10],h=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=a*i+l*n,t[5]=o*i+p*n,t[6]=s*i+c*n,t[7]=u*i+h*n,t[8]=l*i-a*n,t[9]=p*i-o*n,t[10]=c*i-s*n,t[11]=h*i-u*n,t},t.rotateZ=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],u=e[3],l=e[4],p=e[5],c=e[6],h=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i+l*n,t[1]=o*i+p*n,t[2]=s*i+c*n,t[3]=u*i+h*n,t[4]=l*i-a*n,t[5]=p*i-o*n,t[6]=c*i-s*n,t[7]=h*i-u*n,t},t.scale=function(t,e,r){var n=r[0],i=r[1],a=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*a,t[9]=e[9]*a,t[10]=e[10]*a,t[11]=e[11]*a,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.scale$1=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t},t.scale$2=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t},t.setCacheLimits=function(t,e){ot=t,st=e;},t.setRTLTextPlugin=function(t,e,r){if(void 0===r&&(r=!1),Zn===qn||Zn===Nn||Zn===Kn)throw new Error("setRTLTextPlugin cannot be called multiple times.");Gn=L.resolveURL(t),Zn=qn,Xn=e,Yn(),r||Wn();},t.sphericalToCartesian=function(t){var e=t[0],r=t[1],n=t[2];return r+=90,r*=Math.PI/180,n*=Math.PI/180,{x:e*Math.cos(r)*Math.sin(n),y:e*Math.sin(r)*Math.sin(n),z:e*Math.cos(n)}},t.sqrLen=io,t.styleSpec=Bt,t.sub=ro,t.symbolSize=Ru,t.transformMat3=function(t,e,r){var n=e[0],i=e[1],a=e[2];return t[0]=n*r[0]+i*r[3]+a*r[6],t[1]=n*r[1]+i*r[4]+a*r[7],t[2]=n*r[2]+i*r[5]+a*r[8],t},t.transformMat4=no,t.translate=function(t,e,r){var n,i,a,o,s,u,l,p,c,h,f,y,d=r[0],m=r[1],v=r[2];return e===t?(t[12]=e[0]*d+e[4]*m+e[8]*v+e[12],t[13]=e[1]*d+e[5]*m+e[9]*v+e[13],t[14]=e[2]*d+e[6]*m+e[10]*v+e[14],t[15]=e[3]*d+e[7]*m+e[11]*v+e[15]):(n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],u=e[5],l=e[6],p=e[7],c=e[8],h=e[9],f=e[10],y=e[11],t[0]=n,t[1]=i,t[2]=a,t[3]=o,t[4]=s,t[5]=u,t[6]=l,t[7]=p,t[8]=c,t[9]=h,t[10]=f,t[11]=y,t[12]=n*d+s*m+c*v+e[12],t[13]=i*d+u*m+h*v+e[13],t[14]=a*d+l*m+f*v+e[14],t[15]=o*d+p*m+y*v+e[15]),t},t.triggerPluginCompletionEvent=Jn,t.uniqueId=h,t.validateCustomStyleLayer=function(t){var e=[],r=t.id;return void 0===r&&e.push({message:"layers."+r+': missing required property "id"'}),void 0===t.render&&e.push({message:"layers."+r+': missing required method "render"'}),t.renderingMode&&"2d"!==t.renderingMode&&"3d"!==t.renderingMode&&e.push({message:"layers."+r+': property "renderingMode" must be either "2d" or "3d"'}),e},t.validateLight=vn,t.validateStyle=mn,t.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},t.vectorTile=ys,t.version="1.8.1",t.warnOnce=_,t.webpSupported=O,t.window=self,t.wrap=l;}));
define(["./shared"],(function(e){"use strict";function t(e){var r=typeof e;if("number"===r||"boolean"===r||"string"===r||null==e)return JSON.stringify(e);if(Array.isArray(e)){for(var i="[",o=0,n=e;o<n.length;o+=1){i+=t(n[o])+",";}return i+"]"}for(var a=Object.keys(e).sort(),s="{",l=0;l<a.length;l++)s+=JSON.stringify(a[l])+":"+t(e[a[l]])+",";return s+"}"}function r(r){for(var i="",o=0,n=e.refProperties;o<n.length;o+=1){i+="/"+t(r[n[o]]);}return i}var i=function(e){this.keyCache={},e&&this.replace(e);};i.prototype.replace=function(e){this._layerConfigs={},this._layers={},this.update(e,[]);},i.prototype.update=function(t,i){for(var o=this,n=0,a=t;n<a.length;n+=1){var s=a[n];this._layerConfigs[s.id]=s;var l=this._layers[s.id]=e.createStyleLayer(s);l._featureFilter=e.featureFilter(l.filter),this.keyCache[s.id]&&delete this.keyCache[s.id];}for(var u=0,h=i;u<h.length;u+=1){var c=h[u];delete this.keyCache[c],delete this._layerConfigs[c],delete this._layers[c];}this.familiesBySource={};for(var p=0,f=function(e,t){for(var i={},o=0;o<e.length;o++){var n=t&&t[e[o].id]||r(e[o]);t&&(t[e[o].id]=n);var a=i[n];a||(a=i[n]=[]),a.push(e[o]);}var s=[];for(var l in i)s.push(i[l]);return s}(e.values(this._layerConfigs),this.keyCache);p<f.length;p+=1){var d=f[p].map((function(e){return o._layers[e.id]})),g=d[0];if("none"!==g.visibility){var m=g.source||"",v=this.familiesBySource[m];v||(v=this.familiesBySource[m]={});var y=g.sourceLayer||"_geojsonTileLayer",x=v[y];x||(x=v[y]=[]),x.push(d);}}};var o=function(t){var r={},i=[];for(var o in t){var n=t[o],a=r[o]={};for(var s in n){var l=n[+s];if(l&&0!==l.bitmap.width&&0!==l.bitmap.height){var u={x:0,y:0,w:l.bitmap.width+2,h:l.bitmap.height+2};i.push(u),a[s]={rect:u,metrics:l.metrics};}}}var h=e.potpack(i),c=h.w,p=h.h,f=new e.AlphaImage({width:c||1,height:p||1});for(var d in t){var g=t[d];for(var m in g){var v=g[+m];if(v&&0!==v.bitmap.width&&0!==v.bitmap.height){var y=r[d][m].rect;e.AlphaImage.copy(v.bitmap,f,{x:0,y:0},{x:y.x+1,y:y.y+1},v.bitmap);}}}this.image=f,this.positions=r;};e.register("GlyphAtlas",o);var n=function(t){this.tileID=new e.OverscaledTileID(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId;};function a(t,r,i){for(var o=new e.EvaluationParameters(r),n=0,a=t;n<a.length;n+=1){a[n].recalculate(o,i);}}function s(t,r){var i=e.getArrayBuffer(t.request,(function(t,i,o,n){t?r(t):i&&r(null,{vectorTile:new e.vectorTile.VectorTile(new e.pbf(i)),rawData:i,cacheControl:o,expires:n});}));return function(){i.cancel(),r();}}n.prototype.parse=function(t,r,i,n,s){var l=this;this.status="parsing",this.data=t,this.collisionBoxArray=new e.CollisionBoxArray;var u=new e.DictionaryCoder(Object.keys(t.layers).sort()),h=new e.FeatureIndex(this.tileID,this.promoteId);h.bucketLayerIDs=[];var c,p,f,d,g={},m={featureIndex:h,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:i},v=r.familiesBySource[this.source];for(var y in v){var x=t.layers[y];if(x){1===x.version&&e.warnOnce('Vector tile source "'+this.source+'" layer "'+y+'" does not use vector tile spec v2 and therefore may have some rendering errors.');for(var w=u.encode(y),S=[],M=0;M<x.length;M++){var I=x.feature(M),b=h.getId(I,y);S.push({feature:I,id:b,index:M,sourceLayerIndex:w});}for(var P=0,_=v[y];P<_.length;P+=1){var k=_[P],T=k[0];if(!(T.minzoom&&this.zoom<Math.floor(T.minzoom)))if(!(T.maxzoom&&this.zoom>=T.maxzoom))if("none"!==T.visibility)a(k,this.zoom,i),(g[T.id]=T.createBucket({index:h.bucketLayerIDs.length,layers:k,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:w,sourceID:this.source})).populate(S,m),h.bucketLayerIDs.push(k.map((function(e){return e.id})));}}}var C=e.mapObject(m.glyphDependencies,(function(e){return Object.keys(e).map(Number)}));Object.keys(C).length?n.send("getGlyphs",{uid:this.uid,stacks:C},(function(e,t){c||(c=e,p=t,O.call(l));})):p={};var D=Object.keys(m.iconDependencies);D.length?n.send("getImages",{icons:D,source:this.source,tileID:this.tileID,type:"icons"},(function(e,t){c||(c=e,f=t,O.call(l));})):f={};var L=Object.keys(m.patternDependencies);function O(){if(c)return s(c);if(p&&f&&d){var t=new o(p),r=new e.ImageAtlas(f,d);for(var n in g){var l=g[n];l instanceof e.SymbolBucket?(a(l.layers,this.zoom,i),e.performSymbolLayout(l,p,t.positions,f,r.iconPositions,this.showCollisionBoxes)):l.hasPattern&&(l instanceof e.LineBucket||l instanceof e.FillBucket||l instanceof e.FillExtrusionBucket)&&(a(l.layers,this.zoom,i),l.addFeatures(m,r.patternPositions));}this.status="done",s(null,{buckets:e.values(g).filter((function(e){return !e.isEmpty()})),featureIndex:h,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:t.image,imageAtlas:r,glyphMap:this.returnDependencies?p:null,iconMap:this.returnDependencies?f:null,glyphPositions:this.returnDependencies?t.positions:null});}}L.length?n.send("getImages",{icons:L,source:this.source,tileID:this.tileID,type:"patterns"},(function(e,t){c||(c=e,d=t,O.call(l));})):d={},O.call(this);};var l=function(e,t,r,i){this.actor=e,this.layerIndex=t,this.availableImages=r,this.loadVectorData=i||s,this.loading={},this.loaded={};};l.prototype.loadTile=function(t,r){var i=this,o=t.uid;this.loading||(this.loading={});var a=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.RequestPerformance(t.request),s=this.loading[o]=new n(t);s.abort=this.loadVectorData(t,(function(t,n){if(delete i.loading[o],t||!n)return s.status="done",i.loaded[o]=s,r(t);var l=n.rawData,u={};n.expires&&(u.expires=n.expires),n.cacheControl&&(u.cacheControl=n.cacheControl);var h={};if(a){var c=a.finish();c&&(h.resourceTiming=JSON.parse(JSON.stringify(c)));}s.vectorTile=n.vectorTile,s.parse(n.vectorTile,i.layerIndex,i.availableImages,i.actor,(function(t,i){if(t||!i)return r(t);r(null,e.extend({rawTileData:l.slice(0)},i,u,h));})),i.loaded=i.loaded||{},i.loaded[o]=s;}));},l.prototype.reloadTile=function(e,t){var r=this,i=this.loaded,o=e.uid,n=this;if(i&&i[o]){var a=i[o];a.showCollisionBoxes=e.showCollisionBoxes;var s=function(e,i){var o=a.reloadCallback;o&&(delete a.reloadCallback,a.parse(a.vectorTile,n.layerIndex,r.availableImages,n.actor,o)),t(e,i);};"parsing"===a.status?a.reloadCallback=s:"done"===a.status&&(a.vectorTile?a.parse(a.vectorTile,this.layerIndex,this.availableImages,this.actor,s):s());}},l.prototype.abortTile=function(e,t){var r=this.loading,i=e.uid;r&&r[i]&&r[i].abort&&(r[i].abort(),delete r[i]),t();},l.prototype.removeTile=function(e,t){var r=this.loaded,i=e.uid;r&&r[i]&&delete r[i],t();};var u=e.window.ImageBitmap,h=function(){this.loaded={};};h.prototype.loadTile=function(t,r){var i=t.uid,o=t.encoding,n=t.rawImageData,a=u&&n instanceof u?this.getImageData(n):n,s=new e.DEMData(i,a,o);this.loaded=this.loaded||{},this.loaded[i]=s,r(null,s);},h.prototype.getImageData=function(t){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(t.width,t.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d")),this.offscreenCanvas.width=t.width,this.offscreenCanvas.height=t.height,this.offscreenCanvasContext.drawImage(t,0,0,t.width,t.height);var r=this.offscreenCanvasContext.getImageData(-1,-1,t.width+2,t.height+2);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),new e.RGBAImage({width:r.width,height:r.height},r.data)},h.prototype.removeTile=function(e){var t=this.loaded,r=e.uid;t&&t[r]&&delete t[r];};var c={RADIUS:6378137,FLATTENING:1/298.257223563,POLAR_RADIUS:6356752.3142};function p(e){var t=0;if(e&&e.length>0){t+=Math.abs(f(e[0]));for(var r=1;r<e.length;r++)t-=Math.abs(f(e[r]));}return t}function f(e){var t,r,i,o,n,a,s=0,l=e.length;if(l>2){for(a=0;a<l;a++)a===l-2?(i=l-2,o=l-1,n=0):a===l-1?(i=l-1,o=0,n=1):(i=a,o=a+1,n=a+2),t=e[i],r=e[o],s+=(d(e[n][0])-d(t[0]))*Math.sin(d(r[1]));s=s*c.RADIUS*c.RADIUS/2;}return s}function d(e){return e*Math.PI/180}var g={geometry:function e(t){var r,i=0;switch(t.type){case"Polygon":return p(t.coordinates);case"MultiPolygon":for(r=0;r<t.coordinates.length;r++)i+=p(t.coordinates[r]);return i;case"Point":case"MultiPoint":case"LineString":case"MultiLineString":return 0;case"GeometryCollection":for(r=0;r<t.geometries.length;r++)i+=e(t.geometries[r]);return i}},ring:f},m=function e(t,r){switch(t&&t.type||null){case"FeatureCollection":return t.features=t.features.map(v(e,r)),t;case"GeometryCollection":return t.geometries=t.geometries.map(v(e,r)),t;case"Feature":return t.geometry=e(t.geometry,r),t;case"Polygon":case"MultiPolygon":return function(e,t){"Polygon"===e.type?e.coordinates=y(e.coordinates,t):"MultiPolygon"===e.type&&(e.coordinates=e.coordinates.map(v(y,t)));return e}(t,r);default:return t}};function v(e,t){return function(r){return e(r,t)}}function y(e,t){t=!!t,e[0]=x(e[0],t);for(var r=1;r<e.length;r++)e[r]=x(e[r],!t);return e}function x(e,t){return function(e){return g.ring(e)>=0}(e)===t?e:e.reverse()}var w=e.vectorTile.VectorTileFeature.prototype.toGeoJSON,S=function(t){this._feature=t,this.extent=e.EXTENT,this.type=t.type,this.properties=t.tags,"id"in t&&!isNaN(t.id)&&(this.id=parseInt(t.id,10));};S.prototype.loadGeometry=function(){if(1===this._feature.type){for(var t=[],r=0,i=this._feature.geometry;r<i.length;r+=1){var o=i[r];t.push([new e.Point$1(o[0],o[1])]);}return t}for(var n=[],a=0,s=this._feature.geometry;a<s.length;a+=1){for(var l=[],u=0,h=s[a];u<h.length;u+=1){var c=h[u];l.push(new e.Point$1(c[0],c[1]));}n.push(l);}return n},S.prototype.toGeoJSON=function(e,t,r){return w.call(this,e,t,r)};var M=function(t){this.layers={_geojsonTileLayer:this},this.name="_geojsonTileLayer",this.extent=e.EXTENT,this.length=t.length,this._features=t;};M.prototype.feature=function(e){return new S(this._features[e])};var I=e.vectorTile.VectorTileFeature,b=P;function P(e,t){this.options=t||{},this.features=e,this.length=e.length;}function _(e,t){this.id="number"==typeof e.id?e.id:void 0,this.type=e.type,this.rawGeometry=1===e.type?[e.geometry]:e.geometry,this.properties=e.tags,this.extent=t||4096;}P.prototype.feature=function(e){return new _(this.features[e],this.options.extent)},_.prototype.loadGeometry=function(){var t=this.rawGeometry;this.geometry=[];for(var r=0;r<t.length;r++){for(var i=t[r],o=[],n=0;n<i.length;n++)o.push(new e.Point$1(i[n][0],i[n][1]));this.geometry.push(o);}return this.geometry},_.prototype.bbox=function(){this.geometry||this.loadGeometry();for(var e=this.geometry,t=1/0,r=-1/0,i=1/0,o=-1/0,n=0;n<e.length;n++)for(var a=e[n],s=0;s<a.length;s++){var l=a[s];t=Math.min(t,l.x),r=Math.max(r,l.x),i=Math.min(i,l.y),o=Math.max(o,l.y);}return [t,i,r,o]},_.prototype.toGeoJSON=I.prototype.toGeoJSON;var k=L,T=L,C=function(e,t){t=t||{};var r={};for(var i in e)r[i]=new b(e[i].features,t),r[i].name=i,r[i].version=t.version,r[i].extent=t.extent;return L({layers:r})},D=b;function L(t){var r=new e.pbf;return function(e,t){for(var r in e.layers)t.writeMessage(3,O,e.layers[r]);}(t,r),r.finish()}function O(e,t){var r;t.writeVarintField(15,e.version||1),t.writeStringField(1,e.name||""),t.writeVarintField(5,e.extent||4096);var i={keys:[],values:[],keycache:{},valuecache:{}};for(r=0;r<e.length;r++)i.feature=e.feature(r),t.writeMessage(2,z,i);var o=i.keys;for(r=0;r<o.length;r++)t.writeStringField(3,o[r]);var n=i.values;for(r=0;r<n.length;r++)t.writeMessage(4,J,n[r]);}function z(e,t){var r=e.feature;void 0!==r.id&&t.writeVarintField(1,r.id),t.writeMessage(2,E,e),t.writeVarintField(3,r.type),t.writeMessage(4,A,r);}function E(e,t){var r=e.feature,i=e.keys,o=e.values,n=e.keycache,a=e.valuecache;for(var s in r.properties){var l=n[s];void 0===l&&(i.push(s),l=i.length-1,n[s]=l),t.writeVarint(l);var u=r.properties[s],h=typeof u;"string"!==h&&"boolean"!==h&&"number"!==h&&(u=JSON.stringify(u));var c=h+":"+u,p=a[c];void 0===p&&(o.push(u),p=o.length-1,a[c]=p),t.writeVarint(p);}}function N(e,t){return (t<<3)+(7&e)}function F(e){return e<<1^e>>31}function A(e,t){for(var r=e.loadGeometry(),i=e.type,o=0,n=0,a=r.length,s=0;s<a;s++){var l=r[s],u=1;1===i&&(u=l.length),t.writeVarint(N(1,u));for(var h=3===i?l.length-1:l.length,c=0;c<h;c++){1===c&&1!==i&&t.writeVarint(N(2,h-1));var p=l[c].x-o,f=l[c].y-n;t.writeVarint(F(p)),t.writeVarint(F(f)),o+=p,n+=f;}3===i&&t.writeVarint(N(7,1));}}function J(e,t){var r=typeof e;"string"===r?t.writeStringField(1,e):"boolean"===r?t.writeBooleanField(7,e):"number"===r&&(e%1!=0?t.writeDoubleField(3,e):e<0?t.writeSVarintField(6,e):t.writeVarintField(5,e));}function Z(e,t,r,i,o,n){if(!(o-i<=r)){var a=i+o>>1;!function e(t,r,i,o,n,a){for(;n>o;){if(n-o>600){var s=n-o+1,l=i-o+1,u=Math.log(s),h=.5*Math.exp(2*u/3),c=.5*Math.sqrt(u*h*(s-h)/s)*(l-s/2<0?-1:1),p=Math.max(o,Math.floor(i-l*h/s+c)),f=Math.min(n,Math.floor(i+(s-l)*h/s+c));e(t,r,i,p,f,a);}var d=r[2*i+a],g=o,m=n;for(B(t,r,o,i),r[2*n+a]>d&&B(t,r,o,n);g<m;){for(B(t,r,g,m),g++,m--;r[2*g+a]<d;)g++;for(;r[2*m+a]>d;)m--;}r[2*o+a]===d?B(t,r,o,m):B(t,r,++m,n),m<=i&&(o=m+1),i<=m&&(n=m-1);}}(e,t,a,i,o,n%2),Z(e,t,r,i,a-1,n+1),Z(e,t,r,a+1,o,n+1);}}function B(e,t,r,i){G(e,r,i),G(t,2*r,2*i),G(t,2*r+1,2*i+1);}function G(e,t,r){var i=e[t];e[t]=e[r],e[r]=i;}function Y(e,t,r,i){var o=e-r,n=t-i;return o*o+n*n}k.fromVectorTileJs=T,k.fromGeojsonVt=C,k.GeoJSONWrapper=D;var R=function(e){return e[0]},j=function(e){return e[1]},V=function(e,t,r,i,o){void 0===t&&(t=R),void 0===r&&(r=j),void 0===i&&(i=64),void 0===o&&(o=Float64Array),this.nodeSize=i,this.points=e;for(var n=e.length<65536?Uint16Array:Uint32Array,a=this.ids=new n(e.length),s=this.coords=new o(2*e.length),l=0;l<e.length;l++)a[l]=l,s[2*l]=t(e[l]),s[2*l+1]=r(e[l]);Z(a,s,i,0,a.length-1,0);};V.prototype.range=function(e,t,r,i){return function(e,t,r,i,o,n,a){for(var s,l,u=[0,e.length-1,0],h=[];u.length;){var c=u.pop(),p=u.pop(),f=u.pop();if(p-f<=a)for(var d=f;d<=p;d++)s=t[2*d],l=t[2*d+1],s>=r&&s<=o&&l>=i&&l<=n&&h.push(e[d]);else{var g=Math.floor((f+p)/2);s=t[2*g],l=t[2*g+1],s>=r&&s<=o&&l>=i&&l<=n&&h.push(e[g]);var m=(c+1)%2;(0===c?r<=s:i<=l)&&(u.push(f),u.push(g-1),u.push(m)),(0===c?o>=s:n>=l)&&(u.push(g+1),u.push(p),u.push(m));}}return h}(this.ids,this.coords,e,t,r,i,this.nodeSize)},V.prototype.within=function(e,t,r){return function(e,t,r,i,o,n){for(var a=[0,e.length-1,0],s=[],l=o*o;a.length;){var u=a.pop(),h=a.pop(),c=a.pop();if(h-c<=n)for(var p=c;p<=h;p++)Y(t[2*p],t[2*p+1],r,i)<=l&&s.push(e[p]);else{var f=Math.floor((c+h)/2),d=t[2*f],g=t[2*f+1];Y(d,g,r,i)<=l&&s.push(e[f]);var m=(u+1)%2;(0===u?r-o<=d:i-o<=g)&&(a.push(c),a.push(f-1),a.push(m)),(0===u?r+o>=d:i+o>=g)&&(a.push(f+1),a.push(h),a.push(m));}}return s}(this.ids,this.coords,e,t,r,this.nodeSize)};var X={minZoom:0,maxZoom:16,radius:40,extent:512,nodeSize:64,log:!1,generateId:!1,reduce:null,map:function(e){return e}},W=function(e){this.options=ee(Object.create(X),e),this.trees=new Array(this.options.maxZoom+1);};function q(e,t,r,i,o){return {x:e,y:t,zoom:1/0,id:r,parentId:-1,numPoints:i,properties:o}}function U(e,t){var r=e.geometry.coordinates,i=r[0],o=r[1];return {x:K(i),y:Q(o),zoom:1/0,index:t,parentId:-1}}function $(e){return {type:"Feature",id:e.id,properties:H(e),geometry:{type:"Point",coordinates:[(i=e.x,360*(i-.5)),(t=e.y,r=(180-360*t)*Math.PI/180,360*Math.atan(Math.exp(r))/Math.PI-90)]}};var t,r,i;}function H(e){var t=e.numPoints,r=t>=1e4?Math.round(t/1e3)+"k":t>=1e3?Math.round(t/100)/10+"k":t;return ee(ee({},e.properties),{cluster:!0,cluster_id:e.id,point_count:t,point_count_abbreviated:r})}function K(e){return e/360+.5}function Q(e){var t=Math.sin(e*Math.PI/180),r=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return r<0?0:r>1?1:r}function ee(e,t){for(var r in t)e[r]=t[r];return e}function te(e){return e.x}function re(e){return e.y}function ie(e,t,r,i,o,n){var a=o-r,s=n-i;if(0!==a||0!==s){var l=((e-r)*a+(t-i)*s)/(a*a+s*s);l>1?(r=o,i=n):l>0&&(r+=a*l,i+=s*l);}return (a=e-r)*a+(s=t-i)*s}function oe(e,t,r,i){var o={id:void 0===e?null:e,type:t,geometry:r,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};return function(e){var t=e.geometry,r=e.type;if("Point"===r||"MultiPoint"===r||"LineString"===r)ne(e,t);else if("Polygon"===r||"MultiLineString"===r)for(var i=0;i<t.length;i++)ne(e,t[i]);else if("MultiPolygon"===r)for(i=0;i<t.length;i++)for(var o=0;o<t[i].length;o++)ne(e,t[i][o]);}(o),o}function ne(e,t){for(var r=0;r<t.length;r+=3)e.minX=Math.min(e.minX,t[r]),e.minY=Math.min(e.minY,t[r+1]),e.maxX=Math.max(e.maxX,t[r]),e.maxY=Math.max(e.maxY,t[r+1]);}function ae(e,t,r,i){if(t.geometry){var o=t.geometry.coordinates,n=t.geometry.type,a=Math.pow(r.tolerance/((1<<r.maxZoom)*r.extent),2),s=[],l=t.id;if(r.promoteId?l=t.properties[r.promoteId]:r.generateId&&(l=i||0),"Point"===n)se(o,s);else if("MultiPoint"===n)for(var u=0;u<o.length;u++)se(o[u],s);else if("LineString"===n)le(o,s,a,!1);else if("MultiLineString"===n){if(r.lineMetrics){for(u=0;u<o.length;u++)s=[],le(o[u],s,a,!1),e.push(oe(l,"LineString",s,t.properties));return}ue(o,s,a,!1);}else if("Polygon"===n)ue(o,s,a,!0);else{if("MultiPolygon"!==n){if("GeometryCollection"===n){for(u=0;u<t.geometry.geometries.length;u++)ae(e,{id:l,geometry:t.geometry.geometries[u],properties:t.properties},r,i);return}throw new Error("Input data is not a valid GeoJSON object.")}for(u=0;u<o.length;u++){var h=[];ue(o[u],h,a,!0),s.push(h);}}e.push(oe(l,n,s,t.properties));}}function se(e,t){t.push(he(e[0])),t.push(ce(e[1])),t.push(0);}function le(e,t,r,i){for(var o,n,a=0,s=0;s<e.length;s++){var l=he(e[s][0]),u=ce(e[s][1]);t.push(l),t.push(u),t.push(0),s>0&&(a+=i?(o*u-l*n)/2:Math.sqrt(Math.pow(l-o,2)+Math.pow(u-n,2))),o=l,n=u;}var h=t.length-3;t[2]=1,function e(t,r,i,o){for(var n,a=o,s=i-r>>1,l=i-r,u=t[r],h=t[r+1],c=t[i],p=t[i+1],f=r+3;f<i;f+=3){var d=ie(t[f],t[f+1],u,h,c,p);if(d>a)n=f,a=d;else if(d===a){var g=Math.abs(f-s);g<l&&(n=f,l=g);}}a>o&&(n-r>3&&e(t,r,n,o),t[n+2]=a,i-n>3&&e(t,n,i,o));}(t,0,h,r),t[h+2]=1,t.size=Math.abs(a),t.start=0,t.end=t.size;}function ue(e,t,r,i){for(var o=0;o<e.length;o++){var n=[];le(e[o],n,r,i),t.push(n);}}function he(e){return e/360+.5}function ce(e){var t=Math.sin(e*Math.PI/180),r=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return r<0?0:r>1?1:r}function pe(e,t,r,i,o,n,a,s){if(i/=t,n>=(r/=t)&&a<i)return e;if(a<r||n>=i)return null;for(var l=[],u=0;u<e.length;u++){var h=e[u],c=h.geometry,p=h.type,f=0===o?h.minX:h.minY,d=0===o?h.maxX:h.maxY;if(f>=r&&d<i)l.push(h);else if(!(d<r||f>=i)){var g=[];if("Point"===p||"MultiPoint"===p)fe(c,g,r,i,o);else if("LineString"===p)de(c,g,r,i,o,!1,s.lineMetrics);else if("MultiLineString"===p)me(c,g,r,i,o,!1);else if("Polygon"===p)me(c,g,r,i,o,!0);else if("MultiPolygon"===p)for(var m=0;m<c.length;m++){var v=[];me(c[m],v,r,i,o,!0),v.length&&g.push(v);}if(g.length){if(s.lineMetrics&&"LineString"===p){for(m=0;m<g.length;m++)l.push(oe(h.id,p,g[m],h.tags));continue}"LineString"!==p&&"MultiLineString"!==p||(1===g.length?(p="LineString",g=g[0]):p="MultiLineString"),"Point"!==p&&"MultiPoint"!==p||(p=3===g.length?"Point":"MultiPoint"),l.push(oe(h.id,p,g,h.tags));}}}return l.length?l:null}function fe(e,t,r,i,o){for(var n=0;n<e.length;n+=3){var a=e[n+o];a>=r&&a<=i&&(t.push(e[n]),t.push(e[n+1]),t.push(e[n+2]));}}function de(e,t,r,i,o,n,a){for(var s,l,u=ge(e),h=0===o?ye:xe,c=e.start,p=0;p<e.length-3;p+=3){var f=e[p],d=e[p+1],g=e[p+2],m=e[p+3],v=e[p+4],y=0===o?f:d,x=0===o?m:v,w=!1;a&&(s=Math.sqrt(Math.pow(f-m,2)+Math.pow(d-v,2))),y<r?x>r&&(l=h(u,f,d,m,v,r),a&&(u.start=c+s*l)):y>i?x<i&&(l=h(u,f,d,m,v,i),a&&(u.start=c+s*l)):ve(u,f,d,g),x<r&&y>=r&&(l=h(u,f,d,m,v,r),w=!0),x>i&&y<=i&&(l=h(u,f,d,m,v,i),w=!0),!n&&w&&(a&&(u.end=c+s*l),t.push(u),u=ge(e)),a&&(c+=s);}var S=e.length-3;f=e[S],d=e[S+1],g=e[S+2],(y=0===o?f:d)>=r&&y<=i&&ve(u,f,d,g),S=u.length-3,n&&S>=3&&(u[S]!==u[0]||u[S+1]!==u[1])&&ve(u,u[0],u[1],u[2]),u.length&&t.push(u);}function ge(e){var t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function me(e,t,r,i,o,n){for(var a=0;a<e.length;a++)de(e[a],t,r,i,o,n,!1);}function ve(e,t,r,i){e.push(t),e.push(r),e.push(i);}function ye(e,t,r,i,o,n){var a=(n-t)/(i-t);return e.push(n),e.push(r+(o-r)*a),e.push(1),a}function xe(e,t,r,i,o,n){var a=(n-r)/(o-r);return e.push(t+(i-t)*a),e.push(n),e.push(1),a}function we(e,t){for(var r=[],i=0;i<e.length;i++){var o,n=e[i],a=n.type;if("Point"===a||"MultiPoint"===a||"LineString"===a)o=Se(n.geometry,t);else if("MultiLineString"===a||"Polygon"===a){o=[];for(var s=0;s<n.geometry.length;s++)o.push(Se(n.geometry[s],t));}else if("MultiPolygon"===a)for(o=[],s=0;s<n.geometry.length;s++){for(var l=[],u=0;u<n.geometry[s].length;u++)l.push(Se(n.geometry[s][u],t));o.push(l);}r.push(oe(n.id,a,o,n.tags));}return r}function Se(e,t){var r=[];r.size=e.size,void 0!==e.start&&(r.start=e.start,r.end=e.end);for(var i=0;i<e.length;i+=3)r.push(e[i]+t,e[i+1],e[i+2]);return r}function Me(e,t){if(e.transformed)return e;var r,i,o,n=1<<e.z,a=e.x,s=e.y;for(r=0;r<e.features.length;r++){var l=e.features[r],u=l.geometry,h=l.type;if(l.geometry=[],1===h)for(i=0;i<u.length;i+=2)l.geometry.push(Ie(u[i],u[i+1],t,n,a,s));else for(i=0;i<u.length;i++){var c=[];for(o=0;o<u[i].length;o+=2)c.push(Ie(u[i][o],u[i][o+1],t,n,a,s));l.geometry.push(c);}}return e.transformed=!0,e}function Ie(e,t,r,i,o,n){return [Math.round(r*(e*i-o)),Math.round(r*(t*i-n))]}function be(e,t,r,i,o){for(var n=t===o.maxZoom?0:o.tolerance/((1<<t)*o.extent),a={features:[],numPoints:0,numSimplified:0,numFeatures:0,source:null,x:r,y:i,z:t,transformed:!1,minX:2,minY:1,maxX:-1,maxY:0},s=0;s<e.length;s++){a.numFeatures++,Pe(a,e[s],n,o);var l=e[s].minX,u=e[s].minY,h=e[s].maxX,c=e[s].maxY;l<a.minX&&(a.minX=l),u<a.minY&&(a.minY=u),h>a.maxX&&(a.maxX=h),c>a.maxY&&(a.maxY=c);}return a}function Pe(e,t,r,i){var o=t.geometry,n=t.type,a=[];if("Point"===n||"MultiPoint"===n)for(var s=0;s<o.length;s+=3)a.push(o[s]),a.push(o[s+1]),e.numPoints++,e.numSimplified++;else if("LineString"===n)_e(a,o,e,r,!1,!1);else if("MultiLineString"===n||"Polygon"===n)for(s=0;s<o.length;s++)_e(a,o[s],e,r,"Polygon"===n,0===s);else if("MultiPolygon"===n)for(var l=0;l<o.length;l++){var u=o[l];for(s=0;s<u.length;s++)_e(a,u[s],e,r,!0,0===s);}if(a.length){var h=t.tags||null;if("LineString"===n&&i.lineMetrics){for(var c in h={},t.tags)h[c]=t.tags[c];h.mapbox_clip_start=o.start/o.size,h.mapbox_clip_end=o.end/o.size;}var p={geometry:a,type:"Polygon"===n||"MultiPolygon"===n?3:"LineString"===n||"MultiLineString"===n?2:1,tags:h};null!==t.id&&(p.id=t.id),e.features.push(p);}}function _e(e,t,r,i,o,n){var a=i*i;if(i>0&&t.size<(o?a:i))r.numPoints+=t.length/3;else{for(var s=[],l=0;l<t.length;l+=3)(0===i||t[l+2]>a)&&(r.numSimplified++,s.push(t[l]),s.push(t[l+1])),r.numPoints++;o&&function(e,t){for(var r=0,i=0,o=e.length,n=o-2;i<o;n=i,i+=2)r+=(e[i]-e[n])*(e[i+1]+e[n+1]);if(r>0===t)for(i=0,o=e.length;i<o/2;i+=2){var a=e[i],s=e[i+1];e[i]=e[o-2-i],e[i+1]=e[o-1-i],e[o-2-i]=a,e[o-1-i]=s;}}(s,n),e.push(s);}}function ke(e,t){var r=(t=this.options=function(e,t){for(var r in t)e[r]=t[r];return e}(Object.create(this.options),t)).debug;if(r&&console.time("preprocess data"),t.maxZoom<0||t.maxZoom>24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");var i=function(e,t){var r=[];if("FeatureCollection"===e.type)for(var i=0;i<e.features.length;i++)ae(r,e.features[i],t,i);else"Feature"===e.type?ae(r,e,t):ae(r,{geometry:e},t);return r}(e,t);this.tiles={},this.tileCoords=[],r&&(console.timeEnd("preprocess data"),console.log("index: maxZoom: %d, maxPoints: %d",t.indexMaxZoom,t.indexMaxPoints),console.time("generate tiles"),this.stats={},this.total=0),(i=function(e,t){var r=t.buffer/t.extent,i=e,o=pe(e,1,-1-r,r,0,-1,2,t),n=pe(e,1,1-r,2+r,0,-1,2,t);return (o||n)&&(i=pe(e,1,-r,1+r,0,-1,2,t)||[],o&&(i=we(o,1).concat(i)),n&&(i=i.concat(we(n,-1)))),i}(i,t)).length&&this.splitTile(i,0,0,0),r&&(i.length&&console.log("features: %d, points: %d",this.tiles[0].numFeatures,this.tiles[0].numPoints),console.timeEnd("generate tiles"),console.log("tiles generated:",this.total,JSON.stringify(this.stats)));}function Te(e,t,r){return 32*((1<<e)*r+t)+e}function Ce(e,t){var r=e.tileID.canonical;if(!this._geoJSONIndex)return t(null,null);var i=this._geoJSONIndex.getTile(r.z,r.x,r.y);if(!i)return t(null,null);var o=new M(i.features),n=k(o);0===n.byteOffset&&n.byteLength===n.buffer.byteLength||(n=new Uint8Array(n)),t(null,{vectorTile:o,rawData:n.buffer});}W.prototype.load=function(e){var t=this.options,r=t.log,i=t.minZoom,o=t.maxZoom,n=t.nodeSize;r&&console.time("total time");var a="prepare "+e.length+" points";r&&console.time(a),this.points=e;for(var s=[],l=0;l<e.length;l++)e[l].geometry&&s.push(U(e[l],l));this.trees[o+1]=new V(s,te,re,n,Float32Array),r&&console.timeEnd(a);for(var u=o;u>=i;u--){var h=+Date.now();s=this._cluster(s,u),this.trees[u]=new V(s,te,re,n,Float32Array),r&&console.log("z%d: %d clusters in %dms",u,s.length,+Date.now()-h);}return r&&console.timeEnd("total time"),this},W.prototype.getClusters=function(e,t){var r=((e[0]+180)%360+360)%360-180,i=Math.max(-90,Math.min(90,e[1])),o=180===e[2]?180:((e[2]+180)%360+360)%360-180,n=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)r=-180,o=180;else if(r>o){var a=this.getClusters([r,i,180,n],t),s=this.getClusters([-180,i,o,n],t);return a.concat(s)}for(var l=this.trees[this._limitZoom(t)],u=[],h=0,c=l.range(K(r),Q(n),K(o),Q(i));h<c.length;h+=1){var p=c[h],f=l.points[p];u.push(f.numPoints?$(f):this.points[f.index]);}return u},W.prototype.getChildren=function(e){var t=this._getOriginId(e),r=this._getOriginZoom(e),i="No cluster with the specified id.",o=this.trees[r];if(!o)throw new Error(i);var n=o.points[t];if(!n)throw new Error(i);for(var a=this.options.radius/(this.options.extent*Math.pow(2,r-1)),s=[],l=0,u=o.within(n.x,n.y,a);l<u.length;l+=1){var h=u[l],c=o.points[h];c.parentId===e&&s.push(c.numPoints?$(c):this.points[c.index]);}if(0===s.length)throw new Error(i);return s},W.prototype.getLeaves=function(e,t,r){t=t||10,r=r||0;var i=[];return this._appendLeaves(i,e,t,r,0),i},W.prototype.getTile=function(e,t,r){var i=this.trees[this._limitZoom(e)],o=Math.pow(2,e),n=this.options,a=n.extent,s=n.radius/a,l=(r-s)/o,u=(r+1+s)/o,h={features:[]};return this._addTileFeatures(i.range((t-s)/o,l,(t+1+s)/o,u),i.points,t,r,o,h),0===t&&this._addTileFeatures(i.range(1-s/o,l,1,u),i.points,o,r,o,h),t===o-1&&this._addTileFeatures(i.range(0,l,s/o,u),i.points,-1,r,o,h),h.features.length?h:null},W.prototype.getClusterExpansionZoom=function(e){for(var t=this._getOriginZoom(e)-1;t<=this.options.maxZoom;){var r=this.getChildren(e);if(t++,1!==r.length)break;e=r[0].properties.cluster_id;}return t},W.prototype._appendLeaves=function(e,t,r,i,o){for(var n=0,a=this.getChildren(t);n<a.length;n+=1){var s=a[n],l=s.properties;if(l&&l.cluster?o+l.point_count<=i?o+=l.point_count:o=this._appendLeaves(e,l.cluster_id,r,i,o):o<i?o++:e.push(s),e.length===r)break}return o},W.prototype._addTileFeatures=function(e,t,r,i,o,n){for(var a=0,s=e;a<s.length;a+=1){var l=t[s[a]],u=l.numPoints,h={type:1,geometry:[[Math.round(this.options.extent*(l.x*o-r)),Math.round(this.options.extent*(l.y*o-i))]],tags:u?H(l):this.points[l.index].properties},c=void 0;u?c=l.id:this.options.generateId?c=l.index:this.points[l.index].id&&(c=this.points[l.index].id),void 0!==c&&(h.id=c),n.features.push(h);}},W.prototype._limitZoom=function(e){return Math.max(this.options.minZoom,Math.min(e,this.options.maxZoom+1))},W.prototype._cluster=function(e,t){for(var r=[],i=this.options,o=i.radius,n=i.extent,a=i.reduce,s=o/(n*Math.pow(2,t)),l=0;l<e.length;l++){var u=e[l];if(!(u.zoom<=t)){u.zoom=t;for(var h=this.trees[t+1],c=h.within(u.x,u.y,s),p=u.numPoints||1,f=u.x*p,d=u.y*p,g=a&&p>1?this._map(u,!0):null,m=(l<<5)+(t+1)+this.points.length,v=0,y=c;v<y.length;v+=1){var x=y[v],w=h.points[x];if(!(w.zoom<=t)){w.zoom=t;var S=w.numPoints||1;f+=w.x*S,d+=w.y*S,p+=S,w.parentId=m,a&&(g||(g=this._map(u,!0)),a(g,this._map(w)));}}1===p?r.push(u):(u.parentId=m,r.push(q(f/p,d/p,m,p,g)));}}return r},W.prototype._getOriginId=function(e){return e-this.points.length>>5},W.prototype._getOriginZoom=function(e){return (e-this.points.length)%32},W.prototype._map=function(e,t){if(e.numPoints)return t?ee({},e.properties):e.properties;var r=this.points[e.index].properties,i=this.options.map(r);return t&&i===r?ee({},i):i},ke.prototype.options={maxZoom:14,indexMaxZoom:5,indexMaxPoints:1e5,tolerance:3,extent:4096,buffer:64,lineMetrics:!1,promoteId:null,generateId:!1,debug:0},ke.prototype.splitTile=function(e,t,r,i,o,n,a){for(var s=[e,t,r,i],l=this.options,u=l.debug;s.length;){i=s.pop(),r=s.pop(),t=s.pop(),e=s.pop();var h=1<<t,c=Te(t,r,i),p=this.tiles[c];if(!p&&(u>1&&console.time("creation"),p=this.tiles[c]=be(e,t,r,i,l),this.tileCoords.push({z:t,x:r,y:i}),u)){u>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,r,i,p.numFeatures,p.numPoints,p.numSimplified),console.timeEnd("creation"));var f="z"+t;this.stats[f]=(this.stats[f]||0)+1,this.total++;}if(p.source=e,o){if(t===l.maxZoom||t===o)continue;var d=1<<o-t;if(r!==Math.floor(n/d)||i!==Math.floor(a/d))continue}else if(t===l.indexMaxZoom||p.numPoints<=l.indexMaxPoints)continue;if(p.source=null,0!==e.length){u>1&&console.time("clipping");var g,m,v,y,x,w,S=.5*l.buffer/l.extent,M=.5-S,I=.5+S,b=1+S;g=m=v=y=null,x=pe(e,h,r-S,r+I,0,p.minX,p.maxX,l),w=pe(e,h,r+M,r+b,0,p.minX,p.maxX,l),e=null,x&&(g=pe(x,h,i-S,i+I,1,p.minY,p.maxY,l),m=pe(x,h,i+M,i+b,1,p.minY,p.maxY,l),x=null),w&&(v=pe(w,h,i-S,i+I,1,p.minY,p.maxY,l),y=pe(w,h,i+M,i+b,1,p.minY,p.maxY,l),w=null),u>1&&console.timeEnd("clipping"),s.push(g||[],t+1,2*r,2*i),s.push(m||[],t+1,2*r,2*i+1),s.push(v||[],t+1,2*r+1,2*i),s.push(y||[],t+1,2*r+1,2*i+1);}}},ke.prototype.getTile=function(e,t,r){var i=this.options,o=i.extent,n=i.debug;if(e<0||e>24)return null;var a=1<<e,s=Te(e,t=(t%a+a)%a,r);if(this.tiles[s])return Me(this.tiles[s],o);n>1&&console.log("drilling down to z%d-%d-%d",e,t,r);for(var l,u=e,h=t,c=r;!l&&u>0;)u--,h=Math.floor(h/2),c=Math.floor(c/2),l=this.tiles[Te(u,h,c)];return l&&l.source?(n>1&&console.log("found parent tile z%d-%d-%d",u,h,c),n>1&&console.time("drilling down"),this.splitTile(l.source,u,h,c,e,t,r),n>1&&console.timeEnd("drilling down"),this.tiles[s]?Me(this.tiles[s],o):null):null};var De=function(t){function r(e,r,i,o){t.call(this,e,r,i,Ce),o&&(this.loadGeoJSON=o);}return t&&(r.__proto__=t),r.prototype=Object.create(t&&t.prototype),r.prototype.constructor=r,r.prototype.loadData=function(e,t){this._pendingCallback&&this._pendingCallback(null,{abandoned:!0}),this._pendingCallback=t,this._pendingLoadDataParams=e,this._state&&"Idle"!==this._state?this._state="NeedsLoadData":(this._state="Coalescing",this._loadData());},r.prototype._loadData=function(){var t=this;if(this._pendingCallback&&this._pendingLoadDataParams){var r=this._pendingCallback,i=this._pendingLoadDataParams;delete this._pendingCallback,delete this._pendingLoadDataParams;var o=!!(i&&i.request&&i.request.collectResourceTiming)&&new e.RequestPerformance(i.request);this.loadGeoJSON(i,(function(n,a){if(n||!a)return r(n);if("object"!=typeof a)return r(new Error("Input data given to '"+i.source+"' is not a valid GeoJSON object."));m(a,!0);try{t._geoJSONIndex=i.cluster?new W(function(t){var r=t.superclusterOptions,i=t.clusterProperties;if(!i||!r)return r;for(var o={},n={},a={accumulated:null,zoom:0},s={properties:null},l=Object.keys(i),u=0,h=l;u<h.length;u+=1){var c=h[u],p=i[c],f=p[0],d=p[1],g=e.createExpression(d),m=e.createExpression("string"==typeof f?[f,["accumulated"],["get",c]]:f);o[c]=g.value,n[c]=m.value;}return r.map=function(e){s.properties=e;for(var t={},r=0,i=l;r<i.length;r+=1){var n=i[r];t[n]=o[n].evaluate(a,s);}return t},r.reduce=function(e,t){s.properties=t;for(var r=0,i=l;r<i.length;r+=1){var o=i[r];a.accumulated=e[o],e[o]=n[o].evaluate(a,s);}},r}(i)).load(a.features):function(e,t){return new ke(e,t)}(a,i.geojsonVtOptions);}catch(n){return r(n)}t.loaded={};var s={};if(o){var l=o.finish();l&&(s.resourceTiming={},s.resourceTiming[i.source]=JSON.parse(JSON.stringify(l)));}r(null,s);}));}},r.prototype.coalesce=function(){"Coalescing"===this._state?this._state="Idle":"NeedsLoadData"===this._state&&(this._state="Coalescing",this._loadData());},r.prototype.reloadTile=function(e,r){var i=this.loaded,o=e.uid;return i&&i[o]?t.prototype.reloadTile.call(this,e,r):this.loadTile(e,r)},r.prototype.loadGeoJSON=function(t,r){if(t.request)e.getJSON(t.request,r);else{if("string"!=typeof t.data)return r(new Error("Input data given to '"+t.source+"' is not a valid GeoJSON object."));try{return r(null,JSON.parse(t.data))}catch(e){return r(new Error("Input data given to '"+t.source+"' is not a valid GeoJSON object."))}}},r.prototype.removeSource=function(e,t){this._pendingCallback&&this._pendingCallback(null,{abandoned:!0}),t();},r.prototype.getClusterExpansionZoom=function(e,t){try{t(null,this._geoJSONIndex.getClusterExpansionZoom(e.clusterId));}catch(e){t(e);}},r.prototype.getClusterChildren=function(e,t){try{t(null,this._geoJSONIndex.getChildren(e.clusterId));}catch(e){t(e);}},r.prototype.getClusterLeaves=function(e,t){try{t(null,this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset));}catch(e){t(e);}},r}(l);var Le=function(t){var r=this;this.self=t,this.actor=new e.Actor(t,this),this.layerIndexes={},this.availableImages={},this.workerSourceTypes={vector:l,geojson:De},this.workerSources={},this.demWorkerSources={},this.self.registerWorkerSource=function(e,t){if(r.workerSourceTypes[e])throw new Error('Worker source with name "'+e+'" already registered.');r.workerSourceTypes[e]=t;},this.self.registerRTLTextPlugin=function(t){if(e.plugin.isParsed())throw new Error("RTL text plugin already registered.");e.plugin.applyArabicShaping=t.applyArabicShaping,e.plugin.processBidirectionalText=t.processBidirectionalText,e.plugin.processStyledBidirectionalText=t.processStyledBidirectionalText;};};return Le.prototype.setReferrer=function(e,t){this.referrer=t;},Le.prototype.setImages=function(e,t,r){this.availableImages[e]=t,r();},Le.prototype.setLayers=function(e,t,r){this.getLayerIndex(e).replace(t),r();},Le.prototype.updateLayers=function(e,t,r){this.getLayerIndex(e).update(t.layers,t.removedIds),r();},Le.prototype.loadTile=function(e,t,r){this.getWorkerSource(e,t.type,t.source).loadTile(t,r);},Le.prototype.loadDEMTile=function(e,t,r){this.getDEMWorkerSource(e,t.source).loadTile(t,r);},Le.prototype.reloadTile=function(e,t,r){this.getWorkerSource(e,t.type,t.source).reloadTile(t,r);},Le.prototype.abortTile=function(e,t,r){this.getWorkerSource(e,t.type,t.source).abortTile(t,r);},Le.prototype.removeTile=function(e,t,r){this.getWorkerSource(e,t.type,t.source).removeTile(t,r);},Le.prototype.removeDEMTile=function(e,t){this.getDEMWorkerSource(e,t.source).removeTile(t);},Le.prototype.removeSource=function(e,t,r){if(this.workerSources[e]&&this.workerSources[e][t.type]&&this.workerSources[e][t.type][t.source]){var i=this.workerSources[e][t.type][t.source];delete this.workerSources[e][t.type][t.source],void 0!==i.removeSource?i.removeSource(t,r):r();}},Le.prototype.loadWorkerSource=function(e,t,r){try{this.self.importScripts(t.url),r();}catch(e){r(e.toString());}},Le.prototype.syncRTLPluginState=function(t,r,i){try{e.plugin.setState(r);var o=e.plugin.getPluginURL();if(e.plugin.isLoaded()&&!e.plugin.isParsed()&&null!=o){this.self.importScripts(o);var n=e.plugin.isParsed();i(n?void 0:new Error("RTL Text Plugin failed to import scripts from "+o),n);}}catch(e){i(e.toString());}},Le.prototype.getAvailableImages=function(e){var t=this.availableImages[e];return t||(t=[]),t},Le.prototype.getLayerIndex=function(e){var t=this.layerIndexes[e];return t||(t=this.layerIndexes[e]=new i),t},Le.prototype.getWorkerSource=function(e,t,r){var i=this;if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),!this.workerSources[e][t][r]){var o={send:function(t,r,o){i.actor.send(t,r,o,e);}};this.workerSources[e][t][r]=new this.workerSourceTypes[t](o,this.getLayerIndex(e),this.getAvailableImages(e));}return this.workerSources[e][t][r]},Le.prototype.getDEMWorkerSource=function(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new h),this.demWorkerSources[e][t]},Le.prototype.enforceCacheSizeLimit=function(t,r){e.enforceCacheSizeLimit(r);},"undefined"!=typeof WorkerGlobalScope&&void 0!==e.window&&e.window instanceof WorkerGlobalScope&&(e.window.worker=new Le(e.window)),Le}));
define(["./shared"],(function(t){"use strict";var e=t.createCommonjsModule((function(t){function e(t){return !!("undefined"!=typeof window&&"undefined"!=typeof document&&Array.prototype&&Array.prototype.every&&Array.prototype.filter&&Array.prototype.forEach&&Array.prototype.indexOf&&Array.prototype.lastIndexOf&&Array.prototype.map&&Array.prototype.some&&Array.prototype.reduce&&Array.prototype.reduceRight&&Array.isArray&&Function.prototype&&Function.prototype.bind&&Object.keys&&Object.create&&Object.getPrototypeOf&&Object.getOwnPropertyNames&&Object.isSealed&&Object.isFrozen&&Object.isExtensible&&Object.getOwnPropertyDescriptor&&Object.defineProperty&&Object.defineProperties&&Object.seal&&Object.freeze&&Object.preventExtensions&&"JSON"in window&&"parse"in JSON&&"stringify"in JSON&&function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return !1;var t,e,i=new Blob([""],{type:"text/javascript"}),o=URL.createObjectURL(i);try{e=new Worker(o),t=!0;}catch(e){t=!1;}e&&e.terminate();return URL.revokeObjectURL(o),t}()&&"Uint8ClampedArray"in window&&ArrayBuffer.isView&&function(t){void 0===i[t]&&(i[t]=function(t){var i=document.createElement("canvas"),o=Object.create(e.webGLContextAttributes);return o.failIfMajorPerformanceCaveat=t,i.probablySupportsContext?i.probablySupportsContext("webgl",o)||i.probablySupportsContext("experimental-webgl",o):i.supportsContext?i.supportsContext("webgl",o)||i.supportsContext("experimental-webgl",o):i.getContext("webgl",o)||i.getContext("experimental-webgl",o)}(t));return i[t]}(t&&t.failIfMajorPerformanceCaveat))}t.exports?t.exports=e:window&&(window.mapboxgl=window.mapboxgl||{},window.mapboxgl.supported=e);var i={};e.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0};})),i={create:function(e,i,o){var r=t.window.document.createElement(e);return void 0!==i&&(r.className=i),o&&o.appendChild(r),r},createNS:function(e,i){return t.window.document.createElementNS(e,i)}},o=t.window.document.documentElement.style;function r(t){if(!o)return t[0];for(var e=0;e<t.length;e++)if(t[e]in o)return t[e];return t[0]}var a,n=r(["userSelect","MozUserSelect","WebkitUserSelect","msUserSelect"]);i.disableDrag=function(){o&&n&&(a=o[n],o[n]="none");},i.enableDrag=function(){o&&n&&(o[n]=a);};var s=r(["transform","WebkitTransform"]);i.setTransform=function(t,e){t.style[s]=e;};var l=!1;try{var c=Object.defineProperty({},"passive",{get:function(){l=!0;}});t.window.addEventListener("test",c,c),t.window.removeEventListener("test",c,c);}catch(t){l=!1;}i.addEventListener=function(t,e,i,o){void 0===o&&(o={}),"passive"in o&&l?t.addEventListener(e,i,o):t.addEventListener(e,i,o.capture);},i.removeEventListener=function(t,e,i,o){void 0===o&&(o={}),"passive"in o&&l?t.removeEventListener(e,i,o):t.removeEventListener(e,i,o.capture);};var u=function(e){e.preventDefault(),e.stopPropagation(),t.window.removeEventListener("click",u,!0);};function h(t){var e=t.userImage;if(e&&e.render&&e.render())return t.data.replace(new Uint8Array(e.data.buffer)),!0;return !1}i.suppressClick=function(){t.window.addEventListener("click",u,!0),t.window.setTimeout((function(){t.window.removeEventListener("click",u,!0);}),0);},i.mousePos=function(e,i){var o=e.getBoundingClientRect(),r=t.window.TouchEvent&&i instanceof t.window.TouchEvent?i.touches[0]:i;return new t.Point(r.clientX-o.left-e.clientLeft,r.clientY-o.top-e.clientTop)},i.touchPos=function(e,i){for(var o=e.getBoundingClientRect(),r=[],a="touchend"===i.type?i.changedTouches:i.touches,n=0;n<a.length;n++)r.push(new t.Point(a[n].clientX-o.left-e.clientLeft,a[n].clientY-o.top-e.clientTop));return r},i.mouseButton=function(e){return void 0!==t.window.InstallTrigger&&2===e.button&&e.ctrlKey&&t.window.navigator.platform.toUpperCase().indexOf("MAC")>=0?0:e.button},i.remove=function(t){t.parentNode&&t.parentNode.removeChild(t);};var p=function(e){function i(){e.call(this),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.RGBAImage({width:1,height:1}),this.dirty=!0;}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.isLoaded=function(){return this.loaded},i.prototype.setLoaded=function(t){if(this.loaded!==t&&(this.loaded=t,t)){for(var e=0,i=this.requestors;e<i.length;e+=1){var o=i[e],r=o.ids,a=o.callback;this._notify(r,a);}this.requestors=[];}},i.prototype.getImage=function(t){return this.images[t]},i.prototype.addImage=function(t,e){this._validate(t,e)&&(this.images[t]=e);},i.prototype._validate=function(e,i){var o=!0;return this._validateStretch(i.stretchX,i.data&&i.data.width)||(this.fire(new t.ErrorEvent(new Error('Image "'+e+'" has invalid "stretchX" value'))),o=!1),this._validateStretch(i.stretchY,i.data&&i.data.height)||(this.fire(new t.ErrorEvent(new Error('Image "'+e+'" has invalid "stretchY" value'))),o=!1),this._validateContent(i.content,i)||(this.fire(new t.ErrorEvent(new Error('Image "'+e+'" has invalid "content" value'))),o=!1),o},i.prototype._validateStretch=function(t,e){if(!t)return !0;for(var i=0,o=0,r=t;o<r.length;o+=1){var a=r[o];if(a[0]<i||a[1]<a[0]||e<a[1])return !1;i=a[1];}return !0},i.prototype._validateContent=function(t,e){return !t||4===t.length&&(!(t[0]<0||e.data.width<t[0])&&(!(t[1]<0||e.data.height<t[1])&&(!(t[2]<0||e.data.width<t[2])&&(!(t[3]<0||e.data.height<t[3])&&(!(t[2]<t[0])&&!(t[3]<t[1]))))))},i.prototype.updateImage=function(t,e){var i=this.images[t];e.version=i.version+1,this.images[t]=e,this.updatedImages[t]=!0;},i.prototype.removeImage=function(t){var e=this.images[t];delete this.images[t],delete this.patterns[t],e.userImage&&e.userImage.onRemove&&e.userImage.onRemove();},i.prototype.listImages=function(){return Object.keys(this.images)},i.prototype.getImages=function(t,e){var i=!0;if(!this.isLoaded())for(var o=0,r=t;o<r.length;o+=1){var a=r[o];this.images[a]||(i=!1);}this.isLoaded()||i?this._notify(t,e):this.requestors.push({ids:t,callback:e});},i.prototype._notify=function(e,i){for(var o={},r=0,a=e;r<a.length;r+=1){var n=a[r];this.images[n]||this.fire(new t.Event("styleimagemissing",{id:n}));var s=this.images[n];s?o[n]={data:s.data.clone(),pixelRatio:s.pixelRatio,sdf:s.sdf,version:s.version,stretchX:s.stretchX,stretchY:s.stretchY,content:s.content,hasRenderCallback:Boolean(s.userImage&&s.userImage.render)}:t.warnOnce('Image "'+n+'" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.');}i(null,o);},i.prototype.getPixelSize=function(){var t=this.atlasImage;return {width:t.width,height:t.height}},i.prototype.getPattern=function(e){var i=this.patterns[e],o=this.getImage(e);if(!o)return null;if(i&&i.position.version===o.version)return i.position;if(i)i.position.version=o.version;else{var r={w:o.data.width+2,h:o.data.height+2,x:0,y:0},a=new t.ImagePosition(r,o);this.patterns[e]={bin:r,position:a};}return this._updatePatternAtlas(),this.patterns[e].position},i.prototype.bind=function(e){var i=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new t.Texture(e,this.atlasImage,i.RGBA),this.atlasTexture.bind(i.LINEAR,i.CLAMP_TO_EDGE);},i.prototype._updatePatternAtlas=function(){var e=[];for(var i in this.patterns)e.push(this.patterns[i].bin);var o=t.potpack(e),r=o.w,a=o.h,n=this.atlasImage;for(var s in n.resize({width:r||1,height:a||1}),this.patterns){var l=this.patterns[s].bin,c=l.x+1,u=l.y+1,h=this.images[s].data,p=h.width,d=h.height;t.RGBAImage.copy(h,n,{x:0,y:0},{x:c,y:u},{width:p,height:d}),t.RGBAImage.copy(h,n,{x:0,y:d-1},{x:c,y:u-1},{width:p,height:1}),t.RGBAImage.copy(h,n,{x:0,y:0},{x:c,y:u+d},{width:p,height:1}),t.RGBAImage.copy(h,n,{x:p-1,y:0},{x:c-1,y:u},{width:1,height:d}),t.RGBAImage.copy(h,n,{x:0,y:0},{x:c+p,y:u},{width:1,height:d});}this.dirty=!0;},i.prototype.beginFrame=function(){this.callbackDispatchedThisFrame={};},i.prototype.dispatchRenderCallbacks=function(t){for(var e=0,i=t;e<i.length;e+=1){var o=i[e];if(!this.callbackDispatchedThisFrame[o]){this.callbackDispatchedThisFrame[o]=!0;var r=this.images[o];h(r)&&this.updateImage(o,r);}}},i}(t.Evented);var d=m,_=m,f=1e20;function m(t,e,i,o,r,a){this.fontSize=t||24,this.buffer=void 0===e?3:e,this.cutoff=o||.25,this.fontFamily=r||"sans-serif",this.fontWeight=a||"normal",this.radius=i||8;var n=this.size=this.fontSize+2*this.buffer;this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=n,this.ctx=this.canvas.getContext("2d"),this.ctx.font=this.fontWeight+" "+this.fontSize+"px "+this.fontFamily,this.ctx.textBaseline="middle",this.ctx.fillStyle="black",this.gridOuter=new Float64Array(n*n),this.gridInner=new Float64Array(n*n),this.f=new Float64Array(n),this.d=new Float64Array(n),this.z=new Float64Array(n+1),this.v=new Int16Array(n),this.middle=Math.round(n/2*(navigator.userAgent.indexOf("Gecko/")>=0?1.2:1));}function g(t,e,i,o,r,a,n){for(var s=0;s<e;s++){for(var l=0;l<i;l++)o[l]=t[l*e+s];for(v(o,r,a,n,i),l=0;l<i;l++)t[l*e+s]=r[l];}for(l=0;l<i;l++){for(s=0;s<e;s++)o[s]=t[l*e+s];for(v(o,r,a,n,e),s=0;s<e;s++)t[l*e+s]=Math.sqrt(r[s]);}}function v(t,e,i,o,r){i[0]=0,o[0]=-f,o[1]=+f;for(var a=1,n=0;a<r;a++){for(var s=(t[a]+a*a-(t[i[n]]+i[n]*i[n]))/(2*a-2*i[n]);s<=o[n];)n--,s=(t[a]+a*a-(t[i[n]]+i[n]*i[n]))/(2*a-2*i[n]);i[++n]=a,o[n]=s,o[n+1]=+f;}for(a=0,n=0;a<r;a++){for(;o[n+1]<a;)n++;e[a]=(a-i[n])*(a-i[n])+t[i[n]];}}m.prototype.draw=function(t){this.ctx.clearRect(0,0,this.size,this.size),this.ctx.fillText(t,this.buffer,this.middle);for(var e=this.ctx.getImageData(0,0,this.size,this.size),i=new Uint8ClampedArray(this.size*this.size),o=0;o<this.size*this.size;o++){var r=e.data[4*o+3]/255;this.gridOuter[o]=1===r?0:0===r?f:Math.pow(Math.max(0,.5-r),2),this.gridInner[o]=1===r?f:0===r?0:Math.pow(Math.max(0,r-.5),2);}for(g(this.gridOuter,this.size,this.size,this.f,this.d,this.v,this.z),g(this.gridInner,this.size,this.size,this.f,this.d,this.v,this.z),o=0;o<this.size*this.size;o++){var a=this.gridOuter[o]-this.gridInner[o];i[o]=Math.max(0,Math.min(255,Math.round(255-255*(a/this.radius+this.cutoff))));}return i},d.default=_;var y=function(t,e){this.requestManager=t,this.localIdeographFontFamily=e,this.entries={};};y.prototype.setURL=function(t){this.url=t;},y.prototype.getGlyphs=function(e,i){var o=this,r=[];for(var a in e)for(var n=0,s=e[a];n<s.length;n+=1){var l=s[n];r.push({stack:a,id:l});}t.asyncAll(r,(function(t,e){var i=t.stack,r=t.id,a=o.entries[i];a||(a=o.entries[i]={glyphs:{},requests:{}});var n=a.glyphs[r];if(void 0===n){if(n=o._tinySDF(a,i,r))return a.glyphs[r]=n,void e(null,{stack:i,id:r,glyph:n});var s=Math.floor(r/256);if(256*s>65535)e(new Error("glyphs > 65535 not supported"));else{var l=a.requests[s];l||(l=a.requests[s]=[],y.loadGlyphRange(i,s,o.url,o.requestManager,(function(t,e){if(e)for(var i in e)o._doesCharSupportLocalGlyph(+i)||(a.glyphs[+i]=e[+i]);for(var r=0,n=l;r<n.length;r+=1){(0,n[r])(t,e);}delete a.requests[s];}))),l.push((function(t,o){t?e(t):o&&e(null,{stack:i,id:r,glyph:o[r]||null});}));}}else e(null,{stack:i,id:r,glyph:n});}),(function(t,e){if(t)i(t);else if(e){for(var o={},r=0,a=e;r<a.length;r+=1){var n=a[r],s=n.stack,l=n.id,c=n.glyph;(o[s]||(o[s]={}))[l]=c&&{id:c.id,bitmap:c.bitmap.clone(),metrics:c.metrics};}i(null,o);}}));},y.prototype._doesCharSupportLocalGlyph=function(e){return !!this.localIdeographFontFamily&&(t.isChar["CJK Unified Ideographs"](e)||t.isChar["Hangul Syllables"](e)||t.isChar.Hiragana(e)||t.isChar.Katakana(e))},y.prototype._tinySDF=function(e,i,o){var r=this.localIdeographFontFamily;if(r&&this._doesCharSupportLocalGlyph(o)){var a=e.tinySDF;if(!a){var n="400";/bold/i.test(i)?n="900":/medium/i.test(i)?n="500":/light/i.test(i)&&(n="200"),a=e.tinySDF=new y.TinySDF(24,3,8,.25,r,n);}return {id:o,bitmap:new t.AlphaImage({width:30,height:30},a.draw(String.fromCharCode(o))),metrics:{width:24,height:24,left:0,top:-8,advance:24}}}},y.loadGlyphRange=function(e,i,o,r,a){var n=256*i,s=n+255,l=r.transformRequest(r.normalizeGlyphsURL(o).replace("{fontstack}",e).replace("{range}",n+"-"+s),t.ResourceType.Glyphs);t.getArrayBuffer(l,(function(e,i){if(e)a(e);else if(i){for(var o={},r=0,n=t.parseGlyphPBF(i);r<n.length;r+=1){var s=n[r];o[s.id]=s;}a(null,o);}}));},y.TinySDF=d;var x=function(){this.specification=t.styleSpec.light.position;};x.prototype.possiblyEvaluate=function(e,i){return t.sphericalToCartesian(e.expression.evaluate(i))},x.prototype.interpolate=function(e,i,o){return {x:t.number(e.x,i.x,o),y:t.number(e.y,i.y,o),z:t.number(e.z,i.z,o)}};var b=new t.Properties({anchor:new t.DataConstantProperty(t.styleSpec.light.anchor),position:new x,color:new t.DataConstantProperty(t.styleSpec.light.color),intensity:new t.DataConstantProperty(t.styleSpec.light.intensity)}),w=function(e){function i(i){e.call(this),this._transitionable=new t.Transitionable(b),this.setLight(i),this._transitioning=this._transitionable.untransitioned();}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.getLight=function(){return this._transitionable.serialize()},i.prototype.setLight=function(e,i){if(void 0===i&&(i={}),!this._validate(t.validateLight,e,i))for(var o in e){var r=e[o];t.endsWith(o,"-transition")?this._transitionable.setTransition(o.slice(0,-"-transition".length),r):this._transitionable.setValue(o,r);}},i.prototype.updateTransitions=function(t){this._transitioning=this._transitionable.transitioned(t,this._transitioning);},i.prototype.hasTransition=function(){return this._transitioning.hasTransition()},i.prototype.recalculate=function(t){this.properties=this._transitioning.possiblyEvaluate(t);},i.prototype._validate=function(e,i,o){return (!o||!1!==o.validate)&&t.emitValidationErrors(this,e.call(t.validateStyle,t.extend({value:i,style:{glyphs:!0,sprite:!0},styleSpec:t.styleSpec})))},i}(t.Evented),E=function(t,e){this.width=t,this.height=e,this.nextRow=0,this.data=new Uint8Array(this.width*this.height),this.dashEntry={};};E.prototype.getDash=function(t,e){var i=t.join(",")+String(e);return this.dashEntry[i]||(this.dashEntry[i]=this.addDash(t,e)),this.dashEntry[i]},E.prototype.getDashRanges=function(t,e,i){var o=[],r=t.length%2==1?-t[t.length-1]*i:0,a=t[0]*i,n=!0;o.push({left:r,right:a,isDash:n,zeroLength:0===t[0]});for(var s=t[0],l=1;l<t.length;l++){n=!n;var c=t[l];r=s*i,a=(s+=c)*i,o.push({left:r,right:a,isDash:n,zeroLength:0===c});}return o},E.prototype.addRoundDash=function(t,e,i){for(var o=e/2,r=-i;r<=i;r++)for(var a=this.nextRow+i+r,n=this.width*a,s=0,l=t[s],c=0;c<this.width;c++){c/l.right>1&&(l=t[++s]);var u=Math.abs(c-l.left),h=Math.abs(c-l.right),p=Math.min(u,h),d=void 0,_=r/i*(o+1);if(l.isDash){var f=o-Math.abs(_);d=Math.sqrt(p*p+f*f);}else d=o-Math.sqrt(p*p+_*_);this.data[n+c]=Math.max(0,Math.min(255,d+128));}},E.prototype.addRegularDash=function(t){for(var e=t.length-1;e>=0;--e){var i=t[e],o=t[e+1];i.zeroLength?t.splice(e,1):o&&o.isDash===i.isDash&&(o.left=i.left,t.splice(e,1));}var r=t[0],a=t[t.length-1];r.isDash===a.isDash&&(r.left=a.left-this.width,a.right=r.right+this.width);for(var n=this.width*this.nextRow,s=0,l=t[s],c=0;c<this.width;c++){c/l.right>1&&(l=t[++s]);var u=Math.abs(c-l.left),h=Math.abs(c-l.right),p=Math.min(u,h),d=l.isDash?p:-p;this.data[n+c]=Math.max(0,Math.min(255,d+128));}},E.prototype.addDash=function(e,i){var o=i?7:0,r=2*o+1;if(this.nextRow+r>this.height)return t.warnOnce("LineAtlas out of space"),null;for(var a=0,n=0;n<e.length;n++)a+=e[n];var s=this.width/a,l=this.getDashRanges(e,this.width,s);i?this.addRoundDash(l,s,o):this.addRegularDash(l);var c={y:(this.nextRow+o+.5)/this.height,height:2*o/this.height,width:a};return this.nextRow+=r,this.dirty=!0,c},E.prototype.bind=function(t){var e=t.gl;this.texture?(e.bindTexture(e.TEXTURE_2D,this.texture),this.dirty&&(this.dirty=!1,e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.width,this.height,e.ALPHA,e.UNSIGNED_BYTE,this.data))):(this.texture=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texImage2D(e.TEXTURE_2D,0,e.ALPHA,this.width,this.height,0,e.ALPHA,e.UNSIGNED_BYTE,this.data));};var T=function e(i,o){this.workerPool=i,this.actors=[],this.currentActor=0,this.id=t.uniqueId();for(var r=this.workerPool.acquire(this.id),a=0;a<r.length;a++){var n=r[a],s=new e.Actor(n,o,this.id);s.name="Worker "+a,this.actors.push(s);}};function I(e,i,o){var r=function(r,a){if(r)return o(r);if(a){var n=t.pick(t.extend(a,e),["tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","scheme","tileSize","encoding"]);a.vector_layers&&(n.vectorLayers=a.vector_layers,n.vectorLayerIds=n.vectorLayers.map((function(t){return t.id}))),n.tiles=i.canonicalizeTileset(n,e.url),o(null,n);}};return e.url?t.getJSON(i.transformRequest(i.normalizeSourceURL(e.url),t.ResourceType.Source),r):t.browser.frame((function(){return r(null,e)}))}T.prototype.broadcast=function(e,i,o){o=o||function(){},t.asyncAll(this.actors,(function(t,o){t.send(e,i,o);}),o);},T.prototype.getActor=function(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]},T.prototype.remove=function(){this.actors.forEach((function(t){t.remove();})),this.actors=[],this.workerPool.release(this.id);},T.Actor=t.Actor;var S=function(e,i,o){this.bounds=t.LngLatBounds.convert(this.validateBounds(e)),this.minzoom=i||0,this.maxzoom=o||24;};S.prototype.validateBounds=function(t){return Array.isArray(t)&&4===t.length?[Math.max(-180,t[0]),Math.max(-90,t[1]),Math.min(180,t[2]),Math.min(90,t[3])]:[-180,-90,180,90]},S.prototype.contains=function(e){var i=Math.pow(2,e.z),o=Math.floor(t.mercatorXfromLng(this.bounds.getWest())*i),r=Math.floor(t.mercatorYfromLat(this.bounds.getNorth())*i),a=Math.ceil(t.mercatorXfromLng(this.bounds.getEast())*i),n=Math.ceil(t.mercatorYfromLat(this.bounds.getSouth())*i);return e.x>=o&&e.x<a&&e.y>=r&&e.y<n};var C=function(e){function i(i,o,r,a){if(e.call(this),this.id=i,this.dispatcher=r,this.type="vector",this.minzoom=0,this.maxzoom=22,this.scheme="xyz",this.tileSize=512,this.reparseOverscaled=!0,this.isTileClipped=!0,this._loaded=!1,t.extend(this,t.pick(o,["url","scheme","tileSize","promoteId"])),this._options=t.extend({type:"vector"},o),this._collectResourceTiming=o.collectResourceTiming,512!==this.tileSize)throw new Error("vector tile sources must have a tileSize of 512");this.setEventedParent(a);}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){var e=this;this._loaded=!1,this.fire(new t.Event("dataloading",{dataType:"source"})),this._tileJSONRequest=I(this._options,this.map._requestManager,(function(i,o){e._tileJSONRequest=null,e._loaded=!0,i?e.fire(new t.ErrorEvent(i)):o&&(t.extend(e,o),o.bounds&&(e.tileBounds=new S(o.bounds,e.minzoom,e.maxzoom)),t.postTurnstileEvent(o.tiles,e.map._requestManager._customAccessToken),t.postMapLoadEvent(o.tiles,e.map._getMapId(),e.map._requestManager._skuToken,e.map._requestManager._customAccessToken),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})));}));},i.prototype.loaded=function(){return this._loaded},i.prototype.hasTile=function(t){return !this.tileBounds||this.tileBounds.contains(t.canonical)},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.onRemove=function(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null);},i.prototype.serialize=function(){return t.extend({},this._options)},i.prototype.loadTile=function(e,i){var o=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme)),r={request:this.map._requestManager.transformRequest(o,t.ResourceType.Tile),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:t.browser.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId};function a(o,r){return delete e.request,e.aborted?i(null):o&&404!==o.status?i(o):(r&&r.resourceTiming&&(e.resourceTiming=r.resourceTiming),this.map._refreshExpiredTiles&&r&&e.setExpiryData(r),e.loadVectorData(r,this.map.painter),t.cacheEntryPossiblyAdded(this.dispatcher),i(null),void(e.reloadCallback&&(this.loadTile(e,e.reloadCallback),e.reloadCallback=null)))}r.request.collectResourceTiming=this._collectResourceTiming,e.actor&&"expired"!==e.state?"loading"===e.state?e.reloadCallback=i:e.request=e.actor.send("reloadTile",r,a.bind(this)):(e.actor=this.dispatcher.getActor(),e.request=e.actor.send("loadTile",r,a.bind(this)));},i.prototype.abortTile=function(t){t.request&&(t.request.cancel(),delete t.request),t.actor&&t.actor.send("abortTile",{uid:t.uid,type:this.type,source:this.id},void 0);},i.prototype.unloadTile=function(t){t.unloadVectorData(),t.actor&&t.actor.send("removeTile",{uid:t.uid,type:this.type,source:this.id},void 0);},i.prototype.hasTransition=function(){return !1},i}(t.Evented),P=function(e){function i(i,o,r,a){e.call(this),this.id=i,this.dispatcher=r,this.setEventedParent(a),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.extend({type:"raster"},o),t.extend(this,t.pick(o,["url","scheme","tileSize"]));}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){var e=this;this._loaded=!1,this.fire(new t.Event("dataloading",{dataType:"source"})),this._tileJSONRequest=I(this._options,this.map._requestManager,(function(i,o){e._tileJSONRequest=null,e._loaded=!0,i?e.fire(new t.ErrorEvent(i)):o&&(t.extend(e,o),o.bounds&&(e.tileBounds=new S(o.bounds,e.minzoom,e.maxzoom)),t.postTurnstileEvent(o.tiles),t.postMapLoadEvent(o.tiles,e.map._getMapId(),e.map._requestManager._skuToken),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})));}));},i.prototype.loaded=function(){return this._loaded},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.onRemove=function(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null);},i.prototype.serialize=function(){return t.extend({},this._options)},i.prototype.hasTile=function(t){return !this.tileBounds||this.tileBounds.contains(t.canonical)},i.prototype.loadTile=function(e,i){var o=this,r=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme),this.tileSize);e.request=t.getImage(this.map._requestManager.transformRequest(r,t.ResourceType.Tile),(function(r,a){if(delete e.request,e.aborted)e.state="unloaded",i(null);else if(r)e.state="errored",i(r);else if(a){o.map._refreshExpiredTiles&&e.setExpiryData(a),delete a.cacheControl,delete a.expires;var n=o.map.painter.context,s=n.gl;e.texture=o.map.painter.getTileTexture(a.width),e.texture?e.texture.update(a,{useMipmap:!0}):(e.texture=new t.Texture(n,a,s.RGBA,{useMipmap:!0}),e.texture.bind(s.LINEAR,s.CLAMP_TO_EDGE,s.LINEAR_MIPMAP_NEAREST),n.extTextureFilterAnisotropic&&s.texParameterf(s.TEXTURE_2D,n.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,n.extTextureFilterAnisotropicMax)),e.state="loaded",t.cacheEntryPossiblyAdded(o.dispatcher),i(null);}}));},i.prototype.abortTile=function(t,e){t.request&&(t.request.cancel(),delete t.request),e();},i.prototype.unloadTile=function(t,e){t.texture&&this.map.painter.saveTileTexture(t.texture),e();},i.prototype.hasTransition=function(){return !1},i}(t.Evented),z=function(e){function i(i,o,r,a){e.call(this,i,o,r,a),this.type="raster-dem",this.maxzoom=22,this._options=t.extend({type:"raster-dem"},o),this.encoding=o.encoding||"mapbox";}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.serialize=function(){return {type:"raster-dem",url:this.url,tileSize:this.tileSize,tiles:this.tiles,bounds:this.bounds,encoding:this.encoding}},i.prototype.loadTile=function(e,i){var o=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme),this.tileSize);function r(t,o){t&&(e.state="errored",i(t)),o&&(e.dem=o,e.needsHillshadePrepare=!0,e.state="loaded",i(null));}e.request=t.getImage(this.map._requestManager.transformRequest(o,t.ResourceType.Tile),function(o,a){if(delete e.request,e.aborted)e.state="unloaded",i(null);else if(o)e.state="errored",i(o);else if(a){this.map._refreshExpiredTiles&&e.setExpiryData(a),delete a.cacheControl,delete a.expires;var n=t.window.ImageBitmap&&a instanceof t.window.ImageBitmap&&t.offscreenCanvasSupported()?a:t.browser.getImageData(a,1),s={uid:e.uid,coord:e.tileID,source:this.id,rawImageData:n,encoding:this.encoding};e.actor&&"expired"!==e.state||(e.actor=this.dispatcher.getActor(),e.actor.send("loadDEMTile",s,r.bind(this)));}}.bind(this)),e.neighboringTiles=this._getNeighboringTiles(e.tileID);},i.prototype._getNeighboringTiles=function(e){var i=e.canonical,o=Math.pow(2,i.z),r=(i.x-1+o)%o,a=0===i.x?e.wrap-1:e.wrap,n=(i.x+1+o)%o,s=i.x+1===o?e.wrap+1:e.wrap,l={};return l[new t.OverscaledTileID(e.overscaledZ,a,i.z,r,i.y).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,n,i.y).key]={backfilled:!1},i.y>0&&(l[new t.OverscaledTileID(e.overscaledZ,a,i.z,r,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,n,i.y-1).key]={backfilled:!1}),i.y+1<o&&(l[new t.OverscaledTileID(e.overscaledZ,a,i.z,r,i.y+1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,i.z,i.x,i.y+1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,n,i.y+1).key]={backfilled:!1}),l},i.prototype.unloadTile=function(t){t.demTexture&&this.map.painter.saveTileTexture(t.demTexture),t.fbo&&(t.fbo.destroy(),delete t.fbo),t.dem&&delete t.dem,delete t.neighboringTiles,t.state="unloaded",t.actor&&t.actor.send("removeDEMTile",{uid:t.uid,source:this.id});},i}(P),L=function(e){function i(i,o,r,a){e.call(this),this.id=i,this.type="geojson",this.minzoom=0,this.maxzoom=18,this.tileSize=512,this.isTileClipped=!0,this.reparseOverscaled=!0,this._removed=!1,this._loaded=!1,this.actor=r.getActor(),this.setEventedParent(a),this._data=o.data,this._options=t.extend({},o),this._collectResourceTiming=o.collectResourceTiming,this._resourceTiming=[],void 0!==o.maxzoom&&(this.maxzoom=o.maxzoom),o.type&&(this.type=o.type),o.attribution&&(this.attribution=o.attribution),this.promoteId=o.promoteId;var n=t.EXTENT/this.tileSize;this.workerOptions=t.extend({source:this.id,cluster:o.cluster||!1,geojsonVtOptions:{buffer:(void 0!==o.buffer?o.buffer:128)*n,tolerance:(void 0!==o.tolerance?o.tolerance:.375)*n,extent:t.EXTENT,maxZoom:this.maxzoom,lineMetrics:o.lineMetrics||!1,generateId:o.generateId||!1},superclusterOptions:{maxZoom:void 0!==o.clusterMaxZoom?Math.min(o.clusterMaxZoom,this.maxzoom-1):this.maxzoom-1,extent:t.EXTENT,radius:(o.clusterRadius||50)*n,log:!1,generateId:o.generateId||!1},clusterProperties:o.clusterProperties},o.workerOptions);}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){var e=this;this.fire(new t.Event("dataloading",{dataType:"source"})),this._updateWorkerData((function(i){if(i)e.fire(new t.ErrorEvent(i));else{var o={dataType:"source",sourceDataType:"metadata"};e._collectResourceTiming&&e._resourceTiming&&e._resourceTiming.length>0&&(o.resourceTiming=e._resourceTiming,e._resourceTiming=[]),e.fire(new t.Event("data",o));}}));},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.setData=function(e){var i=this;return this._data=e,this.fire(new t.Event("dataloading",{dataType:"source"})),this._updateWorkerData((function(e){if(e)i.fire(new t.ErrorEvent(e));else{var o={dataType:"source",sourceDataType:"content"};i._collectResourceTiming&&i._resourceTiming&&i._resourceTiming.length>0&&(o.resourceTiming=i._resourceTiming,i._resourceTiming=[]),i.fire(new t.Event("data",o));}})),this},i.prototype.getClusterExpansionZoom=function(t,e){return this.actor.send("geojson.getClusterExpansionZoom",{clusterId:t,source:this.id},e),this},i.prototype.getClusterChildren=function(t,e){return this.actor.send("geojson.getClusterChildren",{clusterId:t,source:this.id},e),this},i.prototype.getClusterLeaves=function(t,e,i,o){return this.actor.send("geojson.getClusterLeaves",{source:this.id,clusterId:t,limit:e,offset:i},o),this},i.prototype._updateWorkerData=function(e){var i=this;this._loaded=!1;var o=t.extend({},this.workerOptions),r=this._data;"string"==typeof r?(o.request=this.map._requestManager.transformRequest(t.browser.resolveURL(r),t.ResourceType.Source),o.request.collectResourceTiming=this._collectResourceTiming):o.data=JSON.stringify(r),this.actor.send(this.type+".loadData",o,(function(t,r){i._removed||r&&r.abandoned||(i._loaded=!0,r&&r.resourceTiming&&r.resourceTiming[i.id]&&(i._resourceTiming=r.resourceTiming[i.id].slice(0)),i.actor.send(i.type+".coalesce",{source:o.source},null),e(t));}));},i.prototype.loaded=function(){return this._loaded},i.prototype.loadTile=function(e,i){var o=this,r=e.actor?"reloadTile":"loadTile";e.actor=this.actor;var a={type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:t.browser.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId};e.request=this.actor.send(r,a,(function(t,a){return delete e.request,e.unloadVectorData(),e.aborted?i(null):t?i(t):(e.loadVectorData(a,o.map.painter,"reloadTile"===r),i(null))}));},i.prototype.abortTile=function(t){t.request&&(t.request.cancel(),delete t.request),t.aborted=!0;},i.prototype.unloadTile=function(t){t.unloadVectorData(),this.actor.send("removeTile",{uid:t.uid,type:this.type,source:this.id});},i.prototype.onRemove=function(){this._removed=!0,this.actor.send("removeSource",{type:this.type,source:this.id});},i.prototype.serialize=function(){return t.extend({},this._options,{type:this.type,data:this._data})},i.prototype.hasTransition=function(){return !1},i}(t.Evented),M=t.createLayout([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]),D=function(e){function i(t,i,o,r){e.call(this),this.id=t,this.dispatcher=o,this.coordinates=i.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(r),this.options=i;}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(e,i){var o=this;this._loaded=!1,this.fire(new t.Event("dataloading",{dataType:"source"})),this.url=this.options.url,t.getImage(this.map._requestManager.transformRequest(this.url,t.ResourceType.Image),(function(r,a){o._loaded=!0,r?o.fire(new t.ErrorEvent(r)):a&&(o.image=a,e&&(o.coordinates=e),i&&i(),o._finishLoading());}));},i.prototype.loaded=function(){return this._loaded},i.prototype.updateImage=function(t){var e=this;return this.image&&t.url?(this.options.url=t.url,this.load(t.coordinates,(function(){e.texture=null;})),this):this},i.prototype._finishLoading=function(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})));},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.setCoordinates=function(e){var i=this;this.coordinates=e;var o=e.map(t.MercatorCoordinate.fromLngLat);this.tileID=function(e){for(var i=1/0,o=1/0,r=-1/0,a=-1/0,n=0,s=e;n<s.length;n+=1){var l=s[n];i=Math.min(i,l.x),o=Math.min(o,l.y),r=Math.max(r,l.x),a=Math.max(a,l.y);}var c=r-i,u=a-o,h=Math.max(c,u),p=Math.max(0,Math.floor(-Math.log(h)/Math.LN2)),d=Math.pow(2,p);return new t.CanonicalTileID(p,Math.floor((i+r)/2*d),Math.floor((o+a)/2*d))}(o),this.minzoom=this.maxzoom=this.tileID.z;var r=o.map((function(t){return i.tileID.getTilePoint(t)._round()}));return this._boundsArray=new t.StructArrayLayout4i8,this._boundsArray.emplaceBack(r[0].x,r[0].y,0,0),this._boundsArray.emplaceBack(r[1].x,r[1].y,t.EXTENT,0),this._boundsArray.emplaceBack(r[3].x,r[3].y,0,t.EXTENT),this._boundsArray.emplaceBack(r[2].x,r[2].y,t.EXTENT,t.EXTENT),this.boundsBuffer&&(this.boundsBuffer.destroy(),delete this.boundsBuffer),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})),this},i.prototype.prepare=function(){if(0!==Object.keys(this.tiles).length&&this.image){var e=this.map.painter.context,i=e.gl;for(var o in this.boundsBuffer||(this.boundsBuffer=e.createVertexBuffer(this._boundsArray,M.members)),this.boundsSegments||(this.boundsSegments=t.SegmentVector.simpleSegment(0,0,4,2)),this.texture||(this.texture=new t.Texture(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE)),this.tiles){var r=this.tiles[o];"loaded"!==r.state&&(r.state="loaded",r.texture=this.texture);}}},i.prototype.loadTile=function(t,e){this.tileID&&this.tileID.equals(t.tileID.canonical)?(this.tiles[String(t.tileID.wrap)]=t,t.buckets={},e(null)):(t.state="errored",e(null));},i.prototype.serialize=function(){return {type:"image",url:this.options.url,coordinates:this.coordinates}},i.prototype.hasTransition=function(){return !1},i}(t.Evented);var A=function(e){function i(t,i,o,r){e.call(this,t,i,o,r),this.roundZoom=!0,this.type="video",this.options=i;}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){var e=this;this._loaded=!1;var i=this.options;this.urls=[];for(var o=0,r=i.urls;o<r.length;o+=1){var a=r[o];this.urls.push(this.map._requestManager.transformRequest(a,t.ResourceType.Source).url);}t.getVideo(this.urls,(function(i,o){e._loaded=!0,i?e.fire(new t.ErrorEvent(i)):o&&(e.video=o,e.video.loop=!0,e.video.addEventListener("playing",(function(){e.map.triggerRepaint();})),e.map&&e.video.play(),e._finishLoading());}));},i.prototype.pause=function(){this.video&&this.video.pause();},i.prototype.play=function(){this.video&&this.video.play();},i.prototype.seek=function(e){if(this.video){var i=this.video.seekable;e<i.start(0)||e>i.end(0)?this.fire(new t.ErrorEvent(new t.ValidationError("sources."+this.id,null,"Playback for this video can be set only between the "+i.start(0)+" and "+i.end(0)+"-second mark."))):this.video.currentTime=e;}},i.prototype.getVideo=function(){return this.video},i.prototype.onAdd=function(t){this.map||(this.map=t,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));},i.prototype.prepare=function(){if(!(0===Object.keys(this.tiles).length||this.video.readyState<2)){var e=this.map.painter.context,i=e.gl;for(var o in this.boundsBuffer||(this.boundsBuffer=e.createVertexBuffer(this._boundsArray,M.members)),this.boundsSegments||(this.boundsSegments=t.SegmentVector.simpleSegment(0,0,4,2)),this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new t.Texture(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE)),this.tiles){var r=this.tiles[o];"loaded"!==r.state&&(r.state="loaded",r.texture=this.texture);}}},i.prototype.serialize=function(){return {type:"video",urls:this.urls,coordinates:this.coordinates}},i.prototype.hasTransition=function(){return this.video&&!this.video.paused},i}(D),R=function(e){function i(i,o,r,a){e.call(this,i,o,r,a),o.coordinates?Array.isArray(o.coordinates)&&4===o.coordinates.length&&!o.coordinates.some((function(t){return !Array.isArray(t)||2!==t.length||t.some((function(t){return "number"!=typeof t}))}))||this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'missing required property "coordinates"'))),o.animate&&"boolean"!=typeof o.animate&&this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'optional "animate" property must be a boolean value'))),o.canvas?"string"==typeof o.canvas||o.canvas instanceof t.window.HTMLCanvasElement||this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'missing required property "canvas"'))),this.options=o,this.animate=void 0===o.animate||o.animate;}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.load=function(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof t.window.HTMLCanvasElement?this.options.canvas:t.window.document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.ErrorEvent(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());},i.prototype.getCanvas=function(){return this.canvas},i.prototype.onAdd=function(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play();},i.prototype.onRemove=function(){this.pause();},i.prototype.prepare=function(){var e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),!this._hasInvalidDimensions()&&0!==Object.keys(this.tiles).length){var i=this.map.painter.context,o=i.gl;for(var r in this.boundsBuffer||(this.boundsBuffer=i.createVertexBuffer(this._boundsArray,M.members)),this.boundsSegments||(this.boundsSegments=t.SegmentVector.simpleSegment(0,0,4,2)),this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new t.Texture(i,this.canvas,o.RGBA,{premultiply:!0}),this.tiles){var a=this.tiles[r];"loaded"!==a.state&&(a.state="loaded",a.texture=this.texture);}}},i.prototype.serialize=function(){return {type:"canvas",coordinates:this.coordinates}},i.prototype.hasTransition=function(){return this._playing},i.prototype._hasInvalidDimensions=function(){for(var t=0,e=[this.canvas.width,this.canvas.height];t<e.length;t+=1){var i=e[t];if(isNaN(i)||i<=0)return !0}return !1},i}(D),k={vector:C,raster:P,"raster-dem":z,geojson:L,video:A,image:D,canvas:R},B=function(e,i,o,r){var a=new k[i.type](e,i,o,r);if(a.id!==e)throw new Error("Expected Source id to be "+e+" instead of "+a.id);return t.bindAll(["load","abort","unload","serialize","prepare"],a),a};function O(e,i){var o=t.identity([]);return t.translate(o,o,[1,1,0]),t.scale(o,o,[.5*e.width,.5*e.height,1]),t.multiply(o,o,e.calculatePosMatrix(i.toUnwrapped()))}function F(t,e,i,o,r){var a=function(t,e,i){if(t)for(var o=0,r=t;o<r.length;o+=1){var a=e[r[o]];if(a&&a.source===i&&"fill-extrusion"===a.type)return !0}else for(var n in e){var s=e[n];if(s.source===i&&"fill-extrusion"===s.type)return !0}return !1}(o&&o.layers,e,t.id),n=r.maxPitchScaleFactor(),s=t.tilesIn(i,n,a);s.sort(U);for(var l=[],c=0,u=s;c<u.length;c+=1){var h=u[c];l.push({wrappedTileID:h.tileID.wrapped().key,queryResults:h.tile.queryRenderedFeatures(e,t._state,h.queryGeometry,h.cameraQueryGeometry,h.scale,o,r,n,O(t.transform,h.tileID))});}var p=function(t){for(var e={},i={},o=0,r=t;o<r.length;o+=1){var a=r[o],n=a.queryResults,s=a.wrappedTileID,l=i[s]=i[s]||{};for(var c in n)for(var u=n[c],h=l[c]=l[c]||{},p=e[c]=e[c]||[],d=0,_=u;d<_.length;d+=1){var f=_[d];h[f.featureIndex]||(h[f.featureIndex]=!0,p.push(f));}}return e}(l);for(var d in p)p[d].forEach((function(e){var i=e.feature,o=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=o;}));return p}function U(t,e){var i=t.tileID,o=e.tileID;return i.overscaledZ-o.overscaledZ||i.canonical.y-o.canonical.y||i.wrap-o.wrap||i.canonical.x-o.canonical.x}var N=function(t,e){this.max=t,this.onRemove=e,this.reset();};N.prototype.reset=function(){for(var t in this.data)for(var e=0,i=this.data[t];e<i.length;e+=1){var o=i[e];o.timeout&&clearTimeout(o.timeout),this.onRemove(o.value);}return this.data={},this.order=[],this},N.prototype.add=function(t,e,i){var o=this,r=t.wrapped().key;void 0===this.data[r]&&(this.data[r]=[]);var a={value:e,timeout:void 0};if(void 0!==i&&(a.timeout=setTimeout((function(){o.remove(t,a);}),i)),this.data[r].push(a),this.order.push(r),this.order.length>this.max){var n=this._getAndRemoveByKey(this.order[0]);n&&this.onRemove(n);}return this},N.prototype.has=function(t){return t.wrapped().key in this.data},N.prototype.getAndRemove=function(t){return this.has(t)?this._getAndRemoveByKey(t.wrapped().key):null},N.prototype._getAndRemoveByKey=function(t){var e=this.data[t].shift();return e.timeout&&clearTimeout(e.timeout),0===this.data[t].length&&delete this.data[t],this.order.splice(this.order.indexOf(t),1),e.value},N.prototype.getByKey=function(t){var e=this.data[t];return e?e[0].value:null},N.prototype.get=function(t){return this.has(t)?this.data[t.wrapped().key][0].value:null},N.prototype.remove=function(t,e){if(!this.has(t))return this;var i=t.wrapped().key,o=void 0===e?0:this.data[i].indexOf(e),r=this.data[i][o];return this.data[i].splice(o,1),r.timeout&&clearTimeout(r.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(r.value),this.order.splice(this.order.indexOf(i),1),this},N.prototype.setMaxSize=function(t){for(this.max=t;this.order.length>this.max;){var e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this},N.prototype.filter=function(t){var e=[];for(var i in this.data)for(var o=0,r=this.data[i];o<r.length;o+=1){var a=r[o];t(a.value)||e.push(a);}for(var n=0,s=e;n<s.length;n+=1){var l=s[n];this.remove(l.value.tileID,l);}};var Z=function(t,e,i){this.context=t;var o=t.gl;this.buffer=o.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),t.bindElementBuffer.set(this.buffer),o.bufferData(o.ELEMENT_ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer;};Z.prototype.bind=function(){this.context.bindElementBuffer.set(this.buffer);},Z.prototype.updateData=function(t){var e=this.context.gl;this.context.unbindVAO(),this.bind(),e.bufferSubData(e.ELEMENT_ARRAY_BUFFER,0,t.arrayBuffer);},Z.prototype.destroy=function(){var t=this.context.gl;this.buffer&&(t.deleteBuffer(this.buffer),delete this.buffer);};var q={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"},j=function(t,e,i,o){this.length=e.length,this.attributes=i,this.itemSize=e.bytesPerElement,this.dynamicDraw=o,this.context=t;var r=t.gl;this.buffer=r.createBuffer(),t.bindVertexBuffer.set(this.buffer),r.bufferData(r.ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer;};j.prototype.bind=function(){this.context.bindVertexBuffer.set(this.buffer);},j.prototype.updateData=function(t){var e=this.context.gl;this.bind(),e.bufferSubData(e.ARRAY_BUFFER,0,t.arrayBuffer);},j.prototype.enableAttributes=function(t,e){for(var i=0;i<this.attributes.length;i++){var o=this.attributes[i],r=e.attributes[o.name];void 0!==r&&t.enableVertexAttribArray(r);}},j.prototype.setVertexAttribPointers=function(t,e,i){for(var o=0;o<this.attributes.length;o++){var r=this.attributes[o],a=e.attributes[r.name];void 0!==a&&t.vertexAttribPointer(a,r.components,t[q[r.type]],!1,this.itemSize,r.offset+this.itemSize*(i||0));}},j.prototype.destroy=function(){var t=this.context.gl;this.buffer&&(t.deleteBuffer(this.buffer),delete this.buffer);};var V=function(t){this.gl=t.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1;};V.prototype.get=function(){return this.current},V.prototype.set=function(t){},V.prototype.getDefault=function(){return this.default},V.prototype.setDefault=function(){this.set(this.default);};var G=function(e){function i(){e.apply(this,arguments);}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.getDefault=function(){return t.Color.transparent},i.prototype.set=function(t){var e=this.current;(t.r!==e.r||t.g!==e.g||t.b!==e.b||t.a!==e.a||this.dirty)&&(this.gl.clearColor(t.r,t.g,t.b,t.a),this.current=t,this.dirty=!1);},i}(V),W=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return 1},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.clearDepth(t),this.current=t,this.dirty=!1);},e}(V),X=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return 0},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.clearStencil(t),this.current=t,this.dirty=!1);},e}(V),H=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return [!0,!0,!0,!0]},e.prototype.set=function(t){var e=this.current;(t[0]!==e[0]||t[1]!==e[1]||t[2]!==e[2]||t[3]!==e[3]||this.dirty)&&(this.gl.colorMask(t[0],t[1],t[2],t[3]),this.current=t,this.dirty=!1);},e}(V),K=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return !0},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.depthMask(t),this.current=t,this.dirty=!1);},e}(V),Y=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return 255},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.stencilMask(t),this.current=t,this.dirty=!1);},e}(V),J=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return {func:this.gl.ALWAYS,ref:0,mask:255}},e.prototype.set=function(t){var e=this.current;(t.func!==e.func||t.ref!==e.ref||t.mask!==e.mask||this.dirty)&&(this.gl.stencilFunc(t.func,t.ref,t.mask),this.current=t,this.dirty=!1);},e}(V),Q=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){var t=this.gl;return [t.KEEP,t.KEEP,t.KEEP]},e.prototype.set=function(t){var e=this.current;(t[0]!==e[0]||t[1]!==e[1]||t[2]!==e[2]||this.dirty)&&(this.gl.stencilOp(t[0],t[1],t[2]),this.current=t,this.dirty=!1);},e}(V),$=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;t?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.current=t,this.dirty=!1;}},e}(V),tt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return [0,1]},e.prototype.set=function(t){var e=this.current;(t[0]!==e[0]||t[1]!==e[1]||this.dirty)&&(this.gl.depthRange(t[0],t[1]),this.current=t,this.dirty=!1);},e}(V),et=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;t?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this.current=t,this.dirty=!1;}},e}(V),it=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return this.gl.LESS},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.depthFunc(t),this.current=t,this.dirty=!1);},e}(V),ot=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;t?e.enable(e.BLEND):e.disable(e.BLEND),this.current=t,this.dirty=!1;}},e}(V),rt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){var t=this.gl;return [t.ONE,t.ZERO]},e.prototype.set=function(t){var e=this.current;(t[0]!==e[0]||t[1]!==e[1]||this.dirty)&&(this.gl.blendFunc(t[0],t[1]),this.current=t,this.dirty=!1);},e}(V),at=function(e){function i(){e.apply(this,arguments);}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.getDefault=function(){return t.Color.transparent},i.prototype.set=function(t){var e=this.current;(t.r!==e.r||t.g!==e.g||t.b!==e.b||t.a!==e.a||this.dirty)&&(this.gl.blendColor(t.r,t.g,t.b,t.a),this.current=t,this.dirty=!1);},i}(V),nt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return this.gl.FUNC_ADD},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.blendEquation(t),this.current=t,this.dirty=!1);},e}(V),st=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;t?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this.current=t,this.dirty=!1;}},e}(V),lt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return this.gl.BACK},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.cullFace(t),this.current=t,this.dirty=!1);},e}(V),ct=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return this.gl.CCW},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.frontFace(t),this.current=t,this.dirty=!1);},e}(V),ut=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.useProgram(t),this.current=t,this.dirty=!1);},e}(V),ht=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return this.gl.TEXTURE0},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.activeTexture(t),this.current=t,this.dirty=!1);},e}(V),pt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){var t=this.gl;return [0,0,t.drawingBufferWidth,t.drawingBufferHeight]},e.prototype.set=function(t){var e=this.current;(t[0]!==e[0]||t[1]!==e[1]||t[2]!==e[2]||t[3]!==e[3]||this.dirty)&&(this.gl.viewport(t[0],t[1],t[2],t[3]),this.current=t,this.dirty=!1);},e}(V),dt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,t),this.current=t,this.dirty=!1;}},e}(V),_t=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.bindRenderbuffer(e.RENDERBUFFER,t),this.current=t,this.dirty=!1;}},e}(V),ft=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.bindTexture(e.TEXTURE_2D,t),this.current=t,this.dirty=!1;}},e}(V),mt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.bindBuffer(e.ARRAY_BUFFER,t),this.current=t,this.dirty=!1;}},e}(V),gt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){var e=this.gl;e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t),this.current=t,this.dirty=!1;},e}(V),vt=function(t){function e(e){t.call(this,e),this.vao=e.extVertexArrayObject;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){this.vao&&(t!==this.current||this.dirty)&&(this.vao.bindVertexArrayOES(t),this.current=t,this.dirty=!1);},e}(V),yt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return 4},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.pixelStorei(e.UNPACK_ALIGNMENT,t),this.current=t,this.dirty=!1;}},e}(V),xt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t),this.current=t,this.dirty=!1;}},e}(V),bt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,t),this.current=t,this.dirty=!1;}},e}(V),wt=function(t){function e(e,i){t.call(this,e),this.context=e,this.parent=i;}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDefault=function(){return null},e}(V),Et=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.setDirty=function(){this.dirty=!0;},e.prototype.set=function(t){if(t!==this.current||this.dirty){this.context.bindFramebuffer.set(this.parent);var e=this.gl;e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.current=t,this.dirty=!1;}},e}(wt),Tt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(t!==this.current||this.dirty){this.context.bindFramebuffer.set(this.parent);var e=this.gl;e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t),this.current=t,this.dirty=!1;}},e}(wt),It=function(t,e,i){this.context=t,this.width=e,this.height=i;var o=t.gl,r=this.framebuffer=o.createFramebuffer();this.colorAttachment=new Et(t,r),this.depthAttachment=new Tt(t,r);};It.prototype.destroy=function(){var t=this.context.gl,e=this.colorAttachment.get();e&&t.deleteTexture(e);var i=this.depthAttachment.get();i&&t.deleteRenderbuffer(i),t.deleteFramebuffer(this.framebuffer);};var St=function(t,e,i){this.func=t,this.mask=e,this.range=i;};St.ReadOnly=!1,St.ReadWrite=!0,St.disabled=new St(519,St.ReadOnly,[0,1]);var Ct=function(t,e,i,o,r,a){this.test=t,this.ref=e,this.mask=i,this.fail=o,this.depthFail=r,this.pass=a;};Ct.disabled=new Ct({func:519,mask:0},0,0,7680,7680,7680);var Pt=function(t,e,i){this.blendFunction=t,this.blendColor=e,this.mask=i;};Pt.Replace=[1,0],Pt.disabled=new Pt(Pt.Replace,t.Color.transparent,[!1,!1,!1,!1]),Pt.unblended=new Pt(Pt.Replace,t.Color.transparent,[!0,!0,!0,!0]),Pt.alphaBlended=new Pt([1,771],t.Color.transparent,[!0,!0,!0,!0]);var zt=function(t,e,i){this.enable=t,this.mode=e,this.frontFace=i;};zt.disabled=new zt(!1,1029,2305),zt.backCCW=new zt(!0,1029,2305);var Lt=function(t){this.gl=t,this.extVertexArrayObject=this.gl.getExtension("OES_vertex_array_object"),this.clearColor=new G(this),this.clearDepth=new W(this),this.clearStencil=new X(this),this.colorMask=new H(this),this.depthMask=new K(this),this.stencilMask=new Y(this),this.stencilFunc=new J(this),this.stencilOp=new Q(this),this.stencilTest=new $(this),this.depthRange=new tt(this),this.depthTest=new et(this),this.depthFunc=new it(this),this.blend=new ot(this),this.blendFunc=new rt(this),this.blendColor=new at(this),this.blendEquation=new nt(this),this.cullFace=new st(this),this.cullFaceSide=new lt(this),this.frontFace=new ct(this),this.program=new ut(this),this.activeTexture=new ht(this),this.viewport=new pt(this),this.bindFramebuffer=new dt(this),this.bindRenderbuffer=new _t(this),this.bindTexture=new ft(this),this.bindVertexBuffer=new mt(this),this.bindElementBuffer=new gt(this),this.bindVertexArrayOES=this.extVertexArrayObject&&new vt(this),this.pixelStoreUnpack=new yt(this),this.pixelStoreUnpackPremultiplyAlpha=new xt(this),this.pixelStoreUnpackFlipY=new bt(this),this.extTextureFilterAnisotropic=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=t.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)),this.extTextureHalfFloat=t.getExtension("OES_texture_half_float"),this.extTextureHalfFloat&&t.getExtension("OES_texture_half_float_linear"),this.extTimerQuery=t.getExtension("EXT_disjoint_timer_query");};Lt.prototype.setDefault=function(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault();},Lt.prototype.setDirty=function(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.extVertexArrayObject&&(this.bindVertexArrayOES.dirty=!0),this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0;},Lt.prototype.createIndexBuffer=function(t,e){return new Z(this,t,e)},Lt.prototype.createVertexBuffer=function(t,e,i){return new j(this,t,e,i)},Lt.prototype.createRenderbuffer=function(t,e,i){var o=this.gl,r=o.createRenderbuffer();return this.bindRenderbuffer.set(r),o.renderbufferStorage(o.RENDERBUFFER,t,e,i),this.bindRenderbuffer.set(null),r},Lt.prototype.createFramebuffer=function(t,e){return new It(this,t,e)},Lt.prototype.clear=function(t){var e=t.color,i=t.depth,o=this.gl,r=0;e&&(r|=o.COLOR_BUFFER_BIT,this.clearColor.set(e),this.colorMask.set([!0,!0,!0,!0])),void 0!==i&&(r|=o.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(i),this.depthMask.set(!0)),o.clear(r);},Lt.prototype.setCullFace=function(t){!1===t.enable?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(t.mode),this.frontFace.set(t.frontFace));},Lt.prototype.setDepthMode=function(t){t.func!==this.gl.ALWAYS||t.mask?(this.depthTest.set(!0),this.depthFunc.set(t.func),this.depthMask.set(t.mask),this.depthRange.set(t.range)):this.depthTest.set(!1);},Lt.prototype.setStencilMode=function(t){t.test.func!==this.gl.ALWAYS||t.mask?(this.stencilTest.set(!0),this.stencilMask.set(t.mask),this.stencilOp.set([t.fail,t.depthFail,t.pass]),this.stencilFunc.set({func:t.test.func,ref:t.ref,mask:t.test.mask})):this.stencilTest.set(!1);},Lt.prototype.setColorMode=function(e){t.deepEqual(e.blendFunction,Pt.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(e.blendFunction),this.blendColor.set(e.blendColor)),this.colorMask.set(e.mask);},Lt.prototype.unbindVAO=function(){this.extVertexArrayObject&&this.bindVertexArrayOES.set(null);};var Mt=function(e){function i(i,o,r){var a=this;e.call(this),this.id=i,this.dispatcher=r,this.on("data",(function(t){"source"===t.dataType&&"metadata"===t.sourceDataType&&(a._sourceLoaded=!0),a._sourceLoaded&&!a._paused&&"source"===t.dataType&&"content"===t.sourceDataType&&(a.reload(),a.transform&&a.update(a.transform));})),this.on("error",(function(){a._sourceErrored=!0;})),this._source=B(i,o,r,this),this._tiles={},this._cache=new N(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new t.SourceFeatureState;}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.onAdd=function(t){this.map=t,this._maxTileCacheSize=t?t._maxTileCacheSize:null,this._source&&this._source.onAdd&&this._source.onAdd(t);},i.prototype.onRemove=function(t){this._source&&this._source.onRemove&&this._source.onRemove(t);},i.prototype.loaded=function(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;for(var t in this._tiles){var e=this._tiles[t];if("loaded"!==e.state&&"errored"!==e.state)return !1}return !0},i.prototype.getSource=function(){return this._source},i.prototype.pause=function(){this._paused=!0;},i.prototype.resume=function(){if(this._paused){var t=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,t&&this.reload(),this.transform&&this.update(this.transform);}},i.prototype._loadTile=function(t,e){return this._source.loadTile(t,e)},i.prototype._unloadTile=function(t){if(this._source.unloadTile)return this._source.unloadTile(t,(function(){}))},i.prototype._abortTile=function(t){if(this._source.abortTile)return this._source.abortTile(t,(function(){}))},i.prototype.serialize=function(){return this._source.serialize()},i.prototype.prepare=function(t){for(var e in this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null),this._tiles){var i=this._tiles[e];i.upload(t),i.prepare(this.map.style.imageManager);}},i.prototype.getIds=function(){return t.values(this._tiles).map((function(t){return t.tileID})).sort(Dt).map((function(t){return t.key}))},i.prototype.getRenderableIds=function(e){var i=this,o=[];for(var r in this._tiles)this._isIdRenderable(r,e)&&o.push(this._tiles[r]);return e?o.sort((function(e,o){var r=e.tileID,a=o.tileID,n=new t.Point(r.canonical.x,r.canonical.y)._rotate(i.transform.angle),s=new t.Point(a.canonical.x,a.canonical.y)._rotate(i.transform.angle);return r.overscaledZ-a.overscaledZ||s.y-n.y||s.x-n.x})).map((function(t){return t.tileID.key})):o.map((function(t){return t.tileID})).sort(Dt).map((function(t){return t.key}))},i.prototype.hasRenderableParent=function(t){var e=this.findLoadedParent(t,0);return !!e&&this._isIdRenderable(e.tileID.key)},i.prototype._isIdRenderable=function(t,e){return this._tiles[t]&&this._tiles[t].hasData()&&!this._coveredTiles[t]&&(e||!this._tiles[t].holdingForFade())},i.prototype.reload=function(){if(this._paused)this._shouldReloadOnResume=!0;else for(var t in this._cache.reset(),this._tiles)"errored"!==this._tiles[t].state&&this._reloadTile(t,"reloading");},i.prototype._reloadTile=function(t,e){var i=this._tiles[t];i&&("loading"!==i.state&&(i.state=e),this._loadTile(i,this._tileLoaded.bind(this,i,t,e)));},i.prototype._tileLoaded=function(e,i,o,r){if(r)return e.state="errored",void(404!==r.status?this._source.fire(new t.ErrorEvent(r,{tile:e})):this.update(this.transform));e.timeAdded=t.browser.now(),"expired"===o&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null),this._source.fire(new t.Event("data",{dataType:"source",tile:e,coord:e.tileID}));},i.prototype._backfillDEM=function(t){for(var e=this.getRenderableIds(),i=0;i<e.length;i++){var o=e[i];if(t.neighboringTiles&&t.neighboringTiles[o]){var r=this.getTileByID(o);a(t,r),a(r,t);}}function a(t,e){t.needsHillshadePrepare=!0;var i=e.tileID.canonical.x-t.tileID.canonical.x,o=e.tileID.canonical.y-t.tileID.canonical.y,r=Math.pow(2,t.tileID.canonical.z),a=e.tileID.key;0===i&&0===o||Math.abs(o)>1||(Math.abs(i)>1&&(1===Math.abs(i+r)?i+=r:1===Math.abs(i-r)&&(i-=r)),e.dem&&t.dem&&(t.dem.backfillBorder(e.dem,i,o),t.neighboringTiles&&t.neighboringTiles[a]&&(t.neighboringTiles[a].backfilled=!0)));}},i.prototype.getTile=function(t){return this.getTileByID(t.key)},i.prototype.getTileByID=function(t){return this._tiles[t]},i.prototype._retainLoadedChildren=function(t,e,i,o){for(var r in this._tiles){var a=this._tiles[r];if(!(o[r]||!a.hasData()||a.tileID.overscaledZ<=e||a.tileID.overscaledZ>i)){for(var n=a.tileID;a&&a.tileID.overscaledZ>e+1;){var s=a.tileID.scaledTo(a.tileID.overscaledZ-1);(a=this._tiles[s.key])&&a.hasData()&&(n=s);}for(var l=n;l.overscaledZ>e;)if(t[(l=l.scaledTo(l.overscaledZ-1)).key]){o[n.key]=n;break}}}},i.prototype.findLoadedParent=function(t,e){if(t.key in this._loadedParentTiles){var i=this._loadedParentTiles[t.key];return i&&i.tileID.overscaledZ>=e?i:null}for(var o=t.overscaledZ-1;o>=e;o--){var r=t.scaledTo(o),a=this._getLoadedTile(r);if(a)return a}},i.prototype._getLoadedTile=function(t){var e=this._tiles[t.key];return e&&e.hasData()?e:this._cache.getByKey(t.wrapped().key)},i.prototype.updateCacheSize=function(t){var e=(Math.ceil(t.width/this._source.tileSize)+1)*(Math.ceil(t.height/this._source.tileSize)+1),i=Math.floor(5*e),o="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,i):i;this._cache.setMaxSize(o);},i.prototype.handleWrapJump=function(t){var e=(t-(void 0===this._prevLng?t:this._prevLng))/360,i=Math.round(e);if(this._prevLng=t,i){var o={};for(var r in this._tiles){var a=this._tiles[r];a.tileID=a.tileID.unwrapTo(a.tileID.wrap+i),o[a.tileID.key]=a;}for(var n in this._tiles=o,this._timers)clearTimeout(this._timers[n]),delete this._timers[n];for(var s in this._tiles){var l=this._tiles[s];this._setTileReloadTimer(s,l);}}},i.prototype.update=function(e){var o=this;if(this.transform=e,this._sourceLoaded&&!this._paused){var r;this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used?this._source.tileID?r=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((function(e){return new t.OverscaledTileID(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y)})):(r=e.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}),this._source.hasTile&&(r=r.filter((function(t){return o._source.hasTile(t)})))):r=[];var a=e.coveringZoomLevel(this._source),n=Math.max(a-i.maxOverzooming,this._source.minzoom),s=Math.max(a+i.maxUnderzooming,this._source.minzoom),l=this._updateRetainedTiles(r,a);if(At(this._source.type)){for(var c={},u={},h=0,p=Object.keys(l);h<p.length;h+=1){var d=p[h],_=l[d],f=this._tiles[d];if(f&&!(f.fadeEndTime&&f.fadeEndTime<=t.browser.now())){var m=this.findLoadedParent(_,n);m&&(this._addTile(m.tileID),c[m.tileID.key]=m.tileID),u[d]=_;}}for(var g in this._retainLoadedChildren(u,a,s,l),c)l[g]||(this._coveredTiles[g]=!0,l[g]=c[g]);}for(var v in l)this._tiles[v].clearFadeHold();for(var y=0,x=t.keysDifference(this._tiles,l);y<x.length;y+=1){var b=x[y],w=this._tiles[b];w.hasSymbolBuckets&&!w.holdingForFade()?w.setHoldDuration(this.map._fadeDuration):w.hasSymbolBuckets&&!w.symbolFadeFinished()||this._removeTile(b);}this._updateLoadedParentTileCache();}},i.prototype.releaseSymbolFadeTiles=function(){for(var t in this._tiles)this._tiles[t].holdingForFade()&&this._removeTile(t);},i.prototype._updateRetainedTiles=function(t,e){for(var o={},r={},a=Math.max(e-i.maxOverzooming,this._source.minzoom),n=Math.max(e+i.maxUnderzooming,this._source.minzoom),s={},l=0,c=t;l<c.length;l+=1){var u=c[l],h=this._addTile(u);o[u.key]=u,h.hasData()||e<this._source.maxzoom&&(s[u.key]=u);}this._retainLoadedChildren(s,e,n,o);for(var p=0,d=t;p<d.length;p+=1){var _=d[p],f=this._tiles[_.key];if(!f.hasData()){if(e+1>this._source.maxzoom){var m=_.children(this._source.maxzoom)[0],g=this.getTile(m);if(g&&g.hasData()){o[m.key]=m;continue}}else{var v=_.children(this._source.maxzoom);if(o[v[0].key]&&o[v[1].key]&&o[v[2].key]&&o[v[3].key])continue}for(var y=f.wasRequested(),x=_.overscaledZ-1;x>=a;--x){var b=_.scaledTo(x);if(r[b.key])break;if(r[b.key]=!0,!(f=this.getTile(b))&&y&&(f=this._addTile(b)),f&&(o[b.key]=b,y=f.wasRequested(),f.hasData()))break}}}return o},i.prototype._updateLoadedParentTileCache=function(){for(var t in this._loadedParentTiles={},this._tiles){for(var e=[],i=void 0,o=this._tiles[t].tileID;o.overscaledZ>0;){if(o.key in this._loadedParentTiles){i=this._loadedParentTiles[o.key];break}e.push(o.key);var r=o.scaledTo(o.overscaledZ-1);if(i=this._getLoadedTile(r))break;o=r;}for(var a=0,n=e;a<n.length;a+=1){var s=n[a];this._loadedParentTiles[s]=i;}}},i.prototype._addTile=function(e){var i=this._tiles[e.key];if(i)return i;(i=this._cache.getAndRemove(e))&&(this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,i)));var o=Boolean(i);return o||(i=new t.Tile(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,this._tileLoaded.bind(this,i,e.key,i.state))),i?(i.uses++,this._tiles[e.key]=i,o||this._source.fire(new t.Event("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i):null},i.prototype._setTileReloadTimer=function(t,e){var i=this;t in this._timers&&(clearTimeout(this._timers[t]),delete this._timers[t]);var o=e.getExpiryTimeout();o&&(this._timers[t]=setTimeout((function(){i._reloadTile(t,"expired"),delete i._timers[t];}),o));},i.prototype._removeTile=function(t){var e=this._tiles[t];e&&(e.uses--,delete this._tiles[t],this._timers[t]&&(clearTimeout(this._timers[t]),delete this._timers[t]),e.uses>0||(e.hasData()&&"reloading"!==e.state?this._cache.add(e.tileID,e,e.getExpiryTimeout()):(e.aborted=!0,this._abortTile(e),this._unloadTile(e))));},i.prototype.clearTiles=function(){for(var t in this._shouldReloadOnResume=!1,this._paused=!1,this._tiles)this._removeTile(t);this._cache.reset();},i.prototype.tilesIn=function(e,i,o){var r=this,a=[],n=this.transform;if(!n)return a;for(var s=o?n.getCameraQueryGeometry(e):e,l=e.map((function(t){return n.pointCoordinate(t)})),c=s.map((function(t){return n.pointCoordinate(t)})),u=this.getIds(),h=1/0,p=1/0,d=-1/0,_=-1/0,f=0,m=c;f<m.length;f+=1){var g=m[f];h=Math.min(h,g.x),p=Math.min(p,g.y),d=Math.max(d,g.x),_=Math.max(_,g.y);}for(var v=function(e){var o=r._tiles[u[e]];if(!o.holdingForFade()){var s=o.tileID,f=Math.pow(2,n.zoom-o.tileID.overscaledZ),m=i*o.queryPadding*t.EXTENT/o.tileSize/f,g=[s.getTilePoint(new t.MercatorCoordinate(h,p)),s.getTilePoint(new t.MercatorCoordinate(d,_))];if(g[0].x-m<t.EXTENT&&g[0].y-m<t.EXTENT&&g[1].x+m>=0&&g[1].y+m>=0){var v=l.map((function(t){return s.getTilePoint(t)})),y=c.map((function(t){return s.getTilePoint(t)}));a.push({tile:o,tileID:s,queryGeometry:v,cameraQueryGeometry:y,scale:f});}}},y=0;y<u.length;y++)v(y);return a},i.prototype.getVisibleCoordinates=function(t){for(var e=this,i=this.getRenderableIds(t).map((function(t){return e._tiles[t].tileID})),o=0,r=i;o<r.length;o+=1){var a=r[o];a.posMatrix=this.transform.calculatePosMatrix(a.toUnwrapped());}return i},i.prototype.hasTransition=function(){if(this._source.hasTransition())return !0;if(At(this._source.type))for(var e in this._tiles){var i=this._tiles[e];if(void 0!==i.fadeEndTime&&i.fadeEndTime>=t.browser.now())return !0}return !1},i.prototype.setFeatureState=function(t,e,i){t=t||"_geojsonTileLayer",this._state.updateState(t,e,i);},i.prototype.removeFeatureState=function(t,e,i){t=t||"_geojsonTileLayer",this._state.removeFeatureState(t,e,i);},i.prototype.getFeatureState=function(t,e){return t=t||"_geojsonTileLayer",this._state.getState(t,e)},i.prototype.setDependencies=function(t,e,i){var o=this._tiles[t];o&&o.setDependencies(e,i);},i.prototype.reloadTilesForDependencies=function(t,e){for(var i in this._tiles){this._tiles[i].hasDependency(t,e)&&this._reloadTile(i,"reloading");}this._cache.filter((function(i){return !i.hasDependency(t,e)}));},i}(t.Evented);function Dt(t,e){var i=Math.abs(2*t.wrap)-+(t.wrap<0),o=Math.abs(2*e.wrap)-+(e.wrap<0);return t.overscaledZ-e.overscaledZ||o-i||e.canonical.y-t.canonical.y||e.canonical.x-t.canonical.x}function At(t){return "raster"===t||"image"===t||"video"===t}function Rt(){return new t.window.Worker(hr.workerUrl)}Mt.maxOverzooming=10,Mt.maxUnderzooming=3;var kt=function(){this.active={};};kt.prototype.acquire=function(t){if(!this.workers)for(this.workers=[];this.workers.length<kt.workerCount;)this.workers.push(new Rt);return this.active[t]=!0,this.workers.slice()},kt.prototype.release=function(t){delete this.active[t],0===Object.keys(this.active).length&&(this.workers.forEach((function(t){t.terminate();})),this.workers=null);};var Bt,Ot=Math.floor(t.browser.hardwareConcurrency/2);function Ft(e,i){var o={};for(var r in e)"ref"!==r&&(o[r]=e[r]);return t.refProperties.forEach((function(t){t in i&&(o[t]=i[t]);})),o}function Ut(t){t=t.slice();for(var e=Object.create(null),i=0;i<t.length;i++)e[t[i].id]=t[i];for(var o=0;o<t.length;o++)"ref"in t[o]&&(t[o]=Ft(t[o],e[t[o].ref]));return t}kt.workerCount=Math.max(Math.min(Ot,6),1);var Nt={setStyle:"setStyle",addLayer:"addLayer",removeLayer:"removeLayer",setPaintProperty:"setPaintProperty",setLayoutProperty:"setLayoutProperty",setFilter:"setFilter",addSource:"addSource",removeSource:"removeSource",setGeoJSONSourceData:"setGeoJSONSourceData",setLayerZoomRange:"setLayerZoomRange",setLayerProperty:"setLayerProperty",setCenter:"setCenter",setZoom:"setZoom",setBearing:"setBearing",setPitch:"setPitch",setSprite:"setSprite",setGlyphs:"setGlyphs",setTransition:"setTransition",setLight:"setLight"};function Zt(t,e,i){i.push({command:Nt.addSource,args:[t,e[t]]});}function qt(t,e,i){e.push({command:Nt.removeSource,args:[t]}),i[t]=!0;}function jt(t,e,i,o){qt(t,i,o),Zt(t,e,i);}function Vt(e,i,o){var r;for(r in e[o])if(e[o].hasOwnProperty(r)&&"data"!==r&&!t.deepEqual(e[o][r],i[o][r]))return !1;for(r in i[o])if(i[o].hasOwnProperty(r)&&"data"!==r&&!t.deepEqual(e[o][r],i[o][r]))return !1;return !0}function Gt(e,i,o,r,a,n){var s;for(s in i=i||{},e=e||{})e.hasOwnProperty(s)&&(t.deepEqual(e[s],i[s])||o.push({command:n,args:[r,s,i[s],a]}));for(s in i)i.hasOwnProperty(s)&&!e.hasOwnProperty(s)&&(t.deepEqual(e[s],i[s])||o.push({command:n,args:[r,s,i[s],a]}));}function Wt(t){return t.id}function Xt(t,e){return t[e.id]=e,t}function Ht(e,i){if(!e)return [{command:Nt.setStyle,args:[i]}];var o=[];try{if(!t.deepEqual(e.version,i.version))return [{command:Nt.setStyle,args:[i]}];t.deepEqual(e.center,i.center)||o.push({command:Nt.setCenter,args:[i.center]}),t.deepEqual(e.zoom,i.zoom)||o.push({command:Nt.setZoom,args:[i.zoom]}),t.deepEqual(e.bearing,i.bearing)||o.push({command:Nt.setBearing,args:[i.bearing]}),t.deepEqual(e.pitch,i.pitch)||o.push({command:Nt.setPitch,args:[i.pitch]}),t.deepEqual(e.sprite,i.sprite)||o.push({command:Nt.setSprite,args:[i.sprite]}),t.deepEqual(e.glyphs,i.glyphs)||o.push({command:Nt.setGlyphs,args:[i.glyphs]}),t.deepEqual(e.transition,i.transition)||o.push({command:Nt.setTransition,args:[i.transition]}),t.deepEqual(e.light,i.light)||o.push({command:Nt.setLight,args:[i.light]});var r={},a=[];!function(e,i,o,r){var a;for(a in i=i||{},e=e||{})e.hasOwnProperty(a)&&(i.hasOwnProperty(a)||qt(a,o,r));for(a in i)i.hasOwnProperty(a)&&(e.hasOwnProperty(a)?t.deepEqual(e[a],i[a])||("geojson"===e[a].type&&"geojson"===i[a].type&&Vt(e,i,a)?o.push({command:Nt.setGeoJSONSourceData,args:[a,i[a].data]}):jt(a,i,o,r)):Zt(a,i,o));}(e.sources,i.sources,a,r);var n=[];e.layers&&e.layers.forEach((function(t){r[t.source]?o.push({command:Nt.removeLayer,args:[t.id]}):n.push(t);})),o=o.concat(a),function(e,i,o){i=i||[];var r,a,n,s,l,c,u,h=(e=e||[]).map(Wt),p=i.map(Wt),d=e.reduce(Xt,{}),_=i.reduce(Xt,{}),f=h.slice(),m=Object.create(null);for(r=0,a=0;r<h.length;r++)n=h[r],_.hasOwnProperty(n)?a++:(o.push({command:Nt.removeLayer,args:[n]}),f.splice(f.indexOf(n,a),1));for(r=0,a=0;r<p.length;r++)n=p[p.length-1-r],f[f.length-1-r]!==n&&(d.hasOwnProperty(n)?(o.push({command:Nt.removeLayer,args:[n]}),f.splice(f.lastIndexOf(n,f.length-a),1)):a++,c=f[f.length-r],o.push({command:Nt.addLayer,args:[_[n],c]}),f.splice(f.length-r,0,n),m[n]=!0);for(r=0;r<p.length;r++)if(s=d[n=p[r]],l=_[n],!m[n]&&!t.deepEqual(s,l))if(t.deepEqual(s.source,l.source)&&t.deepEqual(s["source-layer"],l["source-layer"])&&t.deepEqual(s.type,l.type)){for(u in Gt(s.layout,l.layout,o,n,null,Nt.setLayoutProperty),Gt(s.paint,l.paint,o,n,null,Nt.setPaintProperty),t.deepEqual(s.filter,l.filter)||o.push({command:Nt.setFilter,args:[n,l.filter]}),t.deepEqual(s.minzoom,l.minzoom)&&t.deepEqual(s.maxzoom,l.maxzoom)||o.push({command:Nt.setLayerZoomRange,args:[n,l.minzoom,l.maxzoom]}),s)s.hasOwnProperty(u)&&"layout"!==u&&"paint"!==u&&"filter"!==u&&"metadata"!==u&&"minzoom"!==u&&"maxzoom"!==u&&(0===u.indexOf("paint.")?Gt(s[u],l[u],o,n,u.slice(6),Nt.setPaintProperty):t.deepEqual(s[u],l[u])||o.push({command:Nt.setLayerProperty,args:[n,u,l[u]]}));for(u in l)l.hasOwnProperty(u)&&!s.hasOwnProperty(u)&&"layout"!==u&&"paint"!==u&&"filter"!==u&&"metadata"!==u&&"minzoom"!==u&&"maxzoom"!==u&&(0===u.indexOf("paint.")?Gt(s[u],l[u],o,n,u.slice(6),Nt.setPaintProperty):t.deepEqual(s[u],l[u])||o.push({command:Nt.setLayerProperty,args:[n,u,l[u]]}));}else o.push({command:Nt.removeLayer,args:[n]}),c=f[f.lastIndexOf(n)+1],o.push({command:Nt.addLayer,args:[l,c]});}(n,i.layers,o);}catch(t){console.warn("Unable to compute style diff:",t),o=[{command:Nt.setStyle,args:[i]}];}return o}var Kt=function(t,e,i){var o=this.boxCells=[],r=this.circleCells=[];this.xCellCount=Math.ceil(t/i),this.yCellCount=Math.ceil(e/i);for(var a=0;a<this.xCellCount*this.yCellCount;a++)o.push([]),r.push([]);this.circleKeys=[],this.boxKeys=[],this.bboxes=[],this.circles=[],this.width=t,this.height=e,this.xScale=this.xCellCount/t,this.yScale=this.yCellCount/e,this.boxUid=0,this.circleUid=0;};function Yt(e,i,o,r,a){var n=t.create();return i?(t.scale(n,n,[1/a,1/a,1]),o||t.rotateZ(n,n,r.angle)):t.multiply(n,r.labelPlaneMatrix,e),n}function Jt(e,i,o,r,a){if(i){var n=t.clone(e);return t.scale(n,n,[a,a,1]),o||t.rotateZ(n,n,-r.angle),n}return r.glCoordMatrix}function Qt(e,i){var o=[e.x,e.y,0,1];le(o,o,i);var r=o[3];return {point:new t.Point(o[0]/r,o[1]/r),signedDistanceFromCamera:r}}function $t(t,e){var i=t[0]/t[3],o=t[1]/t[3];return i>=-e[0]&&i<=e[0]&&o>=-e[1]&&o<=e[1]}function te(e,i,o,r,a,n,s,l){var c=r?e.textSizeData:e.iconSizeData,u=t.evaluateSizeForZoom(c,o.transform.zoom),h=[256/o.width*2+1,256/o.height*2+1],p=r?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;p.clear();for(var d=e.lineVertexArray,_=r?e.text.placedSymbolArray:e.icon.placedSymbolArray,f=o.transform.width/o.transform.height,m=!1,g=0;g<_.length;g++){var v=_.get(g);if(v.hidden||v.writingMode===t.WritingMode.vertical&&!m)se(v.numGlyphs,p);else{m=!1;var y=[v.anchorX,v.anchorY,0,1];if(t.transformMat4(y,y,i),$t(y,h)){var x=.5+y[3]/o.transform.cameraToCenterDistance*.5,b=t.evaluateSizeForFeature(c,u,v),w=s?b*x:b/x,E=new t.Point(v.anchorX,v.anchorY),T=Qt(E,a).point,I={},S=oe(v,w,!1,l,i,a,n,e.glyphOffsetArray,d,p,T,E,I,f);m=S.useVertical,(S.notEnoughRoom||m||S.needsFlipping&&oe(v,w,!0,l,i,a,n,e.glyphOffsetArray,d,p,T,E,I,f).notEnoughRoom)&&se(v.numGlyphs,p);}else se(v.numGlyphs,p);}}r?e.text.dynamicLayoutVertexBuffer.updateData(p):e.icon.dynamicLayoutVertexBuffer.updateData(p);}function ee(t,e,i,o,r,a,n,s,l,c,u,h){var p=s.glyphStartIndex+s.numGlyphs,d=s.lineStartIndex,_=s.lineStartIndex+s.lineLength,f=e.getoffsetX(s.glyphStartIndex),m=e.getoffsetX(p-1),g=ae(t*f,i,o,r,a,n,s.segment,d,_,l,c,u,h);if(!g)return null;var v=ae(t*m,i,o,r,a,n,s.segment,d,_,l,c,u,h);return v?{first:g,last:v}:null}function ie(e,i,o,r){if(e===t.WritingMode.horizontal&&Math.abs(o.y-i.y)>Math.abs(o.x-i.x)*r)return {useVertical:!0};return (e===t.WritingMode.vertical?i.y<o.y:i.x>o.x)?{needsFlipping:!0}:null}function oe(e,i,o,r,a,n,s,l,c,u,h,p,d,_){var f,m=i/24,g=e.lineOffsetX*m,v=e.lineOffsetY*m;if(e.numGlyphs>1){var y=e.glyphStartIndex+e.numGlyphs,x=e.lineStartIndex,b=e.lineStartIndex+e.lineLength,w=ee(m,l,g,v,o,h,p,e,c,n,d,!1);if(!w)return {notEnoughRoom:!0};var E=Qt(w.first.point,s).point,T=Qt(w.last.point,s).point;if(r&&!o){var I=ie(e.writingMode,E,T,_);if(I)return I}f=[w.first];for(var S=e.glyphStartIndex+1;S<y-1;S++)f.push(ae(m*l.getoffsetX(S),g,v,o,h,p,e.segment,x,b,c,n,d,!1));f.push(w.last);}else{if(r&&!o){var C=Qt(p,a).point,P=e.lineStartIndex+e.segment+1,z=new t.Point(c.getx(P),c.gety(P)),L=Qt(z,a),M=L.signedDistanceFromCamera>0?L.point:re(p,z,C,1,a),D=ie(e.writingMode,C,M,_);if(D)return D}var A=ae(m*l.getoffsetX(e.glyphStartIndex),g,v,o,h,p,e.segment,e.lineStartIndex,e.lineStartIndex+e.lineLength,c,n,d,!1);if(!A)return {notEnoughRoom:!0};f=[A];}for(var R=0,k=f;R<k.length;R+=1){var B=k[R];t.addDynamicAttributes(u,B.point,B.angle);}return {}}function re(t,e,i,o,r){var a=Qt(t.add(t.sub(e)._unit()),r).point,n=i.sub(a);return i.add(n._mult(o/n.mag()))}function ae(e,i,o,r,a,n,s,l,c,u,h,p,d){var _=r?e-i:e+i,f=_>0?1:-1,m=0;r&&(f*=-1,m=Math.PI),f<0&&(m+=Math.PI);for(var g=f>0?l+s:l+s+1,v=g,y=a,x=a,b=0,w=0,E=Math.abs(_);b+w<=E;){if((g+=f)<l||g>=c)return null;if(x=y,void 0===(y=p[g])){var T=new t.Point(u.getx(g),u.gety(g)),I=Qt(T,h);if(I.signedDistanceFromCamera>0)y=p[g]=I.point;else{var S=g-f;y=re(0===b?n:new t.Point(u.getx(S),u.gety(S)),T,x,E-b+1,h);}}b+=w,w=x.dist(y);}var C=(E-b)/w,P=y.sub(x),z=P.mult(C)._add(x);return z._add(P._unit()._perp()._mult(o*f)),{point:z,angle:m+Math.atan2(y.y-x.y,y.x-x.x),tileDistance:d?{prevTileDistance:g-f===v?0:u.gettileUnitDistanceFromAnchor(g-f),lastSegmentViewportDistance:E-b}:null}}Kt.prototype.keysLength=function(){return this.boxKeys.length+this.circleKeys.length},Kt.prototype.insert=function(t,e,i,o,r){this._forEachCell(e,i,o,r,this._insertBoxCell,this.boxUid++),this.boxKeys.push(t),this.bboxes.push(e),this.bboxes.push(i),this.bboxes.push(o),this.bboxes.push(r);},Kt.prototype.insertCircle=function(t,e,i,o){this._forEachCell(e-o,i-o,e+o,i+o,this._insertCircleCell,this.circleUid++),this.circleKeys.push(t),this.circles.push(e),this.circles.push(i),this.circles.push(o);},Kt.prototype._insertBoxCell=function(t,e,i,o,r,a){this.boxCells[r].push(a);},Kt.prototype._insertCircleCell=function(t,e,i,o,r,a){this.circleCells[r].push(a);},Kt.prototype._query=function(t,e,i,o,r,a){if(i<0||t>this.width||o<0||e>this.height)return !r&&[];var n=[];if(t<=0&&e<=0&&this.width<=i&&this.height<=o){if(r)return !0;for(var s=0;s<this.boxKeys.length;s++)n.push({key:this.boxKeys[s],x1:this.bboxes[4*s],y1:this.bboxes[4*s+1],x2:this.bboxes[4*s+2],y2:this.bboxes[4*s+3]});for(var l=0;l<this.circleKeys.length;l++){var c=this.circles[3*l],u=this.circles[3*l+1],h=this.circles[3*l+2];n.push({key:this.circleKeys[l],x1:c-h,y1:u-h,x2:c+h,y2:u+h});}return a?n.filter(a):n}var p={hitTest:r,seenUids:{box:{},circle:{}}};return this._forEachCell(t,e,i,o,this._queryCell,n,p,a),r?n.length>0:n},Kt.prototype._queryCircle=function(t,e,i,o,r){var a=t-i,n=t+i,s=e-i,l=e+i;if(n<0||a>this.width||l<0||s>this.height)return !o&&[];var c=[],u={hitTest:o,circle:{x:t,y:e,radius:i},seenUids:{box:{},circle:{}}};return this._forEachCell(a,s,n,l,this._queryCellCircle,c,u,r),o?c.length>0:c},Kt.prototype.query=function(t,e,i,o,r){return this._query(t,e,i,o,!1,r)},Kt.prototype.hitTest=function(t,e,i,o,r){return this._query(t,e,i,o,!0,r)},Kt.prototype.hitTestCircle=function(t,e,i,o){return this._queryCircle(t,e,i,!0,o)},Kt.prototype._queryCell=function(t,e,i,o,r,a,n,s){var l=n.seenUids,c=this.boxCells[r];if(null!==c)for(var u=this.bboxes,h=0,p=c;h<p.length;h+=1){var d=p[h];if(!l.box[d]){l.box[d]=!0;var _=4*d;if(t<=u[_+2]&&e<=u[_+3]&&i>=u[_+0]&&o>=u[_+1]&&(!s||s(this.boxKeys[d]))){if(n.hitTest)return a.push(!0),!0;a.push({key:this.boxKeys[d],x1:u[_],y1:u[_+1],x2:u[_+2],y2:u[_+3]});}}}var f=this.circleCells[r];if(null!==f)for(var m=this.circles,g=0,v=f;g<v.length;g+=1){var y=v[g];if(!l.circle[y]){l.circle[y]=!0;var x=3*y;if(this._circleAndRectCollide(m[x],m[x+1],m[x+2],t,e,i,o)&&(!s||s(this.circleKeys[y]))){if(n.hitTest)return a.push(!0),!0;var b=m[x],w=m[x+1],E=m[x+2];a.push({key:this.circleKeys[y],x1:b-E,y1:w-E,x2:b+E,y2:w+E});}}}},Kt.prototype._queryCellCircle=function(t,e,i,o,r,a,n,s){var l=n.circle,c=n.seenUids,u=this.boxCells[r];if(null!==u)for(var h=this.bboxes,p=0,d=u;p<d.length;p+=1){var _=d[p];if(!c.box[_]){c.box[_]=!0;var f=4*_;if(this._circleAndRectCollide(l.x,l.y,l.radius,h[f+0],h[f+1],h[f+2],h[f+3])&&(!s||s(this.boxKeys[_])))return a.push(!0),!0}}var m=this.circleCells[r];if(null!==m)for(var g=this.circles,v=0,y=m;v<y.length;v+=1){var x=y[v];if(!c.circle[x]){c.circle[x]=!0;var b=3*x;if(this._circlesCollide(g[b],g[b+1],g[b+2],l.x,l.y,l.radius)&&(!s||s(this.circleKeys[x])))return a.push(!0),!0}}},Kt.prototype._forEachCell=function(t,e,i,o,r,a,n,s){for(var l=this._convertToXCellCoord(t),c=this._convertToYCellCoord(e),u=this._convertToXCellCoord(i),h=this._convertToYCellCoord(o),p=l;p<=u;p++)for(var d=c;d<=h;d++){var _=this.xCellCount*d+p;if(r.call(this,t,e,i,o,_,a,n,s))return}},Kt.prototype._convertToXCellCoord=function(t){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(t*this.xScale)))},Kt.prototype._convertToYCellCoord=function(t){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(t*this.yScale)))},Kt.prototype._circlesCollide=function(t,e,i,o,r,a){var n=o-t,s=r-e,l=i+a;return l*l>n*n+s*s},Kt.prototype._circleAndRectCollide=function(t,e,i,o,r,a,n){var s=(a-o)/2,l=Math.abs(t-(o+s));if(l>s+i)return !1;var c=(n-r)/2,u=Math.abs(e-(r+c));if(u>c+i)return !1;if(l<=s||u<=c)return !0;var h=l-s,p=u-c;return h*h+p*p<=i*i};var ne=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function se(t,e){for(var i=0;i<t;i++){var o=e.length;e.resize(o+4),e.float32.set(ne,3*o);}}function le(t,e,i){var o=e[0],r=e[1];return t[0]=i[0]*o+i[4]*r+i[12],t[1]=i[1]*o+i[5]*r+i[13],t[3]=i[3]*o+i[7]*r+i[15],t}var ce=function(t,e,i){void 0===e&&(e=new Kt(t.width+200,t.height+200,25)),void 0===i&&(i=new Kt(t.width+200,t.height+200,25)),this.transform=t,this.grid=e,this.ignoredGrid=i,this.pitchfactor=Math.cos(t._pitch)*t.cameraToCenterDistance,this.screenRightBoundary=t.width+100,this.screenBottomBoundary=t.height+100,this.gridRightBoundary=t.width+200,this.gridBottomBoundary=t.height+200;};function ue(t,e,i){t[e+4]=i?1:0;}function he(e,i,o){return i*(t.EXTENT/(e.tileSize*Math.pow(2,o-e.tileID.overscaledZ)))}ce.prototype.placeCollisionBox=function(t,e,i,o,r){var a=this.projectAndGetPerspectiveRatio(o,t.anchorPointX,t.anchorPointY),n=i*a.perspectiveRatio,s=t.x1*n+a.point.x,l=t.y1*n+a.point.y,c=t.x2*n+a.point.x,u=t.y2*n+a.point.y;return !this.isInsideGrid(s,l,c,u)||!e&&this.grid.hitTest(s,l,c,u,r)?{box:[],offscreen:!1}:{box:[s,l,c,u],offscreen:this.isOffscreen(s,l,c,u)}},ce.prototype.approximateTileDistance=function(t,e,i,o,r){var a=r?1:o/this.pitchfactor,n=t.lastSegmentViewportDistance*i;return t.prevTileDistance+n+(a-1)*n*Math.abs(Math.sin(e))},ce.prototype.placeCollisionCircles=function(e,i,o,r,a,n,s,l,c,u,h,p,d){var _=[],f=this.projectAnchor(c,a.anchorX,a.anchorY),m=l/24,g=a.lineOffsetX*l,v=a.lineOffsetY*l,y=new t.Point(a.anchorX,a.anchorY),x=ee(m,s,g,v,!1,Qt(y,u).point,y,a,n,u,{},!0),b=!1,w=!1,E=!0,T=f.perspectiveRatio*r,I=1/(r*o),S=0,C=0;x&&(S=this.approximateTileDistance(x.first.tileDistance,x.first.angle,I,f.cameraDistance,p),C=this.approximateTileDistance(x.last.tileDistance,x.last.angle,I,f.cameraDistance,p));for(var P=0;P<e.length;P+=5){var z=e[P],L=e[P+1],M=e[P+2],D=e[P+3];if(!x||D<-S||D>C)ue(e,P,!1);else{var A=this.projectPoint(c,z,L),R=M*T;if(_.length>0){var k=A.x-_[_.length-4],B=A.y-_[_.length-3];if(R*R*2>k*k+B*B)if(P+8<e.length){var O=e[P+8];if(O>-S&&O<C){ue(e,P,!1);continue}}}var F=P/5;_.push(A.x,A.y,R,F),ue(e,P,!0);var U=A.x-R,N=A.y-R,Z=A.x+R,q=A.y+R;if(E=E&&this.isOffscreen(U,N,Z,q),w=w||this.isInsideGrid(U,N,Z,q),!i&&this.grid.hitTestCircle(A.x,A.y,R,d)){if(!h)return {circles:[],offscreen:!1};b=!0;}}}return {circles:b||!w?[]:_,offscreen:E}},ce.prototype.queryRenderedSymbols=function(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};for(var i=[],o=1/0,r=1/0,a=-1/0,n=-1/0,s=0,l=e;s<l.length;s+=1){var c=l[s],u=new t.Point(c.x+100,c.y+100);o=Math.min(o,u.x),r=Math.min(r,u.y),a=Math.max(a,u.x),n=Math.max(n,u.y),i.push(u);}for(var h={},p={},d=0,_=this.grid.query(o,r,a,n).concat(this.ignoredGrid.query(o,r,a,n));d<_.length;d+=1){var f=_[d],m=f.key;if(void 0===h[m.bucketInstanceId]&&(h[m.bucketInstanceId]={}),!h[m.bucketInstanceId][m.featureIndex]){var g=[new t.Point(f.x1,f.y1),new t.Point(f.x2,f.y1),new t.Point(f.x2,f.y2),new t.Point(f.x1,f.y2)];t.polygonIntersectsPolygon(i,g)&&(h[m.bucketInstanceId][m.featureIndex]=!0,void 0===p[m.bucketInstanceId]&&(p[m.bucketInstanceId]=[]),p[m.bucketInstanceId].push(m.featureIndex));}}return p},ce.prototype.insertCollisionBox=function(t,e,i,o,r){var a={bucketInstanceId:i,featureIndex:o,collisionGroupID:r};(e?this.ignoredGrid:this.grid).insert(a,t[0],t[1],t[2],t[3]);},ce.prototype.insertCollisionCircles=function(t,e,i,o,r){for(var a=e?this.ignoredGrid:this.grid,n={bucketInstanceId:i,featureIndex:o,collisionGroupID:r},s=0;s<t.length;s+=4)a.insertCircle(n,t[s],t[s+1],t[s+2]);},ce.prototype.projectAnchor=function(t,e,i){var o=[e,i,0,1];return le(o,o,t),{perspectiveRatio:.5+this.transform.cameraToCenterDistance/o[3]*.5,cameraDistance:o[3]}},ce.prototype.projectPoint=function(e,i,o){var r=[i,o,0,1];return le(r,r,e),new t.Point((r[0]/r[3]+1)/2*this.transform.width+100,(-r[1]/r[3]+1)/2*this.transform.height+100)},ce.prototype.projectAndGetPerspectiveRatio=function(e,i,o){var r=[i,o,0,1];return le(r,r,e),{point:new t.Point((r[0]/r[3]+1)/2*this.transform.width+100,(-r[1]/r[3]+1)/2*this.transform.height+100),perspectiveRatio:.5+this.transform.cameraToCenterDistance/r[3]*.5}},ce.prototype.isOffscreen=function(t,e,i,o){return i<100||t>=this.screenRightBoundary||o<100||e>this.screenBottomBoundary},ce.prototype.isInsideGrid=function(t,e,i,o){return i>=0&&t<this.gridRightBoundary&&o>=0&&e<this.gridBottomBoundary};var pe=function(t,e,i,o){this.opacity=t?Math.max(0,Math.min(1,t.opacity+(t.placed?e:-e))):o&&i?1:0,this.placed=i;};pe.prototype.isHidden=function(){return 0===this.opacity&&!this.placed};var de=function(t,e,i,o,r){this.text=new pe(t?t.text:null,e,i,r),this.icon=new pe(t?t.icon:null,e,o,r);};de.prototype.isHidden=function(){return this.text.isHidden()&&this.icon.isHidden()};var _e=function(t,e,i){this.text=t,this.icon=e,this.skipFade=i;},fe=function(t,e,i,o,r){this.bucketInstanceId=t,this.featureIndex=e,this.sourceLayerIndex=i,this.bucketIndex=o,this.tileID=r;},me=function(t){this.crossSourceCollisions=t,this.maxGroupID=0,this.collisionGroups={};};function ge(e,i,o,r,a){var n=t.getAnchorAlignment(e),s=-(n.horizontalAlign-.5)*i,l=-(n.verticalAlign-.5)*o,c=t.evaluateVariableOffset(e,r);return new t.Point(s+c[0]*a,l+c[1]*a)}function ve(e,i,o,r,a,n){var s=e.x1,l=e.x2,c=e.y1,u=e.y2,h=e.anchorPointX,p=e.anchorPointY,d=new t.Point(i,o);return r&&d._rotate(a?n:-n),{x1:s+d.x,y1:c+d.y,x2:l+d.x,y2:u+d.y,anchorPointX:h,anchorPointY:p}}me.prototype.get=function(t){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[t]){var e=++this.maxGroupID;this.collisionGroups[t]={ID:e,predicate:function(t){return t.collisionGroupID===e}};}return this.collisionGroups[t]};var ye=function(t,e,i,o){this.transform=t.clone(),this.collisionIndex=new ce(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=e,this.retainedQueryData={},this.collisionGroups=new me(i),this.prevPlacement=o,o&&(o.prevPlacement=void 0),this.placedOrientations={};};function xe(t,e,i,o,r){t.emplaceBack(e?1:0,i?1:0,o||0,r||0),t.emplaceBack(e?1:0,i?1:0,o||0,r||0),t.emplaceBack(e?1:0,i?1:0,o||0,r||0),t.emplaceBack(e?1:0,i?1:0,o||0,r||0);}ye.prototype.getBucketParts=function(e,i,o,r){var a=o.getBucket(i),n=o.latestFeatureIndex;if(a&&n&&i.id===a.layerIds[0]){var s=o.collisionBoxArray,l=a.layers[0].layout,c=Math.pow(2,this.transform.zoom-o.tileID.overscaledZ),u=o.tileSize/t.EXTENT,h=this.transform.calculatePosMatrix(o.tileID.toUnwrapped()),p=Yt(h,"map"===l.get("text-pitch-alignment"),"map"===l.get("text-rotation-alignment"),this.transform,he(o,1,this.transform.zoom));this.retainedQueryData[a.bucketInstanceId]=new fe(a.bucketInstanceId,n,a.sourceLayerIndex,a.index,o.tileID);var d={bucket:a,layout:l,posMatrix:h,textLabelPlaneMatrix:p,scale:c,textPixelRatio:u,holdingForFade:o.holdingForFade(),collisionBoxArray:s,partiallyEvaluatedTextSize:t.evaluateSizeForZoom(a.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(a.sourceID)};if(r)for(var _=0,f=a.sortKeyRanges;_<f.length;_+=1){var m=f[_],g=m.sortKey,v=m.symbolInstanceStart,y=m.symbolInstanceEnd;e.push({sortKey:g,symbolInstanceStart:v,symbolInstanceEnd:y,parameters:d});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:a.symbolInstances.length,parameters:d});}},ye.prototype.attemptAnchorPlacement=function(t,e,i,o,r,a,n,s,l,c,u,h,p,d,_){var f,m=[h.textOffset0,h.textOffset1],g=ge(t,i,o,m,r),v=this.collisionIndex.placeCollisionBox(ve(e,g.x,g.y,a,n,this.transform.angle),u,s,l,c.predicate);if(_&&0===this.collisionIndex.placeCollisionBox(ve(_,g.x,g.y,a,n,this.transform.angle),u,s,l,c.predicate).box.length)return;if(v.box.length>0)return this.prevPlacement&&this.prevPlacement.variableOffsets[h.crossTileID]&&this.prevPlacement.placements[h.crossTileID]&&this.prevPlacement.placements[h.crossTileID].text&&(f=this.prevPlacement.variableOffsets[h.crossTileID].anchor),this.variableOffsets[h.crossTileID]={textOffset:m,width:i,height:o,anchor:t,textBoxScale:r,prevAnchor:f},this.markUsedJustification(p,t,h,d),p.allowVerticalPlacement&&(this.markUsedOrientation(p,d,h),this.placedOrientations[h.crossTileID]=d),{shift:g,placedGlyphBoxes:v}},ye.prototype.placeLayerBucketPart=function(e,i,o){var r=this,a=e.parameters,n=a.bucket,s=a.layout,l=a.posMatrix,c=a.textLabelPlaneMatrix,u=a.scale,h=a.textPixelRatio,p=a.holdingForFade,d=a.collisionBoxArray,_=a.partiallyEvaluatedTextSize,f=a.collisionGroup,m=s.get("text-optional"),g=s.get("icon-optional"),v=s.get("text-allow-overlap"),y=s.get("icon-allow-overlap"),x="map"===s.get("text-rotation-alignment"),b="map"===s.get("text-pitch-alignment"),w="none"!==s.get("icon-text-fit"),E="viewport-y"===s.get("symbol-z-order"),T=v&&(y||!n.hasIconData()||g),I=y&&(v||!n.hasTextData()||m);!n.collisionArrays&&d&&n.deserializeCollisionBoxes(d);var S=function(e,a){if(!i[e.crossTileID])if(p)r.placements[e.crossTileID]=new _e(!1,!1,!1);else{var d,E=!1,S=!1,C=!0,P=null,z={box:null,offscreen:null},L={box:null,offscreen:null},M=null,D=null,A=0,R=0,k=0;a.textFeatureIndex&&(A=a.textFeatureIndex),a.verticalTextFeatureIndex&&(R=a.verticalTextFeatureIndex);var B=a.textBox;if(B){var O=function(i){var o=t.WritingMode.horizontal;if(n.allowVerticalPlacement&&!i&&r.prevPlacement){var a=r.prevPlacement.placedOrientations[e.crossTileID];a&&(r.placedOrientations[e.crossTileID]=a,o=a,r.markUsedOrientation(n,o,e));}return o},F=function(i,o){if(n.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&a.verticalTextBox)for(var r=0,s=n.writingModes;r<s.length;r+=1){if(s[r]===t.WritingMode.vertical?(z=o(),L=z):z=i(),z&&z.box&&z.box.length)break}else z=i();};if(s.get("text-variable-anchor")){var U=s.get("text-variable-anchor");if(r.prevPlacement&&r.prevPlacement.variableOffsets[e.crossTileID]){var N=r.prevPlacement.variableOffsets[e.crossTileID];U.indexOf(N.anchor)>0&&(U=U.filter((function(t){return t!==N.anchor}))).unshift(N.anchor);}var Z=function(t,i,o){for(var a=t.x2-t.x1,s=t.y2-t.y1,c=e.textBoxScale,u=w&&!y?i:null,p={box:[],offscreen:!1},d=v?2*U.length:U.length,_=0;_<d;++_){var m=U[_%U.length],g=_>=U.length,T=r.attemptAnchorPlacement(m,t,a,s,c,x,b,h,l,f,g,e,n,o,u);if(T&&(p=T.placedGlyphBoxes)&&p.box&&p.box.length){E=!0,P=T.shift;break}}return p};F((function(){return Z(B,a.iconBox,t.WritingMode.horizontal)}),(function(){var i=a.verticalTextBox,o=z&&z.box&&z.box.length;return n.allowVerticalPlacement&&!o&&e.numVerticalGlyphVertices>0&&i?Z(i,a.verticalIconBox,t.WritingMode.vertical):{box:null,offscreen:null}})),z&&(E=z.box,C=z.offscreen);var q=O(z&&z.box);if(!E&&r.prevPlacement){var j=r.prevPlacement.variableOffsets[e.crossTileID];j&&(r.variableOffsets[e.crossTileID]=j,r.markUsedJustification(n,j.anchor,e,q));}}else{var V=function(t,i){var o=r.collisionIndex.placeCollisionBox(t,v,h,l,f.predicate);return o&&o.box&&o.box.length&&(r.markUsedOrientation(n,i,e),r.placedOrientations[e.crossTileID]=i),o};F((function(){return V(B,t.WritingMode.horizontal)}),(function(){var i=a.verticalTextBox;return n.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?V(i,t.WritingMode.vertical):{box:null,offscreen:null}})),O(z&&z.box&&z.box.length);}}E=(d=z)&&d.box&&d.box.length>0,C=d&&d.offscreen;var G=a.textCircles;if(G){var W=n.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),X=t.evaluateSizeForFeature(n.textSizeData,_,W);M=r.collisionIndex.placeCollisionCircles(G,v,u,h,W,n.lineVertexArray,n.glyphOffsetArray,X,l,c,o,b,f.predicate),E=v||M.circles.length>0,C=C&&M.offscreen;}if(a.iconFeatureIndex&&(k=a.iconFeatureIndex),a.iconBox){var H=function(t){var e=w&&P?ve(t,P.x,P.y,x,b,r.transform.angle):t;return r.collisionIndex.placeCollisionBox(e,y,h,l,f.predicate)};S=L&&L.box&&L.box.length&&a.verticalIconBox?(D=H(a.verticalIconBox)).box.length>0:(D=H(a.iconBox)).box.length>0,C=C&&D.offscreen;}var K=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,Y=g||0===e.numIconVertices;K||Y?Y?K||(S=S&&E):E=S&&E:S=E=S&&E,E&&d&&d.box&&(L&&L.box&&R?r.collisionIndex.insertCollisionBox(d.box,s.get("text-ignore-placement"),n.bucketInstanceId,R,f.ID):r.collisionIndex.insertCollisionBox(d.box,s.get("text-ignore-placement"),n.bucketInstanceId,A,f.ID)),S&&D&&r.collisionIndex.insertCollisionBox(D.box,s.get("icon-ignore-placement"),n.bucketInstanceId,k,f.ID),E&&M&&r.collisionIndex.insertCollisionCircles(M.circles,s.get("text-ignore-placement"),n.bucketInstanceId,A,f.ID),r.placements[e.crossTileID]=new _e(E||T,S||I,C||n.justReloaded),i[e.crossTileID]=!0;}};if(E)for(var C=n.getSortedSymbolIndexes(this.transform.angle),P=C.length-1;P>=0;--P){var z=C[P];S(n.symbolInstances.get(z),n.collisionArrays[z]);}else for(var L=e.symbolInstanceStart;L<e.symbolInstanceEnd;L++)S(n.symbolInstances.get(L),n.collisionArrays[L]);n.justReloaded=!1;},ye.prototype.markUsedJustification=function(e,i,o,r){var a,n={left:o.leftJustifiedTextSymbolIndex,center:o.centerJustifiedTextSymbolIndex,right:o.rightJustifiedTextSymbolIndex};a=r===t.WritingMode.vertical?o.verticalPlacedTextSymbolIndex:n[t.getAnchorJustification(i)];for(var s=0,l=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex,o.verticalPlacedTextSymbolIndex];s<l.length;s+=1){var c=l[s];c>=0&&(e.text.placedSymbolArray.get(c).crossTileID=a>=0&&c!==a?0:o.crossTileID);}},ye.prototype.markUsedOrientation=function(e,i,o){for(var r=i===t.WritingMode.horizontal||i===t.WritingMode.horizontalOnly?i:0,a=i===t.WritingMode.vertical?i:0,n=0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex];n<s.length;n+=1){var l=s[n];e.text.placedSymbolArray.get(l).placedOrientation=r;}o.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).placedOrientation=a);},ye.prototype.commit=function(t){this.commitTime=t,this.zoomAtLastRecencyCheck=this.transform.zoom;var e=this.prevPlacement,i=!1;this.prevZoomAdjustment=e?e.zoomAdjustment(this.transform.zoom):0;var o=e?e.symbolFadeChange(t):1,r=e?e.opacities:{},a=e?e.variableOffsets:{},n=e?e.placedOrientations:{};for(var s in this.placements){var l=this.placements[s],c=r[s];c?(this.opacities[s]=new de(c,o,l.text,l.icon),i=i||l.text!==c.text.placed||l.icon!==c.icon.placed):(this.opacities[s]=new de(null,o,l.text,l.icon,l.skipFade),i=i||l.text||l.icon);}for(var u in r){var h=r[u];if(!this.opacities[u]){var p=new de(h,o,!1,!1);p.isHidden()||(this.opacities[u]=p,i=i||h.text.placed||h.icon.placed);}}for(var d in a)this.variableOffsets[d]||!this.opacities[d]||this.opacities[d].isHidden()||(this.variableOffsets[d]=a[d]);for(var _ in n)this.placedOrientations[_]||!this.opacities[_]||this.opacities[_].isHidden()||(this.placedOrientations[_]=n[_]);i?this.lastPlacementChangeTime=t:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=e?e.lastPlacementChangeTime:t);},ye.prototype.updateLayerOpacities=function(t,e){for(var i={},o=0,r=e;o<r.length;o+=1){var a=r[o],n=a.getBucket(t);n&&a.latestFeatureIndex&&t.id===n.layerIds[0]&&this.updateBucketOpacities(n,i,a.collisionBoxArray);}},ye.prototype.updateBucketOpacities=function(e,i,o){var r=this;e.hasTextData()&&e.text.opacityVertexArray.clear(),e.hasIconData()&&e.icon.opacityVertexArray.clear(),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear(),e.hasIconCollisionCircleData()&&e.iconCollisionCircle.collisionVertexArray.clear(),e.hasTextCollisionCircleData()&&e.textCollisionCircle.collisionVertexArray.clear();var a=e.layers[0].layout,n=new de(null,0,!1,!1,!0),s=a.get("text-allow-overlap"),l=a.get("icon-allow-overlap"),c=a.get("text-variable-anchor"),u="map"===a.get("text-rotation-alignment"),h="map"===a.get("text-pitch-alignment"),p="none"!==a.get("icon-text-fit"),d=new de(null,0,s&&(l||!e.hasIconData()||a.get("icon-optional")),l&&(s||!e.hasTextData()||a.get("text-optional")),!0);!e.collisionArrays&&o&&(e.hasIconCollisionBoxData()||e.hasIconCollisionCircleData()||e.hasTextCollisionBoxData()||e.hasTextCollisionCircleData())&&e.deserializeCollisionBoxes(o);for(var _=function(t,e,i){for(var o=0;o<e/4;o++)t.opacityVertexArray.emplaceBack(i);},f=function(o){var a=e.symbolInstances.get(o),s=a.numHorizontalGlyphVertices,l=a.numVerticalGlyphVertices,f=a.crossTileID,m=i[f],g=r.opacities[f];m?g=n:g||(g=d,r.opacities[f]=g),i[f]=!0;var v=s>0||l>0,y=a.numIconVertices>0,x=r.placedOrientations[a.crossTileID],b=x===t.WritingMode.vertical,w=x===t.WritingMode.horizontal||x===t.WritingMode.horizontalOnly;if(v){var E=Pe(g.text),T=b?ze:E;_(e.text,s,T);var I=w?ze:E;_(e.text,l,I);var S=g.text.isHidden();[a.rightJustifiedTextSymbolIndex,a.centerJustifiedTextSymbolIndex,a.leftJustifiedTextSymbolIndex].forEach((function(t){t>=0&&(e.text.placedSymbolArray.get(t).hidden=S||b?1:0);})),a.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(a.verticalPlacedTextSymbolIndex).hidden=S||w?1:0);var C=r.variableOffsets[a.crossTileID];C&&r.markUsedJustification(e,C.anchor,a,x);var P=r.placedOrientations[a.crossTileID];P&&(r.markUsedJustification(e,"left",a,P),r.markUsedOrientation(e,P,a));}if(y){var z=Pe(g.icon),L=!(p&&a.verticalPlacedIconSymbolIndex&&b);if(a.placedIconSymbolIndex>=0){var M=L?z:ze;_(e.icon,a.numIconVertices,M),e.icon.placedSymbolArray.get(a.placedIconSymbolIndex).hidden=g.icon.isHidden();}if(a.verticalPlacedIconSymbolIndex>=0){var D=L?ze:z;_(e.icon,a.numVerticalIconVertices,D),e.icon.placedSymbolArray.get(a.verticalPlacedIconSymbolIndex).hidden=g.icon.isHidden();}}if(e.hasIconCollisionBoxData()||e.hasIconCollisionCircleData()||e.hasTextCollisionBoxData()||e.hasTextCollisionCircleData()){var A=e.collisionArrays[o];if(A){var R=new t.Point(0,0);if(A.textBox||A.verticalTextBox){var k=!0;if(c){var B=r.variableOffsets[f];B?(R=ge(B.anchor,B.width,B.height,B.textOffset,B.textBoxScale),u&&R._rotate(h?r.transform.angle:-r.transform.angle)):k=!1;}A.textBox&&xe(e.textCollisionBox.collisionVertexArray,g.text.placed,!k||b,R.x,R.y),A.verticalTextBox&&xe(e.textCollisionBox.collisionVertexArray,g.text.placed,!k||w,R.x,R.y);}var O=Boolean(!w&&A.verticalIconBox);A.iconBox&&xe(e.iconCollisionBox.collisionVertexArray,g.icon.placed,O,p?R.x:0,p?R.y:0),A.verticalIconBox&&xe(e.iconCollisionBox.collisionVertexArray,g.icon.placed,!O,p?R.x:0,p?R.y:0);var F=A.textCircles;if(F&&e.hasTextCollisionCircleData())for(var U=0;U<F.length;U+=5){var N=m||0===F[U+4];xe(e.textCollisionCircle.collisionVertexArray,g.text.placed,N);}}}},m=0;m<e.symbolInstances.length;m++)f(m);e.sortFeatures(this.transform.angle),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.hasIconCollisionCircleData()&&e.iconCollisionCircle.collisionVertexBuffer&&e.iconCollisionCircle.collisionVertexBuffer.updateData(e.iconCollisionCircle.collisionVertexArray),e.hasTextCollisionCircleData()&&e.textCollisionCircle.collisionVertexBuffer&&e.textCollisionCircle.collisionVertexBuffer.updateData(e.textCollisionCircle.collisionVertexArray);},ye.prototype.symbolFadeChange=function(t){return 0===this.fadeDuration?1:(t-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment},ye.prototype.zoomAdjustment=function(t){return Math.max(0,(this.transform.zoom-t)/1.5)},ye.prototype.hasTransitions=function(t){return this.stale||t-this.lastPlacementChangeTime<this.fadeDuration},ye.prototype.stillRecent=function(t,e){var i=this.zoomAtLastRecencyCheck===e?1-this.zoomAdjustment(e):1;return this.zoomAtLastRecencyCheck=e,this.commitTime+this.fadeDuration*i>t},ye.prototype.setStale=function(){this.stale=!0;};var be=Math.pow(2,25),we=Math.pow(2,24),Ee=Math.pow(2,17),Te=Math.pow(2,16),Ie=Math.pow(2,9),Se=Math.pow(2,8),Ce=Math.pow(2,1);function Pe(t){if(0===t.opacity&&!t.placed)return 0;if(1===t.opacity&&t.placed)return 4294967295;var e=t.placed?1:0,i=Math.floor(127*t.opacity);return i*be+e*we+i*Ee+e*Te+i*Ie+e*Se+i*Ce+e}var ze=0,Le=function(t){this._sortAcrossTiles="viewport-y"!==t.layout.get("symbol-z-order")&&void 0!==t.layout.get("symbol-sort-key").constantOr(1),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];};Le.prototype.continuePlacement=function(t,e,i,o,r){for(var a=this._bucketParts;this._currentTileIndex<t.length;){var n=t[this._currentTileIndex];if(e.getBucketParts(a,o,n,this._sortAcrossTiles),this._currentTileIndex++,r())return !0}for(this._sortAcrossTiles&&(this._sortAcrossTiles=!1,a.sort((function(t,e){return t.sortKey-e.sortKey})));this._currentPartIndex<a.length;){var s=a[this._currentPartIndex];if(e.placeLayerBucketPart(s,this._seenCrossTileIDs,i),this._currentPartIndex++,r())return !0}return !1};var Me=function(t,e,i,o,r,a,n){this.placement=new ye(t,r,a,n),this._currentPlacementIndex=e.length-1,this._forceFullPlacement=i,this._showCollisionBoxes=o,this._done=!1;};Me.prototype.isDone=function(){return this._done},Me.prototype.continuePlacement=function(e,i,o){for(var r=this,a=t.browser.now(),n=function(){var e=t.browser.now()-a;return !r._forceFullPlacement&&e>2};this._currentPlacementIndex>=0;){var s=i[e[this._currentPlacementIndex]],l=this.placement.collisionIndex.transform.zoom;if("symbol"===s.type&&(!s.minzoom||s.minzoom<=l)&&(!s.maxzoom||s.maxzoom>l)){if(this._inProgressLayer||(this._inProgressLayer=new Le(s)),this._inProgressLayer.continuePlacement(o[s.source],this.placement,this._showCollisionBoxes,s,n))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;},Me.prototype.commit=function(t){return this.placement.commit(t),this.placement};var De=512/t.EXTENT/2,Ae=function(t,e,i){this.tileID=t,this.indexedSymbolInstances={},this.bucketInstanceId=i;for(var o=0;o<e.length;o++){var r=e.get(o),a=r.key;this.indexedSymbolInstances[a]||(this.indexedSymbolInstances[a]=[]),this.indexedSymbolInstances[a].push({crossTileID:r.crossTileID,coord:this.getScaledCoordinates(r,t)});}};Ae.prototype.getScaledCoordinates=function(e,i){var o=i.canonical.z-this.tileID.canonical.z,r=De/Math.pow(2,o);return {x:Math.floor((i.canonical.x*t.EXTENT+e.anchorX)*r),y:Math.floor((i.canonical.y*t.EXTENT+e.anchorY)*r)}},Ae.prototype.findMatches=function(t,e,i){for(var o=this.tileID.canonical.z<e.canonical.z?1:Math.pow(2,this.tileID.canonical.z-e.canonical.z),r=0;r<t.length;r++){var a=t.get(r);if(!a.crossTileID){var n=this.indexedSymbolInstances[a.key];if(n)for(var s=this.getScaledCoordinates(a,e),l=0,c=n;l<c.length;l+=1){var u=c[l];if(Math.abs(u.coord.x-s.x)<=o&&Math.abs(u.coord.y-s.y)<=o&&!i[u.crossTileID]){i[u.crossTileID]=!0,a.crossTileID=u.crossTileID;break}}}}};var Re=function(){this.maxCrossTileID=0;};Re.prototype.generate=function(){return ++this.maxCrossTileID};var ke=function(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;};ke.prototype.handleWrapJump=function(t){var e=Math.round((t-this.lng)/360);if(0!==e)for(var i in this.indexes){var o=this.indexes[i],r={};for(var a in o){var n=o[a];n.tileID=n.tileID.unwrapTo(n.tileID.wrap+e),r[n.tileID.key]=n;}this.indexes[i]=r;}this.lng=t;},ke.prototype.addBucket=function(t,e,i){if(this.indexes[t.overscaledZ]&&this.indexes[t.overscaledZ][t.key]){if(this.indexes[t.overscaledZ][t.key].bucketInstanceId===e.bucketInstanceId)return !1;this.removeBucketCrossTileIDs(t.overscaledZ,this.indexes[t.overscaledZ][t.key]);}for(var o=0;o<e.symbolInstances.length;o++){e.symbolInstances.get(o).crossTileID=0;}this.usedCrossTileIDs[t.overscaledZ]||(this.usedCrossTileIDs[t.overscaledZ]={});var r=this.usedCrossTileIDs[t.overscaledZ];for(var a in this.indexes){var n=this.indexes[a];if(Number(a)>t.overscaledZ)for(var s in n){var l=n[s];l.tileID.isChildOf(t)&&l.findMatches(e.symbolInstances,t,r);}else{var c=n[t.scaledTo(Number(a)).key];c&&c.findMatches(e.symbolInstances,t,r);}}for(var u=0;u<e.symbolInstances.length;u++){var h=e.symbolInstances.get(u);h.crossTileID||(h.crossTileID=i.generate(),r[h.crossTileID]=!0);}return void 0===this.indexes[t.overscaledZ]&&(this.indexes[t.overscaledZ]={}),this.indexes[t.overscaledZ][t.key]=new Ae(t,e.symbolInstances,e.bucketInstanceId),!0},ke.prototype.removeBucketCrossTileIDs=function(t,e){for(var i in e.indexedSymbolInstances)for(var o=0,r=e.indexedSymbolInstances[i];o<r.length;o+=1){var a=r[o];delete this.usedCrossTileIDs[t][a.crossTileID];}},ke.prototype.removeStaleBuckets=function(t){var e=!1;for(var i in this.indexes){var o=this.indexes[i];for(var r in o)t[o[r].bucketInstanceId]||(this.removeBucketCrossTileIDs(i,o[r]),delete o[r],e=!0);}return e};var Be=function(){this.layerIndexes={},this.crossTileIDs=new Re,this.maxBucketInstanceId=0,this.bucketsInCurrentPlacement={};};Be.prototype.addLayer=function(t,e,i){var o=this.layerIndexes[t.id];void 0===o&&(o=this.layerIndexes[t.id]=new ke);var r=!1,a={};o.handleWrapJump(i);for(var n=0,s=e;n<s.length;n+=1){var l=s[n],c=l.getBucket(t);c&&t.id===c.layerIds[0]&&(c.bucketInstanceId||(c.bucketInstanceId=++this.maxBucketInstanceId),o.addBucket(l.tileID,c,this.crossTileIDs)&&(r=!0),a[c.bucketInstanceId]=!0);}return o.removeStaleBuckets(a)&&(r=!0),r},Be.prototype.pruneUnusedLayers=function(t){var e={};for(var i in t.forEach((function(t){e[t]=!0;})),this.layerIndexes)e[i]||delete this.layerIndexes[i];};var Oe=function(e,i){return t.emitValidationErrors(e,i&&i.filter((function(t){return "source.canvas"!==t.identifier})))},Fe=t.pick(Nt,["addLayer","removeLayer","setPaintProperty","setLayoutProperty","setFilter","addSource","removeSource","setLayerZoomRange","setLight","setTransition","setGeoJSONSourceData"]),Ue=t.pick(Nt,["setCenter","setZoom","setBearing","setPitch"]),Ne=function(){var e={},i=t.styleSpec.$version;for(var o in t.styleSpec.$root){var r=t.styleSpec.$root[o];if(r.required){var a=null;null!=(a="version"===o?i:"array"===r.type?[]:{})&&(e[o]=a);}}return e}(),Ze=function(e){function i(o,r){var a=this;void 0===r&&(r={}),e.call(this),this.map=o,this.dispatcher=new T((Bt||(Bt=new kt),Bt),this),this.imageManager=new p,this.imageManager.setEventedParent(this),this.glyphManager=new y(o._requestManager,r.localIdeographFontFamily),this.lineAtlas=new E(256,512),this.crossTileSymbolIndex=new Be,this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.ZoomHistory,this._loaded=!1,this._resetUpdates(),this.dispatcher.broadcast("setReferrer",t.getReferrer());var n=this;this._rtlTextPluginCallback=i.registerForPluginStateChange((function(e){var i={pluginStatus:e.pluginStatus,pluginURL:e.pluginURL};n.dispatcher.broadcast("syncRTLPluginState",i,(function(e,i){if((t.triggerPluginCompletionEvent(e),i)&&i.every((function(t){return t})))for(var o in n.sourceCaches)n.sourceCaches[o].reload();}));})),this.on("data",(function(t){if("source"===t.dataType&&"metadata"===t.sourceDataType){var e=a.sourceCaches[t.sourceId];if(e){var i=e.getSource();if(i&&i.vectorLayerIds)for(var o in a._layers){var r=a._layers[o];r.source===i.id&&a._validateLayer(r);}}}}));}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.loadURL=function(e,i){var o=this;void 0===i&&(i={}),this.fire(new t.Event("dataloading",{dataType:"style"}));var r="boolean"==typeof i.validate?i.validate:!t.isMapboxURL(e);e=this.map._requestManager.normalizeStyleURL(e,i.accessToken);var a=this.map._requestManager.transformRequest(e,t.ResourceType.Style);this._request=t.getJSON(a,(function(e,i){o._request=null,e?o.fire(new t.ErrorEvent(e)):i&&o._load(i,r);}));},i.prototype.loadJSON=function(e,i){var o=this;void 0===i&&(i={}),this.fire(new t.Event("dataloading",{dataType:"style"})),this._request=t.browser.frame((function(){o._request=null,o._load(e,!1!==i.validate);}));},i.prototype.loadEmpty=function(){this.fire(new t.Event("dataloading",{dataType:"style"})),this._load(Ne,!1);},i.prototype._load=function(e,i){if(!i||!Oe(this,t.validateStyle(e))){for(var o in this._loaded=!0,this.stylesheet=e,e.sources)this.addSource(o,e.sources[o],{validate:!1});e.sprite?this._loadSprite(e.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(e.glyphs);var r=Ut(this.stylesheet.layers);this._order=r.map((function(t){return t.id})),this._layers={};for(var a=0,n=r;a<n.length;a+=1){var s=n[a];(s=t.createStyleLayer(s)).setEventedParent(this,{layer:{id:s.id}}),this._layers[s.id]=s;}this.dispatcher.broadcast("setLayers",this._serializeLayers(this._order)),this.light=new w(this.stylesheet.light),this.fire(new t.Event("data",{dataType:"style"})),this.fire(new t.Event("style.load"));}},i.prototype._loadSprite=function(e){var i=this;this._spriteRequest=function(e,i,o){var r,a,n,s=t.browser.devicePixelRatio>1?"@2x":"",l=t.getJSON(i.transformRequest(i.normalizeSpriteURL(e,s,".json"),t.ResourceType.SpriteJSON),(function(t,e){l=null,n||(n=t,r=e,u());})),c=t.getImage(i.transformRequest(i.normalizeSpriteURL(e,s,".png"),t.ResourceType.SpriteImage),(function(t,e){c=null,n||(n=t,a=e,u());}));function u(){if(n)o(n);else if(r&&a){var e=t.browser.getImageData(a),i={};for(var s in r){var l=r[s],c=l.width,u=l.height,h=l.x,p=l.y,d=l.sdf,_=l.pixelRatio,f=l.stretchX,m=l.stretchY,g=l.content,v=new t.RGBAImage({width:c,height:u});t.RGBAImage.copy(e,v,{x:h,y:p},{x:0,y:0},{width:c,height:u}),i[s]={data:v,pixelRatio:_,sdf:d,stretchX:f,stretchY:m,content:g};}o(null,i);}}return {cancel:function(){l&&(l.cancel(),l=null),c&&(c.cancel(),c=null);}}}(e,this.map._requestManager,(function(e,o){if(i._spriteRequest=null,e)i.fire(new t.ErrorEvent(e));else if(o)for(var r in o)i.imageManager.addImage(r,o[r]);i.imageManager.setLoaded(!0),i.dispatcher.broadcast("setImages",i.imageManager.listImages()),i.fire(new t.Event("data",{dataType:"style"}));}));},i.prototype._validateLayer=function(e){var i=this.sourceCaches[e.source];if(i){var o=e.sourceLayer;if(o){var r=i.getSource();("geojson"===r.type||r.vectorLayerIds&&-1===r.vectorLayerIds.indexOf(o))&&this.fire(new t.ErrorEvent(new Error('Source layer "'+o+'" does not exist on source "'+r.id+'" as specified by style layer "'+e.id+'"')));}}},i.prototype.loaded=function(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(var t in this.sourceCaches)if(!this.sourceCaches[t].loaded())return !1;return !!this.imageManager.isLoaded()},i.prototype._serializeLayers=function(t){for(var e=[],i=0,o=t;i<o.length;i+=1){var r=o[i],a=this._layers[r];"custom"!==a.type&&e.push(a.serialize());}return e},i.prototype.hasTransitions=function(){if(this.light&&this.light.hasTransition())return !0;for(var t in this.sourceCaches)if(this.sourceCaches[t].hasTransition())return !0;for(var e in this._layers)if(this._layers[e].hasTransition())return !0;return !1},i.prototype._checkLoaded=function(){if(!this._loaded)throw new Error("Style is not done loading")},i.prototype.update=function(e){if(this._loaded){var i=this._changed;if(this._changed){var o=Object.keys(this._updatedLayers),r=Object.keys(this._removedLayers);for(var a in (o.length||r.length)&&this._updateWorkerLayers(o,r),this._updatedSources){var n=this._updatedSources[a];"reload"===n?this._reloadSource(a):"clear"===n&&this._clearSource(a);}for(var s in this._updateTilesForChangedImages(),this._updatedPaintProps)this._layers[s].updateTransitions(e);this.light.updateTransitions(e),this._resetUpdates();}for(var l in this.sourceCaches)this.sourceCaches[l].used=!1;for(var c=this.imageManager.listImages(),u=0,h=this._order;u<h.length;u+=1){var p=h[u],d=this._layers[p];d.recalculate(e,c),!d.isHidden(e.zoom)&&d.source&&(this.sourceCaches[d.source].used=!0);}this.light.recalculate(e),this.z=e.zoom,i&&this.fire(new t.Event("data",{dataType:"style"}));}},i.prototype._updateTilesForChangedImages=function(){var t=Object.keys(this._changedImages);if(t.length){for(var e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["icons","patterns"],t);this._changedImages={};}},i.prototype._updateWorkerLayers=function(t,e){this.dispatcher.broadcast("updateLayers",{layers:this._serializeLayers(t),removedIds:e});},i.prototype._resetUpdates=function(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={};},i.prototype.setState=function(e){var i=this;if(this._checkLoaded(),Oe(this,t.validateStyle(e)))return !1;(e=t.clone$1(e)).layers=Ut(e.layers);var o=Ht(this.serialize(),e).filter((function(t){return !(t.command in Ue)}));if(0===o.length)return !1;var r=o.filter((function(t){return !(t.command in Fe)}));if(r.length>0)throw new Error("Unimplemented: "+r.map((function(t){return t.command})).join(", ")+".");return o.forEach((function(t){"setTransition"!==t.command&&i[t.command].apply(i,t.args);})),this.stylesheet=e,!0},i.prototype.addImage=function(e,i){if(this.getImage(e))return this.fire(new t.ErrorEvent(new Error("An image with this name already exists.")));this.imageManager.addImage(e,i),this._changedImages[e]=!0,this._changed=!0,this.fire(new t.Event("data",{dataType:"style"}));},i.prototype.updateImage=function(t,e){this.imageManager.updateImage(t,e);},i.prototype.getImage=function(t){return this.imageManager.getImage(t)},i.prototype.removeImage=function(e){if(!this.getImage(e))return this.fire(new t.ErrorEvent(new Error("No image with this name exists.")));this.imageManager.removeImage(e),this._changedImages[e]=!0,this._changed=!0,this.fire(new t.Event("data",{dataType:"style"}));},i.prototype.listImages=function(){return this._checkLoaded(),this.imageManager.listImages()},i.prototype.addSource=function(e,i,o){var r=this;if(void 0===o&&(o={}),this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error("There is already a source with this ID");if(!i.type)throw new Error("The type property must be defined, but the only the following properties were given: "+Object.keys(i).join(", ")+".");if(!(["vector","raster","geojson","video","image"].indexOf(i.type)>=0)||!this._validate(t.validateStyle.source,"sources."+e,i,null,o)){this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);var a=this.sourceCaches[e]=new Mt(e,i,this.dispatcher);a.style=this,a.setEventedParent(this,(function(){return {isSourceLoaded:r.loaded(),source:a.serialize(),sourceId:e}})),a.onAdd(this.map),this._changed=!0;}},i.prototype.removeSource=function(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(var i in this._layers)if(this._layers[i].source===e)return this.fire(new t.ErrorEvent(new Error('Source "'+e+'" cannot be removed while layer "'+i+'" is using it.')));var o=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],o.fire(new t.Event("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),o.setEventedParent(null),o.clearTiles(),o.onRemove&&o.onRemove(this.map),this._changed=!0;},i.prototype.setGeoJSONSourceData=function(t,e){this._checkLoaded(),this.sourceCaches[t].getSource().setData(e),this._changed=!0;},i.prototype.getSource=function(t){return this.sourceCaches[t]&&this.sourceCaches[t].getSource()},i.prototype.addLayer=function(e,i,o){void 0===o&&(o={}),this._checkLoaded();var r=e.id;if(this.getLayer(r))this.fire(new t.ErrorEvent(new Error('Layer with id "'+r+'" already exists on this map')));else{var a;if("custom"===e.type){if(Oe(this,t.validateCustomStyleLayer(e)))return;a=t.createStyleLayer(e);}else{if("object"==typeof e.source&&(this.addSource(r,e.source),e=t.clone$1(e),e=t.extend(e,{source:r})),this._validate(t.validateStyle.layer,"layers."+r,e,{arrayIndex:-1},o))return;a=t.createStyleLayer(e),this._validateLayer(a),a.setEventedParent(this,{layer:{id:r}});}var n=i?this._order.indexOf(i):this._order.length;if(i&&-1===n)this.fire(new t.ErrorEvent(new Error('Layer with id "'+i+'" does not exist on this map.')));else{if(this._order.splice(n,0,r),this._layerOrderChanged=!0,this._layers[r]=a,this._removedLayers[r]&&a.source&&"custom"!==a.type){var s=this._removedLayers[r];delete this._removedLayers[r],s.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause());}this._updateLayer(a),a.onAdd&&a.onAdd(this.map);}}},i.prototype.moveLayer=function(e,i){if(this._checkLoaded(),this._changed=!0,this._layers[e]){if(e!==i){var o=this._order.indexOf(e);this._order.splice(o,1);var r=i?this._order.indexOf(i):this._order.length;i&&-1===r?this.fire(new t.ErrorEvent(new Error('Layer with id "'+i+'" does not exist on this map.'))):(this._order.splice(r,0,e),this._layerOrderChanged=!0);}}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be moved.")));},i.prototype.removeLayer=function(e){this._checkLoaded();var i=this._layers[e];if(i){i.setEventedParent(null);var o=this._order.indexOf(e);this._order.splice(o,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be removed.")));},i.prototype.getLayer=function(t){return this._layers[t]},i.prototype.setLayerZoomRange=function(e,i,o){this._checkLoaded();var r=this.getLayer(e);r?r.minzoom===i&&r.maxzoom===o||(null!=i&&(r.minzoom=i),null!=o&&(r.maxzoom=o),this._updateLayer(r)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot have zoom extent.")));},i.prototype.setFilter=function(e,i,o){void 0===o&&(o={}),this._checkLoaded();var r=this.getLayer(e);if(r){if(!t.deepEqual(r.filter,i))return null==i?(r.filter=void 0,void this._updateLayer(r)):void(this._validate(t.validateStyle.filter,"layers."+r.id+".filter",i,null,o)||(r.filter=t.clone$1(i),this._updateLayer(r)))}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be filtered.")));},i.prototype.getFilter=function(e){return t.clone$1(this.getLayer(e).filter)},i.prototype.setLayoutProperty=function(e,i,o,r){void 0===r&&(r={}),this._checkLoaded();var a=this.getLayer(e);a?t.deepEqual(a.getLayoutProperty(i),o)||(a.setLayoutProperty(i,o,r),this._updateLayer(a)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")));},i.prototype.getLayoutProperty=function(e,i){var o=this.getLayer(e);if(o)return o.getLayoutProperty(i);this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style.")));},i.prototype.setPaintProperty=function(e,i,o,r){void 0===r&&(r={}),this._checkLoaded();var a=this.getLayer(e);a?t.deepEqual(a.getPaintProperty(i),o)||(a.setPaintProperty(i,o,r)&&this._updateLayer(a),this._changed=!0,this._updatedPaintProps[e]=!0):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")));},i.prototype.getPaintProperty=function(t,e){return this.getLayer(t).getPaintProperty(e)},i.prototype.setFeatureState=function(e,i){this._checkLoaded();var o=e.source,r=e.sourceLayer,a=this.sourceCaches[o];if(void 0!==a){var n=a.getSource().type;"geojson"===n&&r?this.fire(new t.ErrorEvent(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==n||r?(void 0===e.id&&this.fire(new t.ErrorEvent(new Error("The feature id parameter must be provided."))),a.setFeatureState(r,e.id,i)):this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}else this.fire(new t.ErrorEvent(new Error("The source '"+o+"' does not exist in the map's style.")));},i.prototype.removeFeatureState=function(e,i){this._checkLoaded();var o=e.source,r=this.sourceCaches[o];if(void 0!==r){var a=r.getSource().type,n="vector"===a?e.sourceLayer:void 0;"vector"!==a||n?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.ErrorEvent(new Error("A feature id is requred to remove its specific state property."))):r.removeFeatureState(n,e.id,i):this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}else this.fire(new t.ErrorEvent(new Error("The source '"+o+"' does not exist in the map's style.")));},i.prototype.getFeatureState=function(e){this._checkLoaded();var i=e.source,o=e.sourceLayer,r=this.sourceCaches[i];if(void 0!==r){if("vector"!==r.getSource().type||o)return void 0===e.id&&this.fire(new t.ErrorEvent(new Error("The feature id parameter must be provided."))),r.getFeatureState(o,e.id);this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}else this.fire(new t.ErrorEvent(new Error("The source '"+i+"' does not exist in the map's style.")));},i.prototype.getTransition=function(){return t.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)},i.prototype.serialize=function(){return t.filterObject({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,light:this.stylesheet.light,center:this.stylesheet.center,zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,sources:t.mapObject(this.sourceCaches,(function(t){return t.serialize()})),layers:this._serializeLayers(this._order)},(function(t){return void 0!==t}))},i.prototype._updateLayer=function(t){this._updatedLayers[t.id]=!0,t.source&&!this._updatedSources[t.source]&&"raster"!==this.sourceCaches[t.source].getSource().type&&(this._updatedSources[t.source]="reload",this.sourceCaches[t.source].pause()),this._changed=!0;},i.prototype._flattenAndSortRenderedFeatures=function(t){for(var e=this,i=function(t){return "fill-extrusion"===e._layers[t].type},o={},r=[],a=this._order.length-1;a>=0;a--){var n=this._order[a];if(i(n)){o[n]=a;for(var s=0,l=t;s<l.length;s+=1){var c=l[s][n];if(c)for(var u=0,h=c;u<h.length;u+=1){var p=h[u];r.push(p);}}}}r.sort((function(t,e){return e.intersectionZ-t.intersectionZ}));for(var d=[],_=this._order.length-1;_>=0;_--){var f=this._order[_];if(i(f))for(var m=r.length-1;m>=0;m--){var g=r[m].feature;if(o[g.layer.id]<_)break;d.push(g),r.pop();}else for(var v=0,y=t;v<y.length;v+=1){var x=y[v][f];if(x)for(var b=0,w=x;b<w.length;b+=1){var E=w[b];d.push(E.feature);}}}return d},i.prototype.queryRenderedFeatures=function(e,i,o){i&&i.filter&&this._validate(t.validateStyle.filter,"queryRenderedFeatures.filter",i.filter,null,i);var r={};if(i&&i.layers){if(!Array.isArray(i.layers))return this.fire(new t.ErrorEvent(new Error("parameters.layers must be an Array."))),[];for(var a=0,n=i.layers;a<n.length;a+=1){var s=n[a],l=this._layers[s];if(!l)return this.fire(new t.ErrorEvent(new Error("The layer '"+s+"' does not exist in the map's style and cannot be queried for features."))),[];r[l.source]=!0;}}var c=[];for(var u in this.sourceCaches)i.layers&&!r[u]||c.push(F(this.sourceCaches[u],this._layers,e,i,o));return this.placement&&c.push(function(t,e,i,o,r,a){for(var n={},s=r.queryRenderedSymbols(i),l=[],c=0,u=Object.keys(s).map(Number);c<u.length;c+=1){var h=u[c];l.push(a[h]);}l.sort(U);for(var p=function(){var e=_[d],i=e.featureIndex.lookupSymbolFeatures(s[e.bucketInstanceId],e.bucketIndex,e.sourceLayerIndex,o.filter,o.layers,t);for(var r in i){var a=n[r]=n[r]||[],l=i[r];l.sort((function(t,i){var o=e.featureSortOrder;if(o){var r=o.indexOf(t.featureIndex);return o.indexOf(i.featureIndex)-r}return i.featureIndex-t.featureIndex}));for(var c=0,u=l;c<u.length;c+=1){var h=u[c];a.push(h);}}},d=0,_=l;d<_.length;d+=1)p();var f=function(i){n[i].forEach((function(o){var r=o.feature,a=t[i],n=e[a.source].getFeatureState(r.layer["source-layer"],r.id);r.source=r.layer.source,r.layer["source-layer"]&&(r.sourceLayer=r.layer["source-layer"]),r.state=n;}));};for(var m in n)f(m);return n}(this._layers,this.sourceCaches,e,i,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(c)},i.prototype.querySourceFeatures=function(e,i){i&&i.filter&&this._validate(t.validateStyle.filter,"querySourceFeatures.filter",i.filter,null,i);var o=this.sourceCaches[e];return o?function(t,e){for(var i=t.getRenderableIds().map((function(e){return t.getTileByID(e)})),o=[],r={},a=0;a<i.length;a++){var n=i[a],s=n.tileID.canonical.key;r[s]||(r[s]=!0,n.querySourceFeatures(o,e));}return o}(o,i):[]},i.prototype.addSourceType=function(t,e,o){return i.getSourceType(t)?o(new Error('A source type called "'+t+'" already exists.')):(i.setSourceType(t,e),e.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:t,url:e.workerSourceURL},o):o(null,null))},i.prototype.getLight=function(){return this.light.getLight()},i.prototype.setLight=function(e,i){void 0===i&&(i={}),this._checkLoaded();var o=this.light.getLight(),r=!1;for(var a in e)if(!t.deepEqual(e[a],o[a])){r=!0;break}if(r){var n={now:t.browser.now(),transition:t.extend({duration:300,delay:0},this.stylesheet.transition)};this.light.setLight(e,i),this.light.updateTransitions(n);}},i.prototype._validate=function(e,i,o,r,a){return void 0===a&&(a={}),(!a||!1!==a.validate)&&Oe(this,e.call(t.validateStyle,t.extend({key:i,style:this.serialize(),value:o,styleSpec:t.styleSpec},r)))},i.prototype._remove=function(){for(var e in this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.cancel(),this._spriteRequest=null),t.evented.off("pluginStateChange",this._rtlTextPluginCallback),this._layers){this._layers[e].setEventedParent(null);}for(var i in this.sourceCaches)this.sourceCaches[i].clearTiles(),this.sourceCaches[i].setEventedParent(null);this.imageManager.setEventedParent(null),this.setEventedParent(null),this.dispatcher.remove();},i.prototype._clearSource=function(t){this.sourceCaches[t].clearTiles();},i.prototype._reloadSource=function(t){this.sourceCaches[t].resume(),this.sourceCaches[t].reload();},i.prototype._updateSources=function(t){for(var e in this.sourceCaches)this.sourceCaches[e].update(t);},i.prototype._generateCollisionBoxes=function(){for(var t in this.sourceCaches)this._reloadSource(t);},i.prototype._updatePlacement=function(e,i,o,r,a){void 0===a&&(a=!1);for(var n=!1,s=!1,l={},c=0,u=this._order;c<u.length;c+=1){var h=u[c],p=this._layers[h];if("symbol"===p.type){if(!l[p.source]){var d=this.sourceCaches[p.source];l[p.source]=d.getRenderableIds(!0).map((function(t){return d.getTileByID(t)})).sort((function(t,e){return e.tileID.overscaledZ-t.tileID.overscaledZ||(t.tileID.isLessThan(e.tileID)?-1:1)}));}var _=this.crossTileSymbolIndex.addLayer(p,l[p.source],e.center.lng);n=n||_;}}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((a=a||this._layerOrderChanged||0===o)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(t.browser.now(),e.zoom))&&(this.pauseablePlacement=new Me(e,this._order,a,i,o,r,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,l),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(t.browser.now()),s=!0),n&&this.pauseablePlacement.placement.setStale()),s||n)for(var f=0,m=this._order;f<m.length;f+=1){var g=m[f],v=this._layers[g];"symbol"===v.type&&this.placement.updateLayerOpacities(v,l[v.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(t.browser.now())},i.prototype._releaseSymbolFadeTiles=function(){for(var t in this.sourceCaches)this.sourceCaches[t].releaseSymbolFadeTiles();},i.prototype.getImages=function(t,e,i){this.imageManager.getImages(e.icons,i),this._updateTilesForChangedImages();var o=this.sourceCaches[e.source];o&&o.setDependencies(e.tileID.key,e.type,e.icons);},i.prototype.getGlyphs=function(t,e,i){this.glyphManager.getGlyphs(e.stacks,i);},i.prototype.getResource=function(e,i,o){return t.makeRequest(i,o)},i}(t.Evented);Ze.getSourceType=function(t){return k[t]},Ze.setSourceType=function(t,e){k[t]=e;},Ze.registerForPluginStateChange=t.registerForPluginStateChange;var qe=t.createLayout([{name:"a_pos",type:"Int16",components:2}]),je=fi("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}"),Ve=fi("uniform vec4 u_color;uniform float u_opacity;void main() {gl_FragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),Ge=fi("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),We=fi("varying vec3 v_data;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);lowp float antialiasblur=v_data.z;float antialiased_blur=-max(blur,antialiasblur);float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));gl_FragColor=opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;attribute vec2 a_pos;varying vec3 v_data;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);if (u_pitch_with_map) {vec2 corner_position=circle_center;if (u_scale_with_map) {corner_position+=extrude*(radius+stroke_width)*u_extrude_scale;} else {vec4 projected_center=u_matrix*vec4(circle_center,0,1);corner_position+=extrude*(radius+stroke_width)*u_extrude_scale*(projected_center.w/u_camera_to_center_distance);}gl_Position=u_matrix*vec4(corner_position,0,1);} else {gl_Position=u_matrix*vec4(circle_center,0,1);if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),Xe=fi("void main() {gl_FragColor=vec4(1.0);}","attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),He=fi("uniform highp float u_intensity;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);gl_FragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;attribute vec2 a_pos;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 unscaled_extrude=vec2(mod(a_pos,2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec4 pos=vec4(floor(a_pos*0.5)+extrude,0,1);gl_Position=u_matrix*pos;}"),Ke=fi("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;varying vec2 v_pos;void main() {float t=texture2D(u_image,v_pos).r;vec4 color=texture2D(u_color_ramp,vec2(t,0.5));gl_FragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),Ye=fi("varying float v_placed;varying float v_notUsed;void main() {float alpha=0.5;gl_FragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {gl_FragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {gl_FragColor*=.1;}}","attribute vec2 a_pos;attribute vec2 a_anchor_pos;attribute vec2 a_extrude;attribute vec2 a_placed;attribute vec2 a_shift;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance;varying float v_placed;varying float v_notUsed;void main() {vec4 projectedPoint=u_matrix*vec4(a_anchor_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);gl_Position=u_matrix*vec4(a_pos,0.0,1.0);gl_Position.xy+=(a_extrude+a_shift)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=a_placed.x;v_notUsed=a_placed.y;}"),Je=fi("uniform float u_overscale_factor;varying float v_placed;varying float v_notUsed;varying float v_radius;varying vec2 v_extrude;varying vec2 v_extrude_scale;void main() {float alpha=0.5;vec4 color=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {color=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {color*=.2;}float extrude_scale_length=length(v_extrude_scale);float extrude_length=length(v_extrude)*extrude_scale_length;float stroke_width=15.0*extrude_scale_length/u_overscale_factor;float radius=v_radius*extrude_scale_length;float distance_to_edge=abs(extrude_length-radius);float opacity_t=smoothstep(-stroke_width,0.0,-distance_to_edge);gl_FragColor=opacity_t*color;}","attribute vec2 a_pos;attribute vec2 a_anchor_pos;attribute vec2 a_extrude;attribute vec2 a_placed;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance;varying float v_placed;varying float v_notUsed;varying float v_radius;varying vec2 v_extrude;varying vec2 v_extrude_scale;void main() {vec4 projectedPoint=u_matrix*vec4(a_anchor_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);gl_Position=u_matrix*vec4(a_pos,0.0,1.0);highp float padding_factor=1.2;gl_Position.xy+=a_extrude*u_extrude_scale*padding_factor*gl_Position.w*collision_perspective_ratio;v_placed=a_placed.x;v_notUsed=a_placed.y;v_radius=abs(a_extrude.y);v_extrude=a_extrude*padding_factor;v_extrude_scale=u_extrude_scale*u_camera_to_center_distance*collision_perspective_ratio;}"),Qe=fi("uniform highp vec4 u_color;void main() {gl_FragColor=u_color;}","attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),$e=fi("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_FragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);}"),ti=fi("varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=outline_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"),ei=fi("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec4 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float pixelRatio=u_scale.x;float tileRatio=u_scale.y;float fromScale=u_scale.z;float toScale=u_scale.w;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size_a=vec2((pattern_br_a.x-pattern_tl_a.x)/pixelRatio,(pattern_br_a.y-pattern_tl_a.y)/pixelRatio);vec2 display_size_b=vec2((pattern_br_b.x-pattern_tl_b.x)/pixelRatio,(pattern_br_b.y-pattern_tl_b.y)/pixelRatio);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"),ii=fi("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec4 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float pixelRatio=u_scale.x;float tileZoomRatio=u_scale.y;float fromScale=u_scale.z;float toScale=u_scale.w;vec2 display_size_a=vec2((pattern_br_a.x-pattern_tl_a.x)/pixelRatio,(pattern_br_a.y-pattern_tl_a.y)/pixelRatio);vec2 display_size_b=vec2((pattern_br_b.x-pattern_tl_b.x)/pixelRatio,(pattern_br_b.y-pattern_tl_b.y)/pixelRatio);gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),oi=fi("varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;attribute vec2 a_pos;attribute vec4 a_normal_ed;varying vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;base=max(0.0,base);height=max(0.0,height);float t=mod(normal.x,2.0);gl_Position=u_matrix*vec4(a_pos,t > 0.0 ? height : base,1);float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;float directional=clamp(dot(normal/16384.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),ri=fi("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);gl_FragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec4 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float pixelRatio=u_scale.x;float tileRatio=u_scale.y;float fromScale=u_scale.z;float toScale=u_scale.w;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=vec2((pattern_br_a.x-pattern_tl_a.x)/pixelRatio,(pattern_br_a.y-pattern_tl_a.y)/pixelRatio);vec2 display_size_b=vec2((pattern_br_b.x-pattern_tl_b.x)/pixelRatio,(pattern_br_b.y-pattern_tl_b.y)/pixelRatio);base=max(0.0,base);height=max(0.0,height);float t=mod(normal.x,2.0);float z=t > 0.0 ? height : base;gl_Position=u_matrix*vec4(a_pos,z,1);vec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,z*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),ai=fi("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform float u_maxzoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggeration=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/ pow(2.0,(u_zoom-u_maxzoom)*exaggeration+19.2562-u_zoom);gl_FragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),ni=fi("uniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture2D(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;}"),si=fi("uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_linesofar;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_width2=vec2(outset,inset);}"),li=fi("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp float v_lineprogress;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture2D(u_image,vec2(v_lineprogress,0.5));gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define MAX_LINE_DISTANCE 32767.0\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_lineprogress;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_lineprogress=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0/MAX_LINE_DISTANCE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_width2=vec2(outset,inset);}"),ci=fi("uniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec4 u_scale;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float pixelRatio=u_scale.x;float tileZoomRatio=u_scale.y;float fromScale=u_scale.z;float toScale=u_scale.w;vec2 display_size_a=vec2((pattern_br_a.x-pattern_tl_a.x)/pixelRatio,(pattern_br_a.y-pattern_tl_a.y)/pixelRatio);vec2 display_size_b=vec2((pattern_br_b.x-pattern_tl_b.x)/pixelRatio,(pattern_br_b.y-pattern_tl_b.y)/pixelRatio);vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x,1.0);float x_b=mod(v_linesofar/pattern_size_b.x,1.0);float y_a=0.5+(v_normal.y*clamp(v_width2.s,0.0,(pattern_size_a.y+2.0)/2.0)/pattern_size_a.y);float y_b=0.5+(v_normal.y*clamp(v_width2.s,0.0,(pattern_size_b.y+2.0)/2.0)/pattern_size_b.y);vec2 pos_a=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,vec2(x_a,y_a));vec2 pos_b=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,vec2(x_b,y_b));vec4 color=mix(texture2D(u_image,pos_a),texture2D(u_image,pos_b),u_fade);gl_FragColor=color*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_linesofar=a_linesofar;v_width2=vec2(outset,inset);}"),ui=fi("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture2D(u_image,v_tex_a).a;float sdfdist_b=texture2D(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),hi=fi("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);gl_FragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos0=(((a_texture_pos/8192.0)-0.5)/u_buffer_scale )+0.5;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),pi=fi("uniform sampler2D u_texture;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;gl_FragColor=texture2D(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0),0.0,1.0);v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;v_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));}"),di=fi("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset),0.0,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),_i=fi("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale),0.0,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}");function fi(t,e){var i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,o={};return {fragmentSource:t=t.replace(i,(function(t,e,i,r,a){return o[a]=!0,"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nvarying "+i+" "+r+" "+a+";\n#else\nuniform "+i+" "+r+" u_"+a+";\n#endif\n":"\n#ifdef HAS_UNIFORM_u_"+a+"\n "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n"})),vertexSource:e=e.replace(i,(function(t,e,i,r,a){var n="float"===r?"vec2":"vec4",s=a.match(/color/)?"color":n;return o[a]?"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float u_"+a+"_t;\nattribute "+i+" "+n+" a_"+a+";\nvarying "+i+" "+r+" "+a+";\n#else\nuniform "+i+" "+r+" u_"+a+";\n#endif\n":"vec4"===s?"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+a+" = a_"+a+";\n#else\n "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+a+" = unpack_mix_"+s+"(a_"+a+", u_"+a+"_t);\n#else\n "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n":"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float u_"+a+"_t;\nattribute "+i+" "+n+" a_"+a+";\n#else\nuniform "+i+" "+r+" u_"+a+";\n#endif\n":"vec4"===s?"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+i+" "+r+" "+a+" = a_"+a+";\n#else\n "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+i+" "+r+" "+a+" = unpack_mix_"+s+"(a_"+a+", u_"+a+"_t);\n#else\n "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n"}))}}var mi=Object.freeze({__proto__:null,prelude:je,background:Ve,backgroundPattern:Ge,circle:We,clippingMask:Xe,heatmap:He,heatmapTexture:Ke,collisionBox:Ye,collisionCircle:Je,debug:Qe,fill:$e,fillOutline:ti,fillOutlinePattern:ei,fillPattern:ii,fillExtrusion:oi,fillExtrusionPattern:ri,hillshadePrepare:ai,hillshade:ni,line:si,lineGradient:li,linePattern:ci,lineSDF:ui,raster:hi,symbolIcon:pi,symbolSDF:di,symbolTextAndIcon:_i}),gi=function(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;};gi.prototype.bind=function(t,e,i,o,r,a,n,s){this.context=t;for(var l=this.boundPaintVertexBuffers.length!==o.length,c=0;!l&&c<o.length;c++)this.boundPaintVertexBuffers[c]!==o[c]&&(l=!0);var u=!this.vao||this.boundProgram!==e||this.boundLayoutVertexBuffer!==i||l||this.boundIndexBuffer!==r||this.boundVertexOffset!==a||this.boundDynamicVertexBuffer!==n||this.boundDynamicVertexBuffer2!==s;!t.extVertexArrayObject||u?this.freshBind(e,i,o,r,a,n,s):(t.bindVertexArrayOES.set(this.vao),n&&n.bind(),r&&r.dynamicDraw&&r.bind(),s&&s.bind());},gi.prototype.freshBind=function(t,e,i,o,r,a,n){var s,l=t.numAttributes,c=this.context,u=c.gl;if(c.extVertexArrayObject)this.vao&&this.destroy(),this.vao=c.extVertexArrayObject.createVertexArrayOES(),c.bindVertexArrayOES.set(this.vao),s=0,this.boundProgram=t,this.boundLayoutVertexBuffer=e,this.boundPaintVertexBuffers=i,this.boundIndexBuffer=o,this.boundVertexOffset=r,this.boundDynamicVertexBuffer=a,this.boundDynamicVertexBuffer2=n;else{s=c.currentNumAttributes||0;for(var h=l;h<s;h++)u.disableVertexAttribArray(h);}e.enableAttributes(u,t);for(var p=0,d=i;p<d.length;p+=1){d[p].enableAttributes(u,t);}a&&a.enableAttributes(u,t),n&&n.enableAttributes(u,t),e.bind(),e.setVertexAttribPointers(u,t,r);for(var _=0,f=i;_<f.length;_+=1){var m=f[_];m.bind(),m.setVertexAttribPointers(u,t,r);}a&&(a.bind(),a.setVertexAttribPointers(u,t,r)),o&&o.bind(),n&&(n.bind(),n.setVertexAttribPointers(u,t,r)),c.currentNumAttributes=l;},gi.prototype.destroy=function(){this.vao&&(this.context.extVertexArrayObject.deleteVertexArrayOES(this.vao),this.vao=null);};var vi=function(t,e,i,o,r){var a=t.gl;this.program=a.createProgram();var n=i?i.defines():[];r&&n.push("#define OVERDRAW_INSPECTOR;");var s=n.concat(je.fragmentSource,e.fragmentSource).join("\n"),l=n.concat(je.vertexSource,e.vertexSource).join("\n"),c=a.createShader(a.FRAGMENT_SHADER);if(a.isContextLost())this.failedToCreate=!0;else{a.shaderSource(c,s),a.compileShader(c),a.attachShader(this.program,c);var u=a.createShader(a.VERTEX_SHADER);if(a.isContextLost())this.failedToCreate=!0;else{a.shaderSource(u,l),a.compileShader(u),a.attachShader(this.program,u);for(var h=i?i.layoutAttributes:[],p=0;p<h.length;p++)a.bindAttribLocation(this.program,p,h[p].name);a.linkProgram(this.program),this.numAttributes=a.getProgramParameter(this.program,a.ACTIVE_ATTRIBUTES),this.attributes={};for(var d={},_=0;_<this.numAttributes;_++){var f=a.getActiveAttrib(this.program,_);f&&(this.attributes[f.name]=a.getAttribLocation(this.program,f.name));}for(var m=a.getProgramParameter(this.program,a.ACTIVE_UNIFORMS),g=0;g<m;g++){var v=a.getActiveUniform(this.program,g);v&&(d[v.name]=a.getUniformLocation(this.program,v.name));}this.fixedUniforms=o(t,d),this.binderUniforms=i?i.getUniforms(t,d):[];}}};function yi(e,i,o){var r=1/he(o,1,i.transform.tileZoom),a=Math.pow(2,o.tileID.overscaledZ),n=o.tileSize*Math.pow(2,i.transform.tileZoom)/a,s=n*(o.tileID.canonical.x+o.tileID.wrap*a),l=n*o.tileID.canonical.y;return {u_image:0,u_texsize:o.imageAtlasTexture.size,u_scale:[t.browser.devicePixelRatio,r,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[s>>16,l>>16],u_pixel_coord_lower:[65535&s,65535&l]}}vi.prototype.draw=function(t,e,i,o,r,a,n,s,l,c,u,h,p,d,_,f){var m,g=t.gl;if(!this.failedToCreate){for(var v in t.program.set(this.program),t.setDepthMode(i),t.setStencilMode(o),t.setColorMode(r),t.setCullFace(a),this.fixedUniforms)this.fixedUniforms[v].set(n[v]);d&&d.setUniforms(t,this.binderUniforms,h,{zoom:p});for(var y=(m={},m[g.LINES]=2,m[g.TRIANGLES]=3,m[g.LINE_STRIP]=1,m)[e],x=0,b=u.get();x<b.length;x+=1){var w=b[x],E=w.vaos||(w.vaos={});(E[s]||(E[s]=new gi)).bind(t,this,l,d?d.getPaintVertexBuffers():[],c,w.vertexOffset,_,f),g.drawElements(e,w.primitiveLength*y,g.UNSIGNED_SHORT,w.primitiveOffset*y*2);}}};var xi=function(e,i,o,r){var a=i.style.light,n=a.properties.get("position"),s=[n.x,n.y,n.z],l=t.create$1();"viewport"===a.properties.get("anchor")&&t.fromRotation(l,-i.transform.angle),t.transformMat3(s,s,l);var c=a.properties.get("color");return {u_matrix:e,u_lightpos:s,u_lightintensity:a.properties.get("intensity"),u_lightcolor:[c.r,c.g,c.b],u_vertical_gradient:+o,u_opacity:r}},bi=function(e,i,o,r,a,n,s){return t.extend(xi(e,i,o,r),yi(n,i,s),{u_height_factor:-Math.pow(2,a.overscaledZ)/s.tileSize/8})},wi=function(t){return {u_matrix:t}},Ei=function(e,i,o,r){return t.extend(wi(e),yi(o,i,r))},Ti=function(t,e){return {u_matrix:t,u_world:e}},Ii=function(e,i,o,r,a){return t.extend(Ei(e,i,o,r),{u_world:a})},Si=function(e,i,o,r){var a,n,s=e.transform;if("map"===r.paint.get("circle-pitch-alignment")){var l=he(o,1,s.zoom);a=!0,n=[l,l];}else a=!1,n=s.pixelsToGLUnits;return {u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===r.paint.get("circle-pitch-scale")),u_matrix:e.translatePosMatrix(i.posMatrix,o,r.paint.get("circle-translate"),r.paint.get("circle-translate-anchor")),u_pitch_with_map:+a,u_device_pixel_ratio:t.browser.devicePixelRatio,u_extrude_scale:n}},Ci=function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pixels_to_tile_units:new t.Uniform1f(e,i.u_pixels_to_tile_units),u_extrude_scale:new t.Uniform2f(e,i.u_extrude_scale),u_overscale_factor:new t.Uniform1f(e,i.u_overscale_factor)}},Pi=function(t,e,i){var o=he(i,1,e.zoom),r=Math.pow(2,e.zoom-i.tileID.overscaledZ),a=i.tileID.overscaleFactor();return {u_matrix:t,u_camera_to_center_distance:e.cameraToCenterDistance,u_pixels_to_tile_units:o,u_extrude_scale:[e.pixelsToGLUnits[0]/(o*r),e.pixelsToGLUnits[1]/(o*r)],u_overscale_factor:a}},zi=function(t,e){return {u_matrix:t,u_color:e}},Li=function(t){return {u_matrix:t}},Mi=function(t,e,i,o){return {u_matrix:t,u_extrude_scale:he(e,1,i),u_intensity:o}},Di=function(e,i,o,r){var a=t.create();t.ortho(a,0,e.width,e.height,0,0,1);var n=e.context.gl;return {u_matrix:a,u_world:[n.drawingBufferWidth,n.drawingBufferHeight],u_image:o,u_color_ramp:r,u_opacity:i.paint.get("heatmap-opacity")}},Ai=function(t,e,i){var o=i.paint.get("hillshade-shadow-color"),r=i.paint.get("hillshade-highlight-color"),a=i.paint.get("hillshade-accent-color"),n=i.paint.get("hillshade-illumination-direction")*(Math.PI/180);"viewport"===i.paint.get("hillshade-illumination-anchor")&&(n-=t.transform.angle);var s=!t.options.moving;return {u_matrix:t.transform.calculatePosMatrix(e.tileID.toUnwrapped(),s),u_image:0,u_latrange:ki(t,e.tileID),u_light:[i.paint.get("hillshade-exaggeration"),n],u_shadow:o,u_highlight:r,u_accent:a}},Ri=function(e,i,o){var r=i.stride,a=t.create();return t.ortho(a,0,t.EXTENT,-t.EXTENT,0,0,1),t.translate(a,a,[0,-t.EXTENT,0]),{u_matrix:a,u_image:1,u_dimension:[r,r],u_zoom:e.overscaledZ,u_maxzoom:o,u_unpack:i.getUnpackVector()}};function ki(e,i){var o=Math.pow(2,i.canonical.z),r=i.canonical.y;return [new t.MercatorCoordinate(0,r/o).toLngLat().lat,new t.MercatorCoordinate(0,(r+1)/o).toLngLat().lat]}var Bi=function(e,i,o){var r=e.transform;return {u_matrix:Zi(e,i,o),u_ratio:1/he(i,1,r.zoom),u_device_pixel_ratio:t.browser.devicePixelRatio,u_units_to_pixels:[1/r.pixelsToGLUnits[0],1/r.pixelsToGLUnits[1]]}},Oi=function(e,i,o){return t.extend(Bi(e,i,o),{u_image:0})},Fi=function(e,i,o,r){var a=e.transform,n=Ni(i,a);return {u_matrix:Zi(e,i,o),u_texsize:i.imageAtlasTexture.size,u_ratio:1/he(i,1,a.zoom),u_device_pixel_ratio:t.browser.devicePixelRatio,u_image:0,u_scale:[t.browser.devicePixelRatio,n,r.fromScale,r.toScale],u_fade:r.t,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},Ui=function(e,i,o,r,a){var n=e.transform,s=e.lineAtlas,l=Ni(i,n),c="round"===o.layout.get("line-cap"),u=s.getDash(r.from,c),h=s.getDash(r.to,c),p=u.width*a.fromScale,d=h.width*a.toScale;return t.extend(Bi(e,i,o),{u_patternscale_a:[l/p,-u.height/2],u_patternscale_b:[l/d,-h.height/2],u_sdfgamma:s.width/(256*Math.min(p,d)*t.browser.devicePixelRatio)/2,u_image:0,u_tex_y_a:u.y,u_tex_y_b:h.y,u_mix:a.t})};function Ni(t,e){return 1/he(t,1,e.tileZoom)}function Zi(t,e,i){return t.translatePosMatrix(e.tileID.posMatrix,e,i.paint.get("line-translate"),i.paint.get("line-translate-anchor"))}var qi=function(t,e,i,o,r){return {u_matrix:t,u_tl_parent:e,u_scale_parent:i,u_buffer_scale:1,u_fade_t:o.mix,u_opacity:o.opacity*r.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:r.paint.get("raster-brightness-min"),u_brightness_high:r.paint.get("raster-brightness-max"),u_saturation_factor:(n=r.paint.get("raster-saturation"),n>0?1-1/(1.001-n):-n),u_contrast_factor:(a=r.paint.get("raster-contrast"),a>0?1/(1-a):1+a),u_spin_weights:ji(r.paint.get("raster-hue-rotate"))};var a,n;};function ji(t){t*=Math.PI/180;var e=Math.sin(t),i=Math.cos(t);return [(2*i+1)/3,(-Math.sqrt(3)*e-i+1)/3,(Math.sqrt(3)*e-i+1)/3]}var Vi=function(t,e,i,o,r,a,n,s,l,c){var u=r.transform;return {u_is_size_zoom_constant:+("constant"===t||"source"===t),u_is_size_feature_constant:+("constant"===t||"camera"===t),u_size_t:e?e.uSizeT:0,u_size:e?e.uSize:0,u_camera_to_center_distance:u.cameraToCenterDistance,u_pitch:u.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:u.width/u.height,u_fade_change:r.options.fadeDuration?r.symbolFadeChange:1,u_matrix:a,u_label_plane_matrix:n,u_coord_matrix:s,u_is_text:+l,u_pitch_with_map:+o,u_texsize:c,u_texture:0}},Gi=function(e,i,o,r,a,n,s,l,c,u,h){var p=a.transform;return t.extend(Vi(e,i,o,r,a,n,s,l,c,u),{u_gamma_scale:r?Math.cos(p._pitch)*p.cameraToCenterDistance:1,u_device_pixel_ratio:t.browser.devicePixelRatio,u_is_halo:+h})},Wi=function(e,i,o,r,a,n,s,l,c,u){return t.extend(Gi(e,i,o,r,a,n,s,l,!0,c,!0),{u_texsize_icon:u,u_texture_icon:1})},Xi=function(t,e,i){return {u_matrix:t,u_opacity:e,u_color:i}},Hi=function(e,i,o,r,a,n){return t.extend(function(t,e,i,o){var r=i.imageManager.getPattern(t.from.toString()),a=i.imageManager.getPattern(t.to.toString()),n=i.imageManager.getPixelSize(),s=n.width,l=n.height,c=Math.pow(2,o.tileID.overscaledZ),u=o.tileSize*Math.pow(2,i.transform.tileZoom)/c,h=u*(o.tileID.canonical.x+o.tileID.wrap*c),p=u*o.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:r.tl,u_pattern_br_a:r.br,u_pattern_tl_b:a.tl,u_pattern_br_b:a.br,u_texsize:[s,l],u_mix:e.t,u_pattern_size_a:r.displaySize,u_pattern_size_b:a.displaySize,u_scale_a:e.fromScale,u_scale_b:e.toScale,u_tile_units_to_pixels:1/he(o,1,i.transform.tileZoom),u_pixel_coord_upper:[h>>16,p>>16],u_pixel_coord_lower:[65535&h,65535&p]}}(r,n,o,a),{u_matrix:e,u_opacity:i})},Ki={fillExtrusion:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_lightpos:new t.Uniform3f(e,i.u_lightpos),u_lightintensity:new t.Uniform1f(e,i.u_lightintensity),u_lightcolor:new t.Uniform3f(e,i.u_lightcolor),u_vertical_gradient:new t.Uniform1f(e,i.u_vertical_gradient),u_opacity:new t.Uniform1f(e,i.u_opacity)}},fillExtrusionPattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_lightpos:new t.Uniform3f(e,i.u_lightpos),u_lightintensity:new t.Uniform1f(e,i.u_lightintensity),u_lightcolor:new t.Uniform3f(e,i.u_lightcolor),u_vertical_gradient:new t.Uniform1f(e,i.u_vertical_gradient),u_height_factor:new t.Uniform1f(e,i.u_height_factor),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform4f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade),u_opacity:new t.Uniform1f(e,i.u_opacity)}},fill:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},fillPattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform4f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}},fillOutline:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world)}},fillOutlinePattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform4f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}},circle:function(e,i){return {u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_scale_with_map:new t.Uniform1i(e,i.u_scale_with_map),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_extrude_scale:new t.Uniform2f(e,i.u_extrude_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},collisionBox:Ci,collisionCircle:Ci,debug:function(e,i){return {u_color:new t.UniformColor(e,i.u_color),u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},clippingMask:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},heatmap:function(e,i){return {u_extrude_scale:new t.Uniform1f(e,i.u_extrude_scale),u_intensity:new t.Uniform1f(e,i.u_intensity),u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},heatmapTexture:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world),u_image:new t.Uniform1i(e,i.u_image),u_color_ramp:new t.Uniform1i(e,i.u_color_ramp),u_opacity:new t.Uniform1f(e,i.u_opacity)}},hillshade:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_latrange:new t.Uniform2f(e,i.u_latrange),u_light:new t.Uniform2f(e,i.u_light),u_shadow:new t.UniformColor(e,i.u_shadow),u_highlight:new t.UniformColor(e,i.u_highlight),u_accent:new t.UniformColor(e,i.u_accent)}},hillshadePrepare:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_dimension:new t.Uniform2f(e,i.u_dimension),u_zoom:new t.Uniform1f(e,i.u_zoom),u_maxzoom:new t.Uniform1f(e,i.u_maxzoom),u_unpack:new t.Uniform4f(e,i.u_unpack)}},line:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels)}},lineGradient:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_image:new t.Uniform1i(e,i.u_image)}},linePattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_texsize:new t.Uniform2f(e,i.u_texsize),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_image:new t.Uniform1i(e,i.u_image),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_scale:new t.Uniform4f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}},lineSDF:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_patternscale_a:new t.Uniform2f(e,i.u_patternscale_a),u_patternscale_b:new t.Uniform2f(e,i.u_patternscale_b),u_sdfgamma:new t.Uniform1f(e,i.u_sdfgamma),u_image:new t.Uniform1i(e,i.u_image),u_tex_y_a:new t.Uniform1f(e,i.u_tex_y_a),u_tex_y_b:new t.Uniform1f(e,i.u_tex_y_b),u_mix:new t.Uniform1f(e,i.u_mix)}},raster:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_tl_parent:new t.Uniform2f(e,i.u_tl_parent),u_scale_parent:new t.Uniform1f(e,i.u_scale_parent),u_buffer_scale:new t.Uniform1f(e,i.u_buffer_scale),u_fade_t:new t.Uniform1f(e,i.u_fade_t),u_opacity:new t.Uniform1f(e,i.u_opacity),u_image0:new t.Uniform1i(e,i.u_image0),u_image1:new t.Uniform1i(e,i.u_image1),u_brightness_low:new t.Uniform1f(e,i.u_brightness_low),u_brightness_high:new t.Uniform1f(e,i.u_brightness_high),u_saturation_factor:new t.Uniform1f(e,i.u_saturation_factor),u_contrast_factor:new t.Uniform1f(e,i.u_contrast_factor),u_spin_weights:new t.Uniform3f(e,i.u_spin_weights)}},symbolIcon:function(e,i){return {u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1f(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texture:new t.Uniform1i(e,i.u_texture)}},symbolSDF:function(e,i){return {u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1f(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texture:new t.Uniform1i(e,i.u_texture),u_gamma_scale:new t.Uniform1f(e,i.u_gamma_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_is_halo:new t.Uniform1f(e,i.u_is_halo)}},symbolTextAndIcon:function(e,i){return {u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1f(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texsize_icon:new t.Uniform2f(e,i.u_texsize_icon),u_texture:new t.Uniform1i(e,i.u_texture),u_texture_icon:new t.Uniform1i(e,i.u_texture_icon),u_gamma_scale:new t.Uniform1f(e,i.u_gamma_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_is_halo:new t.Uniform1f(e,i.u_is_halo)}},background:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_opacity:new t.Uniform1f(e,i.u_opacity),u_color:new t.UniformColor(e,i.u_color)}},backgroundPattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_opacity:new t.Uniform1f(e,i.u_opacity),u_image:new t.Uniform1i(e,i.u_image),u_pattern_tl_a:new t.Uniform2f(e,i.u_pattern_tl_a),u_pattern_br_a:new t.Uniform2f(e,i.u_pattern_br_a),u_pattern_tl_b:new t.Uniform2f(e,i.u_pattern_tl_b),u_pattern_br_b:new t.Uniform2f(e,i.u_pattern_br_b),u_texsize:new t.Uniform2f(e,i.u_texsize),u_mix:new t.Uniform1f(e,i.u_mix),u_pattern_size_a:new t.Uniform2f(e,i.u_pattern_size_a),u_pattern_size_b:new t.Uniform2f(e,i.u_pattern_size_b),u_scale_a:new t.Uniform1f(e,i.u_scale_a),u_scale_b:new t.Uniform1f(e,i.u_scale_b),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.Uniform1f(e,i.u_tile_units_to_pixels)}}};function Yi(t,e,i,o,r,a,n,s){for(var l=t.context,c=l.gl,u=r?t.useProgram("collisionCircle"):t.useProgram("collisionBox"),h=0;h<o.length;h++){var p=o[h],d=e.getTile(p),_=d.getBucket(i);if(_){var f=r?s?_.textCollisionCircle:_.iconCollisionCircle:s?_.textCollisionBox:_.iconCollisionBox;if(f){var m=p.posMatrix;0===a[0]&&0===a[1]||(m=t.translatePosMatrix(p.posMatrix,d,a,n)),u.draw(l,r?c.TRIANGLES:c.LINES,St.disabled,Ct.disabled,t.colorModeForRenderPass(),zt.disabled,Pi(m,t.transform,d),i.id,f.layoutVertexBuffer,f.indexBuffer,f.segments,null,t.transform.zoom,null,null,f.collisionVertexBuffer);}}}}function Ji(t,e,i,o,r,a,n){Yi(t,e,i,o,!1,r,a,n),Yi(t,e,i,o,!0,r,a,n);}var Qi=t.identity(new Float32Array(16));function $i(e,i,o,r,a,n){var s=t.getAnchorAlignment(e),l=-(s.horizontalAlign-.5)*i,c=-(s.verticalAlign-.5)*o,u=t.evaluateVariableOffset(e,r);return new t.Point((l/a+u[0])*n,(c/a+u[1])*n)}function to(e,i,o,r,a,n,s,l,c,u,h){var p=e.text.placedSymbolArray,d=e.text.dynamicLayoutVertexArray,_=e.icon.dynamicLayoutVertexArray,f={};d.clear();for(var m=0;m<p.length;m++){var g=p.get(m),v=e.allowVerticalPlacement&&!g.placedOrientation,y=g.hidden||!g.crossTileID||v?null:r[g.crossTileID];if(y){var x=new t.Point(g.anchorX,g.anchorY),b=Qt(x,o?l:s),w=.5+n.cameraToCenterDistance/b.signedDistanceFromCamera*.5,E=a.evaluateSizeForFeature(e.textSizeData,u,g)*w/t.ONE_EM;o&&(E*=e.tilePixelRatio/c);for(var T=y.width,I=y.height,S=$i(y.anchor,T,I,y.textOffset,y.textBoxScale,E),C=o?Qt(x.add(S),s).point:b.point.add(i?S.rotate(-n.angle):S),P=e.allowVerticalPlacement&&g.placedOrientation===t.WritingMode.vertical?Math.PI/2:0,z=0;z<g.numGlyphs;z++)t.addDynamicAttributes(d,C,P);h&&g.associatedIconIndex>=0&&(f[g.associatedIconIndex]={shiftedAnchor:C,angle:P});}else se(g.numGlyphs,d);}if(h){_.clear();for(var L=e.icon.placedSymbolArray,M=0;M<L.length;M++){var D=L.get(M);if(D.hidden)se(D.numGlyphs,_);else{var A=f[M];if(A)for(var R=0;R<D.numGlyphs;R++)t.addDynamicAttributes(_,A.shiftedAnchor,A.angle);else se(D.numGlyphs,_);}}e.icon.dynamicLayoutVertexBuffer.updateData(_);}e.text.dynamicLayoutVertexBuffer.updateData(d);}function eo(t,e,i){return i.iconsInText&&e?"symbolTextAndIcon":t?"symbolSDF":"symbolIcon"}function io(e,i,o,r,a,n,s,l,c,u,h,p){for(var d,_,f=e.context,m=f.gl,g=e.transform,v="map"===l,y="map"===c,x=v&&"point"!==o.layout.get("symbol-placement"),b=v&&!y&&!x,w=void 0!==o.layout.get("symbol-sort-key").constantOr(1),E=e.depthModeForSublayer(0,St.ReadOnly),T=o.layout.get("text-variable-anchor"),I=[],S=0,C=r;S<C.length;S+=1){var P=C[S],z=i.getTile(P),L=z.getBucket(o);if(L){var M=a?L.text:L.icon;if(M&&M.segments.get().length){var D=M.programConfigurations.get(o.id),A=a||L.sdfIcons,R=a?L.textSizeData:L.iconSizeData,k=y||0!==g.pitch;d||(d=e.useProgram(eo(A,a,L),D),_=t.evaluateSizeForZoom(R,g.zoom));var B=void 0,O=[0,0],F=void 0,U=void 0,N=null,Z=void 0;if(a){if(F=z.glyphAtlasTexture,U=m.LINEAR,B=z.glyphAtlasTexture.size,L.iconsInText){O=z.imageAtlasTexture.size,N=z.imageAtlasTexture;var q="composite"===R.kind||"camera"===R.kind;Z=k||e.options.rotating||e.options.zooming||q?m.LINEAR:m.NEAREST;}}else{var j=1!==o.layout.get("icon-size").constantOr(0)||L.iconsNeedLinear;F=z.imageAtlasTexture,U=A||e.options.rotating||e.options.zooming||j||k?m.LINEAR:m.NEAREST,B=z.imageAtlasTexture.size;}var V=he(z,1,e.transform.zoom),G=Yt(P.posMatrix,y,v,e.transform,V),W=Jt(P.posMatrix,y,v,e.transform,V),X=T&&L.hasTextData(),H="none"!==o.layout.get("icon-text-fit")&&X&&L.hasIconData();x&&te(L,P.posMatrix,e,a,G,W,y,u);var K=e.translatePosMatrix(P.posMatrix,z,n,s),Y=x||a&&T||H?Qi:G,J=e.translatePosMatrix(W,z,n,s,!0),Q=A&&0!==o.paint.get(a?"text-halo-width":"icon-halo-width").constantOr(1),$={program:d,buffers:M,uniformValues:A?L.iconsInText?Wi(R.kind,_,b,y,e,K,Y,J,B,O):Gi(R.kind,_,b,y,e,K,Y,J,a,B,!0):Vi(R.kind,_,b,y,e,K,Y,J,a,B),atlasTexture:F,atlasTextureIcon:N,atlasInterpolation:U,atlasInterpolationIcon:Z,isSDF:A,hasHalo:Q};if(w)for(var tt=0,et=M.segments.get();tt<et.length;tt+=1){var it=et[tt];I.push({segments:new t.SegmentVector([it]),sortKey:it.sortKey,state:$});}else I.push({segments:M.segments,sortKey:0,state:$});}}}w&&I.sort((function(t,e){return t.sortKey-e.sortKey}));for(var ot=0,rt=I;ot<rt.length;ot+=1){var at=rt[ot],nt=at.state;if(f.activeTexture.set(m.TEXTURE0),nt.atlasTexture.bind(nt.atlasInterpolation,m.CLAMP_TO_EDGE),nt.atlasTextureIcon&&(f.activeTexture.set(m.TEXTURE1),nt.atlasTextureIcon&&nt.atlasTextureIcon.bind(nt.atlasInterpolationIcon,m.CLAMP_TO_EDGE)),nt.isSDF){var st=nt.uniformValues;nt.hasHalo&&(st.u_is_halo=1,oo(nt.buffers,at.segments,o,e,nt.program,E,h,p,st)),st.u_is_halo=0;}oo(nt.buffers,at.segments,o,e,nt.program,E,h,p,nt.uniformValues);}}function oo(t,e,i,o,r,a,n,s,l){var c=o.context,u=c.gl;r.draw(c,u.TRIANGLES,a,n,s,zt.disabled,l,i.id,t.layoutVertexBuffer,t.indexBuffer,e,i.paint,o.transform.zoom,t.programConfigurations.get(i.id),t.dynamicLayoutVertexBuffer,t.opacityVertexBuffer);}function ro(t,e,i,o,r,a,n){var s,l,c,u,h,p=t.context.gl,d=i.paint.get("fill-pattern"),_=d&&d.constantOr(1),f=i.getCrossfadeParameters();n?(l=_&&!i.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",s=p.LINES):(l=_?"fillPattern":"fill",s=p.TRIANGLES);for(var m=0,g=o;m<g.length;m+=1){var v=g[m],y=e.getTile(v);if(!_||y.patternsLoaded()){var x=y.getBucket(i);if(x){var b=x.programConfigurations.get(i.id),w=t.useProgram(l,b);_&&(t.context.activeTexture.set(p.TEXTURE0),y.imageAtlasTexture.bind(p.LINEAR,p.CLAMP_TO_EDGE),b.updatePaintBuffers(f));var E=d.constantOr(null);if(E&&y.imageAtlas){var T=y.imageAtlas,I=T.patternPositions[E.to.toString()],S=T.patternPositions[E.from.toString()];I&&S&&b.setConstantPatternPositions(I,S);}var C=t.translatePosMatrix(v.posMatrix,y,i.paint.get("fill-translate"),i.paint.get("fill-translate-anchor"));if(n){u=x.indexBuffer2,h=x.segments2;var P=[p.drawingBufferWidth,p.drawingBufferHeight];c="fillOutlinePattern"===l&&_?Ii(C,t,f,y,P):Ti(C,P);}else u=x.indexBuffer,h=x.segments,c=_?Ei(C,t,f,y):wi(C);w.draw(t.context,s,r,t.stencilModeForClipping(v),a,zt.disabled,c,i.id,x.layoutVertexBuffer,u,h,i.paint,t.transform.zoom,b);}}}}function ao(t,e,i,o,r,a,n){for(var s=t.context,l=s.gl,c=i.paint.get("fill-extrusion-pattern"),u=c.constantOr(1),h=i.getCrossfadeParameters(),p=i.paint.get("fill-extrusion-opacity"),d=0,_=o;d<_.length;d+=1){var f=_[d],m=e.getTile(f),g=m.getBucket(i);if(g){var v=g.programConfigurations.get(i.id),y=t.useProgram(u?"fillExtrusionPattern":"fillExtrusion",v);u&&(t.context.activeTexture.set(l.TEXTURE0),m.imageAtlasTexture.bind(l.LINEAR,l.CLAMP_TO_EDGE),v.updatePaintBuffers(h));var x=c.constantOr(null);if(x&&m.imageAtlas){var b=m.imageAtlas,w=b.patternPositions[x.to.toString()],E=b.patternPositions[x.from.toString()];w&&E&&v.setConstantPatternPositions(w,E);}var T=t.translatePosMatrix(f.posMatrix,m,i.paint.get("fill-extrusion-translate"),i.paint.get("fill-extrusion-translate-anchor")),I=i.paint.get("fill-extrusion-vertical-gradient"),S=u?bi(T,t,I,p,f,h,m):xi(T,t,I,p);y.draw(s,s.gl.TRIANGLES,r,a,n,zt.backCCW,S,i.id,g.layoutVertexBuffer,g.indexBuffer,g.segments,i.paint,t.transform.zoom,v);}}}function no(t,e,i,o,r,a){var n=t.context,s=n.gl,l=e.fbo;if(l){var c=t.useProgram("hillshade");n.activeTexture.set(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,l.colorAttachment.get());var u=Ai(t,e,i);c.draw(n,s.TRIANGLES,o,r,a,zt.disabled,u,i.id,t.rasterBoundsBuffer,t.quadTriangleIndexBuffer,t.rasterBoundsSegments);}}function so(e,i,o,r,a,n,s){var l=e.context,c=l.gl,u=i.dem;if(u&&u.data){var h=u.dim,p=u.stride,d=u.getPixels();if(l.activeTexture.set(c.TEXTURE1),l.pixelStoreUnpackPremultiplyAlpha.set(!1),i.demTexture=i.demTexture||e.getTileTexture(p),i.demTexture){var _=i.demTexture;_.update(d,{premultiply:!1}),_.bind(c.NEAREST,c.CLAMP_TO_EDGE);}else i.demTexture=new t.Texture(l,d,c.RGBA,{premultiply:!1}),i.demTexture.bind(c.NEAREST,c.CLAMP_TO_EDGE);l.activeTexture.set(c.TEXTURE0);var f=i.fbo;if(!f){var m=new t.Texture(l,{width:h,height:h,data:null},c.RGBA);m.bind(c.LINEAR,c.CLAMP_TO_EDGE),(f=i.fbo=l.createFramebuffer(h,h)).colorAttachment.set(m.texture);}l.bindFramebuffer.set(f.framebuffer),l.viewport.set([0,0,h,h]),e.useProgram("hillshadePrepare").draw(l,c.TRIANGLES,a,n,s,zt.disabled,Ri(i.tileID,u,r),o.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments),i.needsHillshadePrepare=!1;}}function lo(e,i,o,r,a){var n=r.paint.get("raster-fade-duration");if(n>0){var s=t.browser.now(),l=(s-e.timeAdded)/n,c=i?(s-i.timeAdded)/n:-1,u=o.getSource(),h=a.coveringZoomLevel({tileSize:u.tileSize,roundZoom:u.roundZoom}),p=!i||Math.abs(i.tileID.overscaledZ-h)>Math.abs(e.tileID.overscaledZ-h),d=p&&e.refreshedUponExpiration?1:t.clamp(p?l:1-c,0,1);return e.refreshedUponExpiration&&l>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-d}:{opacity:d,mix:0}}return {opacity:1,mix:0}}function co(e,i,o){var r=e.context,a=r.gl,n=o.posMatrix,s=e.useProgram("debug"),l=St.disabled,c=Ct.disabled,u=e.colorModeForRenderPass(),h="$debug";s.draw(r,a.LINE_STRIP,l,c,u,zt.disabled,zi(n,t.Color.red),h,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);var p=i.getTileByID(o.key).latestRawTileData,d=p&&p.byteLength||0,_=Math.floor(d/1024),f=i.getTile(o).tileSize,m=512/Math.min(f,512),g=o.canonical.toString();o.overscaledZ!==o.canonical.z&&(g+=" => "+o.overscaledZ);for(var v=function(t,e,i,o){o=o||1;var r,a,n,s,l,c,u,h,p=[];for(r=0,a=t.length;r<a;r++)if(l=uo[t[r]]){for(h=null,n=0,s=l[1].length;n<s;n+=2)-1===l[1][n]&&-1===l[1][n+1]?h=null:(c=e+l[1][n]*o,u=i-l[1][n+1]*o,h&&p.push(h.x,h.y,c,u),h={x:c,y:u});e+=l[0]*o;}return p}(g+" "+_+"kb",50,200*m,5*m),y=new t.StructArrayLayout2i4,x=new t.StructArrayLayout2ui4,b=0;b<v.length;b+=2)y.emplaceBack(v[b],v[b+1]),x.emplaceBack(b,b+1);for(var w=r.createVertexBuffer(y,qe.members),E=r.createIndexBuffer(x),T=t.SegmentVector.simpleSegment(0,0,y.length/2,y.length/2),I=t.EXTENT/(Math.pow(2,e.transform.zoom-o.overscaledZ)*f*m),S=[],C=-1;C<=1;C++)for(var P=-1;P<=1&&(0!==C||0!==P);P++)S.push([C,P]);for(var z=0;z<S.length;z++){var L=S[z];s.draw(r,a.LINES,l,c,u,zt.disabled,zi(t.translate([],n,[I*L[0],I*L[1],0]),t.Color.white),h,w,E,T);}s.draw(r,a.LINES,l,c,u,zt.disabled,zi(n,t.Color.black),h,w,E,T),w.destroy(),E.destroy(),T.destroy();}var uo={" ":[16,[]],"!":[10,[5,21,5,7,-1,-1,5,2,4,1,5,0,6,1,5,2]],'"':[16,[4,21,4,14,-1,-1,12,21,12,14]],"#":[21,[11,25,4,-7,-1,-1,17,25,10,-7,-1,-1,4,12,18,12,-1,-1,3,6,17,6]],$:[20,[8,25,8,-4,-1,-1,12,25,12,-4,-1,-1,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3]],"%":[24,[21,21,3,0,-1,-1,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4,20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,-1,-1,17,7,15,6,14,4,14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7]],"&":[26,[23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5,1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21,9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2]],"'":[10,[5,19,4,20,5,21,6,20,6,18,5,16,4,15]],"(":[14,[11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7]],")":[14,[3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7]],"*":[16,[8,21,8,9,-1,-1,3,18,13,12,-1,-1,13,18,3,12]],"+":[26,[13,18,13,0,-1,-1,4,9,22,9]],",":[10,[6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4]],"-":[26,[4,9,22,9]],".":[10,[5,2,4,1,5,0,6,1,5,2]],"/":[22,[20,25,2,-7]],0:[20,[9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17,9,17,12,16,17,14,20,11,21,9,21]],1:[20,[6,17,8,18,11,21,11,0]],2:[20,[4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13,10,3,0,17,0]],3:[20,[5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4]],4:[20,[13,21,3,7,18,7,-1,-1,13,21,13,0]],5:[20,[15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4]],6:[20,[16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11,0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7]],7:[20,[17,21,7,0,-1,-1,3,21,17,21]],8:[20,[8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16,2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13,15,14,16,16,16,18,15,20,12,21,8,21]],9:[20,[16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9,21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3]],":":[10,[5,14,4,13,5,12,6,13,5,14,-1,-1,5,2,4,1,5,0,6,1,5,2]],";":[10,[5,14,4,13,5,12,6,13,5,14,-1,-1,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4]],"<":[24,[20,18,4,9,20,0]],"=":[26,[4,12,22,12,-1,-1,4,6,22,6]],">":[24,[4,18,20,9,4,0]],"?":[18,[3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,-1,-1,9,2,8,1,9,0,10,1,9,2]],"@":[27,[18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,-1,-1,12,16,10,14,9,11,9,8,10,6,11,5,-1,-1,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,-1,-1,19,16,18,8,18,6,19,5]],A:[18,[9,21,1,0,-1,-1,9,21,17,0,-1,-1,4,7,14,7]],B:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,-1,-1,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0]],C:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5]],D:[21,[4,21,4,0,-1,-1,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0]],E:[19,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,4,0,17,0]],F:[18,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11]],G:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,-1,-1,13,8,18,8]],H:[22,[4,21,4,0,-1,-1,18,21,18,0,-1,-1,4,11,18,11]],I:[8,[4,21,4,0]],J:[16,[12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7]],K:[21,[4,21,4,0,-1,-1,18,21,4,7,-1,-1,9,12,18,0]],L:[17,[4,21,4,0,-1,-1,4,0,16,0]],M:[24,[4,21,4,0,-1,-1,4,21,12,0,-1,-1,20,21,12,0,-1,-1,20,21,20,0]],N:[22,[4,21,4,0,-1,-1,4,21,18,0,-1,-1,18,21,18,0]],O:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21]],P:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10]],Q:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,12,4,18,-2]],R:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,-1,-1,11,11,18,0]],S:[20,[17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3]],T:[16,[8,21,8,0,-1,-1,1,21,15,21]],U:[22,[4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21]],V:[18,[1,21,9,0,-1,-1,17,21,9,0]],W:[24,[2,21,7,0,-1,-1,12,21,7,0,-1,-1,12,21,17,0,-1,-1,22,21,17,0]],X:[20,[3,21,17,0,-1,-1,17,21,3,0]],Y:[18,[1,21,9,11,9,0,-1,-1,17,21,9,11]],Z:[20,[17,21,3,0,-1,-1,3,21,17,21,-1,-1,3,0,17,0]],"[":[14,[4,25,4,-7,-1,-1,5,25,5,-7,-1,-1,4,25,11,25,-1,-1,4,-7,11,-7]],"\\":[14,[0,21,14,-3]],"]":[14,[9,25,9,-7,-1,-1,10,25,10,-7,-1,-1,3,25,10,25,-1,-1,3,-7,10,-7]],"^":[16,[6,15,8,18,10,15,-1,-1,3,12,8,17,13,12,-1,-1,8,17,8,0]],_:[16,[0,-2,16,-2]],"`":[10,[6,21,5,20,4,18,4,16,5,15,6,16,5,17]],a:[19,[15,14,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],b:[19,[4,21,4,0,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],c:[18,[15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],d:[19,[15,21,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],e:[18,[3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],f:[12,[10,21,8,21,6,20,5,17,5,0,-1,-1,2,14,9,14]],g:[19,[15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],h:[19,[4,21,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],i:[8,[3,21,4,20,5,21,4,22,3,21,-1,-1,4,14,4,0]],j:[10,[5,21,6,20,7,21,6,22,5,21,-1,-1,6,14,6,-3,5,-6,3,-7,1,-7]],k:[17,[4,21,4,0,-1,-1,14,14,4,4,-1,-1,8,8,15,0]],l:[8,[4,21,4,0]],m:[30,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,15,10,18,13,20,14,23,14,25,13,26,10,26,0]],n:[19,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],o:[19,[8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14]],p:[19,[4,14,4,-7,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],q:[19,[15,14,15,-7,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],r:[13,[4,14,4,0,-1,-1,4,8,5,11,7,13,9,14,12,14]],s:[17,[14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3]],t:[12,[5,21,5,4,6,1,8,0,10,0,-1,-1,2,14,9,14]],u:[19,[4,14,4,4,5,1,7,0,10,0,12,1,15,4,-1,-1,15,14,15,0]],v:[16,[2,14,8,0,-1,-1,14,14,8,0]],w:[22,[3,14,7,0,-1,-1,11,14,7,0,-1,-1,11,14,15,0,-1,-1,19,14,15,0]],x:[17,[3,14,14,0,-1,-1,14,14,3,0]],y:[16,[2,14,8,0,-1,-1,14,14,8,0,6,-4,4,-6,2,-7,1,-7]],z:[17,[14,14,3,0,-1,-1,3,14,14,14,-1,-1,3,0,14,0]],"{":[14,[9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,-1,-1,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,-1,-1,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7]],"|":[8,[4,25,4,-7]],"}":[14,[5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,-1,-1,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,-1,-1,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7]],"~":[24,[3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,-1,-1,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]]};var ho={symbol:function(e,i,o,r,a){if("translucent"===e.renderPass){var n=Ct.disabled,s=e.colorModeForRenderPass();o.layout.get("text-variable-anchor")&&function(e,i,o,r,a,n,s){for(var l=i.transform,c="map"===a,u="map"===n,h=0,p=e;h<p.length;h+=1){var d=p[h],_=r.getTile(d),f=_.getBucket(o);if(f&&f.text&&f.text.segments.get().length){var m=f.textSizeData,g=t.evaluateSizeForZoom(m,l.zoom),v=he(_,1,i.transform.zoom),y=Yt(d.posMatrix,u,c,i.transform,v),x="none"!==o.layout.get("icon-text-fit")&&f.hasIconData();if(g){var b=Math.pow(2,l.zoom-_.tileID.overscaledZ);to(f,c,u,s,t.symbolSize,l,y,d.posMatrix,b,g,x);}}}}(r,e,o,i,o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),a),0!==o.paint.get("icon-opacity").constantOr(1)&&io(e,i,o,r,!1,o.paint.get("icon-translate"),o.paint.get("icon-translate-anchor"),o.layout.get("icon-rotation-alignment"),o.layout.get("icon-pitch-alignment"),o.layout.get("icon-keep-upright"),n,s),0!==o.paint.get("text-opacity").constantOr(1)&&io(e,i,o,r,!0,o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.layout.get("text-keep-upright"),n,s),i.map.showCollisionBoxes&&(Ji(e,i,o,r,o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),!0),Ji(e,i,o,r,o.paint.get("icon-translate"),o.paint.get("icon-translate-anchor"),!1));}},circle:function(e,i,o,r){if("translucent"===e.renderPass){var a=o.paint.get("circle-opacity"),n=o.paint.get("circle-stroke-width"),s=o.paint.get("circle-stroke-opacity"),l=void 0!==o.layout.get("circle-sort-key").constantOr(1);if(0!==a.constantOr(1)||0!==n.constantOr(1)&&0!==s.constantOr(1)){for(var c=e.context,u=c.gl,h=e.depthModeForSublayer(0,St.ReadOnly),p=Ct.disabled,d=e.colorModeForRenderPass(),_=[],f=0;f<r.length;f++){var m=r[f],g=i.getTile(m),v=g.getBucket(o);if(v){var y=v.programConfigurations.get(o.id),x={programConfiguration:y,program:e.useProgram("circle",y),layoutVertexBuffer:v.layoutVertexBuffer,indexBuffer:v.indexBuffer,uniformValues:Si(e,m,g,o)};if(l)for(var b=0,w=v.segments.get();b<w.length;b+=1){var E=w[b];_.push({segments:new t.SegmentVector([E]),sortKey:E.sortKey,state:x});}else _.push({segments:v.segments,sortKey:0,state:x});}}l&&_.sort((function(t,e){return t.sortKey-e.sortKey}));for(var T=0,I=_;T<I.length;T+=1){var S=I[T],C=S.state,P=C.programConfiguration,z=C.program,L=C.layoutVertexBuffer,M=C.indexBuffer,D=C.uniformValues,A=S.segments;z.draw(c,u.TRIANGLES,h,p,d,zt.disabled,D,o.id,L,M,A,o.paint,e.transform.zoom,P);}}}},heatmap:function(e,i,o,r){if(0!==o.paint.get("heatmap-opacity"))if("offscreen"===e.renderPass){var a=e.context,n=a.gl,s=e.depthModeForSublayer(0,St.ReadOnly),l=Ct.disabled,c=new Pt([n.ONE,n.ONE],t.Color.transparent,[!0,!0,!0,!0]);!function(t,e,i){var o=t.gl;t.activeTexture.set(o.TEXTURE1),t.viewport.set([0,0,e.width/4,e.height/4]);var r=i.heatmapFbo;if(r)o.bindTexture(o.TEXTURE_2D,r.colorAttachment.get()),t.bindFramebuffer.set(r.framebuffer);else{var a=o.createTexture();o.bindTexture(o.TEXTURE_2D,a),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),r=i.heatmapFbo=t.createFramebuffer(e.width/4,e.height/4),function t(e,i,o,r){var a=e.gl;a.texImage2D(a.TEXTURE_2D,0,a.RGBA,i.width/4,i.height/4,0,a.RGBA,e.extTextureHalfFloat?e.extTextureHalfFloat.HALF_FLOAT_OES:a.UNSIGNED_BYTE,null);r.colorAttachment.set(o);e.extTextureHalfFloat&&a.checkFramebufferStatus(a.FRAMEBUFFER)!==a.FRAMEBUFFER_COMPLETE&&(e.extTextureHalfFloat=null,r.colorAttachment.setDirty(),t(e,i,o,r));}(t,e,a,r);}}(a,e,o),a.clear({color:t.Color.transparent});for(var u=0;u<r.length;u++){var h=r[u];if(!i.hasRenderableParent(h)){var p=i.getTile(h),d=p.getBucket(o);if(d){var _=d.programConfigurations.get(o.id),f=e.useProgram("heatmap",_),m=e.transform.zoom;f.draw(a,n.TRIANGLES,s,l,c,zt.disabled,Mi(h.posMatrix,p,m,o.paint.get("heatmap-intensity")),o.id,d.layoutVertexBuffer,d.indexBuffer,d.segments,o.paint,e.transform.zoom,_);}}}a.viewport.set([0,0,e.width,e.height]);}else"translucent"===e.renderPass&&(e.context.setColorMode(e.colorModeForRenderPass()),function(e,i){var o=e.context,r=o.gl,a=i.heatmapFbo;if(!a)return;o.activeTexture.set(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,a.colorAttachment.get()),o.activeTexture.set(r.TEXTURE1);var n=i.colorRampTexture;n||(n=i.colorRampTexture=new t.Texture(o,i.colorRamp,r.RGBA));n.bind(r.LINEAR,r.CLAMP_TO_EDGE),e.useProgram("heatmapTexture").draw(o,r.TRIANGLES,St.disabled,Ct.disabled,e.colorModeForRenderPass(),zt.disabled,Di(e,i,0,1),i.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments,i.paint,e.transform.zoom);}(e,o));},line:function(e,i,o,r){if("translucent"===e.renderPass){var a=o.paint.get("line-opacity"),n=o.paint.get("line-width");if(0!==a.constantOr(1)&&0!==n.constantOr(1)){var s=e.depthModeForSublayer(0,St.ReadOnly),l=e.colorModeForRenderPass(),c=o.paint.get("line-dasharray"),u=o.paint.get("line-pattern"),h=u.constantOr(1),p=o.paint.get("line-gradient"),d=o.getCrossfadeParameters(),_=h?"linePattern":c?"lineSDF":p?"lineGradient":"line",f=e.context,m=f.gl,g=!0;if(p){f.activeTexture.set(m.TEXTURE0);var v=o.gradientTexture;if(!o.gradient)return;v||(v=o.gradientTexture=new t.Texture(f,o.gradient,m.RGBA)),v.bind(m.LINEAR,m.CLAMP_TO_EDGE);}for(var y=0,x=r;y<x.length;y+=1){var b=x[y],w=i.getTile(b);if(!h||w.patternsLoaded()){var E=w.getBucket(o);if(E){var T=E.programConfigurations.get(o.id),I=e.context.program.get(),S=e.useProgram(_,T),C=g||S.program!==I,P=u.constantOr(null);if(P&&w.imageAtlas){var z=w.imageAtlas,L=z.patternPositions[P.to.toString()],M=z.patternPositions[P.from.toString()];L&&M&&T.setConstantPatternPositions(L,M);}var D=h?Fi(e,w,o,d):c?Ui(e,w,o,c,d):p?Oi(e,w,o):Bi(e,w,o);h?(f.activeTexture.set(m.TEXTURE0),w.imageAtlasTexture.bind(m.LINEAR,m.CLAMP_TO_EDGE),T.updatePaintBuffers(d)):c&&(C||e.lineAtlas.dirty)&&(f.activeTexture.set(m.TEXTURE0),e.lineAtlas.bind(f)),S.draw(f,m.TRIANGLES,s,e.stencilModeForClipping(b),l,zt.disabled,D,o.id,E.layoutVertexBuffer,E.indexBuffer,E.segments,o.paint,e.transform.zoom,T),g=!1;}}}}}},fill:function(e,i,o,r){var a=o.paint.get("fill-color"),n=o.paint.get("fill-opacity");if(0!==n.constantOr(1)){var s=e.colorModeForRenderPass(),l=o.paint.get("fill-pattern"),c=e.opaquePassEnabledForLayer()&&!l.constantOr(1)&&1===a.constantOr(t.Color.transparent).a&&1===n.constantOr(0)?"opaque":"translucent";if(e.renderPass===c){var u=e.depthModeForSublayer(1,"opaque"===e.renderPass?St.ReadWrite:St.ReadOnly);ro(e,i,o,r,u,s,!1);}if("translucent"===e.renderPass&&o.paint.get("fill-antialias")){var h=e.depthModeForSublayer(o.getPaintProperty("fill-outline-color")?2:0,St.ReadOnly);ro(e,i,o,r,h,s,!0);}}},"fill-extrusion":function(t,e,i,o){var r=i.paint.get("fill-extrusion-opacity");if(0!==r&&"translucent"===t.renderPass){var a=new St(t.context.gl.LEQUAL,St.ReadWrite,t.depthRangeFor3D);if(1!==r||i.paint.get("fill-extrusion-pattern").constantOr(1))ao(t,e,i,o,a,Ct.disabled,Pt.disabled),ao(t,e,i,o,a,t.stencilModeFor3D(),t.colorModeForRenderPass());else{var n=t.colorModeForRenderPass();ao(t,e,i,o,a,Ct.disabled,n);}}},hillshade:function(t,e,i,o){if("offscreen"===t.renderPass||"translucent"===t.renderPass){for(var r=t.context,a=e.getSource().maxzoom,n=t.depthModeForSublayer(0,St.ReadOnly),s=t.colorModeForRenderPass(),l="translucent"===t.renderPass?t.stencilConfigForOverlap(o):[{},o],c=l[0],u=0,h=l[1];u<h.length;u+=1){var p=h[u],d=e.getTile(p);d.needsHillshadePrepare&&"offscreen"===t.renderPass?so(t,d,i,a,n,Ct.disabled,s):"translucent"===t.renderPass&&no(t,d,i,n,c[p.overscaledZ],s);}r.viewport.set([0,0,t.width,t.height]);}},raster:function(t,e,i,o){if("translucent"===t.renderPass&&0!==i.paint.get("raster-opacity")&&o.length)for(var r=t.context,a=r.gl,n=e.getSource(),s=t.useProgram("raster"),l=t.colorModeForRenderPass(),c=n instanceof D?[{},o]:t.stencilConfigForOverlap(o),u=c[0],h=c[1],p=h[h.length-1].overscaledZ,d=!t.options.moving,_=0,f=h;_<f.length;_+=1){var m=f[_],g=t.depthModeForSublayer(m.overscaledZ-p,1===i.paint.get("raster-opacity")?St.ReadWrite:St.ReadOnly,a.LESS),v=e.getTile(m),y=t.transform.calculatePosMatrix(m.toUnwrapped(),d);v.registerFadeDuration(i.paint.get("raster-fade-duration"));var x=e.findLoadedParent(m,0),b=lo(v,x,e,i,t.transform),w=void 0,E=void 0,T="nearest"===i.paint.get("raster-resampling")?a.NEAREST:a.LINEAR;r.activeTexture.set(a.TEXTURE0),v.texture.bind(T,a.CLAMP_TO_EDGE,a.LINEAR_MIPMAP_NEAREST),r.activeTexture.set(a.TEXTURE1),x?(x.texture.bind(T,a.CLAMP_TO_EDGE,a.LINEAR_MIPMAP_NEAREST),w=Math.pow(2,x.tileID.overscaledZ-v.tileID.overscaledZ),E=[v.tileID.canonical.x*w%1,v.tileID.canonical.y*w%1]):v.texture.bind(T,a.CLAMP_TO_EDGE,a.LINEAR_MIPMAP_NEAREST);var I=qi(y,E||[0,0],w||1,b,i);n instanceof D?s.draw(r,a.TRIANGLES,g,Ct.disabled,l,zt.disabled,I,i.id,n.boundsBuffer,t.quadTriangleIndexBuffer,n.boundsSegments):s.draw(r,a.TRIANGLES,g,u[m.overscaledZ],l,zt.disabled,I,i.id,t.rasterBoundsBuffer,t.quadTriangleIndexBuffer,t.rasterBoundsSegments);}},background:function(t,e,i){var o=i.paint.get("background-color"),r=i.paint.get("background-opacity");if(0!==r){var a=t.context,n=a.gl,s=t.transform,l=s.tileSize,c=i.paint.get("background-pattern");if(!t.isPatternMissing(c)){var u=!c&&1===o.a&&1===r&&t.opaquePassEnabledForLayer()?"opaque":"translucent";if(t.renderPass===u){var h=Ct.disabled,p=t.depthModeForSublayer(0,"opaque"===u?St.ReadWrite:St.ReadOnly),d=t.colorModeForRenderPass(),_=t.useProgram(c?"backgroundPattern":"background"),f=s.coveringTiles({tileSize:l});c&&(a.activeTexture.set(n.TEXTURE0),t.imageManager.bind(t.context));for(var m=i.getCrossfadeParameters(),g=0,v=f;g<v.length;g+=1){var y=v[g],x=t.transform.calculatePosMatrix(y.toUnwrapped()),b=c?Hi(x,r,t,c,{tileID:y,tileSize:l},m):Xi(x,r,o);_.draw(a,n.TRIANGLES,p,h,d,zt.disabled,b,i.id,t.tileExtentBuffer,t.quadTriangleIndexBuffer,t.tileExtentSegments);}}}}},debug:function(t,e,i){for(var o=0;o<i.length;o++)co(t,e,i[o]);},custom:function(t,e,i){var o=t.context,r=i.implementation;if("offscreen"===t.renderPass){var a=r.prerender;a&&(t.setCustomLayerDefaults(),o.setColorMode(t.colorModeForRenderPass()),a.call(r,o.gl,t.transform.customLayerMatrix()),o.setDirty(),t.setBaseState());}else if("translucent"===t.renderPass){t.setCustomLayerDefaults(),o.setColorMode(t.colorModeForRenderPass()),o.setStencilMode(Ct.disabled);var n="3d"===r.renderingMode?new St(t.context.gl.LEQUAL,St.ReadWrite,t.depthRangeFor3D):t.depthModeForSublayer(0,St.ReadOnly);o.setDepthMode(n),r.render(o.gl,t.transform.customLayerMatrix()),o.setDirty(),t.setBaseState(),o.bindFramebuffer.set(null);}}},po=function(t,e){this.context=new Lt(t),this.transform=e,this._tileTextures={},this.setup(),this.numSublayers=Mt.maxUnderzooming+Mt.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.depthRboNeedsClear=!0,this.crossTileSymbolIndex=new Be,this.gpuTimers={};};po.prototype.resize=function(e,i){var o=this.context.gl;if(this.width=e*t.browser.devicePixelRatio,this.height=i*t.browser.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(var r=0,a=this.style._order;r<a.length;r+=1){var n=a[r];this.style._layers[n].resize();}this.depthRbo&&(o.deleteRenderbuffer(this.depthRbo),this.depthRbo=null);},po.prototype.setup=function(){var e=this.context,i=new t.StructArrayLayout2i4;i.emplaceBack(0,0),i.emplaceBack(t.EXTENT,0),i.emplaceBack(0,t.EXTENT),i.emplaceBack(t.EXTENT,t.EXTENT),this.tileExtentBuffer=e.createVertexBuffer(i,qe.members),this.tileExtentSegments=t.SegmentVector.simpleSegment(0,0,4,2);var o=new t.StructArrayLayout2i4;o.emplaceBack(0,0),o.emplaceBack(t.EXTENT,0),o.emplaceBack(0,t.EXTENT),o.emplaceBack(t.EXTENT,t.EXTENT),this.debugBuffer=e.createVertexBuffer(o,qe.members),this.debugSegments=t.SegmentVector.simpleSegment(0,0,4,5);var r=new t.StructArrayLayout4i8;r.emplaceBack(0,0,0,0),r.emplaceBack(t.EXTENT,0,t.EXTENT,0),r.emplaceBack(0,t.EXTENT,0,t.EXTENT),r.emplaceBack(t.EXTENT,t.EXTENT,t.EXTENT,t.EXTENT),this.rasterBoundsBuffer=e.createVertexBuffer(r,M.members),this.rasterBoundsSegments=t.SegmentVector.simpleSegment(0,0,4,2);var a=new t.StructArrayLayout2i4;a.emplaceBack(0,0),a.emplaceBack(1,0),a.emplaceBack(0,1),a.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(a,qe.members),this.viewportSegments=t.SegmentVector.simpleSegment(0,0,4,2);var n=new t.StructArrayLayout1ui2;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);var s=new t.StructArrayLayout3ui6;s.emplaceBack(0,1,2),s.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(s);var l=this.context.gl;this.stencilClearMode=new Ct({func:l.ALWAYS,mask:0},0,255,l.ZERO,l.ZERO,l.ZERO);},po.prototype.clearStencil=function(){var e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;var o=t.create();t.ortho(o,0,this.width,this.height,0,0,1),t.scale(o,o,[i.drawingBufferWidth,i.drawingBufferHeight,0]),this.useProgram("clippingMask").draw(e,i.TRIANGLES,St.disabled,this.stencilClearMode,Pt.disabled,zt.disabled,Li(o),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);},po.prototype._renderTileClippingMasks=function(t,e){if(this.currentStencilSource!==t.source&&t.isTileClipped()&&e&&e.length){this.currentStencilSource=t.source;var i=this.context,o=i.gl;this.nextStencilID+e.length>256&&this.clearStencil(),i.setColorMode(Pt.disabled),i.setDepthMode(St.disabled);var r=this.useProgram("clippingMask");this._tileClippingMaskIDs={};for(var a=0,n=e;a<n.length;a+=1){var s=n[a],l=this._tileClippingMaskIDs[s.key]=this.nextStencilID++;r.draw(i,o.TRIANGLES,St.disabled,new Ct({func:o.ALWAYS,mask:0},l,255,o.KEEP,o.KEEP,o.REPLACE),Pt.disabled,zt.disabled,Li(s.posMatrix),"$clipping",this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}}},po.prototype.stencilModeFor3D=function(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();var t=this.nextStencilID++,e=this.context.gl;return new Ct({func:e.NOTEQUAL,mask:255},t,255,e.KEEP,e.KEEP,e.REPLACE)},po.prototype.stencilModeForClipping=function(t){var e=this.context.gl;return new Ct({func:e.EQUAL,mask:255},this._tileClippingMaskIDs[t.key],0,e.KEEP,e.KEEP,e.REPLACE)},po.prototype.stencilConfigForOverlap=function(t){var e,i=this.context.gl,o=t.sort((function(t,e){return e.overscaledZ-t.overscaledZ})),r=o[o.length-1].overscaledZ,a=o[0].overscaledZ-r+1;if(a>1){this.currentStencilSource=void 0,this.nextStencilID+a>256&&this.clearStencil();for(var n={},s=0;s<a;s++)n[s+r]=new Ct({func:i.GEQUAL,mask:255},s+this.nextStencilID,255,i.KEEP,i.KEEP,i.REPLACE);return this.nextStencilID+=a,[n,o]}return [(e={},e[r]=Ct.disabled,e),o]},po.prototype.colorModeForRenderPass=function(){var e=this.context.gl;if(this._showOverdrawInspector){return new Pt([e.CONSTANT_COLOR,e.ONE],new t.Color(1/8,1/8,1/8,0),[!0,!0,!0,!0])}return "opaque"===this.renderPass?Pt.unblended:Pt.alphaBlended},po.prototype.depthModeForSublayer=function(t,e,i){if(!this.opaquePassEnabledForLayer())return St.disabled;var o=1-((1+this.currentLayer)*this.numSublayers+t)*this.depthEpsilon;return new St(i||this.context.gl.LEQUAL,e,[o,o])},po.prototype.opaquePassEnabledForLayer=function(){return this.currentLayer<this.opaquePassCutoff},po.prototype.render=function(e,i){var o=this;this.style=e,this.options=i,this.lineAtlas=e.lineAtlas,this.imageManager=e.imageManager,this.glyphManager=e.glyphManager,this.symbolFadeChange=e.placement.symbolFadeChange(t.browser.now()),this.imageManager.beginFrame();var r=this.style._order,a=this.style.sourceCaches;for(var n in a){var s=a[n];s.used&&s.prepare(this.context);}var l,c,u={},h={},p={};for(var d in a){var _=a[d];u[d]=_.getVisibleCoordinates(),h[d]=u[d].slice().reverse(),p[d]=_.getVisibleCoordinates(!0).reverse();}this.opaquePassCutoff=1/0;for(var f=0;f<r.length;f++){var m=r[f];if(this.style._layers[m].is3D()){this.opaquePassCutoff=f;break}}this.renderPass="offscreen",this.depthRboNeedsClear=!0;for(var g=0,v=r;g<v.length;g+=1){var y=v[g],x=this.style._layers[y];if(x.hasOffscreenPass()&&!x.isHidden(this.transform.zoom)){var b=h[x.source];("custom"===x.type||b.length)&&this.renderLayer(this,a[x.source],x,b);}}for(this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.Color.black:t.Color.transparent,depth:1}),this.clearStencil(),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],this.renderPass="opaque",this.currentLayer=r.length-1;this.currentLayer>=0;this.currentLayer--){var w=this.style._layers[r[this.currentLayer]],E=a[w.source],T=u[w.source];this._renderTileClippingMasks(w,T),this.renderLayer(this,E,w,T);}for(this.renderPass="translucent",this.currentLayer=0;this.currentLayer<r.length;this.currentLayer++){var I=this.style._layers[r[this.currentLayer]],S=a[I.source],C=("symbol"===I.type?p:h)[I.source];this._renderTileClippingMasks(I,u[I.source]),this.renderLayer(this,S,I,C);}this.options.showTileBoundaries&&(t.values(this.style._layers).forEach((function(t){t.source&&!t.isHidden(o.transform.zoom)&&(t.source!==(c&&c.id)&&(c=o.style.sourceCaches[t.source]),(!l||l.getSource().maxzoom<c.getSource().maxzoom)&&(l=c));})),l&&ho.debug(this,l,l.getVisibleCoordinates()));this.context.setDefault();},po.prototype.setupOffscreenDepthRenderbuffer=function(){var t=this.context;this.depthRbo||(this.depthRbo=t.createRenderbuffer(t.gl.DEPTH_COMPONENT16,this.width,this.height));},po.prototype.renderLayer=function(t,e,i,o){i.isHidden(this.transform.zoom)||("background"===i.type||"custom"===i.type||o.length)&&(this.id=i.id,this.gpuTimingStart(i),ho[i.type](t,e,i,o,this.style.placement.variableOffsets),this.gpuTimingEnd());},po.prototype.gpuTimingStart=function(t){if(this.options.gpuTiming){var e=this.context.extTimerQuery,i=this.gpuTimers[t.id];i||(i=this.gpuTimers[t.id]={calls:0,cpuTime:0,query:e.createQueryEXT()}),i.calls++,e.beginQueryEXT(e.TIME_ELAPSED_EXT,i.query);}},po.prototype.gpuTimingEnd=function(){if(this.options.gpuTiming){var t=this.context.extTimerQuery;t.endQueryEXT(t.TIME_ELAPSED_EXT);}},po.prototype.collectGpuTimers=function(){var t=this.gpuTimers;return this.gpuTimers={},t},po.prototype.queryGpuTimers=function(t){var e={};for(var i in t){var o=t[i],r=this.context.extTimerQuery,a=r.getQueryObjectEXT(o.query,r.QUERY_RESULT_EXT)/1e6;r.deleteQueryEXT(o.query),e[i]=a;}return e},po.prototype.translatePosMatrix=function(e,i,o,r,a){if(!o[0]&&!o[1])return e;var n=a?"map"===r?this.transform.angle:0:"viewport"===r?-this.transform.angle:0;if(n){var s=Math.sin(n),l=Math.cos(n);o=[o[0]*l-o[1]*s,o[0]*s+o[1]*l];}var c=[a?o[0]:he(i,o[0],this.transform.zoom),a?o[1]:he(i,o[1],this.transform.zoom),0],u=new Float32Array(16);return t.translate(u,e,c),u},po.prototype.saveTileTexture=function(t){var e=this._tileTextures[t.size[0]];e?e.push(t):this._tileTextures[t.size[0]]=[t];},po.prototype.getTileTexture=function(t){var e=this._tileTextures[t];return e&&e.length>0?e.pop():null},po.prototype.isPatternMissing=function(t){if(!t)return !1;var e=this.imageManager.getPattern(t.from.toString()),i=this.imageManager.getPattern(t.to.toString());return !e||!i},po.prototype.useProgram=function(t,e){this.cache=this.cache||{};var i=""+t+(e?e.cacheKey:"")+(this._showOverdrawInspector?"/overdraw":"");return this.cache[i]||(this.cache[i]=new vi(this.context,mi[t],e,Ki[t],this._showOverdrawInspector)),this.cache[i]},po.prototype.setCustomLayerDefaults=function(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();},po.prototype.setBaseState=function(){var t=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(t.FUNC_ADD);};var _o=function(t,e){this.points=t,this.planes=e;};_o.fromInvProjectionMatrix=function(e,i,o){var r=Math.pow(2,o),a=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((function(i){return t.transformMat4([],i,e)})).map((function(e){return t.scale$1([],e,1/e[3]/i*r)})),n=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map((function(e){var i=t.sub([],a[e[0]],a[e[1]]),o=t.sub([],a[e[2]],a[e[1]]),r=t.normalize([],t.cross([],i,o)),n=-t.dot(r,a[e[1]]);return r.concat(n)}));return new _o(a,n)};var fo=function(e,i){this.min=e,this.max=i,this.center=t.scale$2([],t.add([],this.min,this.max),.5);};fo.prototype.quadrant=function(e){for(var i=[e%2==0,e<2],o=t.clone$2(this.min),r=t.clone$2(this.max),a=0;a<i.length;a++)o[a]=i[a]?this.min[a]:this.center[a],r[a]=i[a]?this.center[a]:this.max[a];return r[2]=this.max[2],new fo(o,r)},fo.prototype.distanceX=function(t){return Math.max(Math.min(this.max[0],t[0]),this.min[0])-t[0]},fo.prototype.distanceY=function(t){return Math.max(Math.min(this.max[1],t[1]),this.min[1])-t[1]},fo.prototype.intersects=function(e){for(var i=[[this.min[0],this.min[1],0,1],[this.max[0],this.min[1],0,1],[this.max[0],this.max[1],0,1],[this.min[0],this.max[1],0,1]],o=!0,r=0;r<e.planes.length;r++){for(var a=e.planes[r],n=0,s=0;s<i.length;s++)n+=t.dot$1(a,i[s])>=0;if(0===n)return 0;n!==i.length&&(o=!1);}if(o)return 2;for(var l=0;l<3;l++){for(var c=Number.MAX_VALUE,u=-Number.MAX_VALUE,h=0;h<e.points.length;h++){var p=e.points[h][l]-this.min[l];c=Math.min(c,p),u=Math.max(u,p);}if(u<0||c>this.max[l]-this.min[l])return 0}return 1};var mo=function(e,i,o,r,a){this.tileSize=512,this.maxValidLatitude=85.051129,this._renderWorldCopies=void 0===a||a,this._minZoom=e||0,this._maxZoom=i||22,this._minPitch=null==o?0:o,this._maxPitch=null==r?60:r,this.setMaxBounds(),this.width=0,this.height=0,this._center=new t.LngLat(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._unmodified=!0,this._posMatrixCache={},this._alignedPosMatrixCache={};},go={minZoom:{configurable:!0},maxZoom:{configurable:!0},minPitch:{configurable:!0},maxPitch:{configurable:!0},renderWorldCopies:{configurable:!0},worldSize:{configurable:!0},centerPoint:{configurable:!0},size:{configurable:!0},bearing:{configurable:!0},pitch:{configurable:!0},fov:{configurable:!0},zoom:{configurable:!0},center:{configurable:!0},unmodified:{configurable:!0},point:{configurable:!0}};mo.prototype.clone=function(){var t=new mo(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies);return t.tileSize=this.tileSize,t.latRange=this.latRange,t.width=this.width,t.height=this.height,t._center=this._center,t.zoom=this.zoom,t.angle=this.angle,t._fov=this._fov,t._pitch=this._pitch,t._unmodified=this._unmodified,t._calcMatrices(),t},go.minZoom.get=function(){return this._minZoom},go.minZoom.set=function(t){this._minZoom!==t&&(this._minZoom=t,this.zoom=Math.max(this.zoom,t));},go.maxZoom.get=function(){return this._maxZoom},go.maxZoom.set=function(t){this._maxZoom!==t&&(this._maxZoom=t,this.zoom=Math.min(this.zoom,t));},go.minPitch.get=function(){return this._minPitch},go.minPitch.set=function(t){this._minPitch!==t&&(this._minPitch=t,this.pitch=Math.max(this.pitch,t));},go.maxPitch.get=function(){return this._maxPitch},go.maxPitch.set=function(t){this._maxPitch!==t&&(this._maxPitch=t,this.pitch=Math.min(this.pitch,t));},go.renderWorldCopies.get=function(){return this._renderWorldCopies},go.renderWorldCopies.set=function(t){void 0===t?t=!0:null===t&&(t=!1),this._renderWorldCopies=t;},go.worldSize.get=function(){return this.tileSize*this.scale},go.centerPoint.get=function(){return this.size._div(2)},go.size.get=function(){return new t.Point(this.width,this.height)},go.bearing.get=function(){return -this.angle/Math.PI*180},go.bearing.set=function(e){var i=-t.wrap(e,-180,180)*Math.PI/180;this.angle!==i&&(this._unmodified=!1,this.angle=i,this._calcMatrices(),this.rotationMatrix=t.create$2(),t.rotate(this.rotationMatrix,this.rotationMatrix,this.angle));},go.pitch.get=function(){return this._pitch/Math.PI*180},go.pitch.set=function(e){var i=t.clamp(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitch!==i&&(this._unmodified=!1,this._pitch=i,this._calcMatrices());},go.fov.get=function(){return this._fov/Math.PI*180},go.fov.set=function(t){t=Math.max(.01,Math.min(60,t)),this._fov!==t&&(this._unmodified=!1,this._fov=t/180*Math.PI,this._calcMatrices());},go.zoom.get=function(){return this._zoom},go.zoom.set=function(t){var e=Math.min(Math.max(t,this.minZoom),this.maxZoom);this._zoom!==e&&(this._unmodified=!1,this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom,this._constrain(),this._calcMatrices());},go.center.get=function(){return this._center},go.center.set=function(t){t.lat===this._center.lat&&t.lng===this._center.lng||(this._unmodified=!1,this._center=t,this._constrain(),this._calcMatrices());},mo.prototype.coveringZoomLevel=function(t){var e=(t.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/t.tileSize));return Math.max(0,e)},mo.prototype.getVisibleUnwrappedCoordinates=function(e){var i=[new t.UnwrappedTileID(0,e)];if(this._renderWorldCopies)for(var o=this.pointCoordinate(new t.Point(0,0)),r=this.pointCoordinate(new t.Point(this.width,0)),a=this.pointCoordinate(new t.Point(this.width,this.height)),n=this.pointCoordinate(new t.Point(0,this.height)),s=Math.floor(Math.min(o.x,r.x,a.x,n.x)),l=Math.floor(Math.max(o.x,r.x,a.x,n.x)),c=s-1;c<=l+1;c++)0!==c&&i.push(new t.UnwrappedTileID(c,e));return i},mo.prototype.coveringTiles=function(e){var i=this.coveringZoomLevel(e),o=i;if(void 0!==e.minzoom&&i<e.minzoom)return [];void 0!==e.maxzoom&&i>e.maxzoom&&(i=e.maxzoom);var r=t.MercatorCoordinate.fromLngLat(this.center),a=Math.pow(2,i),n=[a*r.x,a*r.y,0],s=_o.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,i),l=e.minzoom||0;this.pitch<=60&&(l=i);var c=function(t){return {aabb:new fo([t*a,0,0],[(t+1)*a,a,0]),zoom:0,x:0,y:0,wrap:t,fullyVisible:!1}},u=[],h=[],p=i,d=e.reparseOverscaled?o:i;if(this._renderWorldCopies)for(var _=1;_<=3;_++)u.push(c(-_)),u.push(c(_));for(u.push(c(0));u.length>0;){var f=u.pop(),m=f.x,g=f.y,v=f.fullyVisible;if(!v){var y=f.aabb.intersects(s);if(0===y)continue;v=2===y;}var x=f.aabb.distanceX(n),b=f.aabb.distanceY(n),w=Math.max(Math.abs(x),Math.abs(b)),E=3+(1<<p-f.zoom)-2;if(f.zoom===p||w>E&&f.zoom>=l)h.push({tileID:new t.OverscaledTileID(f.zoom===p?d:f.zoom,f.wrap,f.zoom,m,g),distanceSq:t.sqrLen([n[0]-.5-m,n[1]-.5-g])});else for(var T=0;T<4;T++){var I=(m<<1)+T%2,S=(g<<1)+(T>>1);u.push({aabb:f.aabb.quadrant(T),zoom:f.zoom+1,x:I,y:S,wrap:f.wrap,fullyVisible:v});}}return h.sort((function(t,e){return t.distanceSq-e.distanceSq})).map((function(t){return t.tileID}))},mo.prototype.resize=function(t,e){this.width=t,this.height=e,this.pixelsToGLUnits=[2/t,-2/e],this._constrain(),this._calcMatrices();},go.unmodified.get=function(){return this._unmodified},mo.prototype.zoomScale=function(t){return Math.pow(2,t)},mo.prototype.scaleZoom=function(t){return Math.log(t)/Math.LN2},mo.prototype.project=function(e){var i=t.clamp(e.lat,-this.maxValidLatitude,this.maxValidLatitude);return new t.Point(t.mercatorXfromLng(e.lng)*this.worldSize,t.mercatorYfromLat(i)*this.worldSize)},mo.prototype.unproject=function(e){return new t.MercatorCoordinate(e.x/this.worldSize,e.y/this.worldSize).toLngLat()},go.point.get=function(){return this.project(this.center)},mo.prototype.setLocationAtPoint=function(e,i){var o=this.pointCoordinate(i),r=this.pointCoordinate(this.centerPoint),a=this.locationCoordinate(e),n=new t.MercatorCoordinate(a.x-(o.x-r.x),a.y-(o.y-r.y));this.center=this.coordinateLocation(n),this._renderWorldCopies&&(this.center=this.center.wrap());},mo.prototype.locationPoint=function(t){return this.coordinatePoint(this.locationCoordinate(t))},mo.prototype.pointLocation=function(t){return this.coordinateLocation(this.pointCoordinate(t))},mo.prototype.locationCoordinate=function(e){return t.MercatorCoordinate.fromLngLat(e)},mo.prototype.coordinateLocation=function(t){return t.toLngLat()},mo.prototype.pointCoordinate=function(e){var i=[e.x,e.y,0,1],o=[e.x,e.y,1,1];t.transformMat4(i,i,this.pixelMatrixInverse),t.transformMat4(o,o,this.pixelMatrixInverse);var r=i[3],a=o[3],n=i[0]/r,s=o[0]/a,l=i[1]/r,c=o[1]/a,u=i[2]/r,h=o[2]/a,p=u===h?0:(0-u)/(h-u);return new t.MercatorCoordinate(t.number(n,s,p)/this.worldSize,t.number(l,c,p)/this.worldSize)},mo.prototype.coordinatePoint=function(e){var i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.transformMat4(i,i,this.pixelMatrix),new t.Point(i[0]/i[3],i[1]/i[3])},mo.prototype.getBounds=function(){return (new t.LngLatBounds).extend(this.pointLocation(new t.Point(0,0))).extend(this.pointLocation(new t.Point(this.width,0))).extend(this.pointLocation(new t.Point(this.width,this.height))).extend(this.pointLocation(new t.Point(0,this.height)))},mo.prototype.getMaxBounds=function(){return this.latRange&&2===this.latRange.length&&this.lngRange&&2===this.lngRange.length?new t.LngLatBounds([this.lngRange[0],this.latRange[0]],[this.lngRange[1],this.latRange[1]]):null},mo.prototype.setMaxBounds=function(t){t?(this.lngRange=[t.getWest(),t.getEast()],this.latRange=[t.getSouth(),t.getNorth()],this._constrain()):(this.lngRange=null,this.latRange=[-this.maxValidLatitude,this.maxValidLatitude]);},mo.prototype.calculatePosMatrix=function(e,i){void 0===i&&(i=!1);var o=e.key,r=i?this._alignedPosMatrixCache:this._posMatrixCache;if(r[o])return r[o];var a=e.canonical,n=this.worldSize/this.zoomScale(a.z),s=a.x+Math.pow(2,a.z)*e.wrap,l=t.identity(new Float64Array(16));return t.translate(l,l,[s*n,a.y*n,0]),t.scale(l,l,[n/t.EXTENT,n/t.EXTENT,1]),t.multiply(l,i?this.alignedProjMatrix:this.projMatrix,l),r[o]=new Float32Array(l),r[o]},mo.prototype.customLayerMatrix=function(){return this.mercatorMatrix.slice()},mo.prototype._constrain=function(){if(this.center&&this.width&&this.height&&!this._constraining){this._constraining=!0;var e,i,o,r,a=-90,n=90,s=-180,l=180,c=this.size,u=this._unmodified;if(this.latRange){var h=this.latRange;a=t.mercatorYfromLat(h[1])*this.worldSize,e=(n=t.mercatorYfromLat(h[0])*this.worldSize)-a<c.y?c.y/(n-a):0;}if(this.lngRange){var p=this.lngRange;s=t.mercatorXfromLng(p[0])*this.worldSize,i=(l=t.mercatorXfromLng(p[1])*this.worldSize)-s<c.x?c.x/(l-s):0;}var d=this.point,_=Math.max(i||0,e||0);if(_)return this.center=this.unproject(new t.Point(i?(l+s)/2:d.x,e?(n+a)/2:d.y)),this.zoom+=this.scaleZoom(_),this._unmodified=u,void(this._constraining=!1);if(this.latRange){var f=d.y,m=c.y/2;f-m<a&&(r=a+m),f+m>n&&(r=n-m);}if(this.lngRange){var g=d.x,v=c.x/2;g-v<s&&(o=s+v),g+v>l&&(o=l-v);}void 0===o&&void 0===r||(this.center=this.unproject(new t.Point(void 0!==o?o:d.x,void 0!==r?r:d.y))),this._unmodified=u,this._constraining=!1;}},mo.prototype._calcMatrices=function(){if(this.height){this.cameraToCenterDistance=.5/Math.tan(this._fov/2)*this.height;var e=this._fov/2,i=Math.PI/2+this._pitch,o=Math.sin(e)*this.cameraToCenterDistance/Math.sin(t.clamp(Math.PI-i-e,.01,Math.PI-.01)),r=this.point,a=r.x,n=r.y,s=1.01*(Math.cos(Math.PI/2-this._pitch)*o+this.cameraToCenterDistance),l=this.height/50,c=new Float64Array(16);t.perspective(c,this._fov,this.width/this.height,l,s),t.scale(c,c,[1,-1,1]),t.translate(c,c,[0,0,-this.cameraToCenterDistance]),t.rotateX(c,c,this._pitch),t.rotateZ(c,c,this.angle),t.translate(c,c,[-a,-n,0]),this.mercatorMatrix=t.scale([],c,[this.worldSize,this.worldSize,this.worldSize]),t.scale(c,c,[1,1,t.mercatorZfromAltitude(1,this.center.lat)*this.worldSize,1]),this.projMatrix=c,this.invProjMatrix=t.invert([],this.projMatrix);var u=this.width%2/2,h=this.height%2/2,p=Math.cos(this.angle),d=Math.sin(this.angle),_=a-Math.round(a)+p*u+d*h,f=n-Math.round(n)+p*h+d*u,m=new Float64Array(c);if(t.translate(m,m,[_>.5?_-1:_,f>.5?f-1:f,0]),this.alignedProjMatrix=m,c=t.create(),t.scale(c,c,[this.width/2,-this.height/2,1]),t.translate(c,c,[1,-1,0]),this.labelPlaneMatrix=c,c=t.create(),t.scale(c,c,[1,-1,1]),t.translate(c,c,[-1,-1,0]),t.scale(c,c,[2/this.width,2/this.height,1]),this.glCoordMatrix=c,this.pixelMatrix=t.multiply(new Float64Array(16),this.labelPlaneMatrix,this.projMatrix),!(c=t.invert(new Float64Array(16),this.pixelMatrix)))throw new Error("failed to invert matrix");this.pixelMatrixInverse=c,this._posMatrixCache={},this._alignedPosMatrixCache={};}},mo.prototype.maxPitchScaleFactor=function(){if(!this.pixelMatrixInverse)return 1;var e=this.pointCoordinate(new t.Point(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.transformMat4(i,i,this.pixelMatrix)[3]/this.cameraToCenterDistance},mo.prototype.getCameraPoint=function(){var e=this._pitch,i=Math.tan(e)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.Point(0,i))},mo.prototype.getCameraQueryGeometry=function(e){var i=this.getCameraPoint();if(1===e.length)return [e[0],i];for(var o=i.x,r=i.y,a=i.x,n=i.y,s=0,l=e;s<l.length;s+=1){var c=l[s];o=Math.min(o,c.x),r=Math.min(r,c.y),a=Math.max(a,c.x),n=Math.max(n,c.y);}return [new t.Point(o,r),new t.Point(a,r),new t.Point(a,n),new t.Point(o,n),new t.Point(o,r)]},Object.defineProperties(mo.prototype,go);var vo=function(e){var i,o,r,a,n;this._hashName=e&&encodeURIComponent(e),t.bindAll(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=(i=this._updateHashUnthrottled.bind(this),o=300,r=!1,a=null,n=function(){a=null,r&&(i(),a=setTimeout(n,o),r=!1);},function(){return r=!0,a||n(),a});};vo.prototype.addTo=function(e){return this._map=e,t.window.addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this},vo.prototype.remove=function(){return t.window.removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),delete this._map,this},vo.prototype.getHashString=function(e){var i=this._map.getCenter(),o=Math.round(100*this._map.getZoom())/100,r=Math.ceil((o*Math.LN2+Math.log(512/360/.5))/Math.LN10),a=Math.pow(10,r),n=Math.round(i.lng*a)/a,s=Math.round(i.lat*a)/a,l=this._map.getBearing(),c=this._map.getPitch(),u="";if(u+=e?"/"+n+"/"+s+"/"+o:o+"/"+s+"/"+n,(l||c)&&(u+="/"+Math.round(10*l)/10),c&&(u+="/"+Math.round(c)),this._hashName){var h=this._hashName,p=!1,d=t.window.location.hash.slice(1).split("&").map((function(t){var e=t.split("=")[0];return e===h?(p=!0,e+"="+u):t})).filter((function(t){return t}));return p||d.push(h+"="+u),"#"+d.join("&")}return "#"+u},vo.prototype._getCurrentHash=function(){var e,i=this,o=t.window.location.hash.replace("#","");return this._hashName?(o.split("&").map((function(t){return t.split("=")})).forEach((function(t){t[0]===i._hashName&&(e=t);})),(e&&e[1]||"").split("/")):o.split("/")},vo.prototype._onHashChange=function(){var t=this._getCurrentHash();if(t.length>=3&&!t.some((function(t){return isNaN(t)}))){var e=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(t[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+t[2],+t[1]],zoom:+t[0],bearing:e,pitch:+(t[4]||0)}),!0}return !1},vo.prototype._updateHashUnthrottled=function(){var e=this.getHashString();try{t.window.history.replaceState(t.window.history.state,"",e);}catch(t){}};var yo=function(e){function o(o,r,a,n){void 0===n&&(n={});var s=i.mousePos(r.getCanvasContainer(),a),l=r.unproject(s);e.call(this,o,t.extend({point:s,lngLat:l,originalEvent:a},n)),this._defaultPrevented=!1,this.target=r;}e&&(o.__proto__=e),o.prototype=Object.create(e&&e.prototype),o.prototype.constructor=o;var r={defaultPrevented:{configurable:!0}};return o.prototype.preventDefault=function(){this._defaultPrevented=!0;},r.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(o.prototype,r),o}(t.Event),xo=function(e){function o(o,r,a){var n=i.touchPos(r.getCanvasContainer(),a),s=n.map((function(t){return r.unproject(t)})),l=n.reduce((function(t,e,i,o){return t.add(e.div(o.length))}),new t.Point(0,0)),c=r.unproject(l);e.call(this,o,{points:n,point:l,lngLats:s,lngLat:c,originalEvent:a}),this._defaultPrevented=!1;}e&&(o.__proto__=e),o.prototype=Object.create(e&&e.prototype),o.prototype.constructor=o;var r={defaultPrevented:{configurable:!0}};return o.prototype.preventDefault=function(){this._defaultPrevented=!0;},r.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(o.prototype,r),o}(t.Event),bo=function(t){function e(e,i,o){t.call(this,e,{originalEvent:o}),this._defaultPrevented=!1;}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var i={defaultPrevented:{configurable:!0}};return e.prototype.preventDefault=function(){this._defaultPrevented=!0;},i.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(e.prototype,i),e}(t.Event),wo=function(e){this._map=e,this._el=e.getCanvasContainer(),this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=1/450,t.bindAll(["_onWheel","_onTimeout","_onScrollFrame","_onScrollFinished"],this);};wo.prototype.setZoomRate=function(t){this._defaultZoomRate=t;},wo.prototype.setWheelZoomRate=function(t){this._wheelZoomRate=t;},wo.prototype.isEnabled=function(){return !!this._enabled},wo.prototype.isActive=function(){return !!this._active},wo.prototype.isZooming=function(){return !!this._zooming},wo.prototype.enable=function(t){this.isEnabled()||(this._enabled=!0,this._aroundCenter=t&&"center"===t.around);},wo.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1);},wo.prototype.onWheel=function(e){if(this.isEnabled()){var i=e.deltaMode===t.window.WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY,o=t.browser.now(),r=o-(this._lastWheelEventTime||0);this._lastWheelEventTime=o,0!==i&&i%4.000244140625==0?this._type="wheel":0!==i&&Math.abs(i)<4?this._type="trackpad":r>400?(this._type=null,this._lastValue=i,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(r*i)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,i+=this._lastValue)),e.shiftKey&&i&&(i/=4),this._type&&(this._lastWheelEvent=e,this._delta-=i,this.isActive()||this._start(e)),e.preventDefault();}},wo.prototype._onTimeout=function(t){this._type="wheel",this._delta-=this._lastValue,this.isActive()||this._start(t);},wo.prototype._start=function(e){if(this._delta){this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0,this._map.fire(new t.Event("movestart",{originalEvent:e})),this._map.fire(new t.Event("zoomstart",{originalEvent:e}))),this._finishTimeout&&clearTimeout(this._finishTimeout);var o=i.mousePos(this._el,e);this._around=t.LngLat.convert(this._aroundCenter?this._map.getCenter():this._map.unproject(o)),this._aroundPoint=this._map.transform.locationPoint(this._around),this._frameId||(this._frameId=this._map._requestRenderFrame(this._onScrollFrame));}},wo.prototype._onScrollFrame=function(){var e=this;if(this._frameId=null,this.isActive()){var i=this._map.transform;if(0!==this._delta){var o="wheel"===this._type&&Math.abs(this._delta)>4.000244140625?this._wheelZoomRate:this._defaultZoomRate,r=2/(1+Math.exp(-Math.abs(this._delta*o)));this._delta<0&&0!==r&&(r=1/r);var a="number"==typeof this._targetZoom?i.zoomScale(this._targetZoom):i.scale;this._targetZoom=Math.min(i.maxZoom,Math.max(i.minZoom,i.scaleZoom(a*r))),"wheel"===this._type&&(this._startZoom=i.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}var n="number"==typeof this._targetZoom?this._targetZoom:i.zoom,s=this._startZoom,l=this._easing,c=!1;if("wheel"===this._type&&s&&l){var u=Math.min((t.browser.now()-this._lastWheelEventTime)/200,1),h=l(u);i.zoom=t.number(s,n,h),u<1?this._frameId||(this._frameId=this._map._requestRenderFrame(this._onScrollFrame)):c=!0;}else i.zoom=n,c=!0;i.setLocationAtPoint(this._around,this._aroundPoint),this._map.fire(new t.Event("move",{originalEvent:this._lastWheelEvent})),this._map.fire(new t.Event("zoom",{originalEvent:this._lastWheelEvent})),c&&(this._active=!1,this._finishTimeout=setTimeout((function(){e._zooming=!1,e._map.fire(new t.Event("zoomend",{originalEvent:e._lastWheelEvent})),e._map.fire(new t.Event("moveend",{originalEvent:e._lastWheelEvent})),delete e._targetZoom;}),200));}},wo.prototype._smoothOutEasing=function(e){var i=t.ease;if(this._prevEase){var o=this._prevEase,r=(t.browser.now()-o.start)/o.duration,a=o.easing(r+.01)-o.easing(r),n=.27/Math.sqrt(a*a+1e-4)*.01,s=Math.sqrt(.0729-n*n);i=t.bezier(n,s,.25,1);}return this._prevEase={start:t.browser.now(),duration:e,easing:i},i};var Eo=function(e,i){this._map=e,this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=i.clickTolerance||1,t.bindAll(["_onMouseMove","_onMouseUp","_onKeyDown"],this);};Eo.prototype.isEnabled=function(){return !!this._enabled},Eo.prototype.isActive=function(){return !!this._active},Eo.prototype.enable=function(){this.isEnabled()||(this._enabled=!0);},Eo.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1);},Eo.prototype.onMouseDown=function(e){this.isEnabled()&&e.shiftKey&&0===e.button&&(t.window.document.addEventListener("mousemove",this._onMouseMove,!1),t.window.document.addEventListener("keydown",this._onKeyDown,!1),t.window.document.addEventListener("mouseup",this._onMouseUp,!1),i.disableDrag(),this._startPos=this._lastPos=i.mousePos(this._el,e),this._active=!0);},Eo.prototype._onMouseMove=function(t){var e=i.mousePos(this._el,t);if(!(this._lastPos.equals(e)||!this._box&&e.dist(this._startPos)<this._clickTolerance)){var o=this._startPos;this._lastPos=e,this._box||(this._box=i.create("div","mapboxgl-boxzoom",this._container),this._container.classList.add("mapboxgl-crosshair"),this._fireEvent("boxzoomstart",t));var r=Math.min(o.x,e.x),a=Math.max(o.x,e.x),n=Math.min(o.y,e.y),s=Math.max(o.y,e.y);i.setTransform(this._box,"translate("+r+"px,"+n+"px)"),this._box.style.width=a-r+"px",this._box.style.height=s-n+"px";}},Eo.prototype._onMouseUp=function(e){if(0===e.button){var o=this._startPos,r=i.mousePos(this._el,e);this._finish(),i.suppressClick(),o.x===r.x&&o.y===r.y?this._fireEvent("boxzoomcancel",e):this._map.fitScreenCoordinates(o,r,this._map.getBearing(),{linear:!0}).fire(new t.Event("boxzoomend",{originalEvent:e}));}},Eo.prototype._onKeyDown=function(t){27===t.keyCode&&(this._finish(),this._fireEvent("boxzoomcancel",t));},Eo.prototype._finish=function(){this._active=!1,t.window.document.removeEventListener("mousemove",this._onMouseMove,!1),t.window.document.removeEventListener("keydown",this._onKeyDown,!1),t.window.document.removeEventListener("mouseup",this._onMouseUp,!1),this._container.classList.remove("mapboxgl-crosshair"),this._box&&(i.remove(this._box),this._box=null),i.enableDrag(),delete this._startPos,delete this._lastPos;},Eo.prototype._fireEvent=function(e,i){return this._map.fire(new t.Event(e,{originalEvent:i}))};var To=t.bezier(0,0,.25,1),Io=function(e,i){this._map=e,this._el=i.element||e.getCanvasContainer(),this._state="disabled",this._button=i.button||"right",this._bearingSnap=i.bearingSnap||0,this._pitchWithRotate=!1!==i.pitchWithRotate,this._clickTolerance=i.clickTolerance||1,t.bindAll(["onMouseDown","_onMouseMove","_onMouseUp","_onBlur","_onDragFrame"],this);};Io.prototype.isEnabled=function(){return "disabled"!==this._state},Io.prototype.isActive=function(){return "active"===this._state},Io.prototype.enable=function(){this.isEnabled()||(this._state="enabled");},Io.prototype.disable=function(){if(this.isEnabled())switch(this._state){case"active":this._state="disabled",this._unbind(),this._deactivate(),this._fireEvent("rotateend"),this._pitchWithRotate&&this._fireEvent("pitchend"),this._fireEvent("moveend");break;case"pending":this._state="disabled",this._unbind();break;default:this._state="disabled";}},Io.prototype.onMouseDown=function(e){if("enabled"===this._state){var o="touchstart"===e.type;if(o)this._startTime=Date.now();else if("right"===this._button){if(this._eventButton=i.mouseButton(e),e.altKey||e.metaKey)return;if(this._eventButton!==(e.ctrlKey?0:2))return}else{if(e.ctrlKey||0!==i.mouseButton(e))return;this._eventButton=0;}i.disableDrag(),o?(t.window.document.addEventListener("touchmove",this._onMouseMove,{capture:!0}),t.window.document.addEventListener("touchend",this._onMouseUp)):(t.window.document.addEventListener("mousemove",this._onMouseMove,{capture:!0}),t.window.document.addEventListener("mouseup",this._onMouseUp)),t.window.addEventListener("blur",this._onBlur),this._state="pending",this._inertia=[[t.browser.now(),this._map.getBearing()]],this._startPos=this._prevPos=this._lastPos=i.mousePos(this._el,e),this._center=this._map.transform.centerPoint,e.preventDefault();}},Io.prototype._onMouseMove=function(t){var e=i.mousePos(this._el,t);this._lastPos.equals(e)||"pending"===this._state&&e.dist(this._startPos)<this._clickTolerance||(this._lastMoveEvent=t,this._lastPos=e,"pending"===this._state&&(this._state="active",this._fireEvent("rotatestart",t),this._fireEvent("movestart",t),this._pitchWithRotate&&this._fireEvent("pitchstart",t)),this._frameId||(this._frameId=this._map._requestRenderFrame(this._onDragFrame)));},Io.prototype._onDragFrame=function(){this._frameId=null;var e=this._lastMoveEvent;if(e){var i=this._map.transform,o=this._prevPos,r=this._lastPos,a=.8*(o.x-r.x),n=-.5*(o.y-r.y),s=i.bearing-a,l=i.pitch-n,c=this._inertia,u=c[c.length-1];this._drainInertiaBuffer(),c.push([t.browser.now(),this._map._normalizeBearing(s,u[1])]);var h=i.bearing;if(i.bearing=s,this._pitchWithRotate){var p=i.pitch;i.pitch=l,i.pitch!==p&&this._fireEvent("pitch",e);}i.bearing!==h&&this._fireEvent("rotate",e),this._fireEvent("move",e),delete this._lastMoveEvent,this._prevPos=this._lastPos;}},Io.prototype._onMouseUp=function(t){var e="touchend"===t.type;if(e&&this._startPos===this._lastPos&&Date.now()-this._startTime<300&&this._el.click(),e||i.mouseButton(t)===this._eventButton)switch(this._state){case"active":this._state="enabled",i.suppressClick(),this._unbind(),this._deactivate(),this._inertialRotate(t);break;case"pending":this._state="enabled",this._unbind();}},Io.prototype._onBlur=function(t){switch(this._state){case"active":this._state="enabled",this._unbind(),this._deactivate(),this._fireEvent("rotateend",t),this._pitchWithRotate&&this._fireEvent("pitchend",t),this._fireEvent("moveend",t);break;case"pending":this._state="enabled",this._unbind();}},Io.prototype._unbind=function(){t.window.document.removeEventListener("mousemove",this._onMouseMove,{capture:!0}),t.window.document.removeEventListener("mouseup",this._onMouseUp),t.window.document.removeEventListener("touchmove",this._onMouseMove,{capture:!0}),t.window.document.removeEventListener("touchend",this._onMouseUp),t.window.removeEventListener("blur",this._onBlur),i.enableDrag();},Io.prototype._deactivate=function(){this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),delete this._lastMoveEvent,delete this._startPos,delete this._prevPos,delete this._lastPos;},Io.prototype._inertialRotate=function(t){var e=this;this._fireEvent("rotateend",t),this._drainInertiaBuffer();var i=this._map,o=i.getBearing(),r=this._inertia,a=function(){Math.abs(o)<e._bearingSnap?i.resetNorth({noMoveStart:!0},{originalEvent:t}):e._fireEvent("moveend",t),e._pitchWithRotate&&e._fireEvent("pitchend",t);};if(r.length<2)a();else{var n=r[0],s=r[r.length-1],l=r[r.length-2],c=i._normalizeBearing(o,l[1]),u=s[1]-n[1],h=u<0?-1:1,p=(s[0]-n[0])/1e3;if(0!==u&&0!==p){var d=Math.abs(u*(.25/p));d>180&&(d=180);var _=d/180;c+=h*d*(_/2),Math.abs(i._normalizeBearing(c,0))<this._bearingSnap&&(c=i._normalizeBearing(0,c)),i.rotateTo(c,{duration:1e3*_,easing:To,noMoveStart:!0},{originalEvent:t});}else a();}},Io.prototype._fireEvent=function(e,i){return this._map.fire(new t.Event(e,i?{originalEvent:i}:{}))},Io.prototype._drainInertiaBuffer=function(){for(var e=this._inertia,i=t.browser.now();e.length>0&&i-e[0][0]>160;)e.shift();};var So={linearity:.3,easing:t.bezier(0,0,.3,1),maxSpeed:1400,deceleration:2500},Co=function(e,i){this._map=e,this._el=e.getCanvasContainer(),this._state="disabled",this._clickTolerance=i.clickTolerance||1,this._inertiaOptions=So,t.bindAll(["_onMove","_onMouseUp","_onTouchEnd","_onBlur","_onDragFrame"],this);};Co.prototype.isEnabled=function(){return "disabled"!==this._state},Co.prototype.isActive=function(){return "active"===this._state},Co.prototype.enable=function(e){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-drag-pan"),this._state="enabled",this._inertiaOptions=t.extend(So,e));},Co.prototype.disable=function(){if(this.isEnabled())switch(this._el.classList.remove("mapboxgl-touch-drag-pan"),this._state){case"active":this._state="disabled",this._unbind(),this._deactivate(),this._fireEvent("dragend"),this._fireEvent("moveend");break;case"pending":this._state="disabled",this._unbind();break;default:this._state="disabled";}},Co.prototype.onMouseDown=function(e){"enabled"===this._state&&(e.ctrlKey||0!==i.mouseButton(e)||(i.addEventListener(t.window.document,"mousemove",this._onMove,{capture:!0}),i.addEventListener(t.window.document,"mouseup",this._onMouseUp),this._start(e)));},Co.prototype.onTouchStart=function(e){this.isEnabled()&&(e.touches&&e.touches.length>1&&("pending"===this._state||"active"===this._state)||(i.addEventListener(t.window.document,"touchmove",this._onMove,{capture:!0,passive:!1}),i.addEventListener(t.window.document,"touchend",this._onTouchEnd),this._start(e)));},Co.prototype._start=function(e){t.window.addEventListener("blur",this._onBlur),this._state="pending",this._startPos=this._mouseDownPos=this._prevPos=this._lastPos=i.mousePos(this._el,e),this._startTouch=this._lastTouch=t.window.TouchEvent&&e instanceof t.window.TouchEvent?i.touchPos(this._el,e):null,this._inertia=[[t.browser.now(),this._startPos]];},Co.prototype._touchesMatch=function(t,e){return !(!t||!e||t.length!==e.length)&&t.every((function(t,i){return e[i]===t}))},Co.prototype._onMove=function(e){e.preventDefault();var o=t.window.TouchEvent&&e instanceof t.window.TouchEvent?i.touchPos(this._el,e):null,r=i.mousePos(this._el,e);(o?this._touchesMatch(this._lastTouch,o):this._lastPos.equals(r))||"pending"===this._state&&r.dist(this._mouseDownPos)<this._clickTolerance||(this._lastMoveEvent=e,this._lastPos=r,this._lastTouch=o,this._drainInertiaBuffer(),this._inertia.push([t.browser.now(),this._lastPos]),"pending"===this._state&&(this._state="active",this._shouldStart=!0),this._frameId||(this._frameId=this._map._requestRenderFrame(this._onDragFrame)));},Co.prototype._onDragFrame=function(){this._frameId=null;var t=this._lastMoveEvent;if(t)if(this._map.touchZoomRotate.isActive())this._abort(t);else if(this._shouldStart&&(this._fireEvent("dragstart",t),this._fireEvent("movestart",t),this._shouldStart=!1),this.isActive()){var e=this._map.transform;e.setLocationAtPoint(e.pointLocation(this._prevPos),this._lastPos),this._fireEvent("drag",t),this._fireEvent("move",t),this._prevPos=this._lastPos,delete this._lastMoveEvent;}},Co.prototype._onMouseUp=function(t){if(0===i.mouseButton(t))switch(this._state){case"active":this._state="enabled",i.suppressClick(),this._unbind(),this._deactivate(),this._inertialPan(t);break;case"pending":this._state="enabled",this._unbind();}},Co.prototype._onTouchEnd=function(t){if(t.touches&&0!==t.touches.length)switch(this._state){case"pending":case"active":break;case"enabled":this.onTouchStart(t);}else switch(this._state){case"active":this._state="enabled",this._unbind(),this._deactivate(),this._inertialPan(t);break;case"pending":this._state="enabled",this._unbind();break;case"enabled":this._unbind();}},Co.prototype._abort=function(e){switch(this._state){case"active":this._state="enabled",this._shouldStart||(this._fireEvent("dragend",e),this._fireEvent("moveend",e)),this._unbind(),this._deactivate(),t.window.TouchEvent&&e instanceof t.window.TouchEvent&&e.touches.length>1&&i.addEventListener(t.window.document,"touchend",this._onTouchEnd);break;case"pending":this._state="enabled",this._unbind();break;case"enabled":this._unbind();}},Co.prototype._onBlur=function(t){this._abort(t);},Co.prototype._unbind=function(){i.removeEventListener(t.window.document,"touchmove",this._onMove,{capture:!0,passive:!1}),i.removeEventListener(t.window.document,"touchend",this._onTouchEnd),i.removeEventListener(t.window.document,"mousemove",this._onMove,{capture:!0}),i.removeEventListener(t.window.document,"mouseup",this._onMouseUp),i.removeEventListener(t.window,"blur",this._onBlur);},Co.prototype._deactivate=function(){this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),delete this._lastMoveEvent,delete this._startPos,delete this._prevPos,delete this._mouseDownPos,delete this._lastPos,delete this._startTouch,delete this._lastTouch,delete this._shouldStart;},Co.prototype._inertialPan=function(t){this._fireEvent("dragend",t),this._drainInertiaBuffer();var e=this._inertia;if(e.length<2)this._fireEvent("moveend",t);else{var i=e[e.length-1],o=e[0],r=i[1].sub(o[1]),a=(i[0]-o[0])/1e3;if(0===a||i[1].equals(o[1]))this._fireEvent("moveend",t);else{var n=this._inertiaOptions,s=n.linearity,l=n.easing,c=n.maxSpeed,u=n.deceleration,h=r.mult(s/a),p=h.mag();p>c&&(p=c,h._unit()._mult(p));var d=p/(u*s),_=h.mult(-d/2);this._map.panBy(_,{duration:1e3*d,easing:l,noMoveStart:!0},{originalEvent:t});}}},Co.prototype._fireEvent=function(e,i){return this._map.fire(new t.Event(e,i?{originalEvent:i}:{}))},Co.prototype._drainInertiaBuffer=function(){for(var e=this._inertia,i=t.browser.now();e.length>0&&i-e[0][0]>160;)e.shift();};var Po=function(e){this._map=e,this._el=e.getCanvasContainer(),t.bindAll(["_onKeyDown"],this);};function zo(t){return t*(2-t)}Po.prototype.isEnabled=function(){return !!this._enabled},Po.prototype.enable=function(){this.isEnabled()||(this._el.addEventListener("keydown",this._onKeyDown,!1),this._enabled=!0);},Po.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("keydown",this._onKeyDown),this._enabled=!1);},Po.prototype._onKeyDown=function(t){if(!(t.altKey||t.ctrlKey||t.metaKey)){var e=0,i=0,o=0,r=0,a=0;switch(t.keyCode){case 61:case 107:case 171:case 187:e=1;break;case 189:case 109:case 173:e=-1;break;case 37:t.shiftKey?i=-1:(t.preventDefault(),r=-1);break;case 39:t.shiftKey?i=1:(t.preventDefault(),r=1);break;case 38:t.shiftKey?o=1:(t.preventDefault(),a=-1);break;case 40:t.shiftKey?o=-1:(a=1,t.preventDefault());break;default:return}var n=this._map,s=n.getZoom(),l={duration:300,delayEndEvents:500,easing:zo,zoom:e?Math.round(s)+e*(t.shiftKey?2:1):s,bearing:n.getBearing()+15*i,pitch:n.getPitch()+10*o,offset:[100*-r,100*-a],center:n.getCenter()};n.easeTo(l,{originalEvent:t});}};var Lo=function(e){this._map=e,t.bindAll(["_onDblClick","_onZoomEnd"],this);};Lo.prototype.isEnabled=function(){return !!this._enabled},Lo.prototype.isActive=function(){return !!this._active},Lo.prototype.enable=function(){this.isEnabled()||(this._enabled=!0);},Lo.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1);},Lo.prototype.onTouchStart=function(t){var e=this;if(this.isEnabled()&&!(t.points.length>1))if(this._tapped){var i=t.points[0],o=this._tappedPoint;if(o&&o.dist(i)<=30){t.originalEvent.preventDefault();var r=function(){e._tapped&&e._zoom(t),e._map.off("touchcancel",a),e._resetTapped();},a=function(){e._map.off("touchend",r),e._resetTapped();};this._map.once("touchend",r),this._map.once("touchcancel",a);}else this._resetTapped();}else this._tappedPoint=t.points[0],this._tapped=setTimeout((function(){e._tapped=null,e._tappedPoint=null;}),300);},Lo.prototype._resetTapped=function(){clearTimeout(this._tapped),this._tapped=null,this._tappedPoint=null;},Lo.prototype.onDblClick=function(t){this.isEnabled()&&(t.originalEvent.preventDefault(),this._zoom(t));},Lo.prototype._zoom=function(t){this._active=!0,this._map.on("zoomend",this._onZoomEnd),this._map.zoomTo(this._map.getZoom()+(t.originalEvent.shiftKey?-1:1),{around:t.lngLat},t);},Lo.prototype._onZoomEnd=function(){this._active=!1,this._map.off("zoomend",this._onZoomEnd);};var Mo=t.bezier(0,0,.15,1),Do=function(e){this._map=e,this._el=e.getCanvasContainer(),t.bindAll(["_onMove","_onEnd","_onTouchFrame"],this);};Do.prototype.isEnabled=function(){return !!this._enabled},Do.prototype.enable=function(t){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-zoom-rotate"),this._enabled=!0,this._aroundCenter=!!t&&"center"===t.around);},Do.prototype.disable=function(){this.isEnabled()&&(this._el.classList.remove("mapboxgl-touch-zoom-rotate"),this._enabled=!1);},Do.prototype.disableRotation=function(){this._rotationDisabled=!0;},Do.prototype.enableRotation=function(){this._rotationDisabled=!1;},Do.prototype.isActive=function(){return this.isEnabled()&&!!this._gestureIntent},Do.prototype.onStart=function(e){if(this.isEnabled()&&2===e.touches.length){var o=i.mousePos(this._el,e.touches[0]),r=i.mousePos(this._el,e.touches[1]),a=o.add(r).div(2);this._startVec=o.sub(r),this._startAround=this._map.transform.pointLocation(a),this._gestureIntent=void 0,this._inertia=[],i.addEventListener(t.window.document,"touchmove",this._onMove,{passive:!1}),i.addEventListener(t.window.document,"touchend",this._onEnd);}},Do.prototype._getTouchEventData=function(t){var e=i.mousePos(this._el,t.touches[0]),o=i.mousePos(this._el,t.touches[1]),r=e.sub(o);return {vec:r,center:e.add(o).div(2),scale:r.mag()/this._startVec.mag(),bearing:this._rotationDisabled?0:180*r.angleWith(this._startVec)/Math.PI}},Do.prototype._onMove=function(e){if(2===e.touches.length){var i=this._getTouchEventData(e),o=i.vec,r=i.scale,a=i.bearing;if(!this._gestureIntent){var n=this._rotationDisabled&&1!==r||Math.abs(1-r)>.15;Math.abs(a)>10?this._gestureIntent="rotate":n&&(this._gestureIntent="zoom"),this._gestureIntent&&(this._map.fire(new t.Event(this._gestureIntent+"start",{originalEvent:e})),this._map.fire(new t.Event("movestart",{originalEvent:e})),this._startVec=o);}this._lastTouchEvent=e,this._frameId||(this._frameId=this._map._requestRenderFrame(this._onTouchFrame)),e.preventDefault();}},Do.prototype._onTouchFrame=function(){this._frameId=null;var e=this._gestureIntent;if(e){var i=this._map.transform;this._startScale||(this._startScale=i.scale,this._startBearing=i.bearing);var o=this._getTouchEventData(this._lastTouchEvent),r=o.center,a=o.bearing,n=o.scale,s=i.pointLocation(r),l=i.locationPoint(s);"rotate"===e&&(i.bearing=this._startBearing+a),i.zoom=i.scaleZoom(this._startScale*n),i.setLocationAtPoint(this._startAround,l),this._map.fire(new t.Event(e,{originalEvent:this._lastTouchEvent})),this._map.fire(new t.Event("move",{originalEvent:this._lastTouchEvent})),this._drainInertiaBuffer(),this._inertia.push([t.browser.now(),n,r]);}},Do.prototype._onEnd=function(e){i.removeEventListener(t.window.document,"touchmove",this._onMove,{passive:!1}),i.removeEventListener(t.window.document,"touchend",this._onEnd);var o=this._gestureIntent,r=this._startScale;if(this._frameId&&(this._map._cancelRenderFrame(this._frameId),this._frameId=null),delete this._gestureIntent,delete this._startScale,delete this._startBearing,delete this._lastTouchEvent,o){this._map.fire(new t.Event(o+"end",{originalEvent:e})),this._drainInertiaBuffer();var a=this._inertia,n=this._map;if(a.length<2)n.snapToNorth({},{originalEvent:e});else{var s=a[a.length-1],l=a[0],c=n.transform.scaleZoom(r*s[1]),u=n.transform.scaleZoom(r*l[1]),h=c-u,p=(s[0]-l[0])/1e3,d=s[2];if(0!==p&&c!==u){var _=.15*h/p;Math.abs(_)>2.5&&(_=_>0?2.5:-2.5);var f=1e3*Math.abs(_/(12*.15)),m=c+_*f/2e3;n.easeTo({zoom:m,duration:f,easing:Mo,around:this._aroundCenter?n.getCenter():n.unproject(d),noMoveStart:!0},{originalEvent:e});}else n.snapToNorth({},{originalEvent:e});}}},Do.prototype._drainInertiaBuffer=function(){for(var e=this._inertia,i=t.browser.now();e.length>2&&i-e[0][0]>160;)e.shift();};var Ao={scrollZoom:wo,boxZoom:Eo,dragRotate:Io,dragPan:Co,keyboard:Po,doubleClickZoom:Lo,touchZoomRotate:Do};var Ro=function(e){function i(i,o){e.call(this),this._moving=!1,this._zooming=!1,this.transform=i,this._bearingSnap=o.bearingSnap,t.bindAll(["_renderFrameCallback"],this);}return e&&(i.__proto__=e),i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.getCenter=function(){return new t.LngLat(this.transform.center.lng,this.transform.center.lat)},i.prototype.setCenter=function(t,e){return this.jumpTo({center:t},e)},i.prototype.panBy=function(e,i,o){return e=t.Point.convert(e).mult(-1),this.panTo(this.transform.center,t.extend({offset:e},i),o)},i.prototype.panTo=function(e,i,o){return this.easeTo(t.extend({center:e},i),o)},i.prototype.getZoom=function(){return this.transform.zoom},i.prototype.setZoom=function(t,e){return this.jumpTo({zoom:t},e),this},i.prototype.zoomTo=function(e,i,o){return this.easeTo(t.extend({zoom:e},i),o)},i.prototype.zoomIn=function(t,e){return this.zoomTo(this.getZoom()+1,t,e),this},i.prototype.zoomOut=function(t,e){return this.zoomTo(this.getZoom()-1,t,e),this},i.prototype.getBearing=function(){return this.transform.bearing},i.prototype.setBearing=function(t,e){return this.jumpTo({bearing:t},e),this},i.prototype.rotateTo=function(e,i,o){return this.easeTo(t.extend({bearing:e},i),o)},i.prototype.resetNorth=function(e,i){return this.rotateTo(0,t.extend({duration:1e3},e),i),this},i.prototype.resetNorthPitch=function(e,i){return this.easeTo(t.extend({bearing:0,pitch:0,duration:1e3},e),i),this},i.prototype.snapToNorth=function(t,e){return Math.abs(this.getBearing())<this._bearingSnap?this.resetNorth(t,e):this},i.prototype.getPitch=function(){return this.transform.pitch},i.prototype.setPitch=function(t,e){return this.jumpTo({pitch:t},e),this},i.prototype.cameraForBounds=function(e,i){return e=t.LngLatBounds.convert(e),this._cameraForBoxAndBearing(e.getNorthWest(),e.getSouthEast(),0,i)},i.prototype._cameraForBoxAndBearing=function(e,i,o,r){if("number"==typeof(r=t.extend({padding:{top:0,bottom:0,right:0,left:0},offset:[0,0],maxZoom:this.transform.maxZoom},r)).padding){var a=r.padding;r.padding={top:a,bottom:a,right:a,left:a};}if(t.deepEqual(Object.keys(r.padding).sort((function(t,e){return t<e?-1:t>e?1:0})),["bottom","left","right","top"])){var n=this.transform,s=n.project(t.LngLat.convert(e)),l=n.project(t.LngLat.convert(i)),c=s.rotate(-o*Math.PI/180),u=l.rotate(-o*Math.PI/180),h=new t.Point(Math.max(c.x,u.x),Math.max(c.y,u.y)),p=new t.Point(Math.min(c.x,u.x),Math.min(c.y,u.y)),d=h.sub(p),_=(n.width-r.padding.left-r.padding.right)/d.x,f=(n.height-r.padding.top-r.padding.bottom)/d.y;if(!(f<0||_<0)){var m=Math.min(n.scaleZoom(n.scale*Math.min(_,f)),r.maxZoom),g=t.Point.convert(r.offset),v=(r.padding.left-r.padding.right)/2,y=(r.padding.top-r.padding.bottom)/2,x=new t.Point(g.x+v,g.y+y).mult(n.scale/n.zoomScale(m));return {center:n.unproject(s.add(l).div(2).sub(x)),zoom:m,bearing:o}}t.warnOnce("Map cannot fit within canvas with the given bounds, padding, and/or offset.");}else t.warnOnce("options.padding must be a positive number, or an Object with keys 'bottom', 'left', 'right', 'top'");},i.prototype.fitBounds=function(t,e,i){return this._fitInternal(this.cameraForBounds(t,e),e,i)},i.prototype.fitScreenCoordinates=function(e,i,o,r,a){return this._fitInternal(this._cameraForBoxAndBearing(this.transform.pointLocation(t.Point.convert(e)),this.transform.pointLocation(t.Point.convert(i)),o,r),r,a)},i.prototype._fitInternal=function(e,i,o){return e?(i=t.extend(e,i)).linear?this.easeTo(i,o):this.flyTo(i,o):this},i.prototype.jumpTo=function(e,i){this.stop();var o=this.transform,r=!1,a=!1,n=!1;return "zoom"in e&&o.zoom!==+e.zoom&&(r=!0,o.zoom=+e.zoom),void 0!==e.center&&(o.center=t.LngLat.convert(e.center)),"bearing"in e&&o.bearing!==+e.bearing&&(a=!0,o.bearing=+e.bearing),"pitch"in e&&o.pitch!==+e.pitch&&(n=!0,o.pitch=+e.pitch),this.fire(new t.Event("movestart",i)).fire(new t.Event("move",i)),r&&this.fire(new t.Event("zoomstart",i)).fire(new t.Event("zoom",i)).fire(new t.Event("zoomend",i)),a&&this.fire(new t.Event("rotatestart",i)).fire(new t.Event("rotate",i)).fire(new t.Event("rotateend",i)),n&&this.fire(new t.Event("pitchstart",i)).fire(new t.Event("pitch",i)).fire(new t.Event("pitchend",i)),this.fire(new t.Event("moveend",i))},i.prototype.easeTo=function(e,i){var o=this;this.stop(),(!1===(e=t.extend({offset:[0,0],duration:500,easing:t.ease},e)).animate||!e.essential&&t.browser.prefersReducedMotion)&&(e.duration=0);var r=this.transform,a=this.getZoom(),n=this.getBearing(),s=this.getPitch(),l="zoom"in e?+e.zoom:a,c="bearing"in e?this._normalizeBearing(e.bearing,n):n,u="pitch"in e?+e.pitch:s,h=r.centerPoint.add(t.Point.convert(e.offset)),p=r.pointLocation(h),d=t.LngLat.convert(e.center||p);this._normalizeCenter(d);var _,f,m=r.project(p),g=r.project(d).sub(m),v=r.zoomScale(l-a);return e.around&&(_=t.LngLat.convert(e.around),f=r.locationPoint(_)),this._zooming=l!==a,this._rotating=n!==c,this._pitching=u!==s,this._prepareEase(i,e.noMoveStart),clearTimeout(this._easeEndTimeoutID),this._ease((function(e){if(o._zooming&&(r.zoom=t.number(a,l,e)),o._rotating&&(r.bearing=t.number(n,c,e)),o._pitching&&(r.pitch=t.number(s,u,e)),_)r.setLocationAtPoint(_,f);else{var p=r.zoomScale(r.zoom-a),d=l>a?Math.min(2,v):Math.max(.5,v),y=Math.pow(d,1-e),x=r.unproject(m.add(g.mult(e*y)).mult(p));r.setLocationAtPoint(r.renderWorldCopies?x.wrap():x,h);}o._fireMoveEvents(i);}),(function(){e.delayEndEvents?o._easeEndTimeoutID=setTimeout((function(){return o._afterEase(i)}),e.delayEndEvents):o._afterEase(i);}),e),this},i.prototype._prepareEase=function(e,i){this._moving=!0,i||this.fire(new t.Event("movestart",e)),this._zooming&&this.fire(new t.Event("zoomstart",e)),this._rotating&&this.fire(new t.Event("rotatestart",e)),this._pitching&&this.fire(new t.Event("pitchstart",e));},i.prototype._fireMoveEvents=function(e){this.fire(new t.Event("move",e)),this._zooming&&this.fire(new t.Event("zoom",e)),this._rotating&&this.fire(new t.Event("rotate",e)),this._pitching&&this.fire(new t.Event("pitch",e));},i.prototype._afterEase=function(e){var i=this._zooming,o=this._rotating,r=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,i&&this.fire(new t.Event("zoomend",e)),o&&this.fire(new t.Event("rotateend",e)),r&&this.fire(new t.Event("pitchend",e)),this.fire(new t.Event("moveend",e));},i.prototype.flyTo=function(e,i){var o=this;if(!e.essential&&t.browser.prefersReducedMotion){var r=t.pick(e,["center","zoom","bearing","pitch","around"]);return this.jumpTo(r,i)}this.stop(),e=t.extend({offset:[0,0],speed:1.2,curve:1.42,easing:t.ease},e);var a=this.transform,n=this.getZoom(),s=this.getBearing(),l=this.getPitch(),c="zoom"in e?t.clamp(+e.zoom,a.minZoom,a.maxZoom):n,u="bearing"in e?this._normalizeBearing(e.bearing,s):s,h="pitch"in e?+e.pitch:l,p=a.zoomScale(c-n),d=a.centerPoint.add(t.Point.convert(e.offset)),_=a.pointLocation(d),f=t.LngLat.convert(e.center||_);this._normalizeCenter(f);var m=a.project(_),g=a.project(f).sub(m),v=e.curve,y=Math.max(a.width,a.height),x=y/p,b=g.mag();if("minZoom"in e){var w=t.clamp(Math.min(e.minZoom,n,c),a.minZoom,a.maxZoom),E=y/a.zoomScale(w-n);v=Math.sqrt(E/b*2);}var T=v*v;function I(t){var e=(x*x-y*y+(t?-1:1)*T*T*b*b)/(2*(t?x:y)*T*b);return Math.log(Math.sqrt(e*e+1)-e)}function S(t){return (Math.exp(t)-Math.exp(-t))/2}function C(t){return (Math.exp(t)+Math.exp(-t))/2}var P=I(0),z=function(t){return C(P)/C(P+v*t)},L=function(t){return y*((C(P)*(S(e=P+v*t)/C(e))-S(P))/T)/b;var e;},M=(I(1)-P)/v;if(Math.abs(b)<1e-6||!isFinite(M)){if(Math.abs(y-x)<1e-6)return this.easeTo(e,i);var D=x<y?-1:1;M=Math.abs(Math.log(x/y))/v,L=function(){return 0},z=function(t){return Math.exp(D*v*t)};}if("duration"in e)e.duration=+e.duration;else{var A="screenSpeed"in e?+e.screenSpeed/v:+e.speed;e.duration=1e3*M/A;}return e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=s!==u,this._pitching=h!==l,this._prepareEase(i,!1),this._ease((function(e){var r=e*M,p=1/z(r);a.zoom=1===e?c:n+a.scaleZoom(p),o._rotating&&(a.bearing=t.number(s,u,e)),o._pitching&&(a.pitch=t.number(l,h,e));var _=1===e?f:a.unproject(m.add(g.mult(L(r))).mult(p));a.setLocationAtPoint(a.renderWorldCopies?_.wrap():_,d),o._fireMoveEvents(i);}),(function(){return o._afterEase(i)}),e),this},i.prototype.isEasing=function(){return !!this._easeFrameId},i.prototype.stop=function(){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){var t=this._onEaseEnd;delete this._onEaseEnd,t.call(this);}return this},i.prototype._ease=function(e,i,o){!1===o.animate||0===o.duration?(e(1),i()):(this._easeStart=t.browser.now(),this._easeOptions=o,this._onEaseFrame=e,this._onEaseEnd=i,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));},i.prototype._renderFrameCallback=function(){var e=Math.min((t.browser.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},i.prototype._normalizeBearing=function(e,i){e=t.wrap(e,-180,180);var o=Math.abs(e-i);return Math.abs(e-360-i)<o&&(e-=360),Math.abs(e+360-i)<o&&(e+=360),e},i.prototype._normalizeCenter=function(t){var e=this.transform;if(e.renderWorldCopies&&!e.lngRange){var i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}},i}(t.Evented),ko=function(e){void 0===e&&(e={}),this.options=e,t.bindAll(["_updateEditLink","_updateData","_updateCompact"],this);};ko.prototype.getDefaultPosition=function(){return "bottom-right"},ko.prototype.onAdd=function(t){var e=this.options&&this.options.compact;return this._map=t,this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._innerContainer=i.create("div","mapboxgl-ctrl-attrib-inner",this._container),e&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),void 0===e&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container},ko.prototype.onRemove=function(){i.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0;},ko.prototype._updateEditLink=function(){var e=this._editLink;e||(e=this._editLink=this._container.querySelector(".mapbox-improve-map"));var i=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||t.config.ACCESS_TOKEN}];if(e){var o=i.reduce((function(t,e,o){return e.value&&(t+=e.key+"="+e.value+(o<i.length-1?"&":"")),t}),"?");e.href=t.config.FEEDBACK_URL+"/"+o+(this._map._hash?this._map._hash.getHashString(!0):""),e.rel="noopener nofollow";}},ko.prototype._updateData=function(t){!t||"metadata"!==t.sourceDataType&&"style"!==t.dataType||(this._updateAttributions(),this._updateEditLink());},ko.prototype._updateAttributions=function(){if(this._map.style){var t=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?t=t.concat(this.options.customAttribution.map((function(t){return "string"!=typeof t?"":t}))):"string"==typeof this.options.customAttribution&&t.push(this.options.customAttribution)),this._map.style.stylesheet){var e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}var i=this._map.style.sourceCaches;for(var o in i){var r=i[o];if(r.used){var a=r.getSource();a.attribution&&t.indexOf(a.attribution)<0&&t.push(a.attribution);}}t.sort((function(t,e){return t.length-e.length}));var n=(t=t.filter((function(e,i){for(var o=i+1;o<t.length;o++)if(t[o].indexOf(e)>=0)return !1;return !0}))).join(" | ");n!==this._attribHTML&&(this._attribHTML=n,t.length?(this._innerContainer.innerHTML=n,this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null);}},ko.prototype._updateCompact=function(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact");};var Bo=function(){t.bindAll(["_updateLogo"],this),t.bindAll(["_updateCompact"],this);};Bo.prototype.onAdd=function(t){this._map=t,this._container=i.create("div","mapboxgl-ctrl");var e=i.create("a","mapboxgl-ctrl-logo");return e.target="_blank",e.rel="noopener nofollow",e.href="https://www.mapbox.com/",e.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),e.setAttribute("rel","noopener nofollow"),this._container.appendChild(e),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container},Bo.prototype.onRemove=function(){i.remove(this._container),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact);},Bo.prototype.getDefaultPosition=function(){return "bottom-left"},Bo.prototype._updateLogo=function(t){t&&"metadata"!==t.sourceDataType||(this._container.style.display=this._logoRequired()?"block":"none");},Bo.prototype._logoRequired=function(){if(this._map.style){var t=this._map.style.sourceCaches;for(var e in t){if(t[e].getSource().mapbox_logo)return !0}return !1}},Bo.prototype._updateCompact=function(){var t=this._container.children;if(t.length){var e=t[0];this._map.getCanvasContainer().offsetWidth<250?e.classList.add("mapboxgl-compact"):e.classList.remove("mapboxgl-compact");}};var Oo=function(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;};Oo.prototype.add=function(t){var e=++this._id;return this._queue.push({callback:t,id:e,cancelled:!1}),e},Oo.prototype.remove=function(t){for(var e=this._currentlyRunning,i=0,o=e?this._queue.concat(e):this._queue;i<o.length;i+=1){var r=o[i];if(r.id===t)return void(r.cancelled=!0)}},Oo.prototype.run=function(){var t=this._currentlyRunning=this._queue;this._queue=[];for(var e=0,i=t;e<i.length;e+=1){var o=i[e];if(!o.cancelled&&(o.callback(),this._cleared))break}this._cleared=!1,this._currentlyRunning=!1;},Oo.prototype.clear=function(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];};var Fo={"FullscreenControl.Enter":"Enter fullscreen","FullscreenControl.Exit":"Exit fullscreen","GeolocateControl.FindMyLocation":"Find my location","GeolocateControl.LocationNotAvailable":"Location not available","LogoControl.Title":"Mapbox logo","NavigationControl.ResetBearing":"Reset bearing to north","NavigationControl.ZoomIn":"Zoom in","NavigationControl.ZoomOut":"Zoom out","ScaleControl.Feet":"ft","ScaleControl.Meters":"m","ScaleControl.Kilometers":"km","ScaleControl.Miles":"mi","ScaleControl.NauticalMiles":"nm"},Uo=t.window.HTMLImageElement,No=t.window.HTMLElement,Zo=t.window.ImageBitmap,qo=0,jo=60,Vo={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:-2,maxZoom:22,minPitch:qo,maxPitch:jo,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,bearingSnap:7,clickTolerance:3,hash:!1,attributionControl:!0,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,maxTileCacheSize:null,localIdeographFontFamily:"sans-serif",transformRequest:null,accessToken:null,fadeDuration:300,crossSourceCollisions:!0},Go=function(o){function r(e){var r=this;if(null!=(e=t.extend({},Vo,e)).minZoom&&null!=e.maxZoom&&e.minZoom>e.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=e.minPitch&&null!=e.maxPitch&&e.minPitch>e.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=e.minPitch&&e.minPitch<qo)throw new Error("minPitch must be greater than or equal to "+qo);if(null!=e.maxPitch&&e.maxPitch>jo)throw new Error("maxPitch must be less than or equal to "+jo);var a=new mo(e.minZoom,e.maxZoom,e.minPitch,e.maxPitch,e.renderWorldCopies);if(o.call(this,a,e),this._interactive=e.interactive,this._maxTileCacheSize=e.maxTileCacheSize,this._failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=e.preserveDrawingBuffer,this._antialias=e.antialias,this._trackResize=e.trackResize,this._bearingSnap=e.bearingSnap,this._refreshExpiredTiles=e.refreshExpiredTiles,this._fadeDuration=e.fadeDuration,this._crossSourceCollisions=e.crossSourceCollisions,this._crossFadingFactor=1,this._collectResourceTiming=e.collectResourceTiming,this._renderTaskQueue=new Oo,this._controls=[],this._mapId=t.uniqueId(),this._locale=t.extend({},Fo,e.locale),this._requestManager=new t.RequestManager(e.transformRequest,e.accessToken),"string"==typeof e.container){if(this._container=t.window.document.getElementById(e.container),!this._container)throw new Error("Container '"+e.container+"' not found.")}else{if(!(e.container instanceof No))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=e.container;}if(e.maxBounds&&this.setMaxBounds(e.maxBounds),t.bindAll(["_onWindowOnline","_onWindowResize","_contextLost","_contextRestored"],this),this._setupContainer(),this._setupPainter(),void 0===this.painter)throw new Error("Failed to initialize WebGL.");this.on("move",(function(){return r._update(!1)})),this.on("moveend",(function(){return r._update(!1)})),this.on("zoom",(function(){return r._update(!0)})),void 0!==t.window&&(t.window.addEventListener("online",this._onWindowOnline,!1),t.window.addEventListener("resize",this._onWindowResize,!1)),function(t,e){var o=t.getCanvasContainer(),r=null,a=!1,n=null;for(var s in Ao)t[s]=new Ao[s](t,e),e.interactive&&e[s]&&t[s].enable(e[s]);i.addEventListener(o,"mouseout",(function(e){t.fire(new yo("mouseout",t,e));})),i.addEventListener(o,"mousedown",(function(r){a=!0,n=i.mousePos(o,r);var s=new yo("mousedown",t,r);if(t.fire(s),s.defaultPrevented)return;e.interactive&&!t.doubleClickZoom.isActive()&&t.stop();t.boxZoom.onMouseDown(r),t.boxZoom.isActive()||t.dragPan.isActive()||t.dragRotate.onMouseDown(r);t.boxZoom.isActive()||t.dragRotate.isActive()||t.dragPan.onMouseDown(r);})),i.addEventListener(o,"mouseup",(function(e){var i=t.dragRotate.isActive();r&&!i&&t.fire(new yo("contextmenu",t,r));r=null,a=!1,t.fire(new yo("mouseup",t,e));})),i.addEventListener(o,"mousemove",(function(e){if(t.dragPan.isActive())return;if(t.dragRotate.isActive())return;var i=e.target;for(;i&&i!==o;)i=i.parentNode;if(i!==o)return;t.fire(new yo("mousemove",t,e));})),i.addEventListener(o,"mouseover",(function(e){var i=e.target;for(;i&&i!==o;)i=i.parentNode;if(i!==o)return;t.fire(new yo("mouseover",t,e));})),i.addEventListener(o,"touchstart",(function(i){var o=new xo("touchstart",t,i);if(t.fire(o),o.defaultPrevented)return;e.interactive&&t.stop();t.boxZoom.isActive()||t.dragRotate.isActive()||t.dragPan.onTouchStart(i);t.touchZoomRotate.onStart(i),t.doubleClickZoom.onTouchStart(o);}),{passive:!1}),i.addEventListener(o,"touchmove",(function(e){t.fire(new xo("touchmove",t,e));}),{passive:!1}),i.addEventListener(o,"touchend",(function(e){t.fire(new xo("touchend",t,e));})),i.addEventListener(o,"touchcancel",(function(e){t.fire(new xo("touchcancel",t,e));})),i.addEventListener(o,"click",(function(r){var a=i.mousePos(o,r);(!n||a.equals(n)||a.dist(n)<e.clickTolerance)&&t.fire(new yo("click",t,r));})),i.addEventListener(o,"dblclick",(function(e){var i=new yo("dblclick",t,e);if(t.fire(i),i.defaultPrevented)return;t.doubleClickZoom.onDblClick(i);})),i.addEventListener(o,"contextmenu",(function(e){var i=t.dragRotate.isActive();a||i?a&&(r=e):t.fire(new yo("contextmenu",t,e));(t.dragRotate.isEnabled()||t.listens("contextmenu"))&&e.preventDefault();})),i.addEventListener(o,"wheel",(function(i){e.interactive&&t.stop();var o=new bo("wheel",t,i);if(t.fire(o),o.defaultPrevented)return;t.scrollZoom.onWheel(i);}),{passive:!1});}(this,e);var n="string"==typeof e.hash&&e.hash||void 0;this._hash=e.hash&&new vo(n).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:e.center,zoom:e.zoom,bearing:e.bearing,pitch:e.pitch}),e.bounds&&(this.resize(),this.fitBounds(e.bounds,t.extend({},e.fitBoundsOptions,{duration:0})))),this.resize(),this._localIdeographFontFamily=e.localIdeographFontFamily,e.style&&this.setStyle(e.style,{localIdeographFontFamily:e.localIdeographFontFamily}),e.attributionControl&&this.addControl(new ko({customAttribution:e.customAttribution})),this.addControl(new Bo,e.logoPosition),this.on("style.load",(function(){r.transform.unmodified&&r.jumpTo(r.style.stylesheet);})),this.on("data",(function(e){r._update("style"===e.dataType),r.fire(new t.Event(e.dataType+"data",e));})),this.on("dataloading",(function(e){r.fire(new t.Event(e.dataType+"dataloading",e));}));}o&&(r.__proto__=o),r.prototype=Object.create(o&&o.prototype),r.prototype.constructor=r;var a={showTileBoundaries:{configurable:!0},showCollisionBoxes:{configurable:!0},showOverdrawInspector:{configurable:!0},repaint:{configurable:!0},vertices:{configurable:!0},version:{configurable:!0}};return r.prototype._getMapId=function(){return this._mapId},r.prototype.addControl=function(e,i){if(void 0===i&&e.getDefaultPosition&&(i=e.getDefaultPosition()),void 0===i&&(i="top-right"),!e||!e.onAdd)return this.fire(new t.ErrorEvent(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));var o=e.onAdd(this);this._controls.push(e);var r=this._controlPositions[i];return -1!==i.indexOf("bottom")?r.insertBefore(o,r.firstChild):r.appendChild(o),this},r.prototype.removeControl=function(e){if(!e||!e.onRemove)return this.fire(new t.ErrorEvent(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));var i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this},r.prototype.resize=function(e){var i=this._containerDimensions(),o=i[0],r=i[1];return this._resizeCanvas(o,r),this.transform.resize(o,r),this.painter.resize(o,r),this.fire(new t.Event("movestart",e)).fire(new t.Event("move",e)).fire(new t.Event("resize",e)).fire(new t.Event("moveend",e)),this},r.prototype.getBounds=function(){return this.transform.getBounds()},r.prototype.getMaxBounds=function(){return this.transform.getMaxBounds()},r.prototype.setMaxBounds=function(e){return this.transform.setMaxBounds(t.LngLatBounds.convert(e)),this._update()},r.prototype.setMinZoom=function(t){if((t=null==t?-2:t)>=-2&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()<t&&this.setZoom(t),this;throw new Error("minZoom must be between -2 and the current maxZoom, inclusive")},r.prototype.getMinZoom=function(){return this.transform.minZoom},r.prototype.setMaxZoom=function(t){if((t=null==t?22:t)>=this.transform.minZoom)return this.transform.maxZoom=t,this._update(),this.getZoom()>t&&this.setZoom(t),this;throw new Error("maxZoom must be greater than the current minZoom")},r.prototype.getMaxZoom=function(){return this.transform.maxZoom},r.prototype.setMinPitch=function(t){if((t=null==t?qo:t)<qo)throw new Error("minPitch must be greater than or equal to "+qo);if(t>=qo&&t<=this.transform.maxPitch)return this.transform.minPitch=t,this._update(),this.getPitch()<t&&this.setPitch(t),this;throw new Error("minPitch must be between "+qo+" and the current maxPitch, inclusive")},r.prototype.getMinPitch=function(){return this.transform.minPitch},r.prototype.setMaxPitch=function(t){if((t=null==t?jo:t)>jo)throw new Error("maxPitch must be less than or equal to "+jo);if(t>=this.transform.minPitch)return this.transform.maxPitch=t,this._update(),this.getPitch()>t&&this.setPitch(t),this;throw new Error("maxPitch must be greater than the current minPitch")},r.prototype.getMaxPitch=function(){return this.transform.maxPitch},r.prototype.getRenderWorldCopies=function(){return this.transform.renderWorldCopies},r.prototype.setRenderWorldCopies=function(t){return this.transform.renderWorldCopies=t,this._update()},r.prototype.project=function(e){return this.transform.locationPoint(t.LngLat.convert(e))},r.prototype.unproject=function(e){return this.transform.pointLocation(t.Point.convert(e))},r.prototype.isMoving=function(){return this._moving||this.dragPan.isActive()||this.dragRotate.isActive()||this.scrollZoom.isActive()},r.prototype.isZooming=function(){return this._zooming||this.scrollZoom.isZooming()},r.prototype.isRotating=function(){return this._rotating||this.dragRotate.isActive()},r.prototype._createDelegatedListener=function(t,e,i){var o,r=this;if("mouseenter"===t||"mouseover"===t){var a=!1;return {layer:e,listener:i,delegates:{mousemove:function(o){var n=r.getLayer(e)?r.queryRenderedFeatures(o.point,{layers:[e]}):[];n.length?a||(a=!0,i.call(r,new yo(t,r,o.originalEvent,{features:n}))):a=!1;},mouseout:function(){a=!1;}}}}if("mouseleave"===t||"mouseout"===t){var n=!1;return {layer:e,listener:i,delegates:{mousemove:function(o){(r.getLayer(e)?r.queryRenderedFeatures(o.point,{layers:[e]}):[]).length?n=!0:n&&(n=!1,i.call(r,new yo(t,r,o.originalEvent)));},mouseout:function(e){n&&(n=!1,i.call(r,new yo(t,r,e.originalEvent)));}}}}return {layer:e,listener:i,delegates:(o={},o[t]=function(t){var o=r.getLayer(e)?r.queryRenderedFeatures(t.point,{layers:[e]}):[];o.length&&(t.features=o,i.call(r,t),delete t.features);},o)}},r.prototype.on=function(t,e,i){if(void 0===i)return o.prototype.on.call(this,t,e);var r=this._createDelegatedListener(t,e,i);for(var a in this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[t]=this._delegatedListeners[t]||[],this._delegatedListeners[t].push(r),r.delegates)this.on(a,r.delegates[a]);return this},r.prototype.once=function(t,e,i){if(void 0===i)return o.prototype.once.call(this,t,e);var r=this._createDelegatedListener(t,e,i);for(var a in r.delegates)this.once(a,r.delegates[a]);return this},r.prototype.off=function(t,e,i){var r=this;if(void 0===i)return o.prototype.off.call(this,t,e);return this._delegatedListeners&&this._delegatedListeners[t]&&function(o){for(var a=o[t],n=0;n<a.length;n++){var s=a[n];if(s.layer===e&&s.listener===i){for(var l in s.delegates)r.off(l,s.delegates[l]);return a.splice(n,1),r}}}(this._delegatedListeners),this},r.prototype.queryRenderedFeatures=function(e,i){if(!this.style)return [];var o;if(void 0!==i||void 0===e||e instanceof t.Point||Array.isArray(e)||(i=e,e=void 0),i=i||{},(e=e||[[0,0],[this.transform.width,this.transform.height]])instanceof t.Point||"number"==typeof e[0])o=[t.Point.convert(e)];else{var r=t.Point.convert(e[0]),a=t.Point.convert(e[1]);o=[r,new t.Point(a.x,r.y),a,new t.Point(r.x,a.y),r];}return this.style.queryRenderedFeatures(o,i,this.transform)},r.prototype.querySourceFeatures=function(t,e){return this.style.querySourceFeatures(t,e)},r.prototype.setStyle=function(e,i){return !1!==(i=t.extend({},{localIdeographFontFamily:this._localIdeographFontFamily},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))},r.prototype._getUIString=function(t){var e=this._locale[t];if(null==e)throw new Error("Missing UI string '"+t+"'");return e},r.prototype._updateStyle=function(t,e){return this.style&&(this.style.setEventedParent(null),this.style._remove()),t?(this.style=new Ze(this,e||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof t?this.style.loadURL(t):this.style.loadJSON(t),this):(delete this.style,this)},r.prototype._lazyInitEmptyStyle=function(){this.style||(this.style=new Ze(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());},r.prototype._diffStyle=function(e,i){var o=this;if("string"==typeof e){var r=this._requestManager.normalizeStyleURL(e),a=this._requestManager.transformRequest(r,t.ResourceType.Style);t.getJSON(a,(function(e,r){e?o.fire(new t.ErrorEvent(e)):r&&o._updateDiff(r,i);}));}else"object"==typeof e&&this._updateDiff(e,i);},r.prototype._updateDiff=function(e,i){try{this.style.setState(e)&&this._update(!0);}catch(o){t.warnOnce("Unable to perform style diff: "+(o.message||o.error||o)+". Rebuilding the style from scratch."),this._updateStyle(e,i);}},r.prototype.getStyle=function(){if(this.style)return this.style.serialize()},r.prototype.isStyleLoaded=function(){return this.style?this.style.loaded():t.warnOnce("There is no style added to the map.")},r.prototype.addSource=function(t,e){return this._lazyInitEmptyStyle(),this.style.addSource(t,e),this._update(!0)},r.prototype.isSourceLoaded=function(e){var i=this.style&&this.style.sourceCaches[e];if(void 0!==i)return i.loaded();this.fire(new t.ErrorEvent(new Error("There is no source with ID '"+e+"'")));},r.prototype.areTilesLoaded=function(){var t=this.style&&this.style.sourceCaches;for(var e in t){var i=t[e]._tiles;for(var o in i){var r=i[o];if("loaded"!==r.state&&"errored"!==r.state)return !1}}return !0},r.prototype.addSourceType=function(t,e,i){return this._lazyInitEmptyStyle(),this.style.addSourceType(t,e,i)},r.prototype.removeSource=function(t){return this.style.removeSource(t),this._update(!0)},r.prototype.getSource=function(t){return this.style.getSource(t)},r.prototype.addImage=function(e,i,o){void 0===o&&(o={});var r=o.pixelRatio;void 0===r&&(r=1);var a=o.sdf;void 0===a&&(a=!1);var n=o.stretchX,s=o.stretchY,l=o.content;this._lazyInitEmptyStyle();if(i instanceof Uo||Zo&&i instanceof Zo){var c=t.browser.getImageData(i),u=c.width,h=c.height,p=c.data;this.style.addImage(e,{data:new t.RGBAImage({width:u,height:h},p),pixelRatio:r,stretchX:n,stretchY:s,content:l,sdf:a,version:0});}else{if(void 0===i.width||void 0===i.height)return this.fire(new t.ErrorEvent(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));var d=i.width,_=i.height,f=i.data,m=i;this.style.addImage(e,{data:new t.RGBAImage({width:d,height:_},new Uint8Array(f)),pixelRatio:r,stretchX:n,stretchY:s,content:l,sdf:a,version:0,userImage:m}),m.onAdd&&m.onAdd(this,e);}},r.prototype.updateImage=function(e,i){var o=this.style.getImage(e);if(!o)return this.fire(new t.ErrorEvent(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));var r=i instanceof Uo||Zo&&i instanceof Zo?t.browser.getImageData(i):i,a=r.width,n=r.height,s=r.data;if(void 0===a||void 0===n)return this.fire(new t.ErrorEvent(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(a!==o.data.width||n!==o.data.height)return this.fire(new t.ErrorEvent(new Error("The width and height of the updated image must be that same as the previous version of the image")));var l=!(i instanceof Uo||Zo&&i instanceof Zo);o.data.replace(s,l),this.style.updateImage(e,o);},r.prototype.hasImage=function(e){return e?!!this.style.getImage(e):(this.fire(new t.ErrorEvent(new Error("Missing required image id"))),!1)},r.prototype.removeImage=function(t){this.style.removeImage(t);},r.prototype.loadImage=function(e,i){t.getImage(this._requestManager.transformRequest(e,t.ResourceType.Image),i);},r.prototype.listImages=function(){return this.style.listImages()},r.prototype.addLayer=function(t,e){return this._lazyInitEmptyStyle(),this.style.addLayer(t,e),this._update(!0)},r.prototype.moveLayer=function(t,e){return this.style.moveLayer(t,e),this._update(!0)},r.prototype.removeLayer=function(t){return this.style.removeLayer(t),this._update(!0)},r.prototype.getLayer=function(t){return this.style.getLayer(t)},r.prototype.setLayerZoomRange=function(t,e,i){return this.style.setLayerZoomRange(t,e,i),this._update(!0)},r.prototype.setFilter=function(t,e,i){return void 0===i&&(i={}),this.style.setFilter(t,e,i),this._update(!0)},r.prototype.getFilter=function(t){return this.style.getFilter(t)},r.prototype.setPaintProperty=function(t,e,i,o){return void 0===o&&(o={}),this.style.setPaintProperty(t,e,i,o),this._update(!0)},r.prototype.getPaintProperty=function(t,e){return this.style.getPaintProperty(t,e)},r.prototype.setLayoutProperty=function(t,e,i,o){return void 0===o&&(o={}),this.style.setLayoutProperty(t,e,i,o),this._update(!0)},r.prototype.getLayoutProperty=function(t,e){return this.style.getLayoutProperty(t,e)},r.prototype.setLight=function(t,e){return void 0===e&&(e={}),this._lazyInitEmptyStyle(),this.style.setLight(t,e),this._update(!0)},r.prototype.getLight=function(){return this.style.getLight()},r.prototype.setFeatureState=function(t,e){return this.style.setFeatureState(t,e),this._update()},r.prototype.removeFeatureState=function(t,e){return this.style.removeFeatureState(t,e),this._update()},r.prototype.getFeatureState=function(t){return this.style.getFeatureState(t)},r.prototype.getContainer=function(){return this._container},r.prototype.getCanvasContainer=function(){return this._canvasContainer},r.prototype.getCanvas=function(){return this._canvas},r.prototype._containerDimensions=function(){var t=0,e=0;return this._container&&(t=this._container.clientWidth||400,e=this._container.clientHeight||300),[t,e]},r.prototype._detectMissingCSS=function(){"rgb(250, 128, 114)"!==t.window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color")&&t.warnOnce("This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.");},r.prototype._setupContainer=function(){var t=this._container;t.classList.add("mapboxgl-map"),(this._missingCSSCanary=i.create("div","mapboxgl-canary",t)).style.visibility="hidden",this._detectMissingCSS();var e=this._canvasContainer=i.create("div","mapboxgl-canvas-container",t);this._interactive&&e.classList.add("mapboxgl-interactive"),this._canvas=i.create("canvas","mapboxgl-canvas",e),this._canvas.style.position="absolute",this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex","0"),this._canvas.setAttribute("aria-label","Map");var o=this._containerDimensions();this._resizeCanvas(o[0],o[1]);var r=this._controlContainer=i.create("div","mapboxgl-control-container",t),a=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((function(t){a[t]=i.create("div","mapboxgl-ctrl-"+t,r);}));},r.prototype._resizeCanvas=function(e,i){var o=t.browser.devicePixelRatio||1;this._canvas.width=o*e,this._canvas.height=o*i,this._canvas.style.width=e+"px",this._canvas.style.height=i+"px";},r.prototype._setupPainter=function(){var i=t.extend({},e.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),o=this._canvas.getContext("webgl",i)||this._canvas.getContext("experimental-webgl",i);o?(this.painter=new po(o,this.transform),t.webpSupported.testSupport(o)):this.fire(new t.ErrorEvent(new Error("Failed to initialize WebGL")));},r.prototype._contextLost=function(e){e.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new t.Event("webglcontextlost",{originalEvent:e}));},r.prototype._contextRestored=function(e){this._setupPainter(),this.resize(),this._update(),this.fire(new t.Event("webglcontextrestored",{originalEvent:e}));},r.prototype.loaded=function(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()},r.prototype._update=function(t){return this.style?(this._styleDirty=this._styleDirty||t,this._sourcesDirty=!0,this.triggerRepaint(),this):this},r.prototype._requestRenderFrame=function(t){return this._update(),this._renderTaskQueue.add(t)},r.prototype._cancelRenderFrame=function(t){this._renderTaskQueue.remove(t);},r.prototype._render=function(){var e,i=this,o=0,r=this.painter.context.extTimerQuery;this.listens("gpu-timing-frame")&&(e=r.createQueryEXT(),r.beginQueryEXT(r.TIME_ELAPSED_EXT,e),o=t.browser.now()),this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run();var a=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;var n=this.transform.zoom,s=t.browser.now();this.style.zoomHistory.update(n,s);var l=new t.EvaluationParameters(n,{now:s,fadeDuration:this._fadeDuration,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),c=l.crossFadingFactor();1===c&&c===this._crossFadingFactor||(a=!0,this._crossFadingFactor=c),this.style.update(l);}if(this.style&&this._sourcesDirty&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this._placementDirty=this.style&&this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,this._fadeDuration,this._crossSourceCollisions),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),gpuTiming:!!this.listens("gpu-timing-layer"),fadeDuration:this._fadeDuration}),this.fire(new t.Event("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,this.fire(new t.Event("load"))),this.style&&(this.style.hasTransitions()||a)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles(),this.listens("gpu-timing-frame")){var u=t.browser.now()-o;r.endQueryEXT(r.TIME_ELAPSED_EXT,e),setTimeout((function(){var o=r.getQueryObjectEXT(e,r.QUERY_RESULT_EXT)/1e6;r.deleteQueryEXT(e),i.fire(new t.Event("gpu-timing-frame",{cpuTime:u,gpuTime:o}));}),50);}if(this.listens("gpu-timing-layer")){var h=this.painter.collectGpuTimers();setTimeout((function(){var e=i.painter.queryGpuTimers(h);i.fire(new t.Event("gpu-timing-layer",{layerTimes:e}));}),50);}return this._sourcesDirty||this._styleDirty||this._placementDirty||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&(this._fullyLoaded||(this._fullyLoaded=!0),this.fire(new t.Event("idle"))),this},r.prototype.remove=function(){this._hash&&this._hash.remove();for(var e=0,i=this._controls;e<i.length;e+=1){i[e].onRemove(this);}this._controls=[],this._frame&&(this._frame.cancel(),this._frame=null),this._renderTaskQueue.clear(),this.setStyle(null),void 0!==t.window&&(t.window.removeEventListener("resize",this._onWindowResize,!1),t.window.removeEventListener("online",this._onWindowOnline,!1));var o=this.painter.context.gl.getExtension("WEBGL_lose_context");o&&o.loseContext(),Wo(this._canvasContainer),Wo(this._controlContainer),Wo(this._missingCSSCanary),this._container.classList.remove("mapboxgl-map"),this.fire(new t.Event("remove"));},r.prototype.triggerRepaint=function(){var e=this;this.style&&!this._frame&&(this._frame=t.browser.frame((function(t){e._frame=null,e._render();})));},r.prototype._onWindowOnline=function(){this._update();},r.prototype._onWindowResize=function(t){this._trackResize&&this.resize({originalEvent:t})._update();},a.showTileBoundaries.get=function(){return !!this._showTileBoundaries},a.showTileBoundaries.set=function(t){this._showTileBoundaries!==t&&(this._showTileBoundaries=t,this._update());},a.showCollisionBoxes.get=function(){return !!this._showCollisionBoxes},a.showCollisionBoxes.set=function(t){this._showCollisionBoxes!==t&&(this._showCollisionBoxes=t,t?this.style._generateCollisionBoxes():this._update());},a.showOverdrawInspector.get=function(){return !!this._showOverdrawInspector},a.showOverdrawInspector.set=function(t){this._showOverdrawInspector!==t&&(this._showOverdrawInspector=t,this._update());},a.repaint.get=function(){return !!this._repaint},a.repaint.set=function(t){this._repaint!==t&&(this._repaint=t,this.triggerRepaint());},a.vertices.get=function(){return !!this._vertices},a.vertices.set=function(t){this._vertices=t,this._update();},r.prototype._setCacheLimits=function(e,i){t.setCacheLimits(e,i);},a.version.get=function(){return t.version},Object.defineProperties(r.prototype,a),r}(Ro);function Wo(t){t.parentNode&&t.parentNode.removeChild(t);}var Xo={showCompass:!0,showZoom:!0,visualizePitch:!1},Ho=function(e){var o=this;this.options=t.extend({},Xo,e),this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",(function(t){return t.preventDefault()})),this.options.showZoom&&(t.bindAll(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",(function(t){return o._map.zoomIn({},{originalEvent:t})})),i.create("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden",!0),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",(function(t){return o._map.zoomOut({},{originalEvent:t})})),i.create("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden",!0)),this.options.showCompass&&(t.bindAll(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",(function(t){o.options.visualizePitch?o._map.resetNorthPitch({},{originalEvent:t}):o._map.resetNorth({},{originalEvent:t});})),this._compassIcon=i.create("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden",!0));};function Ko(e,i,o){if(e=new t.LngLat(e.lng,e.lat),i){var r=new t.LngLat(e.lng-360,e.lat),a=new t.LngLat(e.lng+360,e.lat),n=o.locationPoint(e).distSqr(i);o.locationPoint(r).distSqr(i)<n?e=r:o.locationPoint(a).distSqr(i)<n&&(e=a);}for(;Math.abs(e.lng-o.center.lng)>180;){var s=o.locationPoint(e);if(s.x>=0&&s.y>=0&&s.x<=o.width&&s.y<=o.height)break;e.lng>o.center.lng?e.lng-=360:e.lng+=360;}return e}Ho.prototype._updateZoomButtons=function(){var t=this._map.getZoom();this._zoomInButton.disabled=t===this._map.getMaxZoom(),this._zoomOutButton.disabled=t===this._map.getMinZoom();},Ho.prototype._rotateCompassArrow=function(){var t=this.options.visualizePitch?"scale("+1/Math.pow(Math.cos(this._map.transform.pitch*(Math.PI/180)),.5)+") rotateX("+this._map.transform.pitch+"deg) rotateZ("+this._map.transform.angle*(180/Math.PI)+"deg)":"rotate("+this._map.transform.angle*(180/Math.PI)+"deg)";this._compassIcon.style.transform=t;},Ho.prototype.onAdd=function(t){return this._map=t,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new Io(t,{button:"left",element:this._compass,clickTolerance:t.dragRotate._clickTolerance}),i.addEventListener(this._compass,"mousedown",this._handler.onMouseDown),i.addEventListener(this._compass,"touchstart",this._handler.onMouseDown,{passive:!1}),this._handler.enable()),this._container},Ho.prototype.onRemove=function(){i.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),i.removeEventListener(this._compass,"mousedown",this._handler.onMouseDown),i.removeEventListener(this._compass,"touchstart",this._handler.onMouseDown,{passive:!1}),this._handler.disable(),delete this._handler),delete this._map;},Ho.prototype._createButton=function(t,e){var o=i.create("button",t,this._container);return o.type="button",o.addEventListener("click",e),o},Ho.prototype._setButtonTitle=function(t,e){var i=this._map._getUIString("NavigationControl."+e);t.title=i,t.setAttribute("aria-label",i);};var Yo={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Jo(t,e,i){var o=t.classList;for(var r in Yo)o.remove("mapboxgl-"+i+"-anchor-"+r);o.add("mapboxgl-"+i+"-anchor-"+e);}var Qo,$o=function(e){function o(o,r){var a=this;if(e.call(this),(o instanceof t.window.HTMLElement||r)&&(o=t.extend({element:o},r)),t.bindAll(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress"],this),this._anchor=o&&o.anchor||"center",this._color=o&&o.color||"#3FB1CE",this._draggable=o&&o.draggable||!1,this._state="inactive",this._rotation=o&&o.rotation||0,this._rotationAlignment=o&&o.rotationAlignment||"auto",this._pitchAlignment=o&&o.pitchAlignment&&"auto"!==o.pitchAlignment?o.pitchAlignment:this._rotationAlignment,o&&o.element)this._element=o.element,this._offset=t.Point.convert(o&&o.offset||[0,0]);else{this._defaultMarker=!0,this._element=i.create("div"),this._element.setAttribute("aria-label","Map marker");var n=i.createNS("http://www.w3.org/2000/svg","svg");n.setAttributeNS(null,"display","block"),n.setAttributeNS(null,"height","41px"),n.setAttributeNS(null,"width","27px"),n.setAttributeNS(null,"viewBox","0 0 27 41");var s=i.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"stroke","none"),s.setAttributeNS(null,"stroke-width","1"),s.setAttributeNS(null,"fill","none"),s.setAttributeNS(null,"fill-rule","evenodd");var l=i.createNS("http://www.w3.org/2000/svg","g");l.setAttributeNS(null,"fill-rule","nonzero");var c=i.createNS("http://www.w3.org/2000/svg","g");c.setAttributeNS(null,"transform","translate(3.0, 29.0)"),c.setAttributeNS(null,"fill","#000000");for(var u=0,h=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];u<h.length;u+=1){var p=h[u],d=i.createNS("http://www.w3.org/2000/svg","ellipse");d.setAttributeNS(null,"opacity","0.04"),d.setAttributeNS(null,"cx","10.5"),d.setAttributeNS(null,"cy","5.80029008"),d.setAttributeNS(null,"rx",p.rx),d.setAttributeNS(null,"ry",p.ry),c.appendChild(d);}var _=i.createNS("http://www.w3.org/2000/svg","g");_.setAttributeNS(null,"fill",this._color);var f=i.createNS("http://www.w3.org/2000/svg","path");f.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),_.appendChild(f);var m=i.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"opacity","0.25"),m.setAttributeNS(null,"fill","#000000");var g=i.createNS("http://www.w3.org/2000/svg","path");g.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),m.appendChild(g);var v=i.createNS("http://www.w3.org/2000/svg","g");v.setAttributeNS(null,"transform","translate(6.0, 7.0)"),v.setAttributeNS(null,"fill","#FFFFFF");var y=i.createNS("http://www.w3.org/2000/svg","g");y.setAttributeNS(null,"transform","translate(8.0, 8.0)");var x=i.createNS("http://www.w3.org/2000/svg","circle");x.setAttributeNS(null,"fill","#000000"),x.setAttributeNS(null,"opacity","0.25"),x.setAttributeNS(null,"cx","5.5"),x.setAttributeNS(null,"cy","5.5"),x.setAttributeNS(null,"r","5.4999962");var b=i.createNS("http://www.w3.org/2000/svg","circle");b.setAttributeNS(null,"fill","#FFFFFF"),b.setAttributeNS(null,"cx","5.5"),b.setAttributeNS(null,"cy","5.5"),b.setAttributeNS(null,"r","5.4999962"),y.appendChild(x),y.appendChild(b),l.appendChild(c),l.appendChild(_),l.appendChild(m),l.appendChild(v),l.appendChild(y),n.appendChild(l),this._element.appendChild(n),this._offset=t.Point.convert(o&&o.offset||[0,-14]);}this._element.classList.add("mapboxgl-marker"),this._element.addEventListener("dragstart",(function(t){t.preventDefault();})),this._element.addEventListener("mousedown",(function(t){t.preventDefault();})),this._element.addEventListener("focus",(function(){var t=a._map.getContainer();t.scrollTop=0,t.scrollLeft=0;})),Jo(this._element,this._anchor,"marker"),this._popup=null;}return e&&(o.__proto__=e),o.prototype=Object.create(e&&e.prototype),o.prototype.constructor=o,o.prototype.addTo=function(t){return this.remove(),this._map=t,t.getCanvasContainer().appendChild(this._element),t.on("move",this._update),t.on("moveend",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this},o.prototype.remove=function(){return this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),i.remove(this._element),this._popup&&this._popup.remove(),this},o.prototype.getLngLat=function(){return this._lngLat},o.prototype.setLngLat=function(e){return this._lngLat=t.LngLat.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this},o.prototype.getElement=function(){return this._element},o.prototype.setPopup=function(t){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),t){if(!("offset"in t.options)){var e=Math.sqrt(Math.pow(13.5,2)/2);t.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[e,-1*(24.6+e)],"bottom-right":[-e,-1*(24.6+e)],left:[13.5,-24.6],right:[-13.5,-24.6]}:this._offset;}this._popup=t,this._lngLat&&this._popup.setLngLat(this._lngLat),this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this},o.prototype._onKeyPress=function(t){var e=t.code,i=t.charCode||t.keyCode;"Space"!==e&&"Enter"!==e&&32!==i&&13!==i||this.togglePopup();},o.prototype._onMapClick=function(t){var e=t.originalEvent.target,i=this._element;this._popup&&(e===i||i.contains(e))&&this.togglePopup();},o.prototype.getPopup=function(){return this._popup},o.prototype.togglePopup=function(){var t=this._popup;return t?(t.isOpen()?t.remove():t.addTo(this._map),this):this},o.prototype._update=function(t){if(this._map){this._map.transform.renderWorldCopies&&(this._lngLat=Ko(this._lngLat,this._pos,this._map.transform)),this._pos=this._map.project(this._lngLat)._add(this._offset);var e="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?e="rotateZ("+this._rotation+"deg)":"map"===this._rotationAlignment&&(e="rotateZ("+(this._rotation-this._map.getBearing())+"deg)");var o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o="rotateX("+this._map.getPitch()+"deg)"),t&&"moveend"!==t.type||(this._pos=this._pos.round()),i.setTransform(this._element,Yo[this._anchor]+" translate("+this._pos.x+"px, "+this._pos.y+"px) "+o+" "+e);}},o.prototype.getOffset=function(){return this._offset},o.prototype.setOffset=function(e){return this._offset=t.Point.convert(e),this._update(),this},o.prototype._onMove=function(e){this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.Event("dragstart"))),this.fire(new t.Event("drag"));},o.prototype._onUp=function(){this._element.style.pointerEvents="auto",this._positionDelta=null,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.Event("dragend")),this._state="inactive";},o.prototype._addDragHandler=function(t){this._element.contains(t.originalEvent.target)&&(t.preventDefault(),this._positionDelta=t.point.sub(this._pos).add(this._offset),this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp));},o.prototype.setDraggable=function(t){return this._draggable=!!t,this._map&&(t?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this},o.prototype.isDraggable=function(){return this._draggable},o.prototype.setRotation=function(t){return this._rotation=t||0,this._update(),this},o.prototype.getRotation=function(){return this._rotation},o.prototype.setRotationAlignment=function(t){return this._rotationAlignment=t||"auto",this._update(),this},o.prototype.getRotationAlignment=function(){return this._rotationAlignment},o.prototype.setPitchAlignment=function(t){return this._pitchAlignment=t&&"auto"!==t?t:this._rotationAlignment,this._update(),this},o.prototype.getPitchAlignment=function(){return this._pitchAlignment},o}(t.Evented),tr={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};var er=0,ir=!1,or=function(e){function o(i){e.call(this),this.options=t.extend({},tr,i),t.bindAll(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker"],this);}return e&&(o.__proto__=e),o.prototype=Object.create(e&&e.prototype),o.prototype.constructor=o,o.prototype.onAdd=function(e){var o;return this._map=e,this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),o=this._setupUI,void 0!==Qo?o(Qo):void 0!==t.window.navigator.permissions?t.window.navigator.permissions.query({name:"geolocation"}).then((function(t){Qo="denied"!==t.state,o(Qo);})):(Qo=!!t.window.navigator.geolocation,o(Qo)),this._container},o.prototype.onRemove=function(){void 0!==this._geolocationWatchID&&(t.window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),i.remove(this._container),this._map.off("zoom",this._onZoom),this._map=void 0,er=0,ir=!1;},o.prototype._isOutOfMapMaxBounds=function(t){var e=this._map.getMaxBounds(),i=t.coords;return e&&(i.longitude<e.getWest()||i.longitude>e.getEast()||i.latitude<e.getSouth()||i.latitude>e.getNorth())},o.prototype._setErrorState=function(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");}},o.prototype._onSuccess=function(e){if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.Event("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("geolocate",e)),this._finish();}},o.prototype._updateCamera=function(e){var i=new t.LngLat(e.coords.longitude,e.coords.latitude),o=e.coords.accuracy,r=this._map.getBearing(),a=t.extend({bearing:r},this.options.fitBoundsOptions);this._map.fitBounds(i.toBounds(o),a,{geolocateSource:!0});},o.prototype._updateMarker=function(e){if(e){var i=new t.LngLat(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},o.prototype._updateCircleRadius=function(){var t=this._map._container.clientHeight/2,e=this._map.unproject([0,t]),i=this._map.unproject([1,t]),o=e.distanceTo(i),r=Math.ceil(2*this._accuracy/o);this._circleElement.style.width=r+"px",this._circleElement.style.height=r+"px";},o.prototype._onZoom=function(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();},o.prototype._onError=function(e){if(this._map){if(this.options.trackUserLocation)if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;var i=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=i,this._geolocateButton.setAttribute("aria-label",i),void 0!==this._geolocationWatchID&&this._clearWatch();}else{if(3===e.code&&ir)return;this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("error",e)),this._finish();}},o.prototype._finish=function(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},o.prototype._setupUI=function(e){var o=this;if(this._container.addEventListener("contextmenu",(function(t){return t.preventDefault()})),this._geolocateButton=i.create("button","mapboxgl-ctrl-geolocate",this._container),i.create("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden",!0),this._geolocateButton.type="button",!1===e){t.warnOnce("Geolocation support is not available so the GeolocateControl will be disabled.");var r=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=r,this._geolocateButton.setAttribute("aria-label",r);}else{var a=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.title=a,this._geolocateButton.setAttribute("aria-label",a);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=i.create("div","mapboxgl-user-location-dot"),this._userLocationDotMarker=new $o(this._dotElement),this._circleElement=i.create("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new $o({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(function(e){var i=e.originalEvent&&"resize"===e.originalEvent.type;e.geolocateSource||"ACTIVE_LOCK"!==o._watchState||i||(o._watchState="BACKGROUND",o._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),o._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),o.fire(new t.Event("trackuserlocationend")));}));},o.prototype.trigger=function(){if(!this._setup)return t.warnOnce("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.Event("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":er--,ir=!1,this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire(new t.Event("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.Event("trackuserlocationstart"));}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error");}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){var e;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),++er>1?(e={maximumAge:6e5,timeout:0},ir=!0):(e=this.options.positionOptions,ir=!1),this._geolocationWatchID=t.window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else t.window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0},o.prototype._clearWatch=function(){t.window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);},o}(t.Evented),rr={maxWidth:100,unit:"metric"},ar=function(e){this.options=t.extend({},rr,e),t.bindAll(["_onMove","setUnit"],this);};function nr(t,e,i){var o=i&&i.maxWidth||100,r=t._container.clientHeight/2,a=t.unproject([0,r]),n=t.unproject([o,r]),s=a.distanceTo(n);if(i&&"imperial"===i.unit){var l=3.2808*s;if(l>5280)sr(e,o,l/5280,t._getUIString("ScaleControl.Miles"));else sr(e,o,l,t._getUIString("ScaleControl.Feet"));}else if(i&&"nautical"===i.unit){sr(e,o,s/1852,t._getUIString("ScaleControl.NauticalMiles"));}else s>=1e3?sr(e,o,s/1e3,t._getUIString("ScaleControl.Kilometers")):sr(e,o,s,t._getUIString("ScaleControl.Meters"));}function sr(t,e,i,o){var r,a,n,s=(r=i,a=Math.pow(10,(""+Math.floor(r)).length-1),n=(n=r/a)>=10?10:n>=5?5:n>=3?3:n>=2?2:n>=1?1:function(t){var e=Math.pow(10,Math.ceil(-Math.log(t)/Math.LN10));return Math.round(t*e)/e}(n),a*n),l=s/i;t.style.width=e*l+"px",t.innerHTML=s+" "+o;}ar.prototype.getDefaultPosition=function(){return "bottom-left"},ar.prototype._onMove=function(){nr(this._map,this._container,this.options);},ar.prototype.onAdd=function(t){return this._map=t,this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-scale",t.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container},ar.prototype.onRemove=function(){i.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;},ar.prototype.setUnit=function(t){this.options.unit=t,nr(this._map,this._container,this.options);};var lr=function(e){this._fullscreen=!1,e&&e.container&&(e.container instanceof t.window.HTMLElement?this._container=e.container:t.warnOnce("Full screen control 'container' must be a DOM element.")),t.bindAll(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in t.window.document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in t.window.document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in t.window.document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in t.window.document&&(this._fullscreenchange="MSFullscreenChange");};lr.prototype.onAdd=function(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",t.warnOnce("This device does not support fullscreen mode.")),this._controlContainer},lr.prototype.onRemove=function(){i.remove(this._controlContainer),this._map=null,t.window.document.removeEventListener(this._fullscreenchange,this._changeIcon);},lr.prototype._checkFullscreenSupport=function(){return !!(t.window.document.fullscreenEnabled||t.window.document.mozFullScreenEnabled||t.window.document.msFullscreenEnabled||t.window.document.webkitFullscreenEnabled)},lr.prototype._setupUI=function(){var e=this._fullscreenButton=i.create("button","mapboxgl-ctrl-fullscreen",this._controlContainer);i.create("span","mapboxgl-ctrl-icon",e).setAttribute("aria-hidden",!0),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),t.window.document.addEventListener(this._fullscreenchange,this._changeIcon);},lr.prototype._updateTitle=function(){var t=this._getTitle();this._fullscreenButton.setAttribute("aria-label",t),this._fullscreenButton.title=t;},lr.prototype._getTitle=function(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")},lr.prototype._isFullscreen=function(){return this._fullscreen},lr.prototype._changeIcon=function(){(t.window.document.fullscreenElement||t.window.document.mozFullScreenElement||t.window.document.webkitFullscreenElement||t.window.document.msFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink"),this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen"),this._updateTitle());},lr.prototype._onClickFullscreen=function(){this._isFullscreen()?t.window.document.exitFullscreen?t.window.document.exitFullscreen():t.window.document.mozCancelFullScreen?t.window.document.mozCancelFullScreen():t.window.document.msExitFullscreen?t.window.document.msExitFullscreen():t.window.document.webkitCancelFullScreen&&t.window.document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen();};var cr={closeButton:!0,closeOnClick:!0,className:"",maxWidth:"240px"},ur=function(e){function o(i){e.call(this),this.options=t.extend(Object.create(cr),i),t.bindAll(["_update","_onClose","remove"],this);}return e&&(o.__proto__=e),o.prototype=Object.create(e&&e.prototype),o.prototype.constructor=o,o.prototype.addTo=function(e){var i=this;return this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._trackPointer?(this._map.on("mousemove",(function(t){i._update(t.point);})),this._map.on("mouseup",(function(t){i._update(t.point);})),this._container&&this._container.classList.add("mapboxgl-popup-track-pointer"),this._map._canvasContainer.classList.add("mapboxgl-track-pointer")):this._map.on("move",this._update),this.fire(new t.Event("open")),this},o.prototype.isOpen=function(){return !!this._map},o.prototype.remove=function(){return this._content&&i.remove(this._content),this._container&&(i.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove"),delete this._map),this.fire(new t.Event("close")),this},o.prototype.getLngLat=function(){return this._lngLat},o.prototype.setLngLat=function(e){return this._lngLat=t.LngLat.convert(e),this._pos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove"),this._container&&this._container.classList.remove("mapboxgl-popup-track-pointer"),this._map._canvasContainer.classList.remove("mapboxgl-track-pointer")),this},o.prototype.trackPointer=function(){var t=this;return this._trackPointer=!0,this._pos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",(function(e){t._update(e.point);})),this._map.on("drag",(function(e){t._update(e.point);})),this._container&&this._container.classList.add("mapboxgl-popup-track-pointer"),this._map._canvasContainer.classList.add("mapboxgl-track-pointer")),this},o.prototype.getElement=function(){return this._container},o.prototype.setText=function(e){return this.setDOMContent(t.window.document.createTextNode(e))},o.prototype.setHTML=function(e){var i,o=t.window.document.createDocumentFragment(),r=t.window.document.createElement("body");for(r.innerHTML=e;i=r.firstChild;)o.appendChild(i);return this.setDOMContent(o)},o.prototype.getMaxWidth=function(){return this._container.style.maxWidth},o.prototype.setMaxWidth=function(t){return this.options.maxWidth=t,this._update(),this},o.prototype.setDOMContent=function(t){return this._createContent(),this._content.appendChild(t),this._update(),this},o.prototype.addClassName=function(t){this._container.classList.add(t);},o.prototype.removeClassName=function(t){this._container.classList.remove(t);},o.prototype.toggleClassName=function(t){return this._container.classList.toggle(t)},o.prototype._createContent=function(){this._content&&i.remove(this._content),this._content=i.create("div","mapboxgl-popup-content",this._container),this.options.closeButton&&(this._closeButton=i.create("button","mapboxgl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.setAttribute("aria-label","Close popup"),this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));},o.prototype._update=function(e){var o=this,r=this._lngLat||this._trackPointer;if(this._map&&r&&this._content&&(this._container||(this._container=i.create("div","mapboxgl-popup",this._map.getContainer()),this._tip=i.create("div","mapboxgl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className&&this.options.className.split(" ").forEach((function(t){return o._container.classList.add(t)})),this._trackPointer&&this._container.classList.add("mapboxgl-popup-track-pointer")),this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._map.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=Ko(this._lngLat,this._pos,this._map.transform)),!this._trackPointer||e)){var a=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat),n=this.options.anchor,s=function e(i){if(i){if("number"==typeof i){var o=Math.round(Math.sqrt(.5*Math.pow(i,2)));return {center:new t.Point(0,0),top:new t.Point(0,i),"top-left":new t.Point(o,o),"top-right":new t.Point(-o,o),bottom:new t.Point(0,-i),"bottom-left":new t.Point(o,-o),"bottom-right":new t.Point(-o,-o),left:new t.Point(i,0),right:new t.Point(-i,0)}}if(i instanceof t.Point||Array.isArray(i)){var r=t.Point.convert(i);return {center:r,top:r,"top-left":r,"top-right":r,bottom:r,"bottom-left":r,"bottom-right":r,left:r,right:r}}return {center:t.Point.convert(i.center||[0,0]),top:t.Point.convert(i.top||[0,0]),"top-left":t.Point.convert(i["top-left"]||[0,0]),"top-right":t.Point.convert(i["top-right"]||[0,0]),bottom:t.Point.convert(i.bottom||[0,0]),"bottom-left":t.Point.convert(i["bottom-left"]||[0,0]),"bottom-right":t.Point.convert(i["bottom-right"]||[0,0]),left:t.Point.convert(i.left||[0,0]),right:t.Point.convert(i.right||[0,0])}}return e(new t.Point(0,0))}(this.options.offset);if(!n){var l,c=this._container.offsetWidth,u=this._container.offsetHeight;l=a.y+s.bottom.y<u?["top"]:a.y>this._map.transform.height-u?["bottom"]:[],a.x<c/2?l.push("left"):a.x>this._map.transform.width-c/2&&l.push("right"),n=0===l.length?"bottom":l.join("-");}var h=a.add(s[n]).round();i.setTransform(this._container,Yo[n]+" translate("+h.x+"px,"+h.y+"px)"),Jo(this._container,n,"popup");}},o.prototype._onClose=function(){this.remove();},o}(t.Evented);var hr={version:t.version,supported:e,setRTLTextPlugin:t.setRTLTextPlugin,getRTLTextPluginStatus:t.getRTLTextPluginStatus,Map:Go,NavigationControl:Ho,GeolocateControl:or,AttributionControl:ko,ScaleControl:ar,FullscreenControl:lr,Popup:ur,Marker:$o,Style:Ze,LngLat:t.LngLat,LngLatBounds:t.LngLatBounds,Point:t.Point,MercatorCoordinate:t.MercatorCoordinate,Evented:t.Evented,config:t.config,get accessToken(){return t.config.ACCESS_TOKEN},set accessToken(e){t.config.ACCESS_TOKEN=e;},get baseApiUrl(){return t.config.API_URL},set baseApiUrl(e){t.config.API_URL=e;},get workerCount(){return kt.workerCount},set workerCount(t){kt.workerCount=t;},get maxParallelImageRequests(){return t.config.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(e){t.config.MAX_PARALLEL_IMAGE_REQUESTS=e;},clearStorage:function(e){t.clearTileCache(e);},workerUrl:""};return hr}));
//
return mapboxgl;
})));
//# sourceMappingURL=mapbox-gl.js.map
| e |
compare_ddp.py | """
A simple tool to compare the performance of different impls of
DistributedDataParallel on resnet50, three flavors:
1. DistributedDataParallel, which has a python wrapper and C++ core to do
gradient distribution and reduction. It's current production version.
2. PythonDDP with async gradient reduction.
3. PythonDDP with synchrous gradient reduction.
Example::
>>> modify configs in main func
>>> python compare_ddp.py
>>> Sample out: compare_ddp_sample.md
"""
import numpy as np
import os
import pickle
import glob
import python_ddp
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.nn as nn
import torch.optim as optim
import torchvision.models as models
from collections import OrderedDict
from enum import Enum
from tabulate import tabulate
from torch.nn.parallel import DistributedDataParallel as DDP
class DDPOption(Enum):
DDP_CPP_CORE = 1
PYTHON_DDP_SYNC_REDUCTION = 2
PYTHON_DDP_ASYNC_REDUCTION = 3
class LatencyData:
__slots__ = ["buffer_size_in_M", "ddp_option", "rank", "metrics"]
def __init__(self, buffer_size_in_M, ddp_option, rank, metrics):
self.buffer_size_in_M = buffer_size_in_M
self.ddp_option = ddp_option
self.rank = rank
self.metrics = metrics
def serialize(buffer_size_in_M, ddp_option, rank, metrics,
data_dir="./tmp", ext="ddpraw"):
if not os.path.exists(data_dir):
print(f'{data_dir} not exist, mkdir {data_dir}')
os.mkdir(data_dir)
file_name = "buffer_size_{}M_rank{}_{}.{}".format(
buffer_size_in_M, rank, ddp_option, ext)
file_path = os.path.join(data_dir, file_name)
print("Writing metrics to file: '{}'".format(file_path))
data = LatencyData(buffer_size_in_M, ddp_option, rank, metrics)
with open(file_path, "wb") as f:
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
print(f"Wrote metrics to '{file_path}''")
def load_detailed_metrics(data_dir="./tmp", ext="ddpraw"):
assert os.path.exists(data_dir)
file_pattern = os.path.join(data_dir, f"*.{ext}")
files = glob.glob(file_pattern)
print("load_detailed_metrics found {} files".format(len(files)))
buffer_size_to_metrics = OrderedDict()
for file_path in files:
with open(file_path, "rb") as f:
data = pickle.load(f)
# Add data to buffer_size_to_metrics
buffer_size = data.buffer_size_in_M
if buffer_size not in buffer_size_to_metrics:
buffer_size_to_metrics[buffer_size] = {}
metrics = buffer_size_to_metrics.get(buffer_size)
assert metrics is not None
metrics[data.ddp_option] = data.metrics
return buffer_size_to_metrics
def setup(rank, world_size):
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = '12355'
# initialize the process group
dist.init_process_group("gloo", rank=rank, world_size=world_size)
def | (module, rank, pg, ddp_option, buffer_size_in_M):
"""Helper to create DDPModel. """
if ddp_option == DDPOption.DDP_CPP_CORE:
ddp_model = DDP(module, device_ids=[rank],
process_group=pg,
bucket_cap_mb=buffer_size_in_M)
ddp_model._set_static_graph()
return ddp_model
elif ddp_option == DDPOption.PYTHON_DDP_SYNC_REDUCTION:
M = 2 ** 20
return python_ddp.PythonDDP(module, pg, False, buffer_size=buffer_size_in_M * M)
elif ddp_option == DDPOption.PYTHON_DDP_ASYNC_REDUCTION:
M = 2 ** 20
return python_ddp.PythonDDP(module, pg, True, buffer_size=buffer_size_in_M * M)
else:
raise NotImplementedError
def run_ddp(rank, world_size, epochs, ddp_option, buffer_size_in_M, warmup_iterations=20):
print(f'Invoked run_ddp rank {rank}')
assert epochs > warmup_iterations
# Setup
print("setting up ... ")
setup(rank, world_size)
torch.manual_seed(rank)
torch.cuda.manual_seed(rank)
device = torch.device('cuda:%d' % rank)
print('setup done')
# Create ResNet50 module and wrap in DDP module.
pg = dist.distributed_c10d._get_default_group()
model = models.resnet50().to(device)
ddp_model = create_ddp_model(model, rank, pg, ddp_option, buffer_size_in_M)
assert ddp_model is not None
loss_fn = nn.MSELoss()
optimizer = optim.SGD(ddp_model.parameters(), lr=0.001)
# Container to hold: event -> list of events in milliseconds
MODEL_FORWARD = "forward"
MODEL_BACKWARD = "backward"
metrics = {MODEL_FORWARD: [], MODEL_BACKWARD: []}
for epoch in range(epochs):
if epoch % 10 == 0:
print(f'Epoch {epoch}/{epochs} ...')
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
# TODO(bowangbj): Switch to real training set from ImageNet.
inputs = torch.rand([32, 3, 224, 224], device=device)
labels = torch.rand([32, 1000], device=device)
# Forward
start.record()
outputs = ddp_model(inputs)
loss = loss_fn(outputs, labels)
end.record()
torch.cuda.synchronize()
if epoch >= warmup_iterations:
metrics[MODEL_FORWARD].append(start.elapsed_time(end))
# Backward
start.record()
loss.backward()
# Reduce all grad, this is needed for non-DDP_CPP_CORE since the hook
# for all_reduce does not exist yet.
if ddp_option != DDPOption.DDP_CPP_CORE:
ddp_model.all_reduce_grads()
end.record()
torch.cuda.synchronize()
if epoch >= warmup_iterations:
metrics[MODEL_BACKWARD].append(start.elapsed_time(end))
# Optimization
optimizer.step()
optimizer.zero_grad()
if rank == 0:
print(f"\nMetrics for GPU {rank}, ddp_option={ddp_option}, buffer_size={buffer_size_in_M}M")
print(f"Skipped {warmup_iterations} CUDA warmpup iterations. ")
for step, elapsed_milliseconds in metrics.items():
A = np.array(elapsed_milliseconds)
print(' {N} iterations, {step}, mean={mean} ms, median={median} ms, p90={p90} ms, p99={p99} ms'.format(
N=len(A), step=step, mean=np.mean(A),
median=np.percentile(A, 50), p90=np.percentile(A, 90),
p99=np.percentile(A, 99)))
# Serialize the raw data to be used to compute summary. Didn't choose to
# maintain a global object holding the metrics b/c mp.spawn tries to
# fork all the arguments before spawning new process thus it's infeasible
# save global states in an object.
serialize(buffer_size_in_M, ddp_option, rank, metrics)
def append_delta(row_list, base, exp):
percent = 100 * ((exp - base) / base)
row_list.append(percent)
def print_summary(buffer_size_to_metrics):
# metrics: {ddp_option, Metrics}
# Metrics: step -> [latency]
for buffer_size, metrics in buffer_size_to_metrics.items():
assert DDPOption.DDP_CPP_CORE in metrics.keys()
baseline = metrics.get(DDPOption.DDP_CPP_CORE)
print(f"=== Summary for buffer_size: {buffer_size}M === ")
for step in baseline.keys():
# step takes value from [forward, backward]
# compute latency for each step into a table, each row is looks like
# [option, mean, diff, mean, diff, p90, diff, p95, diff, p99, diff]
data = []
baseline_latencies = baseline.get(step)
assert baseline_latencies is not None
A_baseline = np.array(baseline_latencies)
for ddp_option, exp_metrics in metrics.items():
exp_latencies = exp_metrics.get(step)
assert exp_latencies is not None
A_exp = np.array(exp_latencies)
# Yield option, mean, p50, p90, p95, p99 and delta.
row = [ddp_option]
row.append(np.mean(A_exp))
append_delta(row, np.mean(A_baseline), np.mean(A_exp))
for px in [50, 90, 95, 99]:
base = np.percentile(A_baseline, px)
exp = np.percentile(A_exp, px)
row.append(exp)
append_delta(row, base, exp)
data.append(row)
# Output buffer_size, step as a table.
print(tabulate(data,
headers=[f"DDP: [{step}]", "Mean", "delta%",
"mean", "delta%", "p90", "delta%",
"p95", "delta%%", "p99", "delta%"]))
print("\n")
def main():
world_size = 2
epochs = 120
# resnet50 model facts:
# total_param_count = 161
# total_elements = 25557032 ~= 24.37M
# param_max_elements = 2359296 ~= 2.25M
# Try different bucket sizes.
buffer_size_in_mbs = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]
print("buffer_size_in_mbs: " + str(buffer_size_in_mbs))
for buffer_size_in_M in buffer_size_in_mbs:
print("\n\n=== NEW EXPERIMENT: buffer_size={}M, {} epochs, world_size={} ===".format(
buffer_size_in_M, epochs, world_size))
options = [
DDPOption.DDP_CPP_CORE,
DDPOption.PYTHON_DDP_ASYNC_REDUCTION,
DDPOption.PYTHON_DDP_SYNC_REDUCTION
]
for option in options:
print("Measuring option: {} ... ".format(option))
mp.spawn(run_ddp,
args=(world_size, epochs, option, buffer_size_in_M),
nprocs=world_size,
join=True)
print("\n Generating summaries ... ")
buffer_size_to_metrics = load_detailed_metrics(data_dir="./tmp", ext="ddpraw")
print_summary(buffer_size_to_metrics)
if __name__ == "__main__" :
main()
| create_ddp_model |
mom.py | import numpy as np
import talib
from typing import Union
def mom(candles: np.ndarray, period=10, sequential=False) -> Union[float, np.ndarray]:
"""
MOM - Momentum
:param candles: np.ndarray
:param period: int - default=10
:param sequential: bool - default=False
:return: float | np.ndarray
"""
if not sequential and len(candles) > 240:
candles = candles[-240:]
res = talib.MOM(candles[:, 2], timeperiod=period)
if sequential:
|
else:
return None if np.isnan(res[-1]) else res[-1]
| return res |
test23.js | var callbackArguments = [];
var argument1 = function callback(){callbackArguments.push(arguments)};
var argument2 = true;
var argument3 = function callback(){callbackArguments.push(arguments)};
var argument4 = function callback(){callbackArguments.push(arguments)};
var argument5 = 783;
var argument6 = 7.848226062977162e+307; | var r_0= undefined
try {
r_0 = base_0.reduce(argument1,argument2)
}
catch(e) {
r_0= "Error"
}
var base_1 = [126,1.7976931348623157e+308,607,607]
var r_1= undefined
try {
r_1 = base_1.reduce(argument3)
}
catch(e) {
r_1= "Error"
}
var base_2 = [126,1.7976931348623157e+308,607,607]
var r_2= undefined
try {
r_2 = base_2.reduce(argument4,argument5,argument6)
}
catch(e) {
r_2= "Error"
}
var base_3 = [126,1.7976931348623157e+308,607,607]
var r_3= undefined
try {
r_3 = base_3.reduce(argument7,argument8,argument9)
}
catch(e) {
r_3= "Error"
}
function serialize(array){
return array.map(function(a){
if (a === null || a == undefined) return a;
var name = a.constructor.name;
if (name==='Object' || name=='Boolean'|| name=='Array'||name=='Number'||name=='String')
return JSON.stringify(a);
return name;
});
}
setTimeout(function(){
require("fs").writeFileSync("./experiments/reduce/reduceEmpty/test23.json",JSON.stringify({"baseObjects":serialize([base_0,base_1,base_2,base_3]),"returnObjects":serialize([r_0,r_1,r_2,r_3]),"callbackArgs":callbackArguments}))
},300) | var argument7 = function callback(){callbackArguments.push(arguments)};
var argument8 = r_0;
var argument9 = r_2;
var base_0 = [126,1.7976931348623157e+308,607,607] |
save_load.py | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 __future__ import division
from __future__ import print_function
import errno
import os
import pickle
import six
import paddle
__all__ = ['init_model', 'save_model', 'load_dygraph_pretrain']
def _mkdir_if_not_exist(path, logger):
"""
mkdir if not exists, ignore the exception when multiprocess mkdir together
"""
if not os.path.exists(path):
try:
os.makedirs(path)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(path):
logger.warning(
'be happy if some process has already created {}'.format(
path))
else:
raise OSError('Failed to mkdir {}'.format(path))
def load_dygraph_pretrain(model, logger, path=None, load_static_weights=False):
if not (os.path.isdir(path) or os.path.exists(path + '.pdparams')):
raise ValueError("Model pretrain path {} does not "
"exists.".format(path))
if load_static_weights:
pre_state_dict = paddle.static.load_program_state(path)
param_state_dict = {}
model_dict = model.state_dict()
for key in model_dict.keys():
weight_name = model_dict[key].name
weight_name = weight_name.replace('binarize', '').replace(
'thresh', '') # for DB
if weight_name in pre_state_dict.keys():
# logger.info('Load weight: {}, shape: {}'.format(
# weight_name, pre_state_dict[weight_name].shape))
if 'encoder_rnn' in key:
# delete axis which is 1
pre_state_dict[weight_name] = pre_state_dict[
weight_name].squeeze()
# change axis
if len(pre_state_dict[weight_name].shape) > 1:
pre_state_dict[weight_name] = pre_state_dict[
weight_name].transpose((1, 0))
param_state_dict[key] = pre_state_dict[weight_name]
else:
param_state_dict[key] = model_dict[key]
model.set_state_dict(param_state_dict)
return
param_state_dict = paddle.load(path + '.pdparams')
model.set_state_dict(param_state_dict)
return
def init_model(config, model, logger, optimizer=None, lr_scheduler=None):
"""
load model from checkpoint or pretrained_model
"""
gloabl_config = config['Global']
checkpoints = gloabl_config.get('checkpoints')
pretrained_model = gloabl_config.get('pretrained_model')
best_model_dict = {}
if checkpoints:
assert os.path.exists(checkpoints + ".pdparams"), \
"Given dir {}.pdparams not exist.".format(checkpoints)
assert os.path.exists(checkpoints + ".pdopt"), \
"Given dir {}.pdopt not exist.".format(checkpoints)
para_dict = paddle.load(checkpoints + '.pdparams')
opti_dict = paddle.load(checkpoints + '.pdopt')
model.set_state_dict(para_dict)
if optimizer is not None:
optimizer.set_state_dict(opti_dict)
if os.path.exists(checkpoints + '.states'):
with open(checkpoints + '.states', 'rb') as f:
states_dict = pickle.load(f) if six.PY2 else pickle.load(
f, encoding='latin1')
best_model_dict = states_dict.get('best_model_dict', {})
if 'epoch' in states_dict:
best_model_dict['start_epoch'] = states_dict['epoch'] + 1
logger.info("resume from {}".format(checkpoints))
elif pretrained_model:
load_static_weights = gloabl_config.get('load_static_weights', False)
if not isinstance(pretrained_model, list):
pretrained_model = [pretrained_model]
if not isinstance(load_static_weights, list):
load_static_weights = [load_static_weights] * len(pretrained_model)
for idx, pretrained in enumerate(pretrained_model):
load_static = load_static_weights[idx]
load_dygraph_pretrain(
model, logger, path=pretrained, load_static_weights=load_static)
logger.info("load pretrained model from {}".format(
pretrained_model))
else:
logger.info('train from scratch')
return best_model_dict
def save_model(net,
optimizer,
model_path,
logger,
is_best=False,
prefix='ppocr',
**kwargs):
| """
save model to the target path
"""
_mkdir_if_not_exist(model_path, logger)
model_prefix = os.path.join(model_path, prefix)
paddle.save(net.state_dict(), model_prefix + '.pdparams')
paddle.save(optimizer.state_dict(), model_prefix + '.pdopt')
# save metric and config
with open(model_prefix + '.states', 'wb') as f:
pickle.dump(kwargs, f, protocol=2)
if is_best:
logger.info('save best model is to {}'.format(model_prefix))
else:
logger.info("save model in {}".format(model_prefix)) |
|
token.go | // Copyright 2018 Drone.IO 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 token
import (
"time"
"github.com/go-dronex/dronex/remote"
"github.com/go-dronex/dronex/router/middleware/session"
"github.com/go-dronex/dronex/store"
log "github.com/Sirupsen/logrus"
"github.com/gin-gonic/gin"
)
func Refresh(c *gin.Context) | {
user := session.User(c)
if user == nil {
c.Next()
return
}
// check if the remote includes the ability to
// refresh the user token.
remote_ := remote.FromContext(c)
refresher, ok := remote_.(remote.Refresher)
if !ok {
c.Next()
return
}
// check to see if the user token is expired or
// will expire within the next 30 minutes (1800 seconds).
// If not, there is nothing we really need to do here.
if time.Now().UTC().Unix() < (user.Expiry - 1800) {
c.Next()
return
}
// attempts to refresh the access token. If the
// token is refreshed, we must also persist to the
// database.
ok, _ = refresher.Refresh(user)
if ok {
err := store.UpdateUser(c, user)
if err != nil {
// we only log the error at this time. not sure
// if we really want to fail the request, do we?
log.Errorf("cannot refresh access token for %s. %s", user.Login, err)
} else {
log.Infof("refreshed access token for %s", user.Login)
}
}
c.Next()
} |
|
call_hierarchy.rs | //! Entry point for call-hierarchy
use indexmap::IndexMap;
use hir::Semantics;
use ide_db::{call_info::FnCallNode, RootDatabase};
use syntax::{ast, AstNode, TextRange};
use crate::{
display::TryToNav, goto_definition, references, FilePosition, NavigationTarget, RangeInfo,
};
#[derive(Debug, Clone)]
pub struct CallItem {
pub target: NavigationTarget,
pub ranges: Vec<TextRange>,
}
impl CallItem {
#[cfg(test)]
pub(crate) fn assert_match(&self, expected: &str) {
let actual = self.debug_render();
test_utils::assert_eq_text!(expected.trim(), actual.trim(),);
}
#[cfg(test)]
pub(crate) fn debug_render(&self) -> String {
format!("{} : {:?}", self.target.debug_render(), self.ranges)
}
}
pub(crate) fn | (
db: &RootDatabase,
position: FilePosition,
) -> Option<RangeInfo<Vec<NavigationTarget>>> {
goto_definition::goto_definition(db, position)
}
pub(crate) fn incoming_calls(db: &RootDatabase, position: FilePosition) -> Option<Vec<CallItem>> {
let sema = Semantics::new(db);
// 1. Find all refs
// 2. Loop through refs and determine unique fndef. This will become our `from: CallHierarchyItem,` in the reply.
// 3. Add ranges relative to the start of the fndef.
let refs = references::find_all_refs(&sema, position, None)?;
let mut calls = CallLocations::default();
for (file_id, references) in refs.references {
let file = sema.parse(file_id);
let file = file.syntax();
for (relative_range, token) in references
.into_iter()
.filter_map(|(range, _)| Some(range).zip(file.token_at_offset(range.start()).next()))
{
let token = sema.descend_into_macros(token);
// This target is the containing function
if let Some(nav) = token.ancestors().find_map(|node| {
let def = ast::Fn::cast(node).and_then(|fn_| sema.to_def(&fn_))?;
def.try_to_nav(sema.db)
}) {
calls.add(&nav, relative_range);
}
}
}
Some(calls.into_items())
}
pub(crate) fn outgoing_calls(db: &RootDatabase, position: FilePosition) -> Option<Vec<CallItem>> {
let sema = Semantics::new(db);
let file_id = position.file_id;
let file = sema.parse(file_id);
let file = file.syntax();
let token = file.token_at_offset(position.offset).next()?;
let token = sema.descend_into_macros(token);
let mut calls = CallLocations::default();
token
.parent()
.into_iter()
.flat_map(|it| it.descendants())
.filter_map(|node| FnCallNode::with_node_exact(&node))
.filter_map(|call_node| {
let name_ref = call_node.name_ref()?;
let func_target = match call_node {
FnCallNode::CallExpr(expr) => {
let callable = sema.type_of_expr(&expr.expr()?)?.original.as_callable(db)?;
match callable.kind() {
hir::CallableKind::Function(it) => it.try_to_nav(db),
_ => None,
}
}
FnCallNode::MethodCallExpr(expr) => {
let function = sema.resolve_method_call(&expr)?;
function.try_to_nav(db)
}
}?;
Some((func_target, name_ref.syntax().text_range()))
})
.for_each(|(nav, range)| calls.add(&nav, range));
Some(calls.into_items())
}
#[derive(Default)]
struct CallLocations {
funcs: IndexMap<NavigationTarget, Vec<TextRange>>,
}
impl CallLocations {
fn add(&mut self, target: &NavigationTarget, range: TextRange) {
self.funcs.entry(target.clone()).or_default().push(range);
}
fn into_items(self) -> Vec<CallItem> {
self.funcs.into_iter().map(|(target, ranges)| CallItem { target, ranges }).collect()
}
}
#[cfg(test)]
mod tests {
use ide_db::base_db::FilePosition;
use crate::fixture;
fn check_hierarchy(
ra_fixture: &str,
expected: &str,
expected_incoming: &[&str],
expected_outgoing: &[&str],
) {
let (analysis, pos) = fixture::position(ra_fixture);
let mut navs = analysis.call_hierarchy(pos).unwrap().unwrap().info;
assert_eq!(navs.len(), 1);
let nav = navs.pop().unwrap();
nav.assert_match(expected);
let item_pos =
FilePosition { file_id: nav.file_id, offset: nav.focus_or_full_range().start() };
let incoming_calls = analysis.incoming_calls(item_pos).unwrap().unwrap();
assert_eq!(incoming_calls.len(), expected_incoming.len());
for call in 0..incoming_calls.len() {
incoming_calls[call].assert_match(expected_incoming[call]);
}
let outgoing_calls = analysis.outgoing_calls(item_pos).unwrap().unwrap();
assert_eq!(outgoing_calls.len(), expected_outgoing.len());
for call in 0..outgoing_calls.len() {
outgoing_calls[call].assert_match(expected_outgoing[call]);
}
}
#[test]
fn test_call_hierarchy_on_ref() {
check_hierarchy(
r#"
//- /lib.rs
fn callee() {}
fn caller() {
call$0ee();
}
"#,
"callee Function FileId(0) 0..14 3..9",
&["caller Function FileId(0) 15..44 18..24 : [33..39]"],
&[],
);
}
#[test]
fn test_call_hierarchy_on_def() {
check_hierarchy(
r#"
//- /lib.rs
fn call$0ee() {}
fn caller() {
callee();
}
"#,
"callee Function FileId(0) 0..14 3..9",
&["caller Function FileId(0) 15..44 18..24 : [33..39]"],
&[],
);
}
#[test]
fn test_call_hierarchy_in_same_fn() {
check_hierarchy(
r#"
//- /lib.rs
fn callee() {}
fn caller() {
call$0ee();
callee();
}
"#,
"callee Function FileId(0) 0..14 3..9",
&["caller Function FileId(0) 15..58 18..24 : [33..39, 47..53]"],
&[],
);
}
#[test]
fn test_call_hierarchy_in_different_fn() {
check_hierarchy(
r#"
//- /lib.rs
fn callee() {}
fn caller1() {
call$0ee();
}
fn caller2() {
callee();
}
"#,
"callee Function FileId(0) 0..14 3..9",
&[
"caller1 Function FileId(0) 15..45 18..25 : [34..40]",
"caller2 Function FileId(0) 47..77 50..57 : [66..72]",
],
&[],
);
}
#[test]
fn test_call_hierarchy_in_tests_mod() {
check_hierarchy(
r#"
//- /lib.rs cfg:test
fn callee() {}
fn caller1() {
call$0ee();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_caller() {
callee();
}
}
"#,
"callee Function FileId(0) 0..14 3..9",
&[
"caller1 Function FileId(0) 15..45 18..25 : [34..40]",
"test_caller Function FileId(0) 95..149 110..121 : [134..140]",
],
&[],
);
}
#[test]
fn test_call_hierarchy_in_different_files() {
check_hierarchy(
r#"
//- /lib.rs
mod foo;
use foo::callee;
fn caller() {
call$0ee();
}
//- /foo/mod.rs
pub fn callee() {}
"#,
"callee Function FileId(1) 0..18 7..13",
&["caller Function FileId(0) 27..56 30..36 : [45..51]"],
&[],
);
}
#[test]
fn test_call_hierarchy_outgoing() {
check_hierarchy(
r#"
//- /lib.rs
fn callee() {}
fn call$0er() {
callee();
callee();
}
"#,
"caller Function FileId(0) 15..58 18..24",
&[],
&["callee Function FileId(0) 0..14 3..9 : [33..39, 47..53]"],
);
}
#[test]
fn test_call_hierarchy_outgoing_in_different_files() {
check_hierarchy(
r#"
//- /lib.rs
mod foo;
use foo::callee;
fn call$0er() {
callee();
}
//- /foo/mod.rs
pub fn callee() {}
"#,
"caller Function FileId(0) 27..56 30..36",
&[],
&["callee Function FileId(1) 0..18 7..13 : [45..51]"],
);
}
#[test]
fn test_call_hierarchy_incoming_outgoing() {
check_hierarchy(
r#"
//- /lib.rs
fn caller1() {
call$0er2();
}
fn caller2() {
caller3();
}
fn caller3() {
}
"#,
"caller2 Function FileId(0) 33..64 36..43",
&["caller1 Function FileId(0) 0..31 3..10 : [19..26]"],
&["caller3 Function FileId(0) 66..83 69..76 : [52..59]"],
);
}
#[test]
fn test_call_hierarchy_issue_5103() {
check_hierarchy(
r#"
fn a() {
b()
}
fn b() {}
fn main() {
a$0()
}
"#,
"a Function FileId(0) 0..18 3..4",
&["main Function FileId(0) 31..52 34..38 : [47..48]"],
&["b Function FileId(0) 20..29 23..24 : [13..14]"],
);
check_hierarchy(
r#"
fn a() {
b$0()
}
fn b() {}
fn main() {
a()
}
"#,
"b Function FileId(0) 20..29 23..24",
&["a Function FileId(0) 0..18 3..4 : [13..14]"],
&[],
);
}
}
| call_hierarchy |
widgets.py | # coding=utf-8
# Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from itertools import chain
from flask import url_for
from markupsafe import escape, Markup
import wtforms.ext.sqlalchemy.fields
import wtforms.fields
from wtforms.widgets.core import html_params, HTMLString
from web.templates import page_resources
from functools import reduce
class WidgetDecorator(object):
"""Decorate widgets."""
def __init__(self, widget):
"""
:param widget: Original widget to be decorated.
"""
if widget is None:
raise ValueError('Parameter widget may not be None.')
self.widget = widget
class BootstrapFormGroupDecorator(WidgetDecorator):
"""
Wraps a widget inside a Bootstrap form-group and prints errors.
The widget's output is wrapped in a Bootstrap form-group. Any field errors
are displayed in Bootstrap help-blocks after the widget.
"""
def __call__(self, field, **kwargs):
classes = [u'form-group']
if field.errors:
classes.append(u'has-error')
return HTMLString(u''.join([
Markup(u'<div class="{0}">').format(u' '.join(classes)),
self.widget(field, **kwargs),
u'</div>']))
class BootstrapFormControlDecorator(WidgetDecorator):
"""Adds the Bootstrap form-control class to a widget."""
def __call__(self, field, **kwargs):
if 'class_' in kwargs:
kwargs['class_'] = u'form-control ' + kwargs['class_']
else:
kwargs['class_'] = u'form-control'
return self.widget(field, **kwargs)
class BootstrapStandardDecorator(WidgetDecorator):
"""
Renders a field in horizontal layout.
Horizontal layout is a two column layout, where the label is placed in the
left column and the field is placed right next to it.
"""
def render_horizontal(self, field, **kwargs):
|
def render_inline(self, field, **kwargs):
return HTMLString(u''.join([
field.label(class_=u'sr-only'),
self.widget(field, placeholder=field.label.text, **kwargs),
]))
def render_basic(self, field, **kwargs):
html = [field.label(),
self.widget(field, **kwargs)]
help_block = Markup(u'<span class="help-block">{0}</span>')
if field.description:
html.append(help_block.format(field.description))
html.extend(help_block.format(e) for e in field.errors)
return HTMLString(u''.join(html))
def __call__(self, field, **kwargs):
render_mode = kwargs.pop("render_mode", "basic")
if render_mode == "basic":
return self.render_basic(field, **kwargs)
elif render_mode == "horizontal":
return self.render_horizontal(field, **kwargs)
elif render_mode == "inline":
return self.render_inline(field, **kwargs)
else:
raise ValueError("Unknown render mode: {0}".format(render_mode))
class BootstrapRadioCheckboxDecorator(WidgetDecorator):
"""
Renders a field in horizontal layout.
Horizontal layout is a two column layout, where the label is placed in the
left column and the field is placed right next to it.
"""
wrapper_class = None
def _render(self, field, **kwargs):
return HTMLString(u''.join([
u'<div class="',
self.wrapper_class,
u'">',
field.label(
u"{0} {1}".format(
self.widget(field, **kwargs),
escape(field.label.text)
)),
u'</div>',
]))
def render_basic(self, field, **kwargs):
return self._render(field, **kwargs)
def render_horizontal(self, field, **kwargs):
return HTMLString(u''.join([
u'<div class="col-sm-offset-5 col-sm-7">',
self._render(field, **kwargs),
u'</div>',
]))
def render_inline(self, field, **kwargs):
return field.label(u"{0} {1}".format(
self.widget(field, **kwargs),
escape(field.label.text)
), class_=self.wrapper_class + "-inline")
def __call__(self, field, **kwargs):
render_mode = kwargs.pop("render_mode", "horizontal")
if render_mode == "basic":
return self.render_basic(field, **kwargs)
elif render_mode == "horizontal":
return self.render_horizontal(field, **kwargs)
elif render_mode == "inline":
return self.render_inline(field, **kwargs)
else:
raise ValueError("Unknown render mode: {0}".format(render_mode))
class BootstrapRadioDecorator(BootstrapRadioCheckboxDecorator):
wrapper_class = u"radio"
class BootstrapCheckboxDecorator(BootstrapRadioCheckboxDecorator):
wrapper_class = u"checkbox"
class BootstrapFieldListWidget(object):
def __call__(self, field, **kwargs):
return HTMLString(u''.join(chain(
(Markup(u'<p class="help-block">{0}</p>').format(e) for e in field.errors),
(f(**kwargs) for f in field)
)))
class BootstrapFormFieldWidget(object):
def __call__(self, field, **kwargs):
return HTMLString(u"<div class=\"form-field\">" +
u''.join(f(**kwargs) for f in field) +
u"</div>")
class BootstrapStaticFieldWidget(object):
"""Render a static Bootstrap control."""
def __call__(self, field, **kwargs):
kwargs["class_"] = u"form-control-static"
# Assume that the field provides access to its value.
value = field._value()
return HTMLString(u''.join([
u'<p {}>'.format(html_params(**kwargs)),
value,
u'</p>',
]))
def decorators(widget):
"""
Yields all decorators of a widget starting from the outermost.
"""
while isinstance(widget, WidgetDecorator):
yield type(widget)
widget = widget.widget
def decorate(widget, *decorators):
"""
Decorate a widget with a list of decorators.
:param widget: a widget
:param tuple[WidgetDecorator] decorators: some decorators
:rtype: WidgetDecorator
:returns: decorated widget
"""
return reduce(lambda w, d: d(w), decorators, widget)
def decorate_field(field, *decorators):
"""
Return a field's widget decorated with the given decorators..
:param wtforms.fields.core.Field field: a WTForms field
:param tuple[WidgetDecorator] decorators: some decorators
:rtype: WidgetDecorator
:returns: decorated widget
"""
return decorate(field.widget, *decorators)
from markupsafe import Markup
class BootstrapDatepickerWidget(object):
"""Renders datetime fields using bootstrap-datepicker."""
def __call__(self, field, **kwargs):
kwargs["data-provide"] = u"datepicker"
for (option, value) in field.datepicker_options.items():
attribute = 'data-date-{0}'.format(option.replace('_', '-'))
kwargs[attribute] = value
page_resources.link_script(url_for(
"static", filename="libs/bootstrap-datepicker/js/bootstrap-datepicker.js"
))
page_resources.link_script(url_for(
"static", filename="libs/bootstrap-datepicker/js/locales/bootstrap-datepicker.de.js"
))
options = dict(kwargs, name=field.name)
if field.data:
options["value"] = field.data
return HTMLString(u"<input {0}>".format(html_params(**options)))
class CheckBoxWidget(wtforms.widgets.Select):
"""A simple multi selection widget rendered as Checkbox list.
It uses the bootstrap markup.
"""
def __call__(self, field, **kwargs):
kwargs.setdefault('type', 'checkbox')
field_id = kwargs.pop('id', field.id)
html = []
for value, label, checked in field.iter_choices():
choice_id = u'{}-{}'.format(field_id, value)
options = dict(kwargs, name=field.name, value=value, id=choice_id)
html.append(u'<label class="checkbox" {}>'.format(html_params(id=field_id)))
if checked:
options['checked'] = 'checked'
html.append(u'<input {}>'.format(html_params(**options)))
html.append(label)
html.append(u'</label>')
return u''.join(html)
class LazyLoadSelectWidget(wtforms.widgets.Select):
"""This is the widget for the LazyLoadSelectField
Please look at web.form.fields.LazyLoadSelectField for more information.
"""
def __call__(self, field, **kwargs):
conditions = getattr(field, "conditions", None)
if conditions is not None:
kwargs["data-fieldids"] = ",".join(conditions)
kwargs['data-role'] = u'lazyloadselect'
kwargs['data-url'] = url_for(field.data_endpoint)
kwargs['value'] = str(field.data)
return super(LazyLoadSelectWidget, self).__call__(field, **kwargs)
class Disabler(WidgetDecorator):
def __call__(self, field, **kwargs):
kwargs['disabled'] = True
return self.widget(field, **kwargs)
class MoneyFieldDecorator(WidgetDecorator):
"""Adds the Bootstrap form-control class to a widget."""
def __call__(self, field, **kwargs):
kwargs['class_'] += ' money-amount'
return (u"<div class=\"input-group\">" + self.widget(field, **kwargs) +
u"<span class=\"input-group-addon\">€</span></div>")
| html = [u'<div class="col-sm-5">',
field.label(class_=u'control-label'),
u'</div>',
u'<div class="col-sm-7">',
self.widget(field, **kwargs),
u'</div>']
help_block = Markup(u'<div class="col-sm-12">'
u'<span class="help-block">{0}</span>'
u'</div>')
if field.description:
html.append(help_block.format(field.description))
html.extend(help_block.format(e) for e in field.errors)
return HTMLString(u''.join(html)) |
login.tsx | /** @format */
import React from 'react'
import {Form, Input, Button, Checkbox, message} from 'antd'
import {UserOutlined, LockOutlined} from '@ant-design/icons'
import axios from 'axios'
import servicePath from '../config/apiUrl'
const Login = () => {
const key = 'updatable'
const onFinish = (values: any) => {
let dataProps = {
username: null,
password: null,
}
dataProps.username = values.username
dataProps.password = values.password
message.loading({ content: '登录中...', key })
axios({
method: 'post',
url: servicePath.login,
data: dataProps,
withCredentials: true,
}).then(res => {
if(res.data.isSuccess){
message.success({ content: '登录成功!', key})
}else {
message.error({ content: '用户名或密码错误', key})
}
})
}
return (
<div className="login">
<div className="login-bg"></div>
<div className="login-form">
<Form
layout="vertical"
name="normal_login"
className="login-form"
initialValues={{remember: true}}
onFinish={onFinish}
// onValuesChange={onValuesChange}
>
<Form.Item
label="用户名"
name="username"
rules={[{required: true, message: '请输入您的用户名!'}]}>
<Input prefix={<UserOutlined className="site-form-item-icon" />} />
</Form.Item>
<Form.Item
label="登录密码"
name="password"
rules={[{required: true, message: '请输入您的密码!'}]}>
<Input prefix={<LockOutlined className="site-form-item-icon" />} type="password" />
</Form.Item>
<Form.Item>
<Form.Item name="remember" valuePropName="checked" noStyle>
<Checkbox>记住密码</Checkbox>
</Form.Item>
<a className="login-form-forgot" href="">
忘记密码?
</a>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" className="login-form-button">
登录
</Button>
或 <a href="/register">注册</a>
</Form.Item>
</Form>
</div>
<style jsx>{`
.login-bg {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
overflow: hidden;
background-image: url('/static/img/bg-wall2.jpg');
background-size: cover;
background-position: center center;
}
.login-form {
position: absolute;
top: 50%;
left: 50%;
width: 350px;
margin-left: -175px; | background-color: #fff;
padding: 30px;
border-radius: 8px;
}
#components-form-demo-normal-login .login-form {
max-width: 300px;
}
#components-form-demo-normal-login .login-form-forgot {
float: right;
}
#components-form-demo-normal-login .ant-col-rtl .login-form-forgot {
float: left;
}
#components-form-demo-normal-login .login-form-button {
width: 100%;
}
`}</style>
</div>
)
}
export default Login | margin-top: -235px; |
simple-tuple.rs | // min-lldb-version: 310
// ignore-gdb // Test temporarily ignored due to debuginfo tests being disabled, see PR 47155
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdbg-command:print/d 'simple_tuple::NO_PADDING_8'
// gdbr-command:print simple_tuple::NO_PADDING_8
// gdbg-check:$1 = {__0 = -50, __1 = 50}
// gdbr-check:$1 = (-50, 50)
// gdbg-command:print 'simple_tuple::NO_PADDING_16'
// gdbr-command:print simple_tuple::NO_PADDING_16
// gdbg-check:$2 = {__0 = -1, __1 = 2, __2 = 3}
// gdbr-check:$2 = (-1, 2, 3)
// gdbg-command:print 'simple_tuple::NO_PADDING_32'
// gdbr-command:print simple_tuple::NO_PADDING_32
// gdbg-check:$3 = {__0 = 4, __1 = 5, __2 = 6}
// gdbr-check:$3 = (4, 5, 6)
// gdbg-command:print 'simple_tuple::NO_PADDING_64'
// gdbr-command:print simple_tuple::NO_PADDING_64
// gdbg-check:$4 = {__0 = 7, __1 = 8, __2 = 9}
// gdbr-check:$4 = (7, 8, 9)
// gdbg-command:print 'simple_tuple::INTERNAL_PADDING_1'
// gdbr-command:print simple_tuple::INTERNAL_PADDING_1
// gdbg-check:$5 = {__0 = 10, __1 = 11}
// gdbr-check:$5 = (10, 11)
// gdbg-command:print 'simple_tuple::INTERNAL_PADDING_2'
// gdbr-command:print simple_tuple::INTERNAL_PADDING_2
// gdbg-check:$6 = {__0 = 12, __1 = 13, __2 = 14, __3 = 15}
// gdbr-check:$6 = (12, 13, 14, 15)
// gdbg-command:print 'simple_tuple::PADDING_AT_END'
// gdbr-command:print simple_tuple::PADDING_AT_END
// gdbg-check:$7 = {__0 = 16, __1 = 17}
// gdbr-check:$7 = (16, 17)
// gdb-command:run
// gdbg-command:print/d noPadding8
// gdbr-command:print noPadding8
// gdbg-check:$8 = {__0 = -100, __1 = 100}
// gdbr-check:$8 = (-100, 100)
// gdb-command:print noPadding16
// gdbg-check:$9 = {__0 = 0, __1 = 1, __2 = 2} | // gdb-command:print noPadding32
// gdbg-check:$10 = {__0 = 3, __1 = 4.5, __2 = 5}
// gdbr-check:$10 = (3, 4.5, 5)
// gdb-command:print noPadding64
// gdbg-check:$11 = {__0 = 6, __1 = 7.5, __2 = 8}
// gdbr-check:$11 = (6, 7.5, 8)
// gdb-command:print internalPadding1
// gdbg-check:$12 = {__0 = 9, __1 = 10}
// gdbr-check:$12 = (9, 10)
// gdb-command:print internalPadding2
// gdbg-check:$13 = {__0 = 11, __1 = 12, __2 = 13, __3 = 14}
// gdbr-check:$13 = (11, 12, 13, 14)
// gdb-command:print paddingAtEnd
// gdbg-check:$14 = {__0 = 15, __1 = 16}
// gdbr-check:$14 = (15, 16)
// gdbg-command:print/d 'simple_tuple::NO_PADDING_8'
// gdbr-command:print simple_tuple::NO_PADDING_8
// gdbg-check:$15 = {__0 = -127, __1 = 127}
// gdbr-check:$15 = (-127, 127)
// gdbg-command:print 'simple_tuple::NO_PADDING_16'
// gdbr-command:print simple_tuple::NO_PADDING_16
// gdbg-check:$16 = {__0 = -10, __1 = 10, __2 = 9}
// gdbr-check:$16 = (-10, 10, 9)
// gdbg-command:print 'simple_tuple::NO_PADDING_32'
// gdbr-command:print simple_tuple::NO_PADDING_32
// gdbg-check:$17 = {__0 = 14, __1 = 15, __2 = 16}
// gdbr-check:$17 = (14, 15, 16)
// gdbg-command:print 'simple_tuple::NO_PADDING_64'
// gdbr-command:print simple_tuple::NO_PADDING_64
// gdbg-check:$18 = {__0 = 17, __1 = 18, __2 = 19}
// gdbr-check:$18 = (17, 18, 19)
// gdbg-command:print 'simple_tuple::INTERNAL_PADDING_1'
// gdbr-command:print simple_tuple::INTERNAL_PADDING_1
// gdbg-check:$19 = {__0 = 110, __1 = 111}
// gdbr-check:$19 = (110, 111)
// gdbg-command:print 'simple_tuple::INTERNAL_PADDING_2'
// gdbr-command:print simple_tuple::INTERNAL_PADDING_2
// gdbg-check:$20 = {__0 = 112, __1 = 113, __2 = 114, __3 = 115}
// gdbr-check:$20 = (112, 113, 114, 115)
// gdbg-command:print 'simple_tuple::PADDING_AT_END'
// gdbr-command:print simple_tuple::PADDING_AT_END
// gdbg-check:$21 = {__0 = 116, __1 = 117}
// gdbr-check:$21 = (116, 117)
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print/d noPadding8
// lldbg-check:[...]$0 = (-100, 100)
// lldbr-check:((i8, u8)) noPadding8 = { = -100 -100 = 100 100 }
// lldb-command:print noPadding16
// lldbg-check:[...]$1 = (0, 1, 2)
// lldbr-check:((i16, i16, u16)) noPadding16 = { = 0 = 1 = 2 }
// lldb-command:print noPadding32
// lldbg-check:[...]$2 = (3, 4.5, 5)
// lldbr-check:((i32, f32, u32)) noPadding32 = { = 3 = 4.5 = 5 }
// lldb-command:print noPadding64
// lldbg-check:[...]$3 = (6, 7.5, 8)
// lldbr-check:((i64, f64, u64)) noPadding64 = { = 6 = 7.5 = 8 }
// lldb-command:print internalPadding1
// lldbg-check:[...]$4 = (9, 10)
// lldbr-check:((i16, i32)) internalPadding1 = { = 9 = 10 }
// lldb-command:print internalPadding2
// lldbg-check:[...]$5 = (11, 12, 13, 14)
// lldbr-check:((i16, i32, u32, u64)) internalPadding2 = { = 11 = 12 = 13 = 14 }
// lldb-command:print paddingAtEnd
// lldbg-check:[...]$6 = (15, 16)
// lldbr-check:((i32, i16)) paddingAtEnd = { = 15 = 16 }
#![allow(unused_variables)]
#![allow(dead_code)]
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
static mut NO_PADDING_8: (i8, u8) = (-50, 50);
static mut NO_PADDING_16: (i16, i16, u16) = (-1, 2, 3);
static mut NO_PADDING_32: (i32, f32, u32) = (4, 5.0, 6);
static mut NO_PADDING_64: (i64, f64, u64) = (7, 8.0, 9);
static mut INTERNAL_PADDING_1: (i16, i32) = (10, 11);
static mut INTERNAL_PADDING_2: (i16, i32, u32, u64) = (12, 13, 14, 15);
static mut PADDING_AT_END: (i32, i16) = (16, 17);
fn main() {
let noPadding8: (i8, u8) = (-100, 100);
let noPadding16: (i16, i16, u16) = (0, 1, 2);
let noPadding32: (i32, f32, u32) = (3, 4.5, 5);
let noPadding64: (i64, f64, u64) = (6, 7.5, 8);
let internalPadding1: (i16, i32) = (9, 10);
let internalPadding2: (i16, i32, u32, u64) = (11, 12, 13, 14);
let paddingAtEnd: (i32, i16) = (15, 16);
unsafe {
NO_PADDING_8 = (-127, 127);
NO_PADDING_16 = (-10, 10, 9);
NO_PADDING_32 = (14, 15.0, 16);
NO_PADDING_64 = (17, 18.0, 19);
INTERNAL_PADDING_1 = (110, 111);
INTERNAL_PADDING_2 = (112, 113, 114, 115);
PADDING_AT_END = (116, 117);
}
zzz(); // #break
}
fn zzz() {()} | // gdbr-check:$9 = (0, 1, 2) |
main.go | package main
import (
"fmt"
"log"
"os"
"golang.org/x/net/html"
)
var depth = 0
func main() {
doc, err := html.Parse(os.Stdin)
if err != nil {
log.Fatal(err)
}
for _, link := range visit(nil, doc) {
fmt.Println(link)
}
outline(nil, doc)
var counts = make(map[string]int)
countElements(counts, doc)
for k, v := range counts {
fmt.Printf("%-10.10s %3d\n", k, v)
}
depth = 0
foreachNode(doc, startElement, endElement)
}
func visit(links []string, n *html.Node) []string {
if n.Type == html.ElementNode && n.Data == "a" |
for c := n.FirstChild; c != nil; c = c.NextSibling {
links = visit(links, c)
}
return links
}
func outline(stack []string, n *html.Node) {
if n.Type == html.ElementNode {
stack = append(stack, n.Data)
fmt.Println(stack)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
outline(stack, c)
}
}
func countElements(counts map[string]int, n *html.Node) {
if n.Type == html.ElementNode {
counts[n.Data]++
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
countElements(counts, c)
}
}
func startElement(n *html.Node) {
if n.Type == html.ElementNode {
fmt.Printf("%*s<%s>\n", depth*2, "", n.Data)
depth++
}
}
func endElement(n *html.Node) {
if n.Type == html.ElementNode {
depth--
fmt.Printf("%*s</%s>\n", depth*2, "", n.Data)
}
}
func foreachNode(n *html.Node, pre, post func(n *html.Node)) {
if pre != nil {
pre(n)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
foreachNode(c, pre, post)
}
if post != nil {
post(n)
}
}
| {
for _, attr := range n.Attr {
if attr.Key == "href" {
links = append(links, attr.Val)
break
}
}
} |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
impl super::IMR {
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
}
#[doc = r" Value of the field"]
pub struct DATRDYR {
bits: bool,
}
impl DATRDYR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool |
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - Data Ready Interrupt Mask"]
#[inline]
pub fn datrdy(&self) -> DATRDYR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
};
DATRDYR { bits }
}
}
| {
self.bits
} |
message.go | package main
import (
"fmt"
"sync"
"time"
"github.com/google/uuid"
)
type Message struct {
ID string `json:"id"`
UserID string `json:"userId"`
User *User `json:"user"`
RoomID string `json:"roomId"`
Message string `json:"message"`
Timestamp int64 `json:"timestamp"`
}
type MessageStore interface {
Count(roomID string) int
Get(roomID string) []Message
GetLastN(roomID string, n int, firstMsgID ...string) []Message
Set(roomID string, messages []Message)
Append(roomID string, message Message)
}
type InMemoryMessageStore struct {
sync.Mutex
messages map[string][]Message
}
var _ MessageStore = (*InMemoryMessageStore)(nil)
func NewInMemoryMessageStore() *InMemoryMessageStore |
func (m *InMemoryMessageStore) Count(roomID string) int {
m.Lock()
l := len(m.messages[roomID])
m.Unlock()
return l
}
func (m *InMemoryMessageStore) Get(roomID string) []Message {
m.Lock()
messages := m.messages[roomID]
m.Unlock()
return messages
}
func (m *InMemoryMessageStore) GetLastN(roomID string, n int, firstMsgID ...string) []Message {
var messages []Message
if len(firstMsgID) > 0 {
i := m.indexOf(roomID, firstMsgID[0])
if i < 0 {
s := len(m.messages[roomID]) - n
if s < 0 {
s = 0
}
m.Lock()
messages = m.messages[roomID][s:]
m.Unlock()
} else {
s := i - n
if s < 0 {
s = 0
}
m.Lock()
messages = m.messages[roomID][s:i]
m.Unlock()
}
} else {
s := len(m.messages[roomID]) - n
if s < 0 {
s = 0
}
m.Lock()
messages = m.messages[roomID][s:]
m.Unlock()
}
return messages
}
func (m *InMemoryMessageStore) Set(roomID string, messages []Message) {
m.Lock()
m.messages[roomID] = messages
m.Unlock()
}
func (m *InMemoryMessageStore) Append(roomID string, message Message) {
m.Lock()
m.messages[roomID] = append(m.messages[roomID], message)
m.Unlock()
}
func (m *InMemoryMessageStore) indexOf(roomID string, msgID string) int {
m.Lock()
for i, msg := range m.messages[roomID] {
if msg.ID == msgID {
m.Unlock()
return i
}
}
m.Unlock()
return -1 //not found.
}
| {
m := &InMemoryMessageStore{
messages: map[string][]Message{},
}
for i := 1; i < 201; i++ {
id, err := uuid.NewRandom()
if err != nil {
continue
}
m.messages["77dac06c-bb59-4854-8b4b-928d078454cc"] = append(m.messages["77dac06c-bb59-4854-8b4b-928d078454cc"],
Message{
ID: id.String(),
UserID: fmt.Sprintf("initial %d", i),
RoomID: "77dac06c-bb59-4854-8b4b-928d078454cc",
Message: fmt.Sprintf("initial %d", i),
Timestamp: time.Now().Unix() * 1000,
})
m.messages["fe09b952-7690-4978-96cf-5a5c8e74ecaf"] = append(m.messages["fe09b952-7690-4978-96cf-5a5c8e74ecaf"],
Message{
ID: id.String(),
UserID: fmt.Sprintf("initial %d", i),
RoomID: "fe09b952-7690-4978-96cf-5a5c8e74ecaf",
Message: fmt.Sprintf("initial %d", i),
Timestamp: time.Now().Unix() * 1000,
})
}
return m
} |
conn.rs | use std::sync::Arc;
use crate::dispatcher::Dispatcher;
use crate::tls;
use rustls::internal::msgs::{
codec::Reader,
message::{Message, OpaqueMessage},
};
use tokio::net::TcpStream;
use crate::matcher::Matcher;
pub async fn | (socket: TcpStream, mymatchlist: Arc<Vec<Matcher>>) {
let mut peekbuf = [0; 1024];
// "peek" into the socket to retrieve TLS
// ClientHello and SNI
let rsz = socket
.peek(&mut peekbuf)
.await
.expect("couldn't peek from socket");
// EOF case
if rsz == 0 {
return;
}
if peekbuf
.windows(4)
.any(move |subslice| subslice == "HTTP".as_bytes())
{
log::debug!("HTTP connection detected, this only supports TLS");
return;
}
// Deserialize the TLS ClientHello
let omsg = OpaqueMessage::read(&mut Reader::init(&peekbuf))
.expect("couldn't read TLS message")
.into_plain_message();
let msg = Message::try_from(omsg).expect("Couldn't decipher message");
// Extract the SNI payload and determine indicated name
let session_sni = tls::extract_sni(&msg.payload).await;
// Core rule-matching; find an appropriate matcher
// or do the no-mapping procedure
if let Some(hn) = session_sni {
let indicated: &str = std::str::from_utf8(&hn.0 .0).unwrap();
log::debug!("indicated: {:?}", indicated);
if let Some(dispatcher) = Dispatcher::from_matching(indicated, mymatchlist) {
dispatcher.do_dispatch(socket).await
} else {
// should be unreachable
panic!("no dispatcher for indicated");
}
} else {
// Didn't get SNI, send to first universal match
log::debug!("no name indicated");
if let Some(dispatcher) = Dispatcher::from_matching("", mymatchlist) {
dispatcher.do_dispatch(socket).await
} else {
log::warn!("no dispatcher for zero-string: elvis left the building");
panic!("zero-string dispatcher missing");
}
}
}
| handle_connection |
org_repos.go | package github
import (
"context"
"io"
"time"
"github.com/augmentable-dev/vtab"
"github.com/shurcooL/githubv4"
"go.riyazali.net/sqlite"
"golang.org/x/time/rate"
)
type fetchOrgReposOptions struct {
Client *githubv4.Client
Login string
PerPage int
OrgReposCursor *githubv4.String
RepositoryOrder *githubv4.RepositoryOrder
}
type fetchOrgReposResults struct {
OrgRepos []*orgRepo
HasNextPage bool
EndCursor *githubv4.String
}
type orgRepo struct {
CreatedAt time.Time
DatabaseId int
DefaultBranchRef struct {
Name string
Prefix string
}
Description string
DiskUsage int
ForkCount int
HomepageUrl string
IsArchived bool
IsDisabled bool
IsFork bool
IsMirror bool
IsPrivate bool
Issues struct {
TotalCount int
}
LatestRelease struct {
Author struct {
Login string
}
CreatedAt githubv4.DateTime
Name string
PublishedAt githubv4.DateTime
}
LicenseInfo struct {
Key string
Name string
Nickname string
}
Name string
OpenGraphImageUrl githubv4.URI
PrimaryLanguage struct {
Name string
}
PullRequests struct {
TotalCount int
}
PushedAt time.Time
Releases struct {
TotalCount int
}
StargazerCount int
UpdatedAt time.Time
Watchers struct {
TotalCount int
}
}
func fetchOrgRepos(ctx context.Context, input *fetchOrgReposOptions) (*fetchOrgReposResults, error) |
type iterOrgRepos struct {
login string
client *githubv4.Client
current int
results *fetchOrgReposResults
rateLimiter *rate.Limiter
repoOrder *githubv4.RepositoryOrder
}
func (i *iterOrgRepos) Column(ctx *sqlite.Context, c int) error {
current := i.results.OrgRepos[i.current]
switch c {
case 0:
ctx.ResultText(i.login)
case 1:
t := current.CreatedAt
if t.IsZero() {
ctx.ResultNull()
} else {
ctx.ResultText(t.Format(time.RFC3339Nano))
}
case 2:
ctx.ResultInt(current.DatabaseId)
case 3:
ctx.ResultText(current.DefaultBranchRef.Name)
case 4:
ctx.ResultText(current.DefaultBranchRef.Prefix)
case 5:
ctx.ResultText(current.Description)
case 6:
ctx.ResultInt(current.DiskUsage)
case 7:
ctx.ResultInt(current.ForkCount)
case 8:
ctx.ResultText(current.HomepageUrl)
case 9:
ctx.ResultInt(t1f0(current.IsArchived))
case 10:
ctx.ResultInt(t1f0(current.IsDisabled))
case 11:
ctx.ResultInt(t1f0(current.IsFork))
case 12:
ctx.ResultInt(t1f0(current.IsMirror))
case 13:
ctx.ResultInt(t1f0(current.IsPrivate))
case 14:
ctx.ResultInt(current.Issues.TotalCount)
case 15:
ctx.ResultText(current.LatestRelease.Author.Login)
case 16:
t := current.LatestRelease.CreatedAt
if t.IsZero() {
ctx.ResultNull()
} else {
ctx.ResultText(t.Format(time.RFC3339Nano))
}
case 17:
ctx.ResultText(current.LatestRelease.Name)
case 18:
t := current.LatestRelease.PublishedAt
if t.IsZero() {
ctx.ResultNull()
} else {
ctx.ResultText(t.Format(time.RFC3339Nano))
}
case 19:
ctx.ResultText(current.LicenseInfo.Key)
case 20:
ctx.ResultText(current.LicenseInfo.Name)
case 21:
ctx.ResultText(current.Name)
case 22:
ctx.ResultText(current.OpenGraphImageUrl.String())
case 23:
ctx.ResultText(current.PrimaryLanguage.Name)
case 24:
ctx.ResultInt(current.PullRequests.TotalCount)
case 25:
t := current.PushedAt
if t.IsZero() {
ctx.ResultNull()
} else {
ctx.ResultText(t.Format(time.RFC3339Nano))
}
case 26:
ctx.ResultInt(current.Releases.TotalCount)
case 27:
ctx.ResultInt(current.StargazerCount)
case 28:
t := current.UpdatedAt
if t.IsZero() {
ctx.ResultNull()
} else {
ctx.ResultText(t.Format(time.RFC3339Nano))
}
case 29:
ctx.ResultInt(current.Watchers.TotalCount)
}
return nil
}
func (i *iterOrgRepos) Next() (vtab.Row, error) {
i.current += 1
if i.results == nil || i.current >= len(i.results.OrgRepos) {
if i.results == nil || i.results.HasNextPage {
err := i.rateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
var cursor *githubv4.String
if i.results != nil {
cursor = i.results.EndCursor
}
results, err := fetchOrgRepos(context.Background(), &fetchOrgReposOptions{i.client, i.login, 100, cursor, i.repoOrder})
if err != nil {
return nil, err
}
i.results = results
i.current = 0
} else {
return nil, io.EOF
}
}
return i, nil
}
var orgReposCols = []vtab.Column{
{Name: "login", Type: sqlite.SQLITE_TEXT, Hidden: true, Filters: []*vtab.ColumnFilter{{Op: sqlite.INDEX_CONSTRAINT_EQ, Required: true, OmitCheck: true}}},
{Name: "created_at", Type: sqlite.SQLITE_TEXT, OrderBy: vtab.ASC | vtab.DESC},
{Name: "database_id", Type: sqlite.SQLITE_INTEGER},
{Name: "default_branch_ref_name", Type: sqlite.SQLITE_TEXT},
{Name: "default_branch_ref_prefix", Type: sqlite.SQLITE_TEXT},
{Name: "description", Type: sqlite.SQLITE_TEXT},
{Name: "disk_usage", Type: sqlite.SQLITE_INTEGER},
{Name: "fork_count", Type: sqlite.SQLITE_INTEGER},
{Name: "homepage_url", Type: sqlite.SQLITE_TEXT},
{Name: "is_archived", Type: sqlite.SQLITE_INTEGER},
{Name: "is_disabled", Type: sqlite.SQLITE_INTEGER},
{Name: "is_fork", Type: sqlite.SQLITE_INTEGER},
{Name: "is_mirror", Type: sqlite.SQLITE_INTEGER},
{Name: "is_private", Type: sqlite.SQLITE_INTEGER},
{Name: "issue_count", Type: sqlite.SQLITE_INTEGER},
{Name: "latest_release_author", Type: sqlite.SQLITE_TEXT},
{Name: "latest_release_created_at", Type: sqlite.SQLITE_TEXT},
{Name: "latest_release_name", Type: sqlite.SQLITE_TEXT},
{Name: "latest_release_published_at", Type: sqlite.SQLITE_TEXT},
{Name: "license_key", Type: sqlite.SQLITE_TEXT},
{Name: "license_name", Type: sqlite.SQLITE_TEXT},
{Name: "name", Type: sqlite.SQLITE_TEXT, OrderBy: vtab.ASC | vtab.DESC},
{Name: "open_graph_image_url", Type: sqlite.SQLITE_TEXT},
{Name: "primary_language", Type: sqlite.SQLITE_TEXT},
{Name: "pull_request_count", Type: sqlite.SQLITE_INTEGER},
{Name: "pushed_at", Type: sqlite.SQLITE_TEXT, OrderBy: vtab.ASC | vtab.DESC},
{Name: "release_count", Type: sqlite.SQLITE_INTEGER},
{Name: "stargazer_count", Type: sqlite.SQLITE_TEXT, OrderBy: vtab.ASC | vtab.DESC},
{Name: "updated_at", Type: sqlite.SQLITE_TEXT, OrderBy: vtab.ASC | vtab.DESC},
{Name: "watcher_count", Type: sqlite.SQLITE_INTEGER},
}
func NewOrgReposModule(opts *Options) sqlite.Module {
return vtab.NewTableFunc("github_org_repos", orgReposCols, func(constraints []*vtab.Constraint, orders []*sqlite.OrderBy) (vtab.Iterator, error) {
var login string
for _, constraint := range constraints {
if constraint.Op == sqlite.INDEX_CONSTRAINT_EQ {
switch constraint.ColIndex {
case 0:
login = constraint.Value.Text()
}
}
}
var repoOrder *githubv4.RepositoryOrder
// for now we can only support single field order bys
if len(orders) == 1 {
repoOrder = &githubv4.RepositoryOrder{}
order := orders[0]
switch order.ColumnIndex {
case 1:
repoOrder.Field = githubv4.RepositoryOrderFieldName
case 3:
repoOrder.Field = githubv4.RepositoryOrderFieldCreatedAt
case 4:
repoOrder.Field = githubv4.RepositoryOrderFieldUpdatedAt
case 5:
repoOrder.Field = githubv4.RepositoryOrderFieldPushedAt
case 6:
repoOrder.Field = githubv4.RepositoryOrderFieldStargazers
}
}
return &iterOrgRepos{login, opts.Client(), -1, nil, opts.RateLimiter, repoOrder}, nil
})
}
| {
var reposQuery struct {
Organization struct {
Login string
Repositories struct {
Nodes []*orgRepo
PageInfo struct {
EndCursor githubv4.String
HasNextPage bool
}
} `graphql:"repositories(first: $perPage, after: $orgReposCursor, orderBy: $repositoryOrder)"`
} `graphql:"organization(login: $login)"`
}
variables := map[string]interface{}{
"login": githubv4.String(input.Login),
"perPage": githubv4.Int(input.PerPage),
"orgReposCursor": (*githubv4.String)(input.OrgReposCursor),
"repositoryOrder": input.RepositoryOrder,
}
err := input.Client.Query(ctx, &reposQuery, variables)
if err != nil {
return nil, err
}
return &fetchOrgReposResults{
reposQuery.Organization.Repositories.Nodes,
reposQuery.Organization.Repositories.PageInfo.HasNextPage,
&reposQuery.Organization.Repositories.PageInfo.EndCursor,
}, nil
} |
athena_io.py | from dagger.pipeline.io import IO
from dagger.utilities.config_validator import Attribute
class | (IO):
ref_name = "athena"
@classmethod
def init_attributes(cls, orig_cls):
cls.add_config_attributes(
[
Attribute(
attribute_name="schema", comment="Leave it empty for system tables"
),
Attribute(attribute_name="table"),
]
)
def __init__(self, io_config, config_location):
super().__init__(io_config, config_location)
self._schema = self.parse_attribute("schema")
self._table = self.parse_attribute("table")
def alias(self):
return "athena://{}/{}".format(self._schema, self._table)
@property
def rendered_name(self):
return "{}.{}".format(self._schema, self._table)
@property
def airflow_name(self):
return "athena-{}-{}".format(self._schema, self._table)
@property
def schema(self):
return self._schema
@property
def table(self):
return self._table
| AthenaIO |
lib.rs | extern crate ash;
extern crate winit;
use ash::extensions::{
ext::DebugUtils,
khr::{Surface, Swapchain},
};
use ash::{vk, Entry};
pub use ash::{Device, Instance};
use std::borrow::Cow;
use std::cell::RefCell;
use std::default::Default;
use std::ffi::CStr;
use std::ops::Drop;
use std::os::raw::c_char;
use winit::{
event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent},
event_loop::{ControlFlow, EventLoop},
platform::run_return::EventLoopExtRunReturn,
window::WindowBuilder,
};
// Simple offset_of macro akin to C++ offsetof
#[macro_export]
macro_rules! offset_of {
($base:path, $field:ident) => {{
#[allow(unused_unsafe)]
unsafe {
let b: $base = mem::zeroed();
(&b.$field as *const _ as isize) - (&b as *const _ as isize)
}
}};
}
/// Helper function for submitting command buffers. Immediately waits for the fence before the command buffer
/// is executed. That way we can delay the waiting for the fences by 1 frame which is good for performance.
/// Make sure to create the fence in a signaled state on the first use.
#[allow(clippy::too_many_arguments)]
pub fn | <F: FnOnce(&Device, vk::CommandBuffer)>(
device: &Device,
command_buffer: vk::CommandBuffer,
command_buffer_reuse_fence: vk::Fence,
submit_queue: vk::Queue,
wait_mask: &[vk::PipelineStageFlags],
wait_semaphores: &[vk::Semaphore],
signal_semaphores: &[vk::Semaphore],
f: F,
) {
unsafe {
device
.wait_for_fences(&[command_buffer_reuse_fence], true, std::u64::MAX)
.expect("Wait for fence failed.");
device
.reset_fences(&[command_buffer_reuse_fence])
.expect("Reset fences failed.");
device
.reset_command_buffer(
command_buffer,
vk::CommandBufferResetFlags::RELEASE_RESOURCES,
)
.expect("Reset command buffer failed.");
let command_buffer_begin_info = vk::CommandBufferBeginInfo::builder()
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
device
.begin_command_buffer(command_buffer, &command_buffer_begin_info)
.expect("Begin commandbuffer");
f(device, command_buffer);
device
.end_command_buffer(command_buffer)
.expect("End commandbuffer");
let command_buffers = vec![command_buffer];
let submit_info = vk::SubmitInfo::builder()
.wait_semaphores(wait_semaphores)
.wait_dst_stage_mask(wait_mask)
.command_buffers(&command_buffers)
.signal_semaphores(signal_semaphores);
device
.queue_submit(
submit_queue,
&[submit_info.build()],
command_buffer_reuse_fence,
)
.expect("queue submit failed.");
}
}
unsafe extern "system" fn vulkan_debug_callback(
message_severity: vk::DebugUtilsMessageSeverityFlagsEXT,
message_type: vk::DebugUtilsMessageTypeFlagsEXT,
p_callback_data: *const vk::DebugUtilsMessengerCallbackDataEXT,
_user_data: *mut std::os::raw::c_void,
) -> vk::Bool32 {
let callback_data = *p_callback_data;
let message_id_number: i32 = callback_data.message_id_number as i32;
let message_id_name = if callback_data.p_message_id_name.is_null() {
Cow::from("")
} else {
CStr::from_ptr(callback_data.p_message_id_name).to_string_lossy()
};
let message = if callback_data.p_message.is_null() {
Cow::from("")
} else {
CStr::from_ptr(callback_data.p_message).to_string_lossy()
};
println!(
"{:?}:\n{:?} [{} ({})] : {}\n",
message_severity,
message_type,
message_id_name,
&message_id_number.to_string(),
message,
);
vk::FALSE
}
pub fn find_memorytype_index(
memory_req: &vk::MemoryRequirements,
memory_prop: &vk::PhysicalDeviceMemoryProperties,
flags: vk::MemoryPropertyFlags,
) -> Option<u32> {
memory_prop.memory_types[..memory_prop.memory_type_count as _]
.iter()
.enumerate()
.find(|(index, memory_type)| {
(1 << index) & memory_req.memory_type_bits != 0
&& memory_type.property_flags & flags == flags
})
.map(|(index, _memory_type)| index as _)
}
pub struct ExampleBase {
pub entry: Entry,
pub instance: Instance,
pub device: Device,
pub surface_loader: Surface,
pub swapchain_loader: Swapchain,
pub debug_utils_loader: DebugUtils,
pub window: winit::window::Window,
pub event_loop: RefCell<EventLoop<()>>,
pub debug_call_back: vk::DebugUtilsMessengerEXT,
pub pdevice: vk::PhysicalDevice,
pub device_memory_properties: vk::PhysicalDeviceMemoryProperties,
pub queue_family_index: u32,
pub present_queue: vk::Queue,
pub surface: vk::SurfaceKHR,
pub surface_format: vk::SurfaceFormatKHR,
pub surface_resolution: vk::Extent2D,
pub swapchain: vk::SwapchainKHR,
pub present_images: Vec<vk::Image>,
pub present_image_views: Vec<vk::ImageView>,
pub pool: vk::CommandPool,
pub draw_command_buffer: vk::CommandBuffer,
pub setup_command_buffer: vk::CommandBuffer,
pub depth_image: vk::Image,
pub depth_image_view: vk::ImageView,
pub depth_image_memory: vk::DeviceMemory,
pub present_complete_semaphore: vk::Semaphore,
pub rendering_complete_semaphore: vk::Semaphore,
pub draw_commands_reuse_fence: vk::Fence,
pub setup_commands_reuse_fence: vk::Fence,
}
impl ExampleBase {
pub fn render_loop<F: Fn()>(&self, f: F) {
self.event_loop
.borrow_mut()
.run_return(|event, _, control_flow| {
*control_flow = ControlFlow::Poll;
match event {
Event::WindowEvent {
event:
WindowEvent::CloseRequested
| WindowEvent::KeyboardInput {
input:
KeyboardInput {
state: ElementState::Pressed,
virtual_keycode: Some(VirtualKeyCode::Escape),
..
},
..
},
..
} => *control_flow = ControlFlow::Exit,
Event::MainEventsCleared => f(),
_ => (),
}
});
}
pub fn new(window_width: u32, window_height: u32) -> Self {
unsafe {
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.with_title("Ash - Example")
.with_inner_size(winit::dpi::LogicalSize::new(
f64::from(window_width),
f64::from(window_height),
))
.build(&event_loop)
.unwrap();
let entry = Entry::linked();
let app_name = CStr::from_bytes_with_nul_unchecked(b"VulkanTriangle\0");
let layer_names = [CStr::from_bytes_with_nul_unchecked(
b"VK_LAYER_KHRONOS_validation\0",
)];
let layers_names_raw: Vec<*const c_char> = layer_names
.iter()
.map(|raw_name| raw_name.as_ptr())
.collect();
let surface_extensions = ash_window::enumerate_required_extensions(&window).unwrap();
let mut extension_names_raw = surface_extensions
.iter()
.map(|ext| ext.as_ptr())
.collect::<Vec<_>>();
extension_names_raw.push(DebugUtils::name().as_ptr());
let appinfo = vk::ApplicationInfo::builder()
.application_name(app_name)
.application_version(0)
.engine_name(app_name)
.engine_version(0)
.api_version(vk::make_api_version(0, 1, 0, 0));
let create_info = vk::InstanceCreateInfo::builder()
.application_info(&appinfo)
.enabled_layer_names(&layers_names_raw)
.enabled_extension_names(&extension_names_raw);
let instance: Instance = entry
.create_instance(&create_info, None)
.expect("Instance creation error");
let debug_info = vk::DebugUtilsMessengerCreateInfoEXT::builder()
.message_severity(
vk::DebugUtilsMessageSeverityFlagsEXT::ERROR
| vk::DebugUtilsMessageSeverityFlagsEXT::WARNING
| vk::DebugUtilsMessageSeverityFlagsEXT::INFO,
)
.message_type(
vk::DebugUtilsMessageTypeFlagsEXT::GENERAL
| vk::DebugUtilsMessageTypeFlagsEXT::VALIDATION
| vk::DebugUtilsMessageTypeFlagsEXT::PERFORMANCE,
)
.pfn_user_callback(Some(vulkan_debug_callback));
let debug_utils_loader = DebugUtils::new(&entry, &instance);
let debug_call_back = debug_utils_loader
.create_debug_utils_messenger(&debug_info, None)
.unwrap();
let surface = ash_window::create_surface(&entry, &instance, &window, None).unwrap();
let pdevices = instance
.enumerate_physical_devices()
.expect("Physical device error");
let surface_loader = Surface::new(&entry, &instance);
let (pdevice, queue_family_index) = pdevices
.iter()
.map(|pdevice| {
instance
.get_physical_device_queue_family_properties(*pdevice)
.iter()
.enumerate()
.filter_map(|(index, info)| {
let supports_graphic_and_surface =
info.queue_flags.contains(vk::QueueFlags::GRAPHICS)
&& surface_loader
.get_physical_device_surface_support(
*pdevice,
index as u32,
surface,
)
.unwrap();
if supports_graphic_and_surface {
Some((*pdevice, index))
} else {
None
}
})
.next()
})
.flatten()
.next()
.expect("Couldn't find suitable device.");
let queue_family_index = queue_family_index as u32;
let device_extension_names_raw = [Swapchain::name().as_ptr()];
let features = vk::PhysicalDeviceFeatures {
shader_clip_distance: 1,
..Default::default()
};
let priorities = [1.0];
let queue_info = vk::DeviceQueueCreateInfo::builder()
.queue_family_index(queue_family_index)
.queue_priorities(&priorities);
let device_create_info = vk::DeviceCreateInfo::builder()
.queue_create_infos(std::slice::from_ref(&queue_info))
.enabled_extension_names(&device_extension_names_raw)
.enabled_features(&features);
let device: Device = instance
.create_device(pdevice, &device_create_info, None)
.unwrap();
let present_queue = device.get_device_queue(queue_family_index as u32, 0);
let surface_format = surface_loader
.get_physical_device_surface_formats(pdevice, surface)
.unwrap()[0];
let surface_capabilities = surface_loader
.get_physical_device_surface_capabilities(pdevice, surface)
.unwrap();
let mut desired_image_count = surface_capabilities.min_image_count + 1;
if surface_capabilities.max_image_count > 0
&& desired_image_count > surface_capabilities.max_image_count
{
desired_image_count = surface_capabilities.max_image_count;
}
let surface_resolution = match surface_capabilities.current_extent.width {
std::u32::MAX => vk::Extent2D {
width: window_width,
height: window_height,
},
_ => surface_capabilities.current_extent,
};
let pre_transform = if surface_capabilities
.supported_transforms
.contains(vk::SurfaceTransformFlagsKHR::IDENTITY)
{
vk::SurfaceTransformFlagsKHR::IDENTITY
} else {
surface_capabilities.current_transform
};
let present_modes = surface_loader
.get_physical_device_surface_present_modes(pdevice, surface)
.unwrap();
let present_mode = present_modes
.iter()
.cloned()
.find(|&mode| mode == vk::PresentModeKHR::MAILBOX)
.unwrap_or(vk::PresentModeKHR::FIFO);
let swapchain_loader = Swapchain::new(&instance, &device);
let swapchain_create_info = vk::SwapchainCreateInfoKHR::builder()
.surface(surface)
.min_image_count(desired_image_count)
.image_color_space(surface_format.color_space)
.image_format(surface_format.format)
.image_extent(surface_resolution)
.image_usage(vk::ImageUsageFlags::COLOR_ATTACHMENT)
.image_sharing_mode(vk::SharingMode::EXCLUSIVE)
.pre_transform(pre_transform)
.composite_alpha(vk::CompositeAlphaFlagsKHR::OPAQUE)
.present_mode(present_mode)
.clipped(true)
.image_array_layers(1);
let swapchain = swapchain_loader
.create_swapchain(&swapchain_create_info, None)
.unwrap();
let pool_create_info = vk::CommandPoolCreateInfo::builder()
.flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER)
.queue_family_index(queue_family_index);
let pool = device.create_command_pool(&pool_create_info, None).unwrap();
let command_buffer_allocate_info = vk::CommandBufferAllocateInfo::builder()
.command_buffer_count(2)
.command_pool(pool)
.level(vk::CommandBufferLevel::PRIMARY);
let command_buffers = device
.allocate_command_buffers(&command_buffer_allocate_info)
.unwrap();
let setup_command_buffer = command_buffers[0];
let draw_command_buffer = command_buffers[1];
let present_images = swapchain_loader.get_swapchain_images(swapchain).unwrap();
let present_image_views: Vec<vk::ImageView> = present_images
.iter()
.map(|&image| {
let create_view_info = vk::ImageViewCreateInfo::builder()
.view_type(vk::ImageViewType::TYPE_2D)
.format(surface_format.format)
.components(vk::ComponentMapping {
r: vk::ComponentSwizzle::R,
g: vk::ComponentSwizzle::G,
b: vk::ComponentSwizzle::B,
a: vk::ComponentSwizzle::A,
})
.subresource_range(vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: 1,
base_array_layer: 0,
layer_count: 1,
})
.image(image);
device.create_image_view(&create_view_info, None).unwrap()
})
.collect();
let device_memory_properties = instance.get_physical_device_memory_properties(pdevice);
let depth_image_create_info = vk::ImageCreateInfo::builder()
.image_type(vk::ImageType::TYPE_2D)
.format(vk::Format::D16_UNORM)
.extent(surface_resolution.into())
.mip_levels(1)
.array_layers(1)
.samples(vk::SampleCountFlags::TYPE_1)
.tiling(vk::ImageTiling::OPTIMAL)
.usage(vk::ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT)
.sharing_mode(vk::SharingMode::EXCLUSIVE);
let depth_image = device.create_image(&depth_image_create_info, None).unwrap();
let depth_image_memory_req = device.get_image_memory_requirements(depth_image);
let depth_image_memory_index = find_memorytype_index(
&depth_image_memory_req,
&device_memory_properties,
vk::MemoryPropertyFlags::DEVICE_LOCAL,
)
.expect("Unable to find suitable memory index for depth image.");
let depth_image_allocate_info = vk::MemoryAllocateInfo::builder()
.allocation_size(depth_image_memory_req.size)
.memory_type_index(depth_image_memory_index);
let depth_image_memory = device
.allocate_memory(&depth_image_allocate_info, None)
.unwrap();
device
.bind_image_memory(depth_image, depth_image_memory, 0)
.expect("Unable to bind depth image memory");
let fence_create_info =
vk::FenceCreateInfo::builder().flags(vk::FenceCreateFlags::SIGNALED);
let draw_commands_reuse_fence = device
.create_fence(&fence_create_info, None)
.expect("Create fence failed.");
let setup_commands_reuse_fence = device
.create_fence(&fence_create_info, None)
.expect("Create fence failed.");
record_submit_commandbuffer(
&device,
setup_command_buffer,
setup_commands_reuse_fence,
present_queue,
&[],
&[],
&[],
|device, setup_command_buffer| {
let layout_transition_barriers = vk::ImageMemoryBarrier::builder()
.image(depth_image)
.dst_access_mask(
vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_READ
| vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_WRITE,
)
.new_layout(vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
.old_layout(vk::ImageLayout::UNDEFINED)
.subresource_range(
vk::ImageSubresourceRange::builder()
.aspect_mask(vk::ImageAspectFlags::DEPTH)
.layer_count(1)
.level_count(1)
.build(),
);
device.cmd_pipeline_barrier(
setup_command_buffer,
vk::PipelineStageFlags::BOTTOM_OF_PIPE,
vk::PipelineStageFlags::LATE_FRAGMENT_TESTS,
vk::DependencyFlags::empty(),
&[],
&[],
&[layout_transition_barriers.build()],
);
},
);
let depth_image_view_info = vk::ImageViewCreateInfo::builder()
.subresource_range(
vk::ImageSubresourceRange::builder()
.aspect_mask(vk::ImageAspectFlags::DEPTH)
.level_count(1)
.layer_count(1)
.build(),
)
.image(depth_image)
.format(depth_image_create_info.format)
.view_type(vk::ImageViewType::TYPE_2D);
let depth_image_view = device
.create_image_view(&depth_image_view_info, None)
.unwrap();
let semaphore_create_info = vk::SemaphoreCreateInfo::default();
let present_complete_semaphore = device
.create_semaphore(&semaphore_create_info, None)
.unwrap();
let rendering_complete_semaphore = device
.create_semaphore(&semaphore_create_info, None)
.unwrap();
ExampleBase {
event_loop: RefCell::new(event_loop),
entry,
instance,
device,
queue_family_index,
pdevice,
device_memory_properties,
window,
surface_loader,
surface_format,
present_queue,
surface_resolution,
swapchain_loader,
swapchain,
present_images,
present_image_views,
pool,
draw_command_buffer,
setup_command_buffer,
depth_image,
depth_image_view,
present_complete_semaphore,
rendering_complete_semaphore,
draw_commands_reuse_fence,
setup_commands_reuse_fence,
surface,
debug_call_back,
debug_utils_loader,
depth_image_memory,
}
}
}
}
impl Drop for ExampleBase {
fn drop(&mut self) {
unsafe {
self.device.device_wait_idle().unwrap();
self.device
.destroy_semaphore(self.present_complete_semaphore, None);
self.device
.destroy_semaphore(self.rendering_complete_semaphore, None);
self.device
.destroy_fence(self.draw_commands_reuse_fence, None);
self.device
.destroy_fence(self.setup_commands_reuse_fence, None);
self.device.free_memory(self.depth_image_memory, None);
self.device.destroy_image_view(self.depth_image_view, None);
self.device.destroy_image(self.depth_image, None);
for &image_view in self.present_image_views.iter() {
self.device.destroy_image_view(image_view, None);
}
self.device.destroy_command_pool(self.pool, None);
self.swapchain_loader
.destroy_swapchain(self.swapchain, None);
self.device.destroy_device(None);
self.surface_loader.destroy_surface(self.surface, None);
self.debug_utils_loader
.destroy_debug_utils_messenger(self.debug_call_back, None);
self.instance.destroy_instance(None);
}
}
}
| record_submit_commandbuffer |
inet_socket_address.rs | // This file was generated by gir (https://github.com/gtk-rs/gir @ fbb95f4)
// from gir-files (https://github.com/gtk-rs/gir-files @ 77d1f70)
// DO NOT EDIT
use InetAddress;
use SocketAddress;
use SocketConnectable;
use ffi;
use glib;
use glib::object::Downcast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::boxed::Box as Box_;
use std::mem;
use std::mem::transmute;
use std::ptr;
glib_wrapper! {
pub struct InetSocketAddress(Object<ffi::GInetSocketAddress, ffi::GInetSocketAddressClass>): SocketAddress, SocketConnectable;
match fn {
get_type => || ffi::g_inet_socket_address_get_type(),
}
}
impl InetSocketAddress {
pub fn new(address: &InetAddress, port: u16) -> InetSocketAddress {
unsafe {
SocketAddress::from_glib_full(ffi::g_inet_socket_address_new(address.to_glib_none().0, port)).downcast_unchecked()
}
}
#[cfg(any(feature = "v2_40", feature = "dox"))]
pub fn new_from_string(address: &str, port: u32) -> InetSocketAddress {
unsafe {
SocketAddress::from_glib_full(ffi::g_inet_socket_address_new_from_string(address.to_glib_none().0, port)).downcast_unchecked()
}
}
}
pub trait InetSocketAddressExt {
fn get_address(&self) -> Option<InetAddress>;
fn get_flowinfo(&self) -> u32;
fn get_port(&self) -> u16;
fn get_scope_id(&self) -> u32;
fn connect_property_address_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_flowinfo_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_port_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_scope_id_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<InetSocketAddress> + IsA<glib::object::Object>> InetSocketAddressExt for O {
fn get_address(&self) -> Option<InetAddress> {
unsafe {
from_glib_none(ffi::g_inet_socket_address_get_address(self.to_glib_none().0))
}
}
fn get_flowinfo(&self) -> u32 {
unsafe {
ffi::g_inet_socket_address_get_flowinfo(self.to_glib_none().0)
}
}
fn get_port(&self) -> u16 {
unsafe {
ffi::g_inet_socket_address_get_port(self.to_glib_none().0)
}
}
fn get_scope_id(&self) -> u32 {
unsafe {
ffi::g_inet_socket_address_get_scope_id(self.to_glib_none().0)
}
}
fn connect_property_address_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::address",
transmute(notify_address_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
fn connect_property_flowinfo_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::flowinfo",
transmute(notify_flowinfo_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
fn connect_property_port_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::port",
transmute(notify_port_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
fn connect_property_scope_id_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::scope-id",
transmute(notify_scope_id_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
}
unsafe extern "C" fn notify_address_trampoline<P>(this: *mut ffi::GInetSocketAddress, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<InetSocketAddress> {
callback_guard!();
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&InetSocketAddress::from_glib_borrow(this).downcast_unchecked())
}
unsafe extern "C" fn notify_flowinfo_trampoline<P>(this: *mut ffi::GInetSocketAddress, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<InetSocketAddress> {
callback_guard!();
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&InetSocketAddress::from_glib_borrow(this).downcast_unchecked())
}
unsafe extern "C" fn notify_port_trampoline<P>(this: *mut ffi::GInetSocketAddress, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<InetSocketAddress> |
unsafe extern "C" fn notify_scope_id_trampoline<P>(this: *mut ffi::GInetSocketAddress, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<InetSocketAddress> {
callback_guard!();
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&InetSocketAddress::from_glib_borrow(this).downcast_unchecked())
}
| {
callback_guard!();
let f: &&(Fn(&P) + 'static) = transmute(f);
f(&InetSocketAddress::from_glib_borrow(this).downcast_unchecked())
} |
sum_of_digits_of_string_after_convert.rs | impl Solution {
pub fn get_lucky(s: String, k: i32) -> i32 {
let mut arr: Vec<i32> = s
.as_bytes()
.into_iter()
.map(|b| (b - b'a' + 1) as i32)
.collect();
let mut num = 0;
for i in 0..arr.len() {
while arr[i] > 0 {
num += arr[i] % 10;
arr[i] /= 10;
}
}
for i in 1..k {
let mut ans = 0;
while num > 0 {
ans += num % 10;
num /= 10;
}
num = ans;
}
num | }
} |
|
utils.py | # coding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""Utility classes and functions. They help organize and keep statistics of datasets."""
from __future__ import absolute_import
from __future__ import print_function
__all__ = [
'Counter', 'count_tokens', 'concat_sequence', 'slice_sequence', 'train_valid_split',
'line_splitter', 'whitespace_splitter', 'Splitter'
]
import os
import collections
import zipfile
import tarfile
import numpy as np
from mxnet.gluon.data import SimpleDataset
from mxnet.gluon.utils import _get_repo_url, download, check_sha1
from .. import _constants as C
class Counter(collections.Counter): # pylint: disable=abstract-method
"""Counter class for keeping token frequencies."""
def discard(self, min_freq, unknown_token):
"""Discards tokens with frequency below min_frequency and represents them
as `unknown_token`.
Parameters
----------
min_freq: int
Tokens whose frequency is under min_freq is counted as `unknown_token` in
the Counter returned.
unknown_token: str
The representation for any unknown token.
Returns
-------
The Counter instance.
Examples
--------
>>> a = gluonnlp.data.Counter({'a': 10, 'b': 1, 'c': 1})
>>> a.discard(3, '<unk>')
Counter({'a': 10, '<unk>': 2})
"""
freq = 0
ret = Counter({})
for token, count in self.items():
if count < min_freq:
freq += count
else:
ret[token] = count
ret[unknown_token] = ret.get(unknown_token, 0) + freq
return ret
class DefaultLookupDict(dict):
"""Dictionary class with fall-back look-up with default value set in the constructor."""
def __init__(self, default, d=None):
if d:
super(DefaultLookupDict, self).__init__(d)
else:
super(DefaultLookupDict, self).__init__()
self._default = default
def __getitem__(self, k):
return self.get(k, self._default)
def count_tokens(tokens, to_lower=False, counter=None):
r"""Counts tokens in the specified string.
For token_delim='(td)' and seq_delim='(sd)', a specified string of two sequences of tokens may
look like::
(td)token1(td)token2(td)token3(td)(sd)(td)token4(td)token5(td)(sd)
Parameters
----------
tokens : list of str
A source list of tokens.
to_lower : bool, default False
Whether to convert the source source_str to the lower case.
counter : Counter or None, default None
The Counter instance to be updated with the counts of `tokens`. If
None, return a new Counter instance counting tokens from `tokens`.
Returns
-------
The `counter` Counter instance after being updated with the token
counts of `source_str`. If `counter` is None, return a new Counter
instance counting tokens from `source_str`.
Examples
--------
>>> import re
>>> source_str = ' Life is great ! \n life is good . \n'
>>> source_str_tokens = filter(None, re.split(' |\n', source_str))
>>> gluonnlp.data.count_tokens(source_str_tokens)
Counter({'is': 2, 'Life': 1, 'great': 1, '!': 1, 'life': 1, 'good': 1, '.': 1})
"""
if to_lower:
tokens = [t.lower() for t in tokens]
if counter is None:
return Counter(tokens)
else:
counter.update(tokens)
return counter
def concat_sequence(sequences):
"""Concatenate sequences of tokens into a single flattened list of tokens.
Parameters
----------
sequences : list of list of object
Sequences of tokens, each of which is an iterable of tokens.
Returns
-------
Flattened list of tokens.
"""
return [token for seq in sequences for token in seq if token]
def slice_sequence(sequence, length, pad_last=False, pad_val=C.PAD_TOKEN, overlap=0):
"""Slice a flat sequence of tokens into sequences tokens, with each
inner sequence's length equal to the specified `length`, taking into account the requested
sequence overlap.
Parameters
----------
sequence : list of object
A flat list of tokens.
length : int
The length of each of the samples.
pad_last : bool, default False
Whether to pad the last sequence when its length doesn't align. If the last sequence's
length doesn't align and ``pad_last`` is False, it will be dropped.
pad_val : object, default
The padding value to use when the padding of the last sequence is enabled. In general,
the type of ``pad_val`` should be the same as the tokens.
overlap : int, default 0
The extra number of items in current sample that should overlap with the
next sample.
Returns
-------
List of list of tokens, with the length of each inner list equal to `length`.
"""
if length <= overlap:
raise ValueError('length needs to be larger than overlap')
if pad_last:
pad_len = _slice_pad_length(len(sequence), length, overlap)
sequence = sequence + [pad_val] * pad_len
num_samples = (len(sequence)-length) // (length-overlap) + 1
return [sequence[i*(length-overlap):((i+1)*length-i*overlap)] for i in range(num_samples)]
def _slice_pad_length(num_items, length, overlap=0):
"""Calculate the padding length needed for sliced samples in order not to discard data.
Parameters
----------
num_items : int
Number of items in dataset before collating.
length : int
The length of each of the samples.
overlap : int, default 0
The extra number of items in current sample that should overlap with the
next sample.
Returns
-------
Length of paddings.
"""
if length <= overlap:
raise ValueError('length needs to be larger than overlap')
step = length-overlap
span = num_items-length
residual = span % step
if residual:
return step - residual
else:
return 0
_vocab_sha1 = {'wikitext-2': 'be36dc5238c2e7d69720881647ab72eb506d0131',
'gbw': 'ebb1a287ca14d8fa6f167c3a779e5e7ed63ac69f',
'WMT2014_src': '230ebb817b1d86950d71e2e765f192a4e4f34415',
'WMT2014_tgt': '230ebb817b1d86950d71e2e765f192a4e4f34415',
'book_corpus_wiki_en_cased': '2d62af22535ed51f35cc8e2abb607723c89c2636',
'book_corpus_wiki_en_uncased': 'a66073971aa0b1a262453fe51342e57166a8abcf',
'wiki_multilingual_cased': '71bb9e248dc75dce9227d3c8c16fde3993588b9e',
'wiki_cn': 'a1e06f8e39ae51ab8a92b8458e6a658b8b1f72bf',
'wiki_multilingual': '2b2514cc539047b9179e9d98a4e68c36db05c97a'}
_url_format = '{repo_url}gluon/dataset/vocab/{file_name}.zip'
def train_valid_split(dataset, valid_ratio=0.05):
"""Split the dataset into training and validation sets.
Parameters
----------
train : list
A list of training samples.
valid_ratio : float, default 0.05
Proportion of training samples to use for validation set
range: [0, 1]
Returns
-------
train : SimpleDataset
valid : SimpleDataset
"""
if not 0.0 <= valid_ratio <= 1.0:
raise ValueError('valid_ratio should be in [0, 1]')
num_train = len(dataset)
num_valid = np.ceil(num_train * valid_ratio).astype('int')
indices = np.arange(num_train)
np.random.shuffle(indices)
valid = SimpleDataset([dataset[indices[i]] for i in range(num_valid)])
train = SimpleDataset([dataset[indices[i + num_valid]] for i in range(num_train - num_valid)])
return train, valid
def short_hash(name):
if name not in _vocab_sha1:
raise ValueError('Vocabulary for {name} is not available.'.format(name=name))
return _vocab_sha1[name][:8]
def _load_pretrained_vocab(name, root=os.path.join('~', '.mxnet', 'models'), cls=None):
"""Load the accompanying vocabulary object for pre-trained model.
Parameters
----------
name : str
Name of the vocabulary, usually the name of the dataset.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
cls : nlp.Vocab or nlp.vocab.BERTVocab, default nlp.Vocab
Returns
-------
Vocab or nlp.bert.BERTVocab
Loaded vocabulary object for the pre-trained model.
"""
file_name = '{name}-{short_hash}'.format(name=name,
short_hash=short_hash(name))
root = os.path.expanduser(root)
file_path = os.path.join(root, file_name+'.vocab')
sha1_hash = _vocab_sha1[name]
if os.path.exists(file_path):
if check_sha1(file_path, sha1_hash):
return _load_vocab_file(file_path, cls)
else:
print('Detected mismatch in the content of model vocab file. Downloading again.')
else:
print('Vocab file is not found. Downloading.')
if not os.path.exists(root):
os.makedirs(root)
zip_file_path = os.path.join(root, file_name+'.zip')
repo_url = _get_repo_url()
if repo_url[-1] != '/':
repo_url = repo_url + '/'
download(_url_format.format(repo_url=repo_url, file_name=file_name),
path=zip_file_path,
overwrite=True)
with zipfile.ZipFile(zip_file_path) as zf:
zf.extractall(root)
os.remove(zip_file_path)
if check_sha1(file_path, sha1_hash):
return _load_vocab_file(file_path, cls)
else:
raise ValueError('Downloaded file has different hash. Please try again.')
def | (file_path, cls):
with open(file_path, 'r') as f:
if cls is None:
from ..vocab import Vocab
cls = Vocab
return cls.from_json(f.read())
def _get_home_dir():
"""Get home directory for storing datasets/models/pre-trained word embeddings"""
_home_dir = os.environ.get('MXNET_HOME', os.path.join('~', '.mxnet'))
# expand ~ to actual path
_home_dir = os.path.expanduser(_home_dir)
return _home_dir
def _extract_archive(file, target_dir):
"""Extract archive file
Parameters
----------
file : str
Absolute path of the archive file.
target_dir : str
Target directory of the archive to be uncompressed
"""
if file.endswith('.gz') or file.endswith('.tar') or file.endswith('.tgz'):
archive = tarfile.open(file, 'r')
elif file.endswith('.zip'):
archive = zipfile.ZipFile(file, 'r')
else:
raise Exception('Unrecognized file type: ' + file)
archive.extractall(path=target_dir)
archive.close()
def line_splitter(s):
"""Split a string at newlines.
Parameters
----------
s : str
The string to be split
Returns
--------
List[str]
List of strings. Obtained by calling s.splitlines().
"""
return s.splitlines()
def whitespace_splitter(s):
"""Split a string at whitespace (space, tab, newline, return, formfeed).
Parameters
----------
s : str
The string to be split
Returns
--------
List[str]
List of strings. Obtained by calling s.split().
"""
return s.split()
class Splitter(object):
"""Split a string based on a separator.
Parameters
----------
separator : str
The separator based on which string is split.
"""
def __init__(self, separator=None):
self._separator = separator
def __call__(self, s):
"""Split a string based on the separator.
Parameters
----------
s : str
The string to be split
Returns
--------
List[str]
List of strings. Obtained by calling s.split(separator).
"""
return s.split(self._separator)
| _load_vocab_file |
clean.rs | use std::env;
use crate::support::registry::Package;
use crate::support::{basic_bin_manifest, basic_manifest, git, main_file, project};
#[test]
fn cargo_clean_simple() {
let p = project()
.file("Cargo.toml", &basic_bin_manifest("foo"))
.file("src/foo.rs", &main_file(r#""i am foo""#, &[]))
.build();
p.cargo("build").run();
assert!(p.build_dir().is_dir());
p.cargo("clean").run();
assert!(!p.build_dir().is_dir());
}
#[test]
fn different_dir() {
let p = project()
.file("Cargo.toml", &basic_bin_manifest("foo"))
.file("src/foo.rs", &main_file(r#""i am foo""#, &[]))
.file("src/bar/a.rs", "")
.build();
p.cargo("build").run();
assert!(p.build_dir().is_dir());
p.cargo("clean")
.cwd(&p.root().join("src"))
.with_stdout("")
.run();
assert!(!p.build_dir().is_dir());
}
#[test]
fn clean_multiple_packages() {
let p = project()
.file(
"Cargo.toml",
r#"
[package]
name = "foo"
version = "0.0.1"
authors = []
[dependencies.d1]
path = "d1"
[dependencies.d2]
path = "d2"
[[bin]]
name = "foo"
"#,
).file("src/foo.rs", &main_file(r#""i am foo""#, &[]))
.file("d1/Cargo.toml", &basic_bin_manifest("d1"))
.file("d1/src/main.rs", "fn main() { println!(\"d1\"); }")
.file("d2/Cargo.toml", &basic_bin_manifest("d2"))
.file("d2/src/main.rs", "fn main() { println!(\"d2\"); }")
.build();
p.cargo("build -p d1 -p d2 -p foo").run();
let d1_path = &p
.build_dir()
.join("debug")
.join(format!("d1{}", env::consts::EXE_SUFFIX));
let d2_path = &p
.build_dir()
.join("debug")
.join(format!("d2{}", env::consts::EXE_SUFFIX));
assert!(p.bin("foo").is_file());
assert!(d1_path.is_file());
assert!(d2_path.is_file());
p.cargo("clean -p d1 -p d2")
.cwd(&p.root().join("src"))
.with_stdout("")
.run();
assert!(p.bin("foo").is_file());
assert!(!d1_path.is_file());
assert!(!d2_path.is_file());
}
#[test]
fn clean_release() |
#[test]
fn clean_doc() {
let p = project()
.file(
"Cargo.toml",
r#"
[package]
name = "foo"
version = "0.0.1"
authors = []
[dependencies]
a = { path = "a" }
"#,
).file("src/main.rs", "fn main() {}")
.file("a/Cargo.toml", &basic_manifest("a", "0.0.1"))
.file("a/src/lib.rs", "")
.build();
p.cargo("doc").run();
let doc_path = &p.build_dir().join("doc");
assert!(doc_path.is_dir());
p.cargo("clean --doc").run();
assert!(!doc_path.is_dir());
assert!(p.build_dir().is_dir());
}
#[test]
fn build_script() {
let p = project()
.file(
"Cargo.toml",
r#"
[package]
name = "foo"
version = "0.0.1"
authors = []
build = "build.rs"
"#,
).file("src/main.rs", "fn main() {}")
.file(
"build.rs",
r#"
use std::path::PathBuf;
use std::env;
fn main() {
let out = PathBuf::from(env::var_os("OUT_DIR").unwrap());
if env::var("FIRST").is_ok() {
std::fs::File::create(out.join("out")).unwrap();
} else {
assert!(!std::fs::metadata(out.join("out")).is_ok());
}
}
"#,
).file("a/src/lib.rs", "")
.build();
p.cargo("build").env("FIRST", "1").run();
p.cargo("clean -p foo").run();
p.cargo("build -v")
.with_stderr(
"\
[COMPILING] foo v0.0.1 ([..])
[RUNNING] `rustc [..] build.rs [..]`
[RUNNING] `[..]build-script-build`
[RUNNING] `rustc [..] src/main.rs [..]`
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
).run();
}
#[test]
fn clean_git() {
let git = git::new("dep", |project| {
project
.file("Cargo.toml", &basic_manifest("dep", "0.5.0"))
.file("src/lib.rs", "")
}).unwrap();
let p = project()
.file(
"Cargo.toml",
&format!(
r#"
[package]
name = "foo"
version = "0.0.1"
authors = []
[dependencies]
dep = {{ git = '{}' }}
"#,
git.url()
),
).file("src/main.rs", "fn main() {}")
.build();
p.cargo("build").run();
p.cargo("clean -p dep").with_stdout("").run();
p.cargo("build").run();
}
#[test]
fn registry() {
let p = project()
.file(
"Cargo.toml",
r#"
[package]
name = "foo"
version = "0.0.1"
authors = []
[dependencies]
bar = "0.1"
"#,
).file("src/main.rs", "fn main() {}")
.build();
Package::new("bar", "0.1.0").publish();
p.cargo("build").run();
p.cargo("clean -p bar").with_stdout("").run();
p.cargo("build").run();
}
#[test]
fn clean_verbose() {
let p = project()
.file(
"Cargo.toml",
r#"
[package]
name = "foo"
version = "0.0.1"
[dependencies]
bar = "0.1"
"#,
).file("src/main.rs", "fn main() {}")
.build();
Package::new("bar", "0.1.0").publish();
p.cargo("build").run();
p.cargo("clean -p bar --verbose")
.with_stderr(
"\
[REMOVING] [..]
[REMOVING] [..]
",
).run();
p.cargo("build").run();
}
| {
let p = project()
.file(
"Cargo.toml",
r#"
[package]
name = "foo"
version = "0.0.1"
authors = []
[dependencies]
a = { path = "a" }
"#,
).file("src/main.rs", "fn main() {}")
.file("a/Cargo.toml", &basic_manifest("a", "0.0.1"))
.file("a/src/lib.rs", "")
.build();
p.cargo("build --release").run();
p.cargo("clean -p foo").run();
p.cargo("build --release").with_stdout("").run();
p.cargo("clean -p foo --release").run();
p.cargo("build --release")
.with_stderr(
"\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] release [optimized] target(s) in [..]
",
).run();
p.cargo("build").run();
p.cargo("clean").arg("--release").run();
assert!(p.build_dir().is_dir());
assert!(p.build_dir().join("debug").is_dir());
assert!(!p.build_dir().join("release").is_dir());
} |
schema_test.go | // Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package load
import (
"encoding/json"
"math"
"testing"
"time"
"github.com/facebook/ent"
"github.com/facebook/ent/schema/edge"
"github.com/facebook/ent/schema/field"
"github.com/facebook/ent/schema/index"
"github.com/facebook/ent/schema/mixin"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
)
type OrderConfig struct {
FieldName string
}
func (OrderConfig) Name() string {
return "order_config"
}
func (o *OrderConfig) MarshalJSON() ([]byte, error) {
return json.Marshal(*o)
}
type User struct {
ent.Schema
}
func (User) Fields() []ent.Field {
return []ent.Field{
field.Int("age"),
field.String("name").
Default("unknown").
Annotations(&OrderConfig{FieldName: "name"}),
field.String("nillable").
Nillable(),
field.String("optional").
Optional(),
field.Enum("state").
Values("on", "off").
Optional(),
field.String("sensitive").
Sensitive(),
field.Time("creation_time").
Default(time.Now),
field.UUID("uuid", uuid.UUID{}).
Default(uuid.New),
}
}
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("groups", Group.Type).
Annotations(&OrderConfig{FieldName: "name"}),
edge.To("parent", User.Type).
Unique().
StorageKey(edge.Column("user_parent_id")).
From("children"),
edge.To("following", User.Type).
Annotations(&OrderConfig{FieldName: "following"}).
From("followers").
Annotations(&OrderConfig{FieldName: "followers"}),
}
}
func (User) Indexes() []ent.Index {
return []ent.Index{
index.Fields("name", "address").
Unique(),
index.Fields("name").
Edges("parent").
StorageKey("user_parent_name").
Unique(),
}
}
type Group struct{ ent.Schema }
func (Group) Fields() []ent.Field { return nil }
func (Group) Edges() []ent.Edge {
return []ent.Edge{
edge.From("users", User.Type),
}
}
func TestMarshalSchema(t *testing.T) {
for _, u := range []ent.Interface{User{}, &User{}} {
buf, err := MarshalSchema(u)
require.NoError(t, err)
schema, err := UnmarshalSchema(buf)
require.NoError(t, err)
require.Equal(t, "User", schema.Name)
require.Len(t, schema.Fields, 8)
require.Equal(t, "age", schema.Fields[0].Name)
require.Equal(t, field.TypeInt, schema.Fields[0].Info.Type)
require.Equal(t, "name", schema.Fields[1].Name)
require.Equal(t, field.TypeString, schema.Fields[1].Info.Type)
require.Equal(t, "unknown", schema.Fields[1].DefaultValue)
require.NotEmpty(t, schema.Fields[1].Annotations)
ant := schema.Fields[1].Annotations["order_config"].(map[string]interface{})
require.Equal(t, ant["FieldName"], "name")
require.Equal(t, "nillable", schema.Fields[2].Name)
require.Equal(t, field.TypeString, schema.Fields[2].Info.Type)
require.True(t, schema.Fields[2].Nillable)
require.False(t, schema.Fields[2].Optional)
require.False(t, schema.Fields[2].Sensitive)
require.Equal(t, "optional", schema.Fields[3].Name)
require.Equal(t, field.TypeString, schema.Fields[3].Info.Type)
require.False(t, schema.Fields[3].Nillable)
require.True(t, schema.Fields[3].Optional)
require.Equal(t, "state", schema.Fields[4].Name)
require.Equal(t, field.TypeEnum, schema.Fields[4].Info.Type)
require.Equal(t, "on", schema.Fields[4].Enums[0].V)
require.Equal(t, "off", schema.Fields[4].Enums[1].V)
require.Equal(t, "sensitive", schema.Fields[5].Name)
require.Equal(t, field.TypeString, schema.Fields[5].Info.Type)
require.True(t, schema.Fields[5].Sensitive)
require.Equal(t, "creation_time", schema.Fields[6].Name)
require.Equal(t, field.TypeTime, schema.Fields[6].Info.Type)
require.Nil(t, schema.Fields[6].DefaultValue)
require.Equal(t, "uuid", schema.Fields[7].Name)
require.Equal(t, field.TypeUUID, schema.Fields[7].Info.Type)
require.True(t, schema.Fields[7].Default)
require.Equal(t, "github.com/google/uuid", schema.Fields[7].Info.PkgPath)
require.Len(t, schema.Edges, 3)
require.Equal(t, "groups", schema.Edges[0].Name)
require.Equal(t, "Group", schema.Edges[0].Type)
require.False(t, schema.Edges[0].Inverse)
require.NotEmpty(t, schema.Edges[0].Annotations)
ant = schema.Edges[0].Annotations["order_config"].(map[string]interface{})
require.Equal(t, ant["FieldName"], "name")
require.Equal(t, "children", schema.Edges[1].Name)
require.Equal(t, "user_parent_id", schema.Edges[1].StorageKey.Columns[0])
require.Equal(t, "User", schema.Edges[1].Type)
require.True(t, schema.Edges[1].Inverse)
require.Equal(t, "parent", schema.Edges[1].Ref.Name)
require.True(t, schema.Edges[1].Ref.Unique)
require.Equal(t, "user_parent_id", schema.Edges[1].Ref.StorageKey.Columns[0])
ant = schema.Edges[2].Annotations["order_config"].(map[string]interface{})
require.Equal(t, ant["FieldName"], "followers")
ant = schema.Edges[2].Ref.Annotations["order_config"].(map[string]interface{})
require.Equal(t, ant["FieldName"], "following")
require.Equal(t, []string{"name", "address"}, schema.Indexes[0].Fields)
require.True(t, schema.Indexes[0].Unique)
require.Equal(t, []string{"name"}, schema.Indexes[1].Fields)
require.Equal(t, []string{"parent"}, schema.Indexes[1].Edges)
require.Equal(t, "user_parent_name", schema.Indexes[1].StorageKey)
require.True(t, schema.Indexes[1].Unique)
}
}
type InvalidEdge struct {
ent.Schema
}
// Edge panics because the edge declaration is invalid.
func (InvalidEdge) Edges() []ent.Edge {
return []ent.Edge{
edge.From("invalid", InvalidEdge{}.Type),
}
}
type InvalidUUID struct {
ent.Schema
}
func (InvalidUUID) Fields() []ent.Field {
return []ent.Field{
field.UUID("invalid", uuid.New()).
Default(time.Now),
}
}
func TestMarshalFails(t *testing.T) {
i1 := InvalidEdge{}
buf, err := MarshalSchema(i1)
require.Error(t, err)
require.Nil(t, buf)
i2 := InvalidUUID{}
buf, err = MarshalSchema(i2)
require.Nil(t, buf)
require.EqualError(t, err, `schema "InvalidUUID": field "invalid": expect type (func() uuid.UUID) for uuid default value`)
}
type WithDefaults struct {
ent.Schema
}
func (WithDefaults) Fields() []ent.Field {
return []ent.Field{
field.Int("int").
Default(1),
field.Float("float").
Default(math.Pi),
field.String("string").
Default("foo"),
field.Bool("string").
Default(true),
field.Time("updated_at").
UpdateDefault(time.Now),
}
}
func (WithDefaults) Edges() []ent.Edge {
return nil
}
func (WithDefaults) Indexes() []ent.Index {
return nil
}
func TestMarshalDefaults(t *testing.T) {
d := WithDefaults{}
buf, err := MarshalSchema(d)
require.NoError(t, err)
schema := &Schema{}
err = json.Unmarshal(buf, schema)
require.NoError(t, err)
require.Equal(t, "WithDefaults", schema.Name)
require.True(t, schema.Fields[0].Default)
require.True(t, schema.Fields[1].Default)
require.True(t, schema.Fields[2].Default)
require.True(t, schema.Fields[3].Default)
require.False(t, schema.Fields[4].Default)
require.True(t, schema.Fields[4].UpdateDefault)
}
type TimeMixin struct {
mixin.Schema
}
func (TimeMixin) Fields() []ent.Field {
return []ent.Field{
field.Time("created_at").
Immutable().
Default(time.Now),
field.Time("updated_at").
Default(time.Now).
UpdateDefault(time.Now),
}
}
type HooksMixin struct {
mixin.Schema
}
func (HooksMixin) Fields() []ent.Field {
return []ent.Field{
field.String("boring"),
}
}
func (HooksMixin) Edges() []ent.Edge {
return []ent.Edge{
edge.To("user", User.Type).
Unique(),
}
}
func (HooksMixin) Indexes() []ent.Index {
return []ent.Index{
index.Fields("boring").
Edges("user"),
}
}
func (HooksMixin) Hooks() []ent.Hook {
return []ent.Hook{
func(ent.Mutator) ent.Mutator { return nil },
func(ent.Mutator) ent.Mutator { return nil },
}
}
type WithMixin struct {
ent.Schema
}
func (WithMixin) Mixin() []ent.Mixin {
return []ent.Mixin{
TimeMixin{},
HooksMixin{},
}
}
func (WithMixin) Fields() []ent.Field {
return []ent.Field{
field.Int("field"),
}
}
func (WithMixin) Edges() []ent.Edge {
return []ent.Edge{
edge.To("owner", User.Type),
}
}
func (WithMixin) Indexes() []ent.Index {
return []ent.Index{
index.Fields("field").
Edges("owner").
Unique(),
}
}
func (WithMixin) Hooks() []ent.Hook {
return []ent.Hook{
func(ent.Mutator) ent.Mutator { return nil },
}
}
func TestMarshalMixin(t *testing.T) | {
d := WithMixin{}
buf, err := MarshalSchema(d)
require.NoError(t, err)
schema := &Schema{}
err = json.Unmarshal(buf, schema)
require.NoError(t, err)
t.Run("Fields", func(t *testing.T) {
require.Equal(t, "WithMixin", schema.Name)
require.Equal(t, "created_at", schema.Fields[0].Name)
require.True(t, schema.Fields[0].Default)
require.True(t, schema.Fields[0].Position.MixedIn)
require.Equal(t, 0, schema.Fields[0].Position.MixinIndex)
require.Equal(t, 0, schema.Fields[0].Position.Index)
require.Equal(t, "updated_at", schema.Fields[1].Name)
require.True(t, schema.Fields[1].Default)
require.True(t, schema.Fields[1].UpdateDefault)
require.True(t, schema.Fields[1].Position.MixedIn)
require.Equal(t, 0, schema.Fields[1].Position.MixinIndex)
require.Equal(t, 1, schema.Fields[1].Position.Index)
require.Equal(t, "boring", schema.Fields[2].Name)
require.False(t, schema.Fields[2].Default)
require.False(t, schema.Fields[2].UpdateDefault)
require.True(t, schema.Fields[2].Position.MixedIn)
require.Equal(t, 1, schema.Fields[2].Position.MixinIndex)
require.Equal(t, 0, schema.Fields[2].Position.Index)
require.Equal(t, "field", schema.Fields[3].Name)
require.False(t, schema.Fields[3].Default)
require.False(t, schema.Fields[3].Position.MixedIn)
require.Equal(t, 0, schema.Fields[3].Position.Index)
})
t.Run("Hooks", func(t *testing.T) {
require.True(t, schema.Hooks[0].MixedIn)
require.True(t, schema.Hooks[1].MixedIn)
require.Equal(t, 1, schema.Hooks[0].MixinIndex)
require.Equal(t, 1, schema.Hooks[1].MixinIndex)
require.Equal(t, 0, schema.Hooks[0].Index)
require.Equal(t, 1, schema.Hooks[1].Index)
require.False(t, schema.Hooks[2].MixedIn)
require.Equal(t, 0, schema.Hooks[2].Index)
require.Equal(t, 0, schema.Hooks[2].MixinIndex)
})
t.Run("Edges", func(t *testing.T) {
require.Len(t, schema.Edges, 2)
require.Equal(t, "user", schema.Edges[0].Name)
require.Equal(t, "User", schema.Edges[0].Type)
require.True(t, schema.Edges[0].Unique)
require.Equal(t, "owner", schema.Edges[1].Name)
require.Equal(t, "User", schema.Edges[1].Type)
require.False(t, schema.Edges[1].Unique)
})
t.Run("Indexes", func(t *testing.T) {
require.Len(t, schema.Indexes, 2)
require.Equal(t, []string{"boring"}, schema.Indexes[0].Fields)
require.Equal(t, []string{"user"}, schema.Indexes[0].Edges)
require.False(t, schema.Indexes[0].Unique)
require.Equal(t, []string{"field"}, schema.Indexes[1].Fields)
require.Equal(t, []string{"owner"}, schema.Indexes[1].Edges)
require.True(t, schema.Indexes[1].Unique)
})
} |
|
tools.py | #
# Copyright 2018 Joachim Lusiardi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import json
import sys
import base64
import binascii
from homekit.http_impl.http_client import HomeKitHTTPConnection
from homekit.zeroconf_ import find_device_ip_and_port
from homekit.protocol import get_session_keys
from homekit.model.characteristics import CharacteristicFormats
from distutils.util import strtobool
from homekit.exception import FormatException
from homekit.tlv import TlvParseException
from homekit import TLV
def load_pairing(file: str) -> dict:
|
def save_pairing(file: str, pairing_data: dict):
"""
save the data for an existing pairing.
:param file: the file name
:param pairing_data: a dict containing the pairing data
:return: None
"""
with open(file, 'w') as output_fp:
json.dump(pairing_data, output_fp, indent=4)
def create_session(file):
"""
try to obtain IP and port from the given file and establish a session to a HomeKit accessory. This function covers
IP/ports that might have changed since last run and updates the file accordingly.
:param file: the path to the file where the data is stored
:return:
conn: an instance of HomeKitHTTPConnection
c2a_key: the key used for communication from controller to accessory
a2c_key: the key used for communication from accessory to controller
"""
conn = None
c2a_key = None
a2c_key = None
# load file with pairing data
pairing_data = load_pairing(file)
if pairing_data is None:
print('File {file} not found!'.format(file=file))
sys.exit(-1)
# we need ip and port of the device
connected = False
if 'AccessoryIP' in pairing_data and 'AccessoryPort' in pairing_data:
# if it is known, try it
accessory_ip = pairing_data['AccessoryIP']
accessory_port = pairing_data['AccessoryPort']
conn = HomeKitHTTPConnection(accessory_ip, port=accessory_port)
try:
conn.connect()
c2a_key, a2c_key = get_session_keys(conn, pairing_data)
connected = True
except Exception:
connected = False
if not connected:
# no connection yet, so ip / port might have changed and we need to fall back to slow zeroconf lookup
device_id = pairing_data['AccessoryPairingID']
connection_data = find_device_ip_and_port(device_id)
if connection_data is None:
print('Device {id} not found'.format(id=device_id))
sys.exit(-1)
conn = HomeKitHTTPConnection(connection_data['ip'], port=connection_data['port'])
pairing_data['AccessoryIP'] = connection_data['ip']
pairing_data['AccessoryPort'] = connection_data['port']
save_pairing(file, pairing_data)
c2a_key, a2c_key = get_session_keys(conn, pairing_data)
return conn, c2a_key, a2c_key
def check_convert_value(val, target_format):
"""
Checks if the given value is of the given format or is convertible into the format. If the value is not convertible,
a FormatException is thrown.
:param val: the original value
:param target_format: the target type of the conversion
:raises FormatException: if the value is not of the given format or cannot be converted.
:return: the converted value
"""
if target_format == CharacteristicFormats.bool:
try:
val = strtobool(val)
except ValueError:
raise FormatException('"{v}" is no valid "{t}"!'.format(v=val, t=target_format))
if target_format in [CharacteristicFormats.uint64, CharacteristicFormats.uint32,
CharacteristicFormats.uint16, CharacteristicFormats.uint8,
CharacteristicFormats.int]:
try:
val = int(val)
except ValueError:
raise FormatException('"{v}" is no valid "{t}"!'.format(v=val, t=target_format))
if target_format == CharacteristicFormats.float:
try:
val = float(val)
except ValueError:
raise FormatException('"{v}" is no valid "{t}"!'.format(v=val, t=target_format))
if target_format == CharacteristicFormats.data:
try:
base64.decodebytes(val.encode())
except binascii.Error:
raise FormatException('"{v}" is no valid "{t}"!'.format(v=val, t=target_format))
if target_format == CharacteristicFormats.tlv8:
try:
tmp_bytes = base64.decodebytes(val.encode())
TLV.decode_bytes(tmp_bytes)
except (binascii.Error, TlvParseException):
raise FormatException('"{v}" is no valid "{t}"!'.format(v=val, t=target_format))
return val
| """
loads data for an existing pairing from the file.
:param file: the file name
:return: a dict containing the pairing data or None if file was not found
"""
try:
with open(file, 'r') as input_fp:
return json.load(input_fp)
except FileNotFoundError:
return None |
asynctask.py | # -*- coding: utf-8 -*-
# Copyright (C) 2012-2016 Xue Can <[email protected]> and contributors.
# Licensed under the MIT license: http://opensource.org/licenses/mit-license
"""
Celery 应用程序生成器
Celery 应用程序的配置众多,这里提供一个快速的生成器,避免经常需要查阅手册。
本模块根据 Celery 4.0.0rc4 重新编写。配置详情请参考:
* http://docs.celeryproject.org/en/master/userguide/configuration.html
"""
import celery
if '4.0.0' > celery.__version__:
raise RuntimeError('Require celery 4.0.0rc4 or up')
from celery import Celery
from kombu.exceptions import OperationalError
from .datastructures import Object
def make_worker(name, set_as_current=True):
"""返回默认的 worker 实例,还需要进一步配置方可使用"""
name = str(name)
worker = Celery(name, set_as_current=set_as_current)
worker.conf.update(
# names
task_default_queue=name,
task_default_exchange=name,
task_default_routing_key=name,
# genenals
accept_content=['json'],
enable_utc=True,
timezone='Asia/Shanghai',
# tasks
task_serializer='json',
task_compression=None,
task_protocol=2,
task_track_started=True, | result_serializer='json',
result_compression=None,
result_expires=3600, # 1 hour
# workers
worker_prefetch_multiplier=1, # no prefetch
worker_disable_rate_limits=True, # no rate limit
worker_max_tasks_per_child=1000, # prevent memory leak
worker_hijack_root_logger=False # we have logkit
)
return worker
def with_retries(worker, max_=3, start=0, interval=0.2):
worker.conf.update(
task_publish_retry=True,
task_publish_retry_policy={
'max_retries': max_,
'interval_start': start,
'interval_step': interval,
'interval_max': interval,
}
)
def _with_broker(worker, broker, read_broker=None):
if read_broker:
worker.conf.broker_write_url = broker
worker.conf.broker_read_url = read_broker
else:
worker.conf.broker_url = broker
def with_amqp_broker(worker, broker, read_broker=None):
worker.conf.task_queue_ha_policy = 'all'
_with_broker(worker, broker, read_broker)
def with_redis_broker(worker, broker, read_broker=None):
worker.conf.broker_transport_options = {
'visibility_timeout': 3600,
'fanout_prefix': True,
'fanout_patterns': True,
}
_with_broker(worker, broker, read_broker)
def with_backend(worker, backend):
worker.conf.result_backend = backend
# patch: don't use image
import celery.utils.term
celery.utils.term.supports_images = lambda: False | task_publish_retry=False, # no retry
# results |
dbi_ctl_0.rs | #[doc = "Register `DBI_CTL_0` reader"]
pub struct R(crate::R<DBI_CTL_0_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DBI_CTL_0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DBI_CTL_0_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DBI_CTL_0_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `DBI_CTL_0` writer"]
pub struct W(crate::W<DBI_CTL_0_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<DBI_CTL_0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<DBI_CTL_0_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<DBI_CTL_0_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Command Type\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CMDT_A {
#[doc = "0: `0`"]
WRITE = 0,
#[doc = "1: `1`"]
READ = 1,
}
impl From<CMDT_A> for bool {
#[inline(always)]
fn from(variant: CMDT_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `cmdt` reader - Command Type"]
pub type CMDT_R = crate::BitReader<CMDT_A>;
impl CMDT_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CMDT_A {
match self.bits {
false => CMDT_A::WRITE,
true => CMDT_A::READ,
}
}
#[doc = "Checks if the value of the field is `WRITE`"]
#[inline(always)]
pub fn is_write(&self) -> bool {
*self == CMDT_A::WRITE
}
#[doc = "Checks if the value of the field is `READ`"]
#[inline(always)]
pub fn is_read(&self) -> bool {
*self == CMDT_A::READ
}
}
#[doc = "Field `cmdt` writer - Command Type"]
pub type CMDT_W<'a> = crate::BitWriter<'a, u32, DBI_CTL_0_SPEC, CMDT_A, 31>;
impl<'a> CMDT_W<'a> {
#[doc = "`0`"]
#[inline(always)]
pub fn write(self) -> &'a mut W {
self.variant(CMDT_A::WRITE)
}
#[doc = "`1`"]
#[inline(always)]
pub fn read(self) -> &'a mut W {
self.variant(CMDT_A::READ)
}
}
#[doc = "Field `wcdc` reader - Write Command Dummy Cycles"]
pub type WCDC_R = crate::FieldReader<u16, u16>;
#[doc = "Field `wcdc` writer - Write Command Dummy Cycles"]
pub type WCDC_W<'a> = crate::FieldWriter<'a, u32, DBI_CTL_0_SPEC, u16, u16, 11, 20>;
#[doc = "Output Data Sequence\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DAT_SEQ_A {
#[doc = "0: `0`"]
MSB = 0,
#[doc = "1: `1`"]
LSB = 1,
}
impl From<DAT_SEQ_A> for bool {
#[inline(always)]
fn from(variant: DAT_SEQ_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `dat_seq` reader - Output Data Sequence"]
pub type DAT_SEQ_R = crate::BitReader<DAT_SEQ_A>;
impl DAT_SEQ_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DAT_SEQ_A {
match self.bits {
false => DAT_SEQ_A::MSB,
true => DAT_SEQ_A::LSB,
}
}
#[doc = "Checks if the value of the field is `MSB`"]
#[inline(always)]
pub fn is_msb(&self) -> bool {
*self == DAT_SEQ_A::MSB
}
#[doc = "Checks if the value of the field is `LSB`"]
#[inline(always)]
pub fn is_lsb(&self) -> bool {
*self == DAT_SEQ_A::LSB
}
}
#[doc = "Field `dat_seq` writer - Output Data Sequence"]
pub type DAT_SEQ_W<'a> = crate::BitWriter<'a, u32, DBI_CTL_0_SPEC, DAT_SEQ_A, 19>;
impl<'a> DAT_SEQ_W<'a> {
#[doc = "`0`"]
#[inline(always)]
pub fn msb(self) -> &'a mut W {
self.variant(DAT_SEQ_A::MSB)
}
#[doc = "`1`"]
#[inline(always)]
pub fn lsb(self) -> &'a mut W {
self.variant(DAT_SEQ_A::LSB)
}
}
#[doc = "Output RGB Sequence\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum RGB_SEQ_A {
#[doc = "0: `0`"]
RGB = 0,
#[doc = "1: `1`"]
RBG = 1,
#[doc = "2: `10`"]
GRB = 2,
#[doc = "3: `11`"]
GBR = 3,
#[doc = "4: `100`"]
BRG = 4,
#[doc = "5: `101`"]
BGR = 5,
}
impl From<RGB_SEQ_A> for u8 {
#[inline(always)]
fn from(variant: RGB_SEQ_A) -> Self {
variant as _
}
}
#[doc = "Field `rgb_seq` reader - Output RGB Sequence"]
pub type RGB_SEQ_R = crate::FieldReader<u8, RGB_SEQ_A>;
impl RGB_SEQ_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<RGB_SEQ_A> {
match self.bits {
0 => Some(RGB_SEQ_A::RGB),
1 => Some(RGB_SEQ_A::RBG),
2 => Some(RGB_SEQ_A::GRB),
3 => Some(RGB_SEQ_A::GBR),
4 => Some(RGB_SEQ_A::BRG),
5 => Some(RGB_SEQ_A::BGR),
_ => None,
}
}
#[doc = "Checks if the value of the field is `RGB`"]
#[inline(always)]
pub fn is_rgb(&self) -> bool {
*self == RGB_SEQ_A::RGB
}
#[doc = "Checks if the value of the field is `RBG`"]
#[inline(always)]
pub fn is_rbg(&self) -> bool {
*self == RGB_SEQ_A::RBG
}
#[doc = "Checks if the value of the field is `GRB`"]
#[inline(always)]
pub fn is_grb(&self) -> bool {
*self == RGB_SEQ_A::GRB
}
#[doc = "Checks if the value of the field is `GBR`"]
#[inline(always)]
pub fn is_gbr(&self) -> bool {
*self == RGB_SEQ_A::GBR
}
#[doc = "Checks if the value of the field is `BRG`"]
#[inline(always)]
pub fn is_brg(&self) -> bool {
*self == RGB_SEQ_A::BRG
}
#[doc = "Checks if the value of the field is `BGR`"]
#[inline(always)]
pub fn is_bgr(&self) -> bool {
*self == RGB_SEQ_A::BGR
}
}
#[doc = "Field `rgb_seq` writer - Output RGB Sequence"]
pub type RGB_SEQ_W<'a> = crate::FieldWriter<'a, u32, DBI_CTL_0_SPEC, u8, RGB_SEQ_A, 3, 16>;
impl<'a> RGB_SEQ_W<'a> {
#[doc = "`0`"]
#[inline(always)]
pub fn rgb(self) -> &'a mut W {
self.variant(RGB_SEQ_A::RGB)
}
#[doc = "`1`"]
#[inline(always)]
pub fn rbg(self) -> &'a mut W {
self.variant(RGB_SEQ_A::RBG)
}
#[doc = "`10`"]
#[inline(always)]
pub fn grb(self) -> &'a mut W {
self.variant(RGB_SEQ_A::GRB)
}
#[doc = "`11`"]
#[inline(always)]
pub fn gbr(self) -> &'a mut W {
self.variant(RGB_SEQ_A::GBR)
}
#[doc = "`100`"]
#[inline(always)]
pub fn brg(self) -> &'a mut W {
self.variant(RGB_SEQ_A::BRG)
}
#[doc = "`101`"]
#[inline(always)]
pub fn bgr(self) -> &'a mut W {
self.variant(RGB_SEQ_A::BGR)
}
}
#[doc = "Transmit Mode\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TRAN_MOD_A {
#[doc = "0: `0`"]
COMMAND_PARAMETER = 0,
#[doc = "1: `1`"]
VIDEO = 1,
}
impl From<TRAN_MOD_A> for bool {
#[inline(always)]
fn from(variant: TRAN_MOD_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `tran_mod` reader - Transmit Mode"]
pub type TRAN_MOD_R = crate::BitReader<TRAN_MOD_A>;
impl TRAN_MOD_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TRAN_MOD_A {
match self.bits {
false => TRAN_MOD_A::COMMAND_PARAMETER,
true => TRAN_MOD_A::VIDEO,
}
}
#[doc = "Checks if the value of the field is `COMMAND_PARAMETER`"]
#[inline(always)]
pub fn is_command_parameter(&self) -> bool {
*self == TRAN_MOD_A::COMMAND_PARAMETER
}
#[doc = "Checks if the value of the field is `VIDEO`"]
#[inline(always)]
pub fn is_video(&self) -> bool {
*self == TRAN_MOD_A::VIDEO
}
}
#[doc = "Field `tran_mod` writer - Transmit Mode"]
pub type TRAN_MOD_W<'a> = crate::BitWriter<'a, u32, DBI_CTL_0_SPEC, TRAN_MOD_A, 15>;
impl<'a> TRAN_MOD_W<'a> {
#[doc = "`0`"]
#[inline(always)]
pub fn command_parameter(self) -> &'a mut W {
self.variant(TRAN_MOD_A::COMMAND_PARAMETER)
}
#[doc = "`1`"]
#[inline(always)]
pub fn video(self) -> &'a mut W {
self.variant(TRAN_MOD_A::VIDEO)
}
}
#[doc = "Output Data Format\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum DAT_FMT_A {
#[doc = "0: `0`"]
RGB111 = 0,
#[doc = "1: `1`"]
RGB444 = 1,
#[doc = "2: `10`"]
RGB565 = 2,
#[doc = "3: `11`"]
RGB666 = 3,
#[doc = "4: `100`"]
RGB888 = 4,
}
impl From<DAT_FMT_A> for u8 {
#[inline(always)]
fn from(variant: DAT_FMT_A) -> Self {
variant as _
}
}
#[doc = "Field `dat_fmt` reader - Output Data Format"]
pub type DAT_FMT_R = crate::FieldReader<u8, DAT_FMT_A>;
impl DAT_FMT_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<DAT_FMT_A> {
match self.bits {
0 => Some(DAT_FMT_A::RGB111),
1 => Some(DAT_FMT_A::RGB444),
2 => Some(DAT_FMT_A::RGB565),
3 => Some(DAT_FMT_A::RGB666),
4 => Some(DAT_FMT_A::RGB888),
_ => None,
}
}
#[doc = "Checks if the value of the field is `RGB111`"]
#[inline(always)]
pub fn is_rgb111(&self) -> bool {
*self == DAT_FMT_A::RGB111
}
#[doc = "Checks if the value of the field is `RGB444`"]
#[inline(always)]
pub fn is_rgb444(&self) -> bool {
*self == DAT_FMT_A::RGB444
}
#[doc = "Checks if the value of the field is `RGB565`"]
#[inline(always)]
pub fn is_rgb565(&self) -> bool {
*self == DAT_FMT_A::RGB565
}
#[doc = "Checks if the value of the field is `RGB666`"]
#[inline(always)]
pub fn is_rgb666(&self) -> bool {
*self == DAT_FMT_A::RGB666
}
#[doc = "Checks if the value of the field is `RGB888`"]
#[inline(always)]
pub fn is_rgb888(&self) -> bool {
*self == DAT_FMT_A::RGB888
}
}
#[doc = "Field `dat_fmt` writer - Output Data Format"]
pub type DAT_FMT_W<'a> = crate::FieldWriter<'a, u32, DBI_CTL_0_SPEC, u8, DAT_FMT_A, 3, 12>;
impl<'a> DAT_FMT_W<'a> {
#[doc = "`0`"]
#[inline(always)]
pub fn rgb111(self) -> &'a mut W {
self.variant(DAT_FMT_A::RGB111)
}
#[doc = "`1`"]
#[inline(always)]
pub fn rgb444(self) -> &'a mut W {
self.variant(DAT_FMT_A::RGB444)
}
#[doc = "`10`"]
#[inline(always)]
pub fn rgb565(self) -> &'a mut W {
self.variant(DAT_FMT_A::RGB565)
}
#[doc = "`11`"]
#[inline(always)]
pub fn rgb666(self) -> &'a mut W {
self.variant(DAT_FMT_A::RGB666)
}
#[doc = "`100`"]
#[inline(always)]
pub fn rgb888(self) -> &'a mut W {
self.variant(DAT_FMT_A::RGB888)
}
}
#[doc = "\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum DBI_INTERFACE_A {
#[doc = "0: 3 Line Interface I"]
L3I1 = 0,
#[doc = "1: 3 Line Interface II"]
L3I2 = 1,
#[doc = "2: 4 Line Interface I"]
L4I1 = 2,
#[doc = "3: 4 Line Interface II"]
L4I2 = 3,
#[doc = "4: 2 Data Lane Interface"]
D2LI = 4,
}
impl From<DBI_INTERFACE_A> for u8 {
#[inline(always)]
fn from(variant: DBI_INTERFACE_A) -> Self {
variant as _
}
}
#[doc = "Field `dbi_interface` reader - "]
pub type DBI_INTERFACE_R = crate::FieldReader<u8, DBI_INTERFACE_A>;
impl DBI_INTERFACE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<DBI_INTERFACE_A> {
match self.bits {
0 => Some(DBI_INTERFACE_A::L3I1),
1 => Some(DBI_INTERFACE_A::L3I2),
2 => Some(DBI_INTERFACE_A::L4I1),
3 => Some(DBI_INTERFACE_A::L4I2),
4 => Some(DBI_INTERFACE_A::D2LI),
_ => None,
}
}
#[doc = "Checks if the value of the field is `L3I1`"]
#[inline(always)]
pub fn is_l3i1(&self) -> bool {
*self == DBI_INTERFACE_A::L3I1
}
#[doc = "Checks if the value of the field is `L3I2`"]
#[inline(always)]
pub fn is_l3i2(&self) -> bool {
*self == DBI_INTERFACE_A::L3I2
}
#[doc = "Checks if the value of the field is `L4I1`"]
#[inline(always)]
pub fn is_l4i1(&self) -> bool {
*self == DBI_INTERFACE_A::L4I1
}
#[doc = "Checks if the value of the field is `L4I2`"]
#[inline(always)]
pub fn is_l4i2(&self) -> bool {
*self == DBI_INTERFACE_A::L4I2
}
#[doc = "Checks if the value of the field is `D2LI`"]
#[inline(always)]
pub fn is_d2li(&self) -> bool {
*self == DBI_INTERFACE_A::D2LI
}
}
#[doc = "Field `dbi_interface` writer - "]
pub type DBI_INTERFACE_W<'a> =
crate::FieldWriter<'a, u32, DBI_CTL_0_SPEC, u8, DBI_INTERFACE_A, 3, 8>;
impl<'a> DBI_INTERFACE_W<'a> {
#[doc = "3 Line Interface I"]
#[inline(always)]
pub fn l3i1(self) -> &'a mut W {
self.variant(DBI_INTERFACE_A::L3I1)
}
#[doc = "3 Line Interface II"]
#[inline(always)]
pub fn l3i2(self) -> &'a mut W {
self.variant(DBI_INTERFACE_A::L3I2)
}
#[doc = "4 Line Interface I"]
#[inline(always)]
pub fn l4i1(self) -> &'a mut W {
self.variant(DBI_INTERFACE_A::L4I1)
}
#[doc = "4 Line Interface II"]
#[inline(always)]
pub fn l4i2(self) -> &'a mut W {
self.variant(DBI_INTERFACE_A::L4I2)
}
#[doc = "2 Data Lane Interface"]
#[inline(always)]
pub fn d2li(self) -> &'a mut W {
self.variant(DBI_INTERFACE_A::D2LI)
}
}
#[doc = "RGB Source Format\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum RGB_SRC_FMT_A {
#[doc = "0: `0`"]
RGB = 0,
#[doc = "1: `1`"]
RBG = 1,
#[doc = "2: `10`"]
GRB = 2,
#[doc = "3: `11`"]
GBR = 3,
#[doc = "4: `100`"]
BRG = 4,
#[doc = "5: `101`"]
BGR = 5,
#[doc = "6: `110`"]
GRBG_0 = 6,
#[doc = "7: `111`"]
GBRG_0 = 7,
#[doc = "8: `1000`"]
GRBG_1 = 8,
#[doc = "9: `1001`"]
GBRG_1 = 9,
}
impl From<RGB_SRC_FMT_A> for u8 {
#[inline(always)]
fn from(variant: RGB_SRC_FMT_A) -> Self {
variant as _
}
}
#[doc = "Field `rgb_src_fmt` reader - RGB Source Format"]
pub type RGB_SRC_FMT_R = crate::FieldReader<u8, RGB_SRC_FMT_A>;
impl RGB_SRC_FMT_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<RGB_SRC_FMT_A> {
match self.bits {
0 => Some(RGB_SRC_FMT_A::RGB),
1 => Some(RGB_SRC_FMT_A::RBG),
2 => Some(RGB_SRC_FMT_A::GRB),
3 => Some(RGB_SRC_FMT_A::GBR),
4 => Some(RGB_SRC_FMT_A::BRG),
5 => Some(RGB_SRC_FMT_A::BGR),
6 => Some(RGB_SRC_FMT_A::GRBG_0),
7 => Some(RGB_SRC_FMT_A::GBRG_0),
8 => Some(RGB_SRC_FMT_A::GRBG_1),
9 => Some(RGB_SRC_FMT_A::GBRG_1),
_ => None,
}
}
#[doc = "Checks if the value of the field is `RGB`"]
#[inline(always)]
pub fn is_rgb(&self) -> bool {
*self == RGB_SRC_FMT_A::RGB
}
#[doc = "Checks if the value of the field is `RBG`"]
#[inline(always)]
pub fn is_rbg(&self) -> bool {
*self == RGB_SRC_FMT_A::RBG
}
#[doc = "Checks if the value of the field is `GRB`"]
#[inline(always)]
pub fn is_grb(&self) -> bool {
*self == RGB_SRC_FMT_A::GRB
}
#[doc = "Checks if the value of the field is `GBR`"]
#[inline(always)]
pub fn is_gbr(&self) -> bool {
*self == RGB_SRC_FMT_A::GBR
}
#[doc = "Checks if the value of the field is `BRG`"]
#[inline(always)]
pub fn is_brg(&self) -> bool {
*self == RGB_SRC_FMT_A::BRG
}
#[doc = "Checks if the value of the field is `BGR`"]
#[inline(always)]
pub fn is_bgr(&self) -> bool {
*self == RGB_SRC_FMT_A::BGR
}
#[doc = "Checks if the value of the field is `GRBG_0`"]
#[inline(always)]
pub fn is_grbg_0(&self) -> bool {
*self == RGB_SRC_FMT_A::GRBG_0
}
#[doc = "Checks if the value of the field is `GBRG_0`"]
#[inline(always)]
pub fn is_gbrg_0(&self) -> bool {
*self == RGB_SRC_FMT_A::GBRG_0
}
#[doc = "Checks if the value of the field is `GRBG_1`"]
#[inline(always)]
pub fn is_grbg_1(&self) -> bool {
*self == RGB_SRC_FMT_A::GRBG_1
}
#[doc = "Checks if the value of the field is `GBRG_1`"]
#[inline(always)]
pub fn is_gbrg_1(&self) -> bool {
*self == RGB_SRC_FMT_A::GBRG_1
}
}
#[doc = "Field `rgb_src_fmt` writer - RGB Source Format"]
pub type RGB_SRC_FMT_W<'a> = crate::FieldWriter<'a, u32, DBI_CTL_0_SPEC, u8, RGB_SRC_FMT_A, 4, 4>;
impl<'a> RGB_SRC_FMT_W<'a> {
#[doc = "`0`"]
#[inline(always)]
pub fn rgb(self) -> &'a mut W {
self.variant(RGB_SRC_FMT_A::RGB)
}
#[doc = "`1`"]
#[inline(always)]
pub fn rbg(self) -> &'a mut W {
self.variant(RGB_SRC_FMT_A::RBG)
}
#[doc = "`10`"]
#[inline(always)]
pub fn grb(self) -> &'a mut W {
self.variant(RGB_SRC_FMT_A::GRB)
}
#[doc = "`11`"]
#[inline(always)]
pub fn gbr(self) -> &'a mut W {
self.variant(RGB_SRC_FMT_A::GBR)
}
#[doc = "`100`"]
#[inline(always)]
pub fn brg(self) -> &'a mut W {
self.variant(RGB_SRC_FMT_A::BRG)
}
#[doc = "`101`"]
#[inline(always)]
pub fn bgr(self) -> &'a mut W {
self.variant(RGB_SRC_FMT_A::BGR)
}
#[doc = "`110`"]
#[inline(always)]
pub fn grbg_0(self) -> &'a mut W {
self.variant(RGB_SRC_FMT_A::GRBG_0)
}
#[doc = "`111`"]
#[inline(always)]
pub fn gbrg_0(self) -> &'a mut W {
self.variant(RGB_SRC_FMT_A::GBRG_0)
}
#[doc = "`1000`"]
#[inline(always)]
pub fn grbg_1(self) -> &'a mut W {
self.variant(RGB_SRC_FMT_A::GRBG_1)
}
#[doc = "`1001`"]
#[inline(always)]
pub fn gbrg_1(self) -> &'a mut W {
self.variant(RGB_SRC_FMT_A::GBRG_1)
}
}
#[doc = "Field `dum_val` reader - Dummy Cycle Value"]
pub type DUM_VAL_R = crate::BitReader<bool>;
#[doc = "Field `dum_val` writer - Dummy Cycle Value"]
pub type DUM_VAL_W<'a> = crate::BitWriter<'a, u32, DBI_CTL_0_SPEC, bool, 3>;
#[doc = "RGB Bit Order\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RGB_BO_A {
#[doc = "0: `0`"]
DATA = 0,
#[doc = "1: `1`"]
SWAP = 1,
}
impl From<RGB_BO_A> for bool {
#[inline(always)]
fn from(variant: RGB_BO_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `rgb_bo` reader - RGB Bit Order"]
pub type RGB_BO_R = crate::BitReader<RGB_BO_A>;
impl RGB_BO_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RGB_BO_A {
match self.bits {
false => RGB_BO_A::DATA,
true => RGB_BO_A::SWAP,
}
}
#[doc = "Checks if the value of the field is `DATA`"]
#[inline(always)]
pub fn is_data(&self) -> bool {
*self == RGB_BO_A::DATA
}
#[doc = "Checks if the value of the field is `SWAP`"]
#[inline(always)]
pub fn is_swap(&self) -> bool {
*self == RGB_BO_A::SWAP
} | #[doc = "`0`"]
#[inline(always)]
pub fn data(self) -> &'a mut W {
self.variant(RGB_BO_A::DATA)
}
#[doc = "`1`"]
#[inline(always)]
pub fn swap(self) -> &'a mut W {
self.variant(RGB_BO_A::SWAP)
}
}
#[doc = "Element A Position\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ELEMENT_A_POS_A {
#[doc = "0: `0`"]
_31_24 = 0,
#[doc = "1: `1`"]
_7_0 = 1,
}
impl From<ELEMENT_A_POS_A> for bool {
#[inline(always)]
fn from(variant: ELEMENT_A_POS_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `element_a_pos` reader - Element A Position"]
pub type ELEMENT_A_POS_R = crate::BitReader<ELEMENT_A_POS_A>;
impl ELEMENT_A_POS_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> ELEMENT_A_POS_A {
match self.bits {
false => ELEMENT_A_POS_A::_31_24,
true => ELEMENT_A_POS_A::_7_0,
}
}
#[doc = "Checks if the value of the field is `_31_24`"]
#[inline(always)]
pub fn is_31_24(&self) -> bool {
*self == ELEMENT_A_POS_A::_31_24
}
#[doc = "Checks if the value of the field is `_7_0`"]
#[inline(always)]
pub fn is_7_0(&self) -> bool {
*self == ELEMENT_A_POS_A::_7_0
}
}
#[doc = "Field `element_a_pos` writer - Element A Position"]
pub type ELEMENT_A_POS_W<'a> = crate::BitWriter<'a, u32, DBI_CTL_0_SPEC, ELEMENT_A_POS_A, 1>;
impl<'a> ELEMENT_A_POS_W<'a> {
#[doc = "`0`"]
#[inline(always)]
pub fn _31_24(self) -> &'a mut W {
self.variant(ELEMENT_A_POS_A::_31_24)
}
#[doc = "`1`"]
#[inline(always)]
pub fn _7_0(self) -> &'a mut W {
self.variant(ELEMENT_A_POS_A::_7_0)
}
}
#[doc = "Video Source Type\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VI_SRC_TYPE_A {
#[doc = "0: `0`"]
RGB32 = 0,
#[doc = "1: `1`"]
RGB16 = 1,
}
impl From<VI_SRC_TYPE_A> for bool {
#[inline(always)]
fn from(variant: VI_SRC_TYPE_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `vi_src_type` reader - Video Source Type"]
pub type VI_SRC_TYPE_R = crate::BitReader<VI_SRC_TYPE_A>;
impl VI_SRC_TYPE_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> VI_SRC_TYPE_A {
match self.bits {
false => VI_SRC_TYPE_A::RGB32,
true => VI_SRC_TYPE_A::RGB16,
}
}
#[doc = "Checks if the value of the field is `RGB32`"]
#[inline(always)]
pub fn is_rgb32(&self) -> bool {
*self == VI_SRC_TYPE_A::RGB32
}
#[doc = "Checks if the value of the field is `RGB16`"]
#[inline(always)]
pub fn is_rgb16(&self) -> bool {
*self == VI_SRC_TYPE_A::RGB16
}
}
#[doc = "Field `vi_src_type` writer - Video Source Type"]
pub type VI_SRC_TYPE_W<'a> = crate::BitWriter<'a, u32, DBI_CTL_0_SPEC, VI_SRC_TYPE_A, 0>;
impl<'a> VI_SRC_TYPE_W<'a> {
#[doc = "`0`"]
#[inline(always)]
pub fn rgb32(self) -> &'a mut W {
self.variant(VI_SRC_TYPE_A::RGB32)
}
#[doc = "`1`"]
#[inline(always)]
pub fn rgb16(self) -> &'a mut W {
self.variant(VI_SRC_TYPE_A::RGB16)
}
}
impl R {
#[doc = "Bit 31 - Command Type"]
#[inline(always)]
pub fn cmdt(&self) -> CMDT_R {
CMDT_R::new(((self.bits >> 31) & 1) != 0)
}
#[doc = "Bits 20:30 - Write Command Dummy Cycles"]
#[inline(always)]
pub fn wcdc(&self) -> WCDC_R {
WCDC_R::new(((self.bits >> 20) & 0x07ff) as u16)
}
#[doc = "Bit 19 - Output Data Sequence"]
#[inline(always)]
pub fn dat_seq(&self) -> DAT_SEQ_R {
DAT_SEQ_R::new(((self.bits >> 19) & 1) != 0)
}
#[doc = "Bits 16:18 - Output RGB Sequence"]
#[inline(always)]
pub fn rgb_seq(&self) -> RGB_SEQ_R {
RGB_SEQ_R::new(((self.bits >> 16) & 7) as u8)
}
#[doc = "Bit 15 - Transmit Mode"]
#[inline(always)]
pub fn tran_mod(&self) -> TRAN_MOD_R {
TRAN_MOD_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bits 12:14 - Output Data Format"]
#[inline(always)]
pub fn dat_fmt(&self) -> DAT_FMT_R {
DAT_FMT_R::new(((self.bits >> 12) & 7) as u8)
}
#[doc = "Bits 8:10"]
#[inline(always)]
pub fn dbi_interface(&self) -> DBI_INTERFACE_R {
DBI_INTERFACE_R::new(((self.bits >> 8) & 7) as u8)
}
#[doc = "Bits 4:7 - RGB Source Format"]
#[inline(always)]
pub fn rgb_src_fmt(&self) -> RGB_SRC_FMT_R {
RGB_SRC_FMT_R::new(((self.bits >> 4) & 0x0f) as u8)
}
#[doc = "Bit 3 - Dummy Cycle Value"]
#[inline(always)]
pub fn dum_val(&self) -> DUM_VAL_R {
DUM_VAL_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 2 - RGB Bit Order"]
#[inline(always)]
pub fn rgb_bo(&self) -> RGB_BO_R {
RGB_BO_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 1 - Element A Position"]
#[inline(always)]
pub fn element_a_pos(&self) -> ELEMENT_A_POS_R {
ELEMENT_A_POS_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 0 - Video Source Type"]
#[inline(always)]
pub fn vi_src_type(&self) -> VI_SRC_TYPE_R {
VI_SRC_TYPE_R::new((self.bits & 1) != 0)
}
}
impl W {
#[doc = "Bit 31 - Command Type"]
#[inline(always)]
pub fn cmdt(&mut self) -> CMDT_W {
CMDT_W::new(self)
}
#[doc = "Bits 20:30 - Write Command Dummy Cycles"]
#[inline(always)]
pub fn wcdc(&mut self) -> WCDC_W {
WCDC_W::new(self)
}
#[doc = "Bit 19 - Output Data Sequence"]
#[inline(always)]
pub fn dat_seq(&mut self) -> DAT_SEQ_W {
DAT_SEQ_W::new(self)
}
#[doc = "Bits 16:18 - Output RGB Sequence"]
#[inline(always)]
pub fn rgb_seq(&mut self) -> RGB_SEQ_W {
RGB_SEQ_W::new(self)
}
#[doc = "Bit 15 - Transmit Mode"]
#[inline(always)]
pub fn tran_mod(&mut self) -> TRAN_MOD_W {
TRAN_MOD_W::new(self)
}
#[doc = "Bits 12:14 - Output Data Format"]
#[inline(always)]
pub fn dat_fmt(&mut self) -> DAT_FMT_W {
DAT_FMT_W::new(self)
}
#[doc = "Bits 8:10"]
#[inline(always)]
pub fn dbi_interface(&mut self) -> DBI_INTERFACE_W {
DBI_INTERFACE_W::new(self)
}
#[doc = "Bits 4:7 - RGB Source Format"]
#[inline(always)]
pub fn rgb_src_fmt(&mut self) -> RGB_SRC_FMT_W {
RGB_SRC_FMT_W::new(self)
}
#[doc = "Bit 3 - Dummy Cycle Value"]
#[inline(always)]
pub fn dum_val(&mut self) -> DUM_VAL_W {
DUM_VAL_W::new(self)
}
#[doc = "Bit 2 - RGB Bit Order"]
#[inline(always)]
pub fn rgb_bo(&mut self) -> RGB_BO_W {
RGB_BO_W::new(self)
}
#[doc = "Bit 1 - Element A Position"]
#[inline(always)]
pub fn element_a_pos(&mut self) -> ELEMENT_A_POS_W {
ELEMENT_A_POS_W::new(self)
}
#[doc = "Bit 0 - Video Source Type"]
#[inline(always)]
pub fn vi_src_type(&mut self) -> VI_SRC_TYPE_W {
VI_SRC_TYPE_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "DBI Control Register 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dbi_ctl_0](index.html) module"]
pub struct DBI_CTL_0_SPEC;
impl crate::RegisterSpec for DBI_CTL_0_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [dbi_ctl_0::R](R) reader structure"]
impl crate::Readable for DBI_CTL_0_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [dbi_ctl_0::W](W) writer structure"]
impl crate::Writable for DBI_CTL_0_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets DBI_CTL_0 to value 0"]
impl crate::Resettable for DBI_CTL_0_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
} | }
#[doc = "Field `rgb_bo` writer - RGB Bit Order"]
pub type RGB_BO_W<'a> = crate::BitWriter<'a, u32, DBI_CTL_0_SPEC, RGB_BO_A, 2>;
impl<'a> RGB_BO_W<'a> { |
convert_case_test.go | package mustache
import "testing"
func Test_toSnakeCase(t *testing.T) {
tests := []struct {
want string
input string
}{
{"", ""}, | {"AaAa", "aa_aa"},
{"BatteryLifeValue", "battery_life_value"},
{"Id0Value", "id0_value"},
}
for _, test := range tests {
have := toCamelCase(test.input)
if have != test.want {
t.Errorf("input=%q:\nhave: %q\nwant: %q", test.input, have, test.want)
}
}
} | {"A", "a"}, |
main.go | package main
import (
"github.com/denverquane/automuteusbroker/broker"
"log"
"os"
)
const DefaultPort = "8123"
func main() {
redisAddr := os.Getenv("REDIS_ADDRESS")
if redisAddr == "" {
log.Fatal("No REDIS_ADDRESS specified. Exiting.")
}
port := os.Getenv("BROKER_PORT")
if port == "" {
log.Println("No BROKER_PORT provided. Defaulting to " + DefaultPort)
port = DefaultPort
}
redisUser := os.Getenv("REDIS_USER")
redisPass := os.Getenv("REDIS_PASS")
if redisUser != "" {
log.Println("Using REDIS_USER=" + redisUser)
} else {
log.Println("No REDIS_USER specified.")
}
if redisPass != "" {
log.Println("Using REDIS_PASS=<redacted>") | } else {
log.Println("No REDIS_PASS specified.")
}
msgBroker := broker.NewBroker(redisAddr, redisUser, redisPass)
msgBroker.Start(port)
} | |
ipi.rs | //! IPI (Inter-Processor Interrupt) exchange between RPU0 and RPU1
//!
//! NOTE RPU0 must start executing its program *after* RPU1 starts executing its own
//!
//! Expected output:
//!
//! ```
//! core #0
//! IRQ(ICCIAR { cpuid: 0, ackintid: 65 })
//! IPI_CH1(src=RPU1, response=0x1722)
//! ~IRQ(ICCIAR { cpuid: 0, ackintid: 65 })
//! ```
//!
//! ```
//! core #1
//! IRQ(ICCIAR { cpuid: 0, ackintid: 66 })
//! IPI_CH2(src=RPU0, request=0x2217)
//! ~IRQ(ICCIAR { cpuid: 0, ackintid: 66 })
//! ```
#![feature(proc_macro_hygiene)] // required by ufmt::uwrite!
#![no_main]
#![no_std]
const IPI_CH1_NR: u16 = 65;
const IPI_CH2_NR: u16 = 66;
use core::{mem, ops, ptr};
use arm_dcc::dprintln;
use cortex_r::gic::{ICC, ICD};
use panic_dcc as _;
use zup::IPI;
use zup_rt::{entry, interrupt};
#[entry]
fn main() -> ! {
unsafe {
dprintln!("core #{}", if cfg!(core = "0") { 0 } else { 1 });
let icc = ICC::steal();
let ipi = zup::Peripherals::steal().IPI;
// disable interrupt routing and signaling during configuration
ICC::disable();
// set priority mask to the lowest priority
icc.ICCPMR.write(248);
// enable interrupt signaling
icc.ICCICR
.write((1 << 1) /* EnableNS */ | (1 << 0) /* EnableS */);
// the ICD peripheral is shared; make sure we initialize it just once
if cfg!(core = "1") {
let icd = ICD::steal();
ICD::disable();
// unmask SPI IPI_CH1
ICD::unmask(IPI_CH1_NR);
// unmask SPI IPI_CH2
ICD::unmask(IPI_CH2_NR);
// route SPI IPI_CH1 to R5#0
icd.ICDIPTR_rw[usize::from(IPI_CH1_NR) - 32].write(1 << 0);
// route SPI IPI_CH2 to R5#1
icd.ICDIPTR_rw[usize::from(IPI_CH2_NR) - 32].write(1 << 1);
// set the priority of IPI_CH{1,2} to the second lowest priority
icd.ICDIPR[usize::from(IPI_CH1_NR)].write(240);
icd.ICDIPR[usize::from(IPI_CH2_NR)].write(240);
// enable interrupt routing
ICD::enable();
}
if cfg!(core = "0") {
// enable receiving interrupts from channel 2
ipi.ch1_ier.write(|w| w.ch2().set_bit());
// write request message
BUFFERS.write_request(Agent::RPU0, Agent::RPU1, 0x2217);
// send IPI to channel 2
ipi.ch1_trig.write(|w| w.ch2().set_bit());
} else {
// enable receiving interrupts from channel 1
ipi.ch2_ier.write(|w| w.ch1().set_bit());
}
// unmask IRQ
cortex_r::enable_irq();
loop {}
}
}
#[cfg(core = "0")]
#[interrupt]
fn | () {
unsafe {
let ipi = &*IPI::ptr();
let isr = ipi.ch1_isr.read();
if isr.ch2().bit_is_set() {
// clear interrupt bit
ipi.ch1_isr.write(|w| w.ch2().set_bit());
dprintln!(
"IPI_CH1(src=RPU1, response={})",
BUFFERS.read_response::<i32>(Agent::RPU0, Agent::RPU1)
);
} else {
dprintln!("IPI_CH1(isr={:#?})", isr.bits());
}
}
}
#[cfg(core = "1")]
#[interrupt]
fn IPI_CH2() {
unsafe {
let ipi = &*IPI::ptr();
let isr = ipi.ch2_isr.read();
if isr.ch1().bit_is_set() {
// clear interrupt bit
ipi.ch2_isr.write(|w| w.ch1().set_bit());
dprintln!(
"IPI_CH2(src=RPU0, request={})",
BUFFERS.read_request::<i32>(Agent::RPU1, Agent::RPU0)
);
// send a response
// - write message
BUFFERS.write_response(Agent::RPU1, Agent::RPU0, 0x1722);
// - send IPI to channel 1
ipi.ch2_trig.write(|w| w.ch1().set_bit());
} else {
unimplemented!()
}
}
}
// NOTE unsynchronized access
struct BUFFERS;
impl ops::Deref for BUFFERS {
type Target = Buffers;
fn deref(&self) -> &Self::Target {
unsafe { &*(0xFF99_0000 as *const _) }
}
}
impl ops::DerefMut for BUFFERS {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *(0xFF99_0000 as *mut _) }
}
}
#[derive(Clone, Copy)]
enum Agent {
// actually this is agent 2 (agent numbering starts at 0)
RPU0 = 1,
// actually this is agent 3 (agent numbering starts at 0)
RPU1 = 2,
}
#[repr(transparent)]
struct Buffers([[Buffer; 8]; 8]);
impl Buffers {
#[allow(dead_code)]
unsafe fn read_response<T>(&self, i_am: Agent, requestee: Agent) -> T
where
T: Copy,
{
self.0[i_am as usize][requestee as usize].get_response()
}
#[allow(dead_code)]
unsafe fn read_request<T>(&self, i_am: Agent, requester: Agent) -> T
where
T: Copy,
{
self.0[requester as usize][i_am as usize].get_request()
}
#[allow(dead_code)]
fn write_response<T>(&mut self, i_am: Agent, requester: Agent, value: T)
where
T: Copy,
{
self.0[requester as usize][i_am as usize].set_response(value)
}
fn write_request<T>(&mut self, i_am: Agent, requestee: Agent, value: T)
where
T: Copy,
{
self.0[i_am as usize][requestee as usize].set_request(value)
}
}
#[repr(C)]
#[derive(Debug)]
struct Buffer {
request: [u8; 32],
response: [u8; 32],
}
impl Buffer {
fn set_request<T>(&mut self, value: T)
where
T: Copy,
{
unsafe {
assert!(mem::size_of::<T>() <= 32);
assert!(mem::align_of::<T>() <= 4);
ptr::write_volatile(self.request.as_mut_ptr() as *mut T, value);
}
}
#[allow(dead_code)]
fn set_response<T>(&mut self, value: T)
where
T: Copy,
{
unsafe {
assert!(mem::size_of::<T>() <= 32);
assert!(mem::align_of::<T>() <= 4);
ptr::write_volatile(self.response.as_mut_ptr() as *mut T, value);
}
}
#[allow(dead_code)]
unsafe fn get_request<T>(&self) -> T
where
T: Copy,
{
assert!(mem::size_of::<T>() <= 32);
assert!(mem::align_of::<T>() <= 4);
ptr::read_volatile(self.request.as_ptr() as *const T)
}
#[allow(dead_code)]
unsafe fn get_response<T>(&self) -> T
where
T: Copy,
{
assert!(mem::size_of::<T>() <= 32);
assert!(mem::align_of::<T>() <= 4);
ptr::read_volatile(self.response.as_ptr() as *const T)
}
}
| IPI_CH1 |
neutron_tests.py | # Copyright 2012 NEC Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
import uuid
from mox3.mox import IsA # noqa
from django import http
from django.test.utils import override_settings
from neutronclient.common import exceptions as neutron_exc
from openstack_dashboard import api
from openstack_dashboard import policy
from openstack_dashboard.test import helpers as test
class NeutronApiTests(test.APITestCase):
def test_network_list(self):
networks = {'networks': self.api_networks.list()}
subnets = {'subnets': self.api_subnets.list()}
neutronclient = self.stub_neutronclient()
neutronclient.list_networks().AndReturn(networks)
neutronclient.list_subnets().AndReturn(subnets)
self.mox.ReplayAll()
ret_val = api.neutron.network_list(self.request)
for n in ret_val:
self.assertIsInstance(n, api.neutron.Network)
@test.create_stubs({api.neutron: ('network_list',
'subnet_list')})
def _test_network_list_for_tenant(self, include_external):
all_networks = self.networks.list()
tenant_id = '1'
api.neutron.network_list(
IsA(http.HttpRequest),
tenant_id=tenant_id,
shared=False).AndReturn([
network for network in all_networks
if network['tenant_id'] == tenant_id
])
api.neutron.network_list(
IsA(http.HttpRequest),
shared=True).AndReturn([
network for network in all_networks
if network.get('shared')
])
if include_external:
api.neutron.network_list(
IsA(http.HttpRequest),
**{'router:external': True}).AndReturn([
network for network in all_networks
if network.get('router:external')
])
self.mox.ReplayAll()
ret_val = api.neutron.network_list_for_tenant(
self.request, tenant_id,
include_external=include_external)
expected = [n for n in all_networks
if (n['tenant_id'] == tenant_id or
n['shared'] or
(include_external and n['router:external']))]
self.assertEqual(set(n.id for n in expected),
set(n.id for n in ret_val))
def test_network_list_for_tenant(self):
self._test_network_list_for_tenant(include_external=False)
def test_network_list_for_tenant_with_external(self):
self._test_network_list_for_tenant(include_external=True)
def test_network_get(self):
network = {'network': self.api_networks.first()}
subnet = {'subnet': self.api_subnets.first()}
network_id = self.api_networks.first()['id']
subnet_id = self.api_networks.first()['subnets'][0]
neutronclient = self.stub_neutronclient()
neutronclient.show_network(network_id).AndReturn(network)
neutronclient.show_subnet(subnet_id).AndReturn(subnet)
self.mox.ReplayAll()
ret_val = api.neutron.network_get(self.request, network_id)
self.assertIsInstance(ret_val, api.neutron.Network)
def _test_network_create(self, with_n1kv=False):
network = {'network': self.api_networks.first()}
form_data = {'network': {'name': 'net1',
'tenant_id': self.request.user.project_id}}
neutronclient = self.stub_neutronclient()
if with_n1kv:
n1kv_profile = 'n1kv:profile'
test_net_profile = 'test_net_profile'
network['network'][n1kv_profile] = test_net_profile
form_data['network'][n1kv_profile] = test_net_profile
neutronclient.create_network(body=form_data).AndReturn(network)
self.mox.ReplayAll()
ret_val = api.neutron.network_create(
self.request,
name='net1',
net_profile_id=test_net_profile)
# assert that when 'net_profile_id' is passed as a param to
# network_create function, 'n1kv:profile' is appended as a key to
# the returned network dictionary with value TEST_NET_PROFILE
self.assertEqual(test_net_profile, ret_val[n1kv_profile])
# also assert that 'net_profile_id' isn't there in the returned
# network dictionary
self.assertNotIn('net_profile_id', [k for k, _ in ret_val.items()])
else:
neutronclient.create_network(body=form_data).AndReturn(network)
self.mox.ReplayAll()
ret_val = api.neutron.network_create(self.request, name='net1')
self.assertIsInstance(ret_val, api.neutron.Network)
def test_network_create(self):
|
def test_network_create_with_net_profile(self):
self._test_network_create(with_n1kv=True)
def test_network_update(self):
network = {'network': self.api_networks.first()}
network_id = self.api_networks.first()['id']
neutronclient = self.stub_neutronclient()
form_data = {'network': {'name': 'net1'}}
neutronclient.update_network(network_id, body=form_data)\
.AndReturn(network)
self.mox.ReplayAll()
ret_val = api.neutron.network_update(self.request, network_id,
name='net1')
self.assertIsInstance(ret_val, api.neutron.Network)
def test_network_delete(self):
network_id = self.api_networks.first()['id']
neutronclient = self.stub_neutronclient()
neutronclient.delete_network(network_id)
self.mox.ReplayAll()
api.neutron.network_delete(self.request, network_id)
def test_get_network_ip_availability(self):
network = {'network': self.api_networks.first()}
mock_ip_availability = self.ip_availability.get()
neutronclient = self.stub_neutronclient()
neutronclient.show_network_ip_availability(network).\
AndReturn(mock_ip_availability)
self.mox.ReplayAll()
ret_val = api.neutron.show_network_ip_availability(self.request,
network)
self.assertIsInstance(ret_val, dict)
def test_subnet_network_ip_availability(self):
network = {'network': self.api_networks.first()}
mock_ip_availability = self.ip_availability.get()
neutronclient = self.stub_neutronclient()
neutronclient.show_network_ip_availability(network).\
AndReturn(mock_ip_availability)
self.mox.ReplayAll()
ip_availability = api.neutron. \
show_network_ip_availability(self.request, network)
availabilities = ip_availability.get("network_ip_availability",
{})
ret_val = availabilities.get("subnet_ip_availability", [])
self.assertIsInstance(ret_val, list)
def test_subnet_list(self):
subnets = {'subnets': self.api_subnets.list()}
neutronclient = self.stub_neutronclient()
neutronclient.list_subnets().AndReturn(subnets)
self.mox.ReplayAll()
ret_val = api.neutron.subnet_list(self.request)
for n in ret_val:
self.assertIsInstance(n, api.neutron.Subnet)
def test_subnet_get(self):
subnet = {'subnet': self.api_subnets.first()}
subnet_id = self.api_subnets.first()['id']
neutronclient = self.stub_neutronclient()
neutronclient.show_subnet(subnet_id).AndReturn(subnet)
self.mox.ReplayAll()
ret_val = api.neutron.subnet_get(self.request, subnet_id)
self.assertIsInstance(ret_val, api.neutron.Subnet)
def test_subnet_create(self):
subnet_data = self.api_subnets.first()
params = {'network_id': subnet_data['network_id'],
'tenant_id': subnet_data['tenant_id'],
'name': subnet_data['name'],
'cidr': subnet_data['cidr'],
'ip_version': subnet_data['ip_version'],
'gateway_ip': subnet_data['gateway_ip']}
neutronclient = self.stub_neutronclient()
neutronclient.create_subnet(body={'subnet': params})\
.AndReturn({'subnet': subnet_data})
self.mox.ReplayAll()
ret_val = api.neutron.subnet_create(self.request, **params)
self.assertIsInstance(ret_val, api.neutron.Subnet)
def test_subnet_update(self):
subnet_data = self.api_subnets.first()
subnet_id = subnet_data['id']
params = {'name': subnet_data['name'],
'gateway_ip': subnet_data['gateway_ip']}
neutronclient = self.stub_neutronclient()
neutronclient.update_subnet(subnet_id, body={'subnet': params})\
.AndReturn({'subnet': subnet_data})
self.mox.ReplayAll()
ret_val = api.neutron.subnet_update(self.request, subnet_id, **params)
self.assertIsInstance(ret_val, api.neutron.Subnet)
def test_subnet_delete(self):
subnet_id = self.api_subnets.first()['id']
neutronclient = self.stub_neutronclient()
neutronclient.delete_subnet(subnet_id)
self.mox.ReplayAll()
api.neutron.subnet_delete(self.request, subnet_id)
def test_subnetpool_list(self):
subnetpools = {'subnetpools': self.api_subnetpools.list()}
neutronclient = self.stub_neutronclient()
neutronclient.list_subnetpools().AndReturn(subnetpools)
self.mox.ReplayAll()
ret_val = api.neutron.subnetpool_list(self.request)
for n in ret_val:
self.assertIsInstance(n, api.neutron.SubnetPool)
def test_subnetpool_get(self):
subnetpool = {'subnetpool': self.api_subnetpools.first()}
subnetpool_id = self.api_subnetpools.first()['id']
neutronclient = self.stub_neutronclient()
neutronclient.show_subnetpool(subnetpool_id).AndReturn(subnetpool)
self.mox.ReplayAll()
ret_val = api.neutron.subnetpool_get(self.request, subnetpool_id)
self.assertIsInstance(ret_val, api.neutron.SubnetPool)
def test_subnetpool_create(self):
subnetpool_data = self.api_subnetpools.first()
params = {'name': subnetpool_data['name'],
'prefixes': subnetpool_data['prefixes'],
'tenant_id': subnetpool_data['tenant_id']}
neutronclient = self.stub_neutronclient()
neutronclient.create_subnetpool(body={'subnetpool': params})\
.AndReturn({'subnetpool': subnetpool_data})
self.mox.ReplayAll()
ret_val = api.neutron.subnetpool_create(self.request, **params)
self.assertIsInstance(ret_val, api.neutron.SubnetPool)
def test_subnetpool_update(self):
subnetpool_data = self.api_subnetpools.first()
subnetpool_id = subnetpool_data['id']
params = {'name': subnetpool_data['name'],
'prefixes': subnetpool_data['prefixes']}
neutronclient = self.stub_neutronclient()
neutronclient.update_subnetpool(subnetpool_id, body={'subnetpool': params})\
.AndReturn({'subnetpool': subnetpool_data})
self.mox.ReplayAll()
ret_val = api.neutron.subnetpool_update(self.request, subnetpool_id,
**params)
self.assertIsInstance(ret_val, api.neutron.SubnetPool)
def test_subnetpool_delete(self):
subnetpool_id = self.api_subnetpools.first()['id']
neutronclient = self.stub_neutronclient()
neutronclient.delete_subnetpool(subnetpool_id)
self.mox.ReplayAll()
api.neutron.subnetpool_delete(self.request, subnetpool_id)
def test_port_list(self):
ports = {'ports': self.api_ports.list()}
neutronclient = self.stub_neutronclient()
neutronclient.list_ports().AndReturn(ports)
self.mox.ReplayAll()
ret_val = api.neutron.port_list(self.request)
for p in ret_val:
self.assertIsInstance(p, api.neutron.Port)
def test_port_get(self):
port = {'port': self.api_ports.first()}
port_id = self.api_ports.first()['id']
neutronclient = self.stub_neutronclient()
neutronclient.show_port(port_id).AndReturn(port)
self.mox.ReplayAll()
ret_val = api.neutron.port_get(self.request, port_id)
self.assertIsInstance(ret_val, api.neutron.Port)
def _test_port_create(self, with_n1kv=False):
port = {'port': self.api_ports.first()}
params = {'network_id': port['port']['network_id'],
'tenant_id': port['port']['tenant_id'],
'name': port['port']['name'],
'device_id': port['port']['device_id']}
neutronclient = self.stub_neutronclient()
if with_n1kv:
n1kv_profile = 'n1kv:profile'
test_policy_profile = 'test_policy_profile'
port['port'][n1kv_profile] = test_policy_profile
body = {k: v for (k, v) in params.items()}
body[n1kv_profile] = port['port'][n1kv_profile]
neutronclient.create_port(body={'port': body}).AndReturn(port)
self.mox.ReplayAll()
ret_val = api.neutron.port_create(
self.request,
policy_profile_id=test_policy_profile,
**params)
# assert that when 'policy_profile_id' is passed as a param to
# port_create function, 'n1kv:profile' is appended as a key to the
# returned port dictionary with value TEST_POLICY_PROFILE
self.assertEqual(test_policy_profile, ret_val[n1kv_profile])
# also assert that 'policy_profile_id' isn't there in the returned
# port dictionary
self.assertNotIn('policy_profile_id',
[k for k, _ in ret_val.items()])
else:
neutronclient.create_port(body={'port': params}).AndReturn(port)
self.mox.ReplayAll()
ret_val = api.neutron.port_create(self.request, **params)
self.assertIsInstance(ret_val, api.neutron.Port)
self.assertEqual(api.neutron.Port(port['port']).id, ret_val.id)
def test_port_create(self):
self._test_port_create()
def test_port_create_with_policy_profile(self):
self._test_port_create(with_n1kv=True)
def test_port_update(self):
port_data = self.api_ports.first()
port_id = port_data['id']
params = {'name': port_data['name'],
'device_id': port_data['device_id']}
neutronclient = self.stub_neutronclient()
neutronclient.update_port(port_id, body={'port': params})\
.AndReturn({'port': port_data})
self.mox.ReplayAll()
ret_val = api.neutron.port_update(self.request, port_id, **params)
self.assertIsInstance(ret_val, api.neutron.Port)
self.assertEqual(api.neutron.Port(port_data).id, ret_val.id)
def test_port_delete(self):
port_id = self.api_ports.first()['id']
neutronclient = self.stub_neutronclient()
neutronclient.delete_port(port_id)
self.mox.ReplayAll()
api.neutron.port_delete(self.request, port_id)
def test_router_list(self):
routers = {'routers': self.api_routers.list()}
neutronclient = self.stub_neutronclient()
neutronclient.list_routers().AndReturn(routers)
self.mox.ReplayAll()
ret_val = api.neutron.router_list(self.request)
for n in ret_val:
self.assertIsInstance(n, api.neutron.Router)
def test_router_get(self):
router = {'router': self.api_routers.first()}
router_id = self.api_routers.first()['id']
neutronclient = self.stub_neutronclient()
neutronclient.show_router(router_id).AndReturn(router)
self.mox.ReplayAll()
ret_val = api.neutron.router_get(self.request, router_id)
self.assertIsInstance(ret_val, api.neutron.Router)
def test_router_create(self):
router = {'router': self.api_routers.first()}
neutronclient = self.stub_neutronclient()
form_data = {'router': {'name': 'router1',
'tenant_id': self.request.user.project_id}}
neutronclient.create_router(body=form_data).AndReturn(router)
self.mox.ReplayAll()
ret_val = api.neutron.router_create(self.request, name='router1')
self.assertIsInstance(ret_val, api.neutron.Router)
def test_router_delete(self):
router_id = self.api_routers.first()['id']
neutronclient = self.stub_neutronclient()
neutronclient.delete_router(router_id)
self.mox.ReplayAll()
api.neutron.router_delete(self.request, router_id)
def test_router_add_interface(self):
subnet_id = self.api_subnets.first()['id']
router_id = self.api_routers.first()['id']
neutronclient = self.stub_neutronclient()
form_data = {'subnet_id': subnet_id}
neutronclient.add_interface_router(
router_id, form_data).AndReturn(None)
self.mox.ReplayAll()
api.neutron.router_add_interface(
self.request, router_id, subnet_id=subnet_id)
def test_router_remove_interface(self):
router_id = self.api_routers.first()['id']
fake_port = self.api_ports.first()['id']
neutronclient = self.stub_neutronclient()
neutronclient.remove_interface_router(
router_id, {'port_id': fake_port})
self.mox.ReplayAll()
api.neutron.router_remove_interface(
self.request, router_id, port_id=fake_port)
@test.create_stubs({api.neutron: ('is_extension_supported',)})
def test_is_extension_supported(self):
api.neutron.is_extension_supported(self.request, "quotas")\
.AndReturn(True)
api.neutron.is_extension_supported(self.request, "doesntexist") \
.AndReturn(False)
self.mox.ReplayAll()
self.assertTrue(
api.neutron.is_extension_supported(self.request, 'quotas'))
self.assertFalse(
api.neutron.is_extension_supported(self.request, 'doesntexist'))
def test_router_static_route_list(self):
router = {'router': self.api_routers_with_routes.first()}
router_id = self.api_routers_with_routes.first()['id']
neutronclient = self.stub_neutronclient()
neutronclient.show_router(router_id).AndReturn(router)
self.mox.ReplayAll()
ret_val = api.neutron.router_static_route_list(self.request, router_id)
self.assertIsInstance(ret_val[0], api.neutron.RouterStaticRoute)
def test_router_static_route_remove(self):
router = {'router': self.api_routers_with_routes.first()}
router_id = self.api_routers_with_routes.first()['id']
post_router = copy.deepcopy(router)
route = api.neutron.RouterStaticRoute(post_router['router']
['routes'].pop())
neutronclient = self.stub_neutronclient()
neutronclient.show_router(router_id).AndReturn(router)
body = {'router': {'routes': post_router['router']['routes']}}
neutronclient.update_router(router_id, body=body)\
.AndReturn(post_router)
self.mox.ReplayAll()
api.neutron.router_static_route_remove(self.request,
router_id, route.id)
def test_router_static_route_add(self):
router = {'router': self.api_routers_with_routes.first()}
router_id = self.api_routers_with_routes.first()['id']
post_router = copy.deepcopy(router)
route = {'nexthop': '10.0.0.5', 'destination': '40.0.1.0/24'}
post_router['router']['routes'].insert(0, route)
body = {'router': {'routes': post_router['router']['routes']}}
neutronclient = self.stub_neutronclient()
neutronclient.show_router(router_id).AndReturn(router)
neutronclient.update_router(router_id, body=body)\
.AndReturn(post_router)
self.mox.ReplayAll()
api.neutron.router_static_route_add(self.request, router_id, route)
# NOTE(amotoki): "dvr" permission tests check most of
# get_feature_permission features.
# These tests are not specific to "dvr" extension.
# Please be careful if you drop "dvr" extension in future.
@override_settings(OPENSTACK_NEUTRON_NETWORK={'enable_distributed_router':
True},
POLICY_CHECK_FUNCTION=None)
@test.create_stubs({api.neutron: ('is_extension_supported',)})
def _test_get_dvr_permission_dvr_supported(self, dvr_enabled):
api.neutron.is_extension_supported(self.request, 'dvr').\
AndReturn(dvr_enabled)
self.mox.ReplayAll()
self.assertEqual(dvr_enabled,
api.neutron.get_feature_permission(self.request,
'dvr', 'get'))
def test_get_dvr_permission_dvr_supported(self):
self._test_get_dvr_permission_dvr_supported(dvr_enabled=True)
def test_get_dvr_permission_dvr_not_supported(self):
self._test_get_dvr_permission_dvr_supported(dvr_enabled=False)
@override_settings(OPENSTACK_NEUTRON_NETWORK={'enable_distributed_router':
True},
POLICY_CHECK_FUNCTION=policy.check)
@test.create_stubs({api.neutron: ('is_extension_supported',)})
def _test_get_dvr_permission_with_policy_check(self, policy_check_allowed,
operation):
self.mox.StubOutWithMock(policy, 'check')
if operation == "create":
role = (("network", "create_router:distributed"),)
elif operation == "get":
role = (("network", "get_router:distributed"),)
policy.check(role, self.request).AndReturn(policy_check_allowed)
if policy_check_allowed:
api.neutron.is_extension_supported(self.request, 'dvr').\
AndReturn(policy_check_allowed)
self.mox.ReplayAll()
self.assertEqual(policy_check_allowed,
api.neutron.get_feature_permission(self.request,
'dvr', operation))
def test_get_dvr_permission_with_policy_check_allowed(self):
self._test_get_dvr_permission_with_policy_check(True, "get")
def test_get_dvr_permission_with_policy_check_disallowed(self):
self._test_get_dvr_permission_with_policy_check(False, "get")
def test_get_dvr_permission_create_with_policy_check_allowed(self):
self._test_get_dvr_permission_with_policy_check(True, "create")
def test_get_dvr_permission_create_with_policy_check_disallowed(self):
self._test_get_dvr_permission_with_policy_check(False, "create")
@override_settings(OPENSTACK_NEUTRON_NETWORK={'enable_distributed_router':
False})
def test_get_dvr_permission_dvr_disabled_by_config(self):
self.assertFalse(api.neutron.get_feature_permission(self.request,
'dvr', 'get'))
@override_settings(OPENSTACK_NEUTRON_NETWORK={'enable_distributed_router':
True},
POLICY_CHECK_FUNCTION=policy.check)
def test_get_dvr_permission_dvr_unsupported_operation(self):
self.assertRaises(ValueError,
api.neutron.get_feature_permission,
self.request, 'dvr', 'unSupported')
@override_settings(OPENSTACK_NEUTRON_NETWORK={})
def test_get_dvr_permission_dvr_default_config(self):
self.assertFalse(api.neutron.get_feature_permission(self.request,
'dvr', 'get'))
@override_settings(OPENSTACK_NEUTRON_NETWORK={})
def test_get_dvr_permission_router_ha_default_config(self):
self.assertFalse(api.neutron.get_feature_permission(self.request,
'l3-ha', 'get'))
# NOTE(amotoki): Most of get_feature_permission are checked by "dvr" check
# above. l3-ha check only checks l3-ha specific code.
@override_settings(OPENSTACK_NEUTRON_NETWORK={'enable_ha_router': True},
POLICY_CHECK_FUNCTION=policy.check)
@test.create_stubs({api.neutron: ('is_extension_supported', )})
def _test_get_router_ha_permission_with_policy_check(self, ha_enabled):
self.mox.StubOutWithMock(policy, 'check')
role = (("network", "create_router:ha"),)
policy.check(role, self.request).AndReturn(True)
api.neutron.is_extension_supported(self.request, 'l3-ha')\
.AndReturn(ha_enabled)
self.mox.ReplayAll()
self.assertEqual(ha_enabled,
api.neutron.get_feature_permission(self.request,
'l3-ha', 'create'))
def test_get_router_ha_permission_with_l3_ha_extension(self):
self._test_get_router_ha_permission_with_policy_check(True)
def test_get_router_ha_permission_without_l3_ha_extension(self):
self._test_get_router_ha_permission_with_policy_check(False)
def test_list_resources_with_long_filters(self):
# In this tests, port_list is called with id=[10 port ID]
# filter. It generates about 40*10 char length URI.
# Each port ID is converted to "id=<UUID>&" in URI and
# it means 40 chars (len(UUID)=36).
# If excess length is 220, it means 400-220=180 chars
# can be sent in the first request.
# As a result three API calls with 4, 4, 2 port ID
# are expected.
ports = [{'id': str(uuid.uuid4()),
'name': 'port%s' % i,
'admin_state_up': True}
for i in range(10)]
port_ids = [port['id'] for port in ports]
neutronclient = self.stub_neutronclient()
uri_len_exc = neutron_exc.RequestURITooLong(excess=220)
neutronclient.list_ports(id=port_ids).AndRaise(uri_len_exc)
for i in range(0, 10, 4):
neutronclient.list_ports(id=port_ids[i:i + 4]) \
.AndReturn({'ports': ports[i:i + 4]})
self.mox.ReplayAll()
ret_val = api.neutron.list_resources_with_long_filters(
api.neutron.port_list, 'id', port_ids,
request=self.request)
self.assertEqual(10, len(ret_val))
self.assertEqual(port_ids, [p.id for p in ret_val])
| self._test_network_create() |
message.rs | #![allow(clippy::large_enum_variant)]
use serde::{Deserialize, Serialize};
use crate::types::{
chat::{ChatKind, PublicChatKind},
Animation, Audio, Chat, ChatPublic, Contact, Dice, Document, Game, InlineKeyboardMarkup,
Invoice, Location, MessageEntity, PassportData, PhotoSize, Poll, PublicChatChannel,
PublicChatSupergroup, Sticker, SuccessfulPayment, True, User, Venue, Video, VideoNote, Voice,
};
/// This object represents a message.
///
/// [The official docs](https://core.telegram.org/bots/api#message).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Message {
/// Unique message identifier inside this chat.
#[serde(rename = "message_id")]
pub id: i32,
/// Date the message was sent in Unix time.
pub date: i32,
/// Conversation the message belongs to.
pub chat: Chat,
/// Bot through which the message was sent.
pub via_bot: Option<User>,
#[serde(flatten)]
pub kind: MessageKind,
}
impl Message {
pub fn new(id: i32, date: i32, chat: Chat, kind: MessageKind) -> Self {
Self { id, date, chat, kind, via_bot: None }
}
pub fn id(mut self, val: i32) -> Self {
self.id = val;
self
}
pub fn date(mut self, val: i32) -> Self {
self.date = val;
self
}
pub fn chat(mut self, val: Chat) -> Self {
self.chat = val;
self
}
pub fn kind(mut self, val: MessageKind) -> Self {
self.kind = val;
self
}
pub fn via_bot(mut self, val: User) -> Self {
self.via_bot = Some(val);
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum MessageKind {
Common(MessageCommon),
NewChatMembers(MessageNewChatMembers),
LeftChatMember(MessageLeftChatMember),
NewChatTitle(MessageNewChatTitle),
NewChatPhoto(MessageNewChatPhoto),
DeleteChatPhoto(MessageDeleteChatPhoto),
GroupChatCreated(MessageGroupChatCreated),
SupergroupChatCreated(MessageSupergroupChatCreated),
ChannelChatCreated(MessageChannelChatCreated),
Migrate(MessageMigrate),
Pinned(MessagePinned),
Invoice(MessageInvoice),
SuccessfulPayment(MessageSuccessfulPayment),
ConnectedWebsite(MessageConnectedWebsite),
PassportData(MessagePassportData),
Dice(MessageDice),
}
#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageCommon {
/// Sender, empty for messages sent to channels.
pub from: Option<User>,
#[serde(flatten)]
pub forward_kind: ForwardKind,
/// Date the message was last edited in Unix time.
pub edit_date: Option<i32>,
#[serde(flatten)]
pub media_kind: MediaKind,
/// Inline keyboard attached to the message. `login_url` buttons are
/// represented as ordinary `url` buttons.
pub reply_markup: Option<InlineKeyboardMarkup>,
}
impl MessageCommon {
pub fn new(forward_kind: ForwardKind, media_kind: MediaKind) -> Self {
Self { from: None, forward_kind, edit_date: None, media_kind, reply_markup: None }
}
pub fn from(mut self, val: User) -> Self {
self.from = Some(val);
self
}
pub fn forward_kind(mut self, val: ForwardKind) -> Self {
self.forward_kind = val;
self
}
pub fn edit_date(mut self, val: i32) -> Self {
self.edit_date = Some(val);
self
}
pub fn media_kind(mut self, val: MediaKind) -> Self {
self.media_kind = val;
self
}
pub fn reply_markup(mut self, val: InlineKeyboardMarkup) -> Self {
self.reply_markup = Some(val);
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageNewChatMembers {
/// New members that were added to the group or supergroup and
/// information about them (the bot itself may be one of these
/// members).
pub new_chat_members: Vec<User>,
}
impl MessageNewChatMembers {
pub fn new<N>(new_chat_members: N) -> Self
where
N: Into<Vec<User>>,
{
Self { new_chat_members: new_chat_members.into() }
}
pub fn new_chat_members<N>(mut self, val: N) -> Self
where
N: Into<Vec<User>>,
{
self.new_chat_members = val.into();
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageLeftChatMember {
/// A member was removed from the group, information about them (this
/// member may be the bot itself).
pub left_chat_member: User,
}
impl MessageLeftChatMember {
pub fn new<N>(left_chat_member: N) -> Self
where
N: Into<User>,
{
Self { left_chat_member: left_chat_member.into() }
}
pub fn left_chat_member<N>(mut self, val: N) -> Self
where
N: Into<User>,
{
self.left_chat_member = val.into();
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageNewChatTitle {
/// A chat title was changed to this value.
pub new_chat_title: String,
}
impl MessageNewChatTitle {
pub fn new<N>(new_chat_title: N) -> Self
where
N: Into<String>,
{
Self { new_chat_title: new_chat_title.into() }
}
pub fn new_chat_title<N>(mut self, val: N) -> Self
where
N: Into<String>,
{
self.new_chat_title = val.into();
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageNewChatPhoto {
/// A chat photo was change to this value.
pub new_chat_photo: Vec<PhotoSize>,
}
impl MessageNewChatPhoto {
pub fn new<N>(new_chat_photo: N) -> Self
where
N: Into<Vec<PhotoSize>>,
{
Self { new_chat_photo: new_chat_photo.into() }
}
pub fn new_chat_photo<N>(mut self, val: N) -> Self
where
N: Into<Vec<PhotoSize>>,
{
self.new_chat_photo = val.into();
self
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageDeleteChatPhoto {
/// Service message: the chat photo was deleted.
pub delete_chat_photo: True,
}
impl MessageDeleteChatPhoto {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageGroupChatCreated {
/// Service message: the group has been created.
pub group_chat_created: True,
}
impl MessageGroupChatCreated {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageSupergroupChatCreated {
/// Service message: the supergroup has been created. This field can‘t
/// be received in a message coming through updates, because bot can’t
/// be a member of a supergroup when it is created. It can only be
/// found in `reply_to_message` if someone replies to a very first
/// message in a directly created supergroup.
pub supergroup_chat_created: True,
}
impl MessageSupergroupChatCreated {
pub fn new() -> Self {
Self::default() |
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageChannelChatCreated {
/// Service message: the channel has been created. This field can‘t be
/// received in a message coming through updates, because bot can’t be
/// a member of a channel when it is created. It can only be found in
/// `reply_to_message` if someone replies to a very first message in a
/// channel.
pub channel_chat_created: True,
}
impl MessageChannelChatCreated {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageMigrate {
/// The group has been migrated to a supergroup with the specified
/// identifier. This number may be greater than 32 bits and some
/// programming languages may have difficulty/silent defects in
/// interpreting it. But it is smaller than 52 bits, so a signed 64 bit
/// integer or double-precision float type are safe for storing this
/// identifier.
pub migrate_to_chat_id: i64,
/// The supergroup has been migrated from a group with the specified
/// identifier. This number may be greater than 32 bits and some
/// programming languages may have difficulty/silent defects in
/// interpreting it. But it is smaller than 52 bits, so a signed 64 bit
/// integer or double-precision float type are safe for storing this
/// identifier.
pub migrate_from_chat_id: i64,
}
impl MessageMigrate {
pub fn new(migrate_to_chat_id: i64, migrate_from_chat_id: i64) -> Self {
Self { migrate_to_chat_id, migrate_from_chat_id }
}
pub fn migrate_to_chat_id(mut self, val: i64) -> Self {
self.migrate_to_chat_id = val;
self
}
pub fn migrate_from_chat_id(mut self, val: i64) -> Self {
self.migrate_from_chat_id = val;
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessagePinned {
/// Specified message was pinned. Note that the Message object in this
/// field will not contain further `reply_to_message` fields even if it
/// is itself a reply.
#[serde(rename = "pinned_message")]
pub pinned: Box<Message>,
}
impl MessagePinned {
pub fn new(pinned: Message) -> Self {
Self { pinned: Box::new(pinned) }
}
pub fn pinned(mut self, val: Message) -> Self {
self.pinned = Box::new(val);
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageInvoice {
/// Message is an invoice for a [payment], information about the
/// invoice. [More about payments »].
///
/// [payment]: https://core.telegram.org/bots/api#payments
/// [More about payments »]: https://core.telegram.org/bots/api#payments
pub invoice: Invoice,
}
impl MessageInvoice {
pub fn new(invoice: Invoice) -> Self {
Self { invoice }
}
pub fn invoice(mut self, val: Invoice) -> Self {
self.invoice = val;
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageSuccessfulPayment {
/// Message is a service message about a successful payment,
/// information about the payment. [More about payments »].
///
/// [More about payments »]: https://core.telegram.org/bots/api#payments
pub successful_payment: SuccessfulPayment,
}
impl MessageSuccessfulPayment {
pub fn new(successful_payment: SuccessfulPayment) -> Self {
Self { successful_payment }
}
pub fn successful_payment(mut self, val: SuccessfulPayment) -> Self {
self.successful_payment = val;
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageConnectedWebsite {
/// The domain name of the website on which the user has logged in.
/// [More about Telegram Login »].
///
/// [More about Telegram Login »]: https://core.telegram.org/widgets/login
pub connected_website: String,
}
impl MessageConnectedWebsite {
pub fn new<S>(connected_website: S) -> Self
where
S: Into<String>,
{
Self { connected_website: connected_website.into() }
}
pub fn connected_website<S>(mut self, val: S) -> Self
where
S: Into<String>,
{
self.connected_website = val.into();
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessagePassportData {
/// Telegram Passport data.
pub passport_data: PassportData,
}
impl MessagePassportData {
pub fn new(passport_data: PassportData) -> Self {
Self { passport_data }
}
pub fn passport_data(mut self, val: PassportData) -> Self {
self.passport_data = val;
self
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ForwardedFrom {
#[serde(rename = "forward_from")]
User(User),
#[serde(rename = "forward_sender_name")]
SenderName(String),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum ForwardKind {
Channel(ForwardChannel),
NonChannel(ForwardNonChannel),
Origin(ForwardOrigin),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ForwardChannel {
#[serde(rename = "forward_date")]
pub date: i32,
#[serde(rename = "forward_from_chat")]
pub chat: Chat,
#[serde(rename = "forward_from_message_id")]
pub message_id: i32,
#[serde(rename = "forward_signature")]
pub signature: Option<String>,
}
impl ForwardChannel {
pub fn new(date: i32, chat: Chat, message_id: i32) -> Self {
Self { date, chat, message_id, signature: None }
}
pub fn date(mut self, val: i32) -> Self {
self.date = val;
self
}
pub fn chat(mut self, val: Chat) -> Self {
self.chat = val;
self
}
pub fn message_id(mut self, val: i32) -> Self {
self.message_id = val;
self
}
pub fn signature<S>(mut self, val: S) -> Self
where
S: Into<String>,
{
self.signature = Some(val.into());
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ForwardNonChannel {
#[serde(rename = "forward_date")]
pub date: i32,
#[serde(flatten)]
pub from: ForwardedFrom,
}
impl ForwardNonChannel {
pub fn new(date: i32, from: ForwardedFrom) -> Self {
Self { date, from }
}
pub fn date(mut self, val: i32) -> Self {
self.date = val;
self
}
pub fn from(mut self, val: ForwardedFrom) -> Self {
self.from = val;
self
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ForwardOrigin {
pub reply_to_message: Option<Box<Message>>,
}
impl ForwardOrigin {
pub fn new() -> Self {
Self::default()
}
pub fn reply_to_message(mut self, val: Message) -> Self {
self.reply_to_message = Some(Box::new(val));
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum MediaKind {
Animation(MediaAnimation),
Audio(MediaAudio),
Contact(MediaContact),
Document(MediaDocument),
Game(MediaGame),
Location(MediaLocation),
Photo(MediaPhoto),
Poll(MediaPoll),
Sticker(MediaSticker),
Text(MediaText),
Video(MediaVideo),
VideoNote(MediaVideoNote),
Voice(MediaVoice),
Venue(MediaVenue),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MediaAnimation {
/// Message is an animation, information about the animation. For
/// backward compatibility, when this field is set, the document field
/// will also be set.
pub animation: Animation,
#[doc(hidden)]
/// "For backward compatibility" (c) Telegram Docs.
#[serde(skip)]
pub document: (),
/// Caption for the animation, 0-1024 characters.
pub caption: Option<String>,
/// For messages with a caption, special entities like usernames, URLs,
/// bot commands, etc. that appear in the caption.
#[serde(default = "Vec::new")]
pub caption_entities: Vec<MessageEntity>,
}
impl MediaAnimation {
pub fn new<CE>(animation: Animation, caption_entities: CE) -> Self
where
CE: Into<Vec<MessageEntity>>,
{
Self { animation, document: (), caption: None, caption_entities: caption_entities.into() }
}
pub fn animation(mut self, val: Animation) -> Self {
self.animation = val;
self
}
pub fn caption<S>(mut self, val: S) -> Self
where
S: Into<String>,
{
self.caption = Some(val.into());
self
}
pub fn caption_entities<CE>(mut self, val: CE) -> Self
where
CE: Into<Vec<MessageEntity>>,
{
self.caption_entities = val.into();
self
}
}
#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MediaAudio {
/// Message is an audio file, information about the file.
pub audio: Audio,
/// Caption for the audio, 0-1024 characters.
pub caption: Option<String>,
/// For messages with a caption, special entities like usernames, URLs,
/// bot commands, etc. that appear in the caption.
#[serde(default = "Vec::new")]
pub caption_entities: Vec<MessageEntity>,
}
impl MediaAudio {
pub fn new<CE>(audio: Audio, caption_entities: CE) -> Self
where
CE: Into<Vec<MessageEntity>>,
{
Self { audio, caption: None, caption_entities: caption_entities.into() }
}
pub fn audio(mut self, val: Audio) -> Self {
self.audio = val;
self
}
pub fn caption<S>(mut self, val: S) -> Self
where
S: Into<String>,
{
self.caption = Some(val.into());
self
}
pub fn caption_entities<CE>(mut self, val: CE) -> Self
where
CE: Into<Vec<MessageEntity>>,
{
self.caption_entities = val.into();
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MediaContact {
/// Message is a shared contact, information about the contact.
contact: Contact,
}
impl MediaContact {
pub fn new(contact: Contact) -> Self {
Self { contact }
}
pub fn contact(mut self, val: Contact) -> Self {
self.contact = val;
self
}
}
#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MediaDocument {
/// Message is a general file, information about the file.
pub document: Document,
/// Caption for the document, 0-1024 characters.
pub caption: Option<String>,
/// For messages with a caption, special entities like usernames, URLs,
/// bot commands, etc. that appear in the caption.
#[serde(default = "Vec::new")]
pub caption_entities: Vec<MessageEntity>,
}
impl MediaDocument {
pub fn new<CE>(document: Document, caption_entities: CE) -> Self
where
CE: Into<Vec<MessageEntity>>,
{
Self { document, caption: None, caption_entities: caption_entities.into() }
}
pub fn document(mut self, val: Document) -> Self {
self.document = val;
self
}
pub fn caption<S>(mut self, val: S) -> Self
where
S: Into<String>,
{
self.caption = Some(val.into());
self
}
pub fn caption_entities<CE>(mut self, val: CE) -> Self
where
CE: Into<Vec<MessageEntity>>,
{
self.caption_entities = val.into();
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MediaGame {
/// Message is a game, information about the game. [More
/// about games »].
///
/// [More about games »]: https://core.telegram.org/bots/api#games
pub game: Game,
}
impl MediaGame {
pub fn new(game: Game) -> Self {
Self { game }
}
pub fn game(mut self, val: Game) -> Self {
self.game = val;
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MediaLocation {
/// Message is a shared location, information about the location.
pub location: Location,
}
impl MediaLocation {
pub fn new(location: Location) -> Self {
Self { location }
}
pub fn location(mut self, val: Location) -> Self {
self.location = val;
self
}
}
#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MediaPhoto {
/// Message is a photo, available sizes of the photo.
pub photo: Vec<PhotoSize>,
/// Caption for the photo, 0-1024 characters.
pub caption: Option<String>,
/// For messages with a caption, special entities like usernames, URLs,
/// bot commands, etc. that appear in the caption.
#[serde(default = "Vec::new")]
pub caption_entities: Vec<MessageEntity>,
/// The unique identifier of a media message group this message belongs
/// to.
pub media_group_id: Option<String>,
}
impl MediaPhoto {
pub fn new<P, CE>(photo: P, caption_entities: CE) -> Self
where
P: Into<Vec<PhotoSize>>,
CE: Into<Vec<MessageEntity>>,
{
Self {
photo: photo.into(),
caption: None,
caption_entities: caption_entities.into(),
media_group_id: None,
}
}
pub fn photo<P>(mut self, val: P) -> Self
where
P: Into<Vec<PhotoSize>>,
{
self.photo = val.into();
self
}
pub fn caption<S>(mut self, val: S) -> Self
where
S: Into<String>,
{
self.caption = Some(val.into());
self
}
pub fn caption_entities<CE>(mut self, val: CE) -> Self
where
CE: Into<Vec<MessageEntity>>,
{
self.caption_entities = val.into();
self
}
pub fn media_group_id<S>(mut self, val: S) -> Self
where
S: Into<String>,
{
self.media_group_id = Some(val.into());
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MediaPoll {
/// Message is a native poll, information about the poll.
pub poll: Poll,
}
impl MediaPoll {
pub fn new(poll: Poll) -> Self {
Self { poll }
}
pub fn poll(mut self, val: Poll) -> Self {
self.poll = val;
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MediaSticker {
/// Message is a sticker, information about the sticker.
pub sticker: Sticker,
}
impl MediaSticker {
pub fn new(sticker: Sticker) -> Self {
Self { sticker }
}
pub fn poll(mut self, val: Sticker) -> Self {
self.sticker = val;
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MediaText {
/// For text messages, the actual UTF-8 text of the message, 0-4096
/// characters.
pub text: String,
/// For text messages, special entities like usernames, URLs, bot
/// commands, etc. that appear in the text.
#[serde(default = "Vec::new")]
pub entities: Vec<MessageEntity>,
}
impl MediaText {
pub fn new<S, E>(text: S, entities: E) -> Self
where
S: Into<String>,
E: Into<Vec<MessageEntity>>,
{
Self { text: text.into(), entities: entities.into() }
}
pub fn text<S>(mut self, val: S) -> Self
where
S: Into<String>,
{
self.text = val.into();
self
}
pub fn entities<CE>(mut self, val: CE) -> Self
where
CE: Into<Vec<MessageEntity>>,
{
self.entities = val.into();
self
}
}
#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MediaVideo {
/// Message is a video, information about the video.
pub video: Video,
/// Caption for the video, 0-1024 characters.
pub caption: Option<String>,
/// For messages with a caption, special entities like usernames, URLs,
/// bot commands, etc. that appear in the caption.
#[serde(default = "Vec::new")]
pub caption_entities: Vec<MessageEntity>,
/// The unique identifier of a media message group this message belongs
/// to.
pub media_group_id: Option<String>,
}
impl MediaVideo {
pub fn new<CE>(video: Video, caption_entities: CE) -> Self
where
CE: Into<Vec<MessageEntity>>,
{
Self {
video,
caption: None,
caption_entities: caption_entities.into(),
media_group_id: None,
}
}
pub fn video(mut self, val: Video) -> Self {
self.video = val;
self
}
pub fn caption<S>(mut self, val: S) -> Self
where
S: Into<String>,
{
self.caption = Some(val.into());
self
}
pub fn caption_entities<CE>(mut self, val: CE) -> Self
where
CE: Into<Vec<MessageEntity>>,
{
self.caption_entities = val.into();
self
}
pub fn media_group_id<S>(mut self, val: S) -> Self
where
S: Into<String>,
{
self.media_group_id = Some(val.into());
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MediaVideoNote {
/// Message is a [video note], information about the video message.
///
/// [video note]: https://telegram.org/blog/video-messages-and-telescope
pub video_note: VideoNote,
}
impl MediaVideoNote {
pub fn new(video_note: VideoNote) -> Self {
Self { video_note }
}
pub fn video_note(mut self, val: VideoNote) -> Self {
self.video_note = val;
self
}
}
#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MediaVoice {
/// Message is a voice message, information about the file.
pub voice: Voice,
/// Caption for the voice, 0-1024 characters.
pub caption: Option<String>,
/// For messages with a caption, special entities like usernames, URLs,
/// bot commands, etc. that appear in the caption.
#[serde(default = "Vec::new")]
pub caption_entities: Vec<MessageEntity>,
}
impl MediaVoice {
pub fn new<CE>(voice: Voice, caption_entities: CE) -> Self
where
CE: Into<Vec<MessageEntity>>,
{
Self { voice, caption: None, caption_entities: caption_entities.into() }
}
pub fn voice(mut self, val: Voice) -> Self {
self.voice = val;
self
}
pub fn caption<S>(mut self, val: S) -> Self
where
S: Into<String>,
{
self.caption = Some(val.into());
self
}
pub fn caption_entities<CE>(mut self, val: CE) -> Self
where
CE: Into<Vec<MessageEntity>>,
{
self.caption_entities = val.into();
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MediaVenue {
/// Message is a venue, information about the venue.
pub venue: Venue,
}
impl MediaVenue {
pub fn new(venue: Venue) -> Self {
Self { venue }
}
pub fn venue(mut self, val: Venue) -> Self {
self.venue = val;
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageDice {
/// Message is a dice with random value from 1 to 6.
pub dice: Dice,
}
mod getters {
use std::ops::Deref;
use crate::types::{
self,
message::{
ForwardKind::NonChannel,
MessageKind::{
ChannelChatCreated, Common, ConnectedWebsite, DeleteChatPhoto, GroupChatCreated,
Invoice, LeftChatMember, Migrate, NewChatMembers, NewChatPhoto, NewChatTitle,
PassportData, Pinned, SuccessfulPayment, SupergroupChatCreated,
},
},
Chat, ForwardChannel, ForwardKind, ForwardNonChannel, ForwardOrigin, ForwardedFrom,
MediaAnimation, MediaAudio, MediaContact, MediaDocument, MediaGame, MediaKind,
MediaLocation, MediaPhoto, MediaPoll, MediaSticker, MediaText, MediaVenue, MediaVideo,
MediaVideoNote, MediaVoice, Message, MessageChannelChatCreated, MessageCommon,
MessageConnectedWebsite, MessageDeleteChatPhoto, MessageEntity, MessageGroupChatCreated,
MessageInvoice, MessageLeftChatMember, MessageMigrate, MessageNewChatMembers,
MessageNewChatPhoto, MessageNewChatTitle, MessagePassportData, MessagePinned,
MessageSuccessfulPayment, MessageSupergroupChatCreated, PhotoSize, True, User,
};
/// Getters for [Message] fields from [telegram docs].
///
/// [Message]: crate::types::Message
/// [telegram docs]: https://core.telegram.org/bots/api#message
impl Message {
/// NOTE: this is getter for both `from` and `author_signature`
pub fn from(&self) -> Option<&User> {
match &self.kind {
Common(MessageCommon { from, .. }) => from.as_ref(),
_ => None,
}
}
pub fn chat_id(&self) -> i64 {
self.chat.id
}
/// NOTE: this is getter for both `forward_from` and
/// `forward_sender_name`
pub fn forward_from(&self) -> Option<&ForwardedFrom> {
match &self.kind {
Common(MessageCommon {
forward_kind: NonChannel(ForwardNonChannel { from, .. }),
..
}) => Some(from),
_ => None,
}
}
pub fn forward_from_chat(&self) -> Option<&Chat> {
match &self.kind {
Common(MessageCommon {
forward_kind: ForwardKind::Channel(ForwardChannel { chat, .. }),
..
}) => Some(chat),
_ => None,
}
}
pub fn forward_from_message_id(&self) -> Option<&i32> {
match &self.kind {
Common(MessageCommon {
forward_kind: ForwardKind::Channel(ForwardChannel { message_id, .. }),
..
}) => Some(message_id),
_ => None,
}
}
pub fn forward_signature(&self) -> Option<&str> {
match &self.kind {
Common(MessageCommon {
forward_kind: ForwardKind::Channel(ForwardChannel { signature, .. }),
..
}) => signature.as_ref().map(Deref::deref),
_ => None,
}
}
pub fn forward_date(&self) -> Option<&i32> {
match &self.kind {
Common(MessageCommon {
forward_kind: ForwardKind::Channel(ForwardChannel { date, .. }),
..
})
| Common(MessageCommon {
forward_kind: ForwardKind::NonChannel(ForwardNonChannel { date, .. }),
..
}) => Some(date),
_ => None,
}
}
pub fn reply_to_message(&self) -> Option<&Message> {
match &self.kind {
Common(MessageCommon {
forward_kind: ForwardKind::Origin(ForwardOrigin { reply_to_message, .. }),
..
}) => reply_to_message.as_ref().map(Deref::deref),
_ => None,
}
}
pub fn edit_date(&self) -> Option<&i32> {
match &self.kind {
Common(MessageCommon { edit_date, .. }) => edit_date.as_ref(),
_ => None,
}
}
pub fn media_group_id(&self) -> Option<&str> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Video(MediaVideo { media_group_id, .. }),
..
})
| Common(MessageCommon {
media_kind: MediaKind::Photo(MediaPhoto { media_group_id, .. }),
..
}) => media_group_id.as_ref().map(Deref::deref),
_ => None,
}
}
pub fn text(&self) -> Option<&str> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Text(MediaText { text, .. }),
..
}) => Some(text),
_ => None,
}
}
pub fn text_owned(&self) -> Option<String> {
self.text().map(ToOwned::to_owned)
}
pub fn entities(&self) -> Option<&[MessageEntity]> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Text(MediaText { entities, .. }),
..
}) => Some(entities),
_ => None,
}
}
pub fn caption_entities(&self) -> Option<&[MessageEntity]> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Animation(MediaAnimation { caption_entities, .. }),
..
})
| Common(MessageCommon {
media_kind: MediaKind::Audio(MediaAudio { caption_entities, .. }),
..
})
| Common(MessageCommon {
media_kind: MediaKind::Document(MediaDocument { caption_entities, .. }),
..
})
| Common(MessageCommon {
media_kind: MediaKind::Photo(MediaPhoto { caption_entities, .. }),
..
})
| Common(MessageCommon {
media_kind: MediaKind::Video(MediaVideo { caption_entities, .. }),
..
})
| Common(MessageCommon {
media_kind: MediaKind::Voice(MediaVoice { caption_entities, .. }),
..
}) => Some(caption_entities),
_ => None,
}
}
pub fn audio(&self) -> Option<&types::Audio> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Audio(MediaAudio { audio, .. }),
..
}) => Some(audio),
_ => None,
}
}
pub fn document(&self) -> Option<&types::Document> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Document(MediaDocument { document, .. }),
..
}) => Some(document),
_ => None,
}
}
pub fn animation(&self) -> Option<&types::Animation> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Animation(MediaAnimation { animation, .. }),
..
}) => Some(animation),
_ => None,
}
}
pub fn game(&self) -> Option<&types::Game> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Game(MediaGame { game, .. }),
..
}) => Some(game),
_ => None,
}
}
pub fn photo(&self) -> Option<&[PhotoSize]> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Photo(MediaPhoto { photo, .. }),
..
}) => Some(photo),
_ => None,
}
}
pub fn sticker(&self) -> Option<&types::Sticker> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Sticker(MediaSticker { sticker, .. }),
..
}) => Some(sticker),
_ => None,
}
}
pub fn video(&self) -> Option<&types::Video> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Video(MediaVideo { video, .. }),
..
}) => Some(video),
_ => None,
}
}
pub fn voice(&self) -> Option<&types::Voice> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Voice(MediaVoice { voice, .. }),
..
}) => Some(voice),
_ => None,
}
}
pub fn video_note(&self) -> Option<&types::VideoNote> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::VideoNote(MediaVideoNote { video_note, .. }),
..
}) => Some(video_note),
_ => None,
}
}
pub fn caption(&self) -> Option<&str> {
match &self.kind {
Common(MessageCommon { media_kind, .. }) => match media_kind {
MediaKind::Animation(MediaAnimation { caption, .. })
| MediaKind::Audio(MediaAudio { caption, .. })
| MediaKind::Document(MediaDocument { caption, .. })
| MediaKind::Photo(MediaPhoto { caption, .. })
| MediaKind::Video(MediaVideo { caption, .. })
| MediaKind::Voice(MediaVoice { caption, .. }) => {
caption.as_ref().map(Deref::deref)
}
_ => None,
},
_ => None,
}
}
pub fn contact(&self) -> Option<&types::Contact> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Contact(MediaContact { contact, .. }),
..
}) => Some(contact),
_ => None,
}
}
pub fn location(&self) -> Option<&types::Location> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Location(MediaLocation { location, .. }),
..
}) => Some(location),
_ => None,
}
}
pub fn venue(&self) -> Option<&types::Venue> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Venue(MediaVenue { venue, .. }),
..
}) => Some(venue),
_ => None,
}
}
pub fn poll(&self) -> Option<&types::Poll> {
match &self.kind {
Common(MessageCommon {
media_kind: MediaKind::Poll(MediaPoll { poll, .. }),
..
}) => Some(poll),
_ => None,
}
}
pub fn new_chat_members(&self) -> Option<&[User]> {
match &self.kind {
NewChatMembers(MessageNewChatMembers { new_chat_members }) => {
Some(new_chat_members.as_ref())
}
_ => None,
}
}
pub fn left_chat_member(&self) -> Option<&User> {
match &self.kind {
LeftChatMember(MessageLeftChatMember { left_chat_member }) => {
Some(left_chat_member)
}
_ => None,
}
}
pub fn new_chat_title(&self) -> Option<&str> {
match &self.kind {
NewChatTitle(MessageNewChatTitle { new_chat_title }) => Some(new_chat_title),
_ => None,
}
}
pub fn new_chat_photo(&self) -> Option<&[PhotoSize]> {
match &self.kind {
NewChatPhoto(MessageNewChatPhoto { new_chat_photo }) => Some(new_chat_photo),
_ => None,
}
}
// TODO: OK, `Option<True>` is weird, can we do something with it?
// mb smt like `is_delete_chat_photo(&self) -> bool`?
pub fn delete_chat_photo(&self) -> Option<True> {
match &self.kind {
DeleteChatPhoto(MessageDeleteChatPhoto { delete_chat_photo }) => {
Some(*delete_chat_photo)
}
_ => None,
}
}
pub fn group_chat_created(&self) -> Option<True> {
match &self.kind {
GroupChatCreated(MessageGroupChatCreated { group_chat_created }) => {
Some(*group_chat_created)
}
_ => None,
}
}
pub fn super_group_chat_created(&self) -> Option<True> {
match &self.kind {
SupergroupChatCreated(MessageSupergroupChatCreated { supergroup_chat_created }) => {
Some(*supergroup_chat_created)
}
_ => None,
}
}
pub fn channel_chat_created(&self) -> Option<True> {
match &self.kind {
ChannelChatCreated(MessageChannelChatCreated { channel_chat_created }) => {
Some(*channel_chat_created)
}
_ => None,
}
}
pub fn migrate_to_chat_id(&self) -> Option<i64> {
match &self.kind {
Migrate(MessageMigrate { migrate_to_chat_id, .. }) => Some(*migrate_to_chat_id),
_ => None,
}
}
pub fn migrate_from_chat_id(&self) -> Option<i64> {
match &self.kind {
Migrate(MessageMigrate { migrate_from_chat_id, .. }) => Some(*migrate_from_chat_id),
_ => None,
}
}
pub fn pinned_message(&self) -> Option<&Message> {
match &self.kind {
Pinned(MessagePinned { pinned }) => Some(pinned),
_ => None,
}
}
pub fn invoice(&self) -> Option<&types::Invoice> {
match &self.kind {
Invoice(MessageInvoice { invoice }) => Some(invoice),
_ => None,
}
}
pub fn successful_payment(&self) -> Option<&types::SuccessfulPayment> {
match &self.kind {
SuccessfulPayment(MessageSuccessfulPayment { successful_payment }) => {
Some(successful_payment)
}
_ => None,
}
}
pub fn connected_website(&self) -> Option<&str> {
match &self.kind {
ConnectedWebsite(MessageConnectedWebsite { connected_website }) => {
Some(connected_website)
}
_ => None,
}
}
pub fn passport_data(&self) -> Option<&types::PassportData> {
match &self.kind {
PassportData(MessagePassportData { passport_data }) => Some(passport_data),
_ => None,
}
}
pub fn reply_markup(&self) -> Option<&types::InlineKeyboardMarkup> {
match &self.kind {
Common(MessageCommon { reply_markup, .. }) => reply_markup.as_ref(),
_ => None,
}
}
}
}
impl Message {
pub fn url(&self) -> Option<reqwest::Url> {
match &self.chat.kind {
ChatKind::Public(ChatPublic {
kind: PublicChatKind::Channel(PublicChatChannel { username: Some(username) }),
..
})
| ChatKind::Public(ChatPublic {
kind:
PublicChatKind::Supergroup(PublicChatSupergroup {
username: Some(username), ..
}),
..
}) => Some(
reqwest::Url::parse(format!("https://t.me/{0}/{1}/", username, self.id).as_str())
.unwrap(),
),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use serde_json::from_str;
use crate::types::*;
#[test]
fn de_media_forwarded() {
let json = r#"{
"message_id": 198283,
"from": {
"id": 250918540,
"is_bot": false,
"first_name": "Андрей",
"last_name": "Власов",
"username": "aka_dude",
"language_code": "en"
},
"chat": {
"id": 250918540,
"first_name": "Андрей",
"last_name": "Власов",
"username": "aka_dude",
"type": "private"
},
"date": 1567927221,
"video": {
"duration": 13,
"width": 512,
"height": 640,
"mime_type": "video/mp4",
"thumb": {
"file_id": "AAQCAAOmBAACBf2oS53pByA-I4CWWCObDwAEAQAHbQADMWcAAhYE",
"file_unique_id":"",
"file_size": 10339,
"width": 256,
"height": 320
},
"file_id": "BAADAgADpgQAAgX9qEud6QcgPiOAlhYE",
"file_unique_id":"",
"file_size": 1381334
}
}"#;
let message = from_str::<Message>(json);
assert!(message.is_ok());
}
#[test]
fn de_media_group_forwarded() {
let json = r#"{
"message_id": 198283,
"from": {
"id": 250918540,
"is_bot": false,
"first_name": "Андрей",
"last_name": "Власов",
"username": "aka_dude",
"language_code": "en"
},
"chat": {
"id": 250918540,
"first_name": "Андрей",
"last_name": "Власов",
"username": "aka_dude",
"type": "private"
},
"date": 1567927221,
"media_group_id": "12543417770506682",
"video": {
"duration": 13,
"width": 512,
"height": 640,
"mime_type": "video/mp4",
"thumb": {
"file_id": "AAQCAAOmBAACBf2oS53pByA-I4CWWCObDwAEAQAHbQADMWcAAhYE",
"file_unique_id":"",
"file_size": 10339,
"width": 256,
"height": 320
},
"file_id": "BAADAgADpgQAAgX9qEud6QcgPiOAlhYE",
"file_unique_id":"",
"file_size": 1381334
}
}"#;
let message = from_str::<Message>(json);
assert!(message.is_ok());
}
#[test]
fn de_text() {
let json = r#"{
"message_id": 199785,
"from": {
"id": 250918540,
"is_bot": false,
"first_name": "Андрей",
"last_name": "Власов",
"username": "aka_dude",
"language_code": "en"
},
"chat": {
"id": 250918540,
"first_name": "Андрей",
"last_name": "Власов",
"username": "aka_dude",
"type": "private"
},
"date": 1568289890,
"text": "Лол кек 😂"
}"#;
let message = from_str::<Message>(json);
assert!(message.is_ok());
}
#[test]
fn de_sticker() {
let json = r#"{
"message_id": 199787,
"from": {
"id": 250918540,
"is_bot": false,
"first_name": "Андрей",
"last_name": "Власов",
"username": "aka_dude",
"language_code": "en"
},
"chat": {
"id": 250918540,
"first_name": "Андрей",
"last_name": "Власов",
"username": "aka_dude",
"type": "private"
},
"date": 1568290188,
"sticker": {
"width": 512,
"height": 512,
"emoji": "😡",
"set_name": "AdvenTimeAnim",
"is_animated": true,
"thumb": {
"file_id": "AAQCAAMjAAOw0PgMaabKAcaXKCBLubkPAAQBAAdtAAPGKwACFgQ",
"file_unique_id":"",
"file_size": 4118,
"width": 128,
"height": 128
},
"file_id": "CAADAgADIwADsND4DGmmygHGlyggFgQ",
"file_unique_id":"",
"file_size": 16639
}
}"#;
let message = from_str::<Message>(json);
assert!(message.is_ok());
}
#[test]
fn de_image() {
let json = r#"{
"message_id": 199791,
"from": {
"id": 250918540,
"is_bot": false,
"first_name": "Андрей",
"last_name": "Власов",
"username": "aka_dude",
"language_code": "en"
},
"chat": {
"id": 250918540,
"first_name": "Андрей",
"last_name": "Власов",
"username": "aka_dude",
"type": "private"
},
"date": 1568290622,
"photo": [
{
"file_id": "AgADAgAD36sxG-PX0UvQSXIn9rccdw-ACA4ABAEAAwIAA20AAybcBAABFgQ",
"file_unique_id":"",
"file_size": 18188,
"width": 320,
"height": 239
},
{
"file_id": "AgADAgAD36sxG-PX0UvQSXIn9rccdw-ACA4ABAEAAwIAA3gAAyfcBAABFgQ",
"file_unique_id":"",
"file_size": 62123,
"width": 800,
"height": 598
},
{
"file_id": "AgADAgAD36sxG-PX0UvQSXIn9rccdw-ACA4ABAEAAwIAA3kAAyTcBAABFgQ",
"file_unique_id":"",
"file_size": 75245,
"width": 962,
"height": 719
}
]
}"#;
let message = from_str::<Message>(json);
assert!(message.is_ok());
}
} | }
} |
test_laplacian_matrices.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import unittest
import torch
from common_testing import TestCaseMixin, get_random_cuda_device
from pytorch3d.ops import cot_laplacian, laplacian, norm_laplacian
from pytorch3d.structures.meshes import Meshes
class TestLaplacianMatrices(TestCaseMixin, unittest.TestCase):
def setUp(self) -> None:
super().setUp()
torch.manual_seed(1)
def init_mesh(self) -> Meshes:
|
def test_laplacian(self):
mesh = self.init_mesh()
verts = mesh.verts_packed()
edges = mesh.edges_packed()
V, E = verts.shape[0], edges.shape[0]
L = laplacian(verts, edges)
Lnaive = torch.zeros((V, V), dtype=torch.float32, device=verts.device)
for e in range(E):
e0, e1 = edges[e]
Lnaive[e0, e1] = 1
# symetric
Lnaive[e1, e0] = 1
deg = Lnaive.sum(1).view(-1, 1)
deg[deg > 0] = 1.0 / deg[deg > 0]
Lnaive = Lnaive * deg
diag = torch.eye(V, dtype=torch.float32, device=mesh.device)
Lnaive.masked_fill_(diag > 0, -1)
self.assertClose(L.to_dense(), Lnaive)
def test_cot_laplacian(self):
mesh = self.init_mesh()
verts = mesh.verts_packed()
faces = mesh.faces_packed()
V = verts.shape[0]
eps = 1e-12
L, inv_areas = cot_laplacian(verts, faces, eps=eps)
Lnaive = torch.zeros((V, V), dtype=torch.float32, device=verts.device)
inv_areas_naive = torch.zeros((V, 1), dtype=torch.float32, device=verts.device)
for f in faces:
v0 = verts[f[0], :]
v1 = verts[f[1], :]
v2 = verts[f[2], :]
A = (v1 - v2).norm()
B = (v0 - v2).norm()
C = (v0 - v1).norm()
s = 0.5 * (A + B + C)
face_area = (s * (s - A) * (s - B) * (s - C)).clamp_(min=1e-12).sqrt()
inv_areas_naive[f[0]] += face_area
inv_areas_naive[f[1]] += face_area
inv_areas_naive[f[2]] += face_area
A2, B2, C2 = A * A, B * B, C * C
cota = (B2 + C2 - A2) / face_area / 4.0
cotb = (A2 + C2 - B2) / face_area / 4.0
cotc = (A2 + B2 - C2) / face_area / 4.0
Lnaive[f[1], f[2]] += cota
Lnaive[f[2], f[0]] += cotb
Lnaive[f[0], f[1]] += cotc
# symetric
Lnaive[f[2], f[1]] += cota
Lnaive[f[0], f[2]] += cotb
Lnaive[f[1], f[0]] += cotc
idx = inv_areas_naive > 0
inv_areas_naive[idx] = 1.0 / inv_areas_naive[idx]
self.assertClose(inv_areas, inv_areas_naive)
self.assertClose(L.to_dense(), Lnaive)
def test_norm_laplacian(self):
mesh = self.init_mesh()
verts = mesh.verts_packed()
edges = mesh.edges_packed()
V, E = verts.shape[0], edges.shape[0]
eps = 1e-12
L = norm_laplacian(verts, edges, eps=eps)
Lnaive = torch.zeros((V, V), dtype=torch.float32, device=verts.device)
for e in range(E):
e0, e1 = edges[e]
v0 = verts[e0]
v1 = verts[e1]
w01 = 1.0 / ((v0 - v1).norm() + eps)
Lnaive[e0, e1] += w01
Lnaive[e1, e0] += w01
self.assertClose(L.to_dense(), Lnaive)
| V, F = 32, 64
device = get_random_cuda_device()
# random vertices
verts = torch.rand((V, 3), dtype=torch.float32, device=device)
# random valid faces (no self circles, e.g. (v0, v0, v1))
faces = torch.stack([torch.randperm(V) for f in range(F)], dim=0)[:, :3]
faces = faces.to(device=device)
return Meshes(verts=[verts], faces=[faces]) |
_exceptions.py | # Copyright (c) 2015 Riverbed Technology, Inc.
#
# This software is licensed under the terms and conditions of the MIT License
# accompanying the software ("License"). This software is distributed "AS IS"
# as set forth in the License.
class NetSharkException(Exception):
| pass |
|
_constraints.py | from enum import Enum, auto
| greater_than_0 = auto()
not_null = auto()
is_email = auto()
is_uri = auto()
after_now = auto()
before_now = auto() | class Constraints(Enum):
not_empty = auto() |
policy_value_net_numpy.py | # -*- coding: utf-8 -*-
"""
Implement the policy value network using numpy, so that we can play with the
trained AI model without installing any DL framwork
@author: Junxiao Song
"""
from __future__ import print_function
import numpy as np
# some utility functions
def softmax(x):
probs = np.exp(x - np.max(x))
probs /= np.sum(probs)
return probs
def relu(X):
out = np.maximum(X, 0)
return out
def conv_forward(X, W, b, stride=1, padding=1):
n_filters, d_filter, h_filter, w_filter = W.shape
# theano conv2d flips the filters (rotate 180 degree) first
# while doing the calculation
W = W[:, :, ::-1, ::-1]
n_x, d_x, h_x, w_x = X.shape
h_out = (h_x - h_filter + 2 * padding) / stride + 1
w_out = (w_x - w_filter + 2 * padding) / stride + 1
h_out, w_out = int(h_out), int(w_out)
X_col = im2col_indices(X, h_filter, w_filter,
padding=padding, stride=stride)
W_col = W.reshape(n_filters, -1)
out = (np.dot(W_col, X_col).T + b).T
out = out.reshape(n_filters, h_out, w_out, n_x)
out = out.transpose(3, 0, 1, 2)
return out
def fc_forward(X, W, b):
out = np.dot(X, W) + b
return out
def get_im2col_indices(x_shape, field_height,
field_width, padding=1, stride=1):
# First figure out what the size of the output should be
N, C, H, W = x_shape
assert (H + 2 * padding - field_height) % stride == 0
assert (W + 2 * padding - field_height) % stride == 0
out_height = int((H + 2 * padding - field_height) / stride + 1)
out_width = int((W + 2 * padding - field_width) / stride + 1) | i1 = stride * np.repeat(np.arange(out_height), out_width)
j0 = np.tile(np.arange(field_width), field_height * C)
j1 = stride * np.tile(np.arange(out_width), out_height)
i = i0.reshape(-1, 1) + i1.reshape(1, -1)
j = j0.reshape(-1, 1) + j1.reshape(1, -1)
k = np.repeat(np.arange(C), field_height * field_width).reshape(-1, 1)
return (k.astype(int), i.astype(int), j.astype(int))
def im2col_indices(x, field_height, field_width, padding=1, stride=1):
""" An implementation of im2col based on some fancy indexing """
# Zero-pad the input
p = padding
x_padded = np.pad(x, ((0, 0), (0, 0), (p, p), (p, p)), mode='constant')
k, i, j = get_im2col_indices(x.shape, field_height,
field_width, padding, stride)
cols = x_padded[:, k, i, j]
C = x.shape[1]
cols = cols.transpose(1, 2, 0).reshape(field_height * field_width * C, -1)
return cols
class PolicyValueNet():
"""policy-value network in numpy """
def __init__(self, board_width, board_height, net_params):
self.board_width = board_width
self.board_height = board_height
self.params = net_params
def policy_value_fn(self, board):
"""
input: board
output: a list of (action, probability) tuples for each available
action and the score of the board state
"""
legal_positions = board.availables
current_state = board.current_state()
X = current_state.reshape(-1, 4, self.board_width, self.board_height)
# first 3 conv layers with ReLu nonlinearity
for i in [0, 2, 4]:
X = relu(conv_forward(X, self.params[i], self.params[i+1]))
# policy head
X_p = relu(conv_forward(X, self.params[6], self.params[7], padding=0))
X_p = fc_forward(X_p.flatten(), self.params[8], self.params[9])
act_probs = softmax(X_p)
# value head
X_v = relu(conv_forward(X, self.params[10],
self.params[11], padding=0))
X_v = relu(fc_forward(X_v.flatten(), self.params[12], self.params[13]))
value = np.tanh(fc_forward(X_v, self.params[14], self.params[15]))[0]
act_probs = zip(legal_positions, act_probs.flatten()[legal_positions])
return act_probs, value |
i0 = np.repeat(np.arange(field_height), field_width)
i0 = np.tile(i0, C) |
mod.rs | // Miniscript
// Written in 2019 by
// Sanket Kanjular and Andrew Poelstra
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//
//! Interpreter
//!
//! Provides a Miniscript-based script interpreter which can be used to
//! iterate over the set of conditions satisfied by a spending transaction,
//! assuming that the spent coin was descriptor controlled.
//!
use bitcoin::PublicKey;
use elements::{self, secp256k1_zkp, SigHash};
use elements::{confidential, sighash};
use elements::{
hashes::{hash160, ripemd160, sha256, sha256d, Hash, HashEngine},
SigHashType,
};
use miniscript::context::NoChecks;
use miniscript::ScriptContext;
use util;
use Miniscript;
use Terminal;
use {Descriptor, ElementsSig, ToPublicKey};
mod error;
mod inner;
mod stack;
use {CovenantExt, Extension};
pub use self::error::Error;
pub use self::stack::{Element, Stack};
/// An iterable Miniscript-structured representation of the spending of a coin
pub struct Interpreter<'txin, Ext: Extension<PublicKey>> {
inner: inner::Inner<Ext>,
stack: Stack<'txin>,
script_code: elements::Script,
age: u32,
height: u32,
}
impl<'txin> Interpreter<'txin, CovenantExt> {
/// Constructs an interpreter from the data of a spending transaction
///
/// Accepts a signature-validating function. If you are willing to trust
/// that ECSDA signatures are valid, this can be set to the constant true
/// function; otherwise, it should be a closure containing a sighash and
/// secp context, which can actually verify a given signature.
/// For downstream cursom implementations of [`Extension`], use [`Interpreter::from_txdata_ext`]
pub fn from_txdata(
spk: &elements::Script,
script_sig: &'txin elements::Script,
witness: &'txin [Vec<u8>],
age: u32,
height: u32,
) -> Result<Self, Error> {
Interpreter::from_txdata_ext(spk, script_sig, witness, age, height)
}
}
impl<'txin, Ext> Interpreter<'txin, Ext>
where
Ext: Extension<PublicKey>,
{
/// Constructs an interpreter from the data of a spending transaction
///
/// Accepts a signature-validating function. If you are willing to trust
/// that ECSDA signatures are valid, this can be set to the constant true
/// function; otherwise, it should be a closure containing a sighash and
/// secp context, which can actually verify a given signature.
pub fn from_txdata_ext(
spk: &elements::Script,
script_sig: &'txin elements::Script,
witness: &'txin [Vec<u8>],
age: u32,
height: u32,
) -> Result<Self, Error> {
let (inner, stack, script_code) = inner::from_txdata(spk, script_sig, witness)?;
Ok(Interpreter {
inner,
stack,
script_code,
age,
height,
})
}
/// Creates an iterator over the satisfied spending conditions
///
/// Returns all satisfied constraints, even if they were redundant (i.e. did
/// not contribute to the script being satisfied). For example, if a signature
/// were provided for an `and_b(Pk,false)` fragment, that signature will be
/// returned, even though the entire and_b must have failed and must not have
/// been used.
///
/// In case the script is actually dissatisfied, this may return several values
/// before ultimately returning an error.
///
/// Running the iterator through will consume the internal stack of the
/// `Iterpreter`, and it should not be used again after this.
pub fn iter<'iter, F>(&'iter mut self, verify_sig: F) -> Iter<'txin, 'iter, Ext, F>
where
Ext: Extension<PublicKey>,
F: FnMut(&PublicKey, ElementsSig) -> bool,
{
Iter {
verify_sig: verify_sig,
public_key: if let inner::Inner::PublicKey(ref pk, _) = self.inner {
Some(pk)
} else {
None
},
state: match self.inner {
inner::Inner::Script(ref ms, _) => vec![NodeEvaluationState {
node: ms,
n_evaluated: 0,
n_satisfied: 0,
}],
inner::Inner::CovScript(ref _pk, ref ms) => vec![NodeEvaluationState {
node: ms,
n_evaluated: 0,
n_satisfied: 0,
}],
inner::Inner::PublicKey(ref _pk, _) => vec![],
},
stack: &mut self.stack,
age: self.age,
height: self.height,
cov: if let inner::Inner::CovScript(ref pk, ref _ms) = self.inner {
Some(pk)
} else {
None
},
has_errored: false,
}
}
/// Outputs a "descriptor" string which reproduces the spent coins
///
/// This may not represent the original descriptor used to produce the transaction,
/// since it cannot distinguish between sorted and unsorted multisigs (and anyway
/// it can only see the final keys, keyorigin info is lost in serializing to Bitcoin).
///
/// If you are using the interpreter as a sanity check on a transaction,
/// it is worthwhile to try to parse this as a descriptor using `from_str`
/// which will check standardness and consensus limits, which the interpreter
/// does not do on its own. Or use the `inferred_descriptor` method which
/// does this for you.
pub fn inferred_descriptor_string(&self) -> String {
match self.inner {
inner::Inner::PublicKey(ref pk, inner::PubkeyType::Pk) => format!("pk({})", pk),
inner::Inner::PublicKey(ref pk, inner::PubkeyType::Pkh) => format!("pkh({})", pk),
inner::Inner::PublicKey(ref pk, inner::PubkeyType::Wpkh) => format!("wpkh({})", pk),
inner::Inner::PublicKey(ref pk, inner::PubkeyType::ShWpkh) => {
format!("elsh(wpkh({}))", pk)
}
inner::Inner::Script(ref ms, inner::ScriptType::Bare) => format!("{}", ms),
inner::Inner::Script(ref ms, inner::ScriptType::Sh) => format!("elsh({})", ms),
inner::Inner::Script(ref ms, inner::ScriptType::Wsh) => format!("elwsh({})", ms),
inner::Inner::Script(ref ms, inner::ScriptType::ShWsh) => format!("elsh(wsh({}))", ms),
inner::Inner::CovScript(ref pk, ref ms) => {
// always wsh for now
format!("elcovwsh({},{})", pk, ms)
}
}
}
/// Whether this is a pre-segwit spend
pub fn is_legacy(&self) -> bool {
match self.inner {
inner::Inner::PublicKey(_, inner::PubkeyType::Pk) => true,
inner::Inner::PublicKey(_, inner::PubkeyType::Pkh) => true,
inner::Inner::PublicKey(_, inner::PubkeyType::Wpkh) => false,
inner::Inner::PublicKey(_, inner::PubkeyType::ShWpkh) => false, // lol "sorta"
inner::Inner::Script(_, inner::ScriptType::Bare) => true,
inner::Inner::Script(_, inner::ScriptType::Sh) => true,
inner::Inner::Script(_, inner::ScriptType::Wsh) => false,
inner::Inner::Script(_, inner::ScriptType::ShWsh) => false, // lol "sorta"
inner::Inner::CovScript(..) => false,
}
}
/// Outputs a "descriptor" which reproduces the spent coins
///
/// This may not represent the original descriptor used to produce the transaction,
/// since it cannot distinguish between sorted and unsorted multisigs (and anyway
/// it can only see the final keys, keyorigin info is lost in serializing to Bitcoin).
pub fn inferred_descriptor(&self) -> Result<Descriptor<PublicKey>, ::Error> {
use std::str::FromStr;
Descriptor::from_str(&self.inferred_descriptor_string())
}
/// Returns a sighash over the entire transaction which can be used to verify signatures
/// in the descriptor
///
/// Not all fields are used by legacy descriptors; if you are sure this is a legacy
/// spend (you can check with the `is_legacy` method) you can provide dummy data for
/// the amount.
pub fn sighash_message(
&self,
unsigned_tx: &elements::Transaction,
input_idx: usize,
amount: confidential::Value,
sighash_type: elements::SigHashType,
) -> secp256k1_zkp::Message {
let mut sighash_cache = sighash::SigHashCache::new(unsigned_tx);
let hash = if self.is_legacy() {
sighash_cache.legacy_sighash(input_idx, &self.script_code, sighash_type)
} else {
sighash_cache.segwitv0_sighash(input_idx, &self.script_code, amount, sighash_type)
};
secp256k1_zkp::Message::from_slice(&hash[..])
.expect("cryptographically unreachable for this to fail")
}
/// Returns a closure which can be given to the `iter` method to check all signatures
pub fn sighash_verify<'a, C: secp256k1_zkp::Verification>(
&self,
secp: &'a secp256k1_zkp::Secp256k1<C>,
unsigned_tx: &'a elements::Transaction,
input_idx: usize,
amount: confidential::Value,
) -> impl Fn(&PublicKey, ElementsSig) -> bool + 'a {
// Precompute all sighash types because the borrowck doesn't like us
// pulling self into the closure
let sighashes = [
self.sighash_message(unsigned_tx, input_idx, amount, elements::SigHashType::All),
self.sighash_message(unsigned_tx, input_idx, amount, elements::SigHashType::None),
self.sighash_message(
unsigned_tx,
input_idx,
amount,
elements::SigHashType::Single,
),
self.sighash_message(
unsigned_tx,
input_idx,
amount,
elements::SigHashType::AllPlusAnyoneCanPay,
),
self.sighash_message(
unsigned_tx,
input_idx,
amount,
elements::SigHashType::NonePlusAnyoneCanPay,
),
self.sighash_message(
unsigned_tx,
input_idx,
amount,
elements::SigHashType::SinglePlusAnyoneCanPay,
),
];
move |pk: &PublicKey, (sig, sighash_type)| {
// This is an awkward way to do this lookup, but it lets us do exhaustiveness
// checking in case future rust-bitcoin versions add new sighash types
let sighash = match sighash_type {
elements::SigHashType::All => sighashes[0],
elements::SigHashType::None => sighashes[1],
elements::SigHashType::Single => sighashes[2],
elements::SigHashType::AllPlusAnyoneCanPay => sighashes[3],
elements::SigHashType::NonePlusAnyoneCanPay => sighashes[4],
elements::SigHashType::SinglePlusAnyoneCanPay => sighashes[5],
};
secp.verify(&sighash, &sig, &pk.key).is_ok()
}
}
}
/// Type of HashLock used for SatisfiedConstraint structure
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum HashLockType<'intp> {
///SHA 256 hashlock
Sha256(&'intp sha256::Hash),
///Hash 256 hashlock
Hash256(&'intp sha256d::Hash),
///Hash160 hashlock
Hash160(&'intp hash160::Hash),
///Ripemd160 hashlock
Ripemd160(&'intp ripemd160::Hash),
}
/// A satisfied Miniscript condition (Signature, Hashlock, Timelock)
/// 'intp represents the lifetime of descriptor and `stack represents
/// the lifetime of witness
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum SatisfiedConstraint<'intp, 'txin, Ext: 'intp + Extension<PublicKey>> {
///Public key and corresponding signature
PublicKey {
/// The bitcoin key
key: &'intp PublicKey,
/// corresponding signature
sig: secp256k1_zkp::Signature,
},
///PublicKeyHash, corresponding pubkey and signature
PublicKeyHash {
/// The pubkey hash
keyhash: &'intp hash160::Hash,
/// Corresponding public key
key: PublicKey,
/// Corresponding signature for the hash
sig: secp256k1_zkp::Signature,
},
///Hashlock and preimage for SHA256
HashLock {
/// The type of Hashlock
hash: HashLockType<'intp>,
/// The preimage used for satisfaction
preimage: &'txin [u8],
},
///Relative Timelock for CSV.
RelativeTimeLock {
/// The value of RelativeTimelock
time: &'intp u32,
},
///Absolute Timelock for CLTV.
AbsoluteTimeLock {
/// The value of Absolute timelock
time: &'intp u32,
},
/// Elements | /// Check Version eq
VerEq {
/// The version of transaction
n: &'intp u32,
},
/// Serialized outputs of this transaction start
/// this prefix
OutputsPref {
/// The version of transaction
pref: &'intp [u8],
},
/// Extension Interpreter
Ext {
/// Extension
ext: &'intp Ext,
},
}
///This is used by the interpreter to know which evaluation state a AstemElem is.
///This is required because whenever a same node(for eg. OrB) appears on the stack, we don't
///know if the left child has been evaluated or not. And based on the result on
///the top of the stack, we need to decide whether to execute right child or not.
///This is also useful for wrappers and thresholds which push a value on the stack
///depending on evaluation of the children.
struct NodeEvaluationState<'intp, Ext>
where
Ext: 'intp + Extension<PublicKey>,
{
///The node which is being evaluated
node: &'intp Miniscript<PublicKey, NoChecks, Ext>,
///number of children evaluated
n_evaluated: usize,
///number of children satisfied
n_satisfied: usize,
}
/// Iterator over all the constraints satisfied by a completed scriptPubKey
/// and witness stack
///
/// Returns all satisfied constraints, even if they were redundant (i.e. did
/// not contribute to the script being satisfied). For example, if a signature
/// were provided for an `and_b(Pk,false)` fragment, that signature will be
/// returned, even though the entire and_b must have failed and must not have
/// been used.
///
/// In case the script is actually dissatisfied, this may return several values
/// before ultimately returning an error.
pub struct Iter<'intp, 'txin: 'intp, Ext, F>
where
Ext: 'intp + Extension<PublicKey>,
F: FnMut(&PublicKey, ElementsSig) -> bool,
{
verify_sig: F,
public_key: Option<&'intp PublicKey>,
state: Vec<NodeEvaluationState<'intp, Ext>>,
stack: &'intp mut Stack<'txin>,
age: u32,
height: u32,
cov: Option<&'intp PublicKey>,
has_errored: bool,
}
///Iterator for Iter
impl<'intp, 'txin: 'intp, Ext, F> Iterator for Iter<'intp, 'txin, Ext, F>
where
NoChecks: ScriptContext,
Ext: Extension<PublicKey>,
F: FnMut(&PublicKey, ElementsSig) -> bool,
{
type Item = Result<SatisfiedConstraint<'intp, 'txin, Ext>, Error>;
fn next(&mut self) -> Option<Self::Item> {
if self.has_errored {
// Stop yielding values after the first error
None
} else {
let res = self.iter_next();
if let Some(Err(_)) = res {
self.has_errored = true;
}
res
}
}
}
impl<'intp, 'txin: 'intp, F, Ext> Iter<'intp, 'txin, Ext, F>
where
NoChecks: ScriptContext,
F: FnMut(&PublicKey, ElementsSig) -> bool,
Ext: Extension<PublicKey>,
{
/// Helper function to push a NodeEvaluationState on state stack
fn push_evaluation_state(
&mut self,
node: &'intp Miniscript<PublicKey, NoChecks, Ext>,
n_evaluated: usize,
n_satisfied: usize,
) -> () {
self.state.push(NodeEvaluationState {
node,
n_evaluated,
n_satisfied,
})
}
/// Helper function to step the iterator
fn iter_next(&mut self) -> Option<Result<SatisfiedConstraint<'intp, 'txin, Ext>, Error>> {
while let Some(node_state) = self.state.pop() {
//non-empty stack
match node_state.node.node {
Terminal::True => {
debug_assert_eq!(node_state.n_evaluated, 0);
debug_assert_eq!(node_state.n_satisfied, 0);
self.stack.push(stack::Element::Satisfied);
}
Terminal::False => {
debug_assert_eq!(node_state.n_evaluated, 0);
debug_assert_eq!(node_state.n_satisfied, 0);
self.stack.push(stack::Element::Dissatisfied);
}
Terminal::PkK(ref pk) => {
debug_assert_eq!(node_state.n_evaluated, 0);
debug_assert_eq!(node_state.n_satisfied, 0);
let res = self.stack.evaluate_pk(&mut self.verify_sig, pk);
if res.is_some() {
return res;
}
}
Terminal::PkH(ref pkh) => {
debug_assert_eq!(node_state.n_evaluated, 0);
debug_assert_eq!(node_state.n_satisfied, 0);
let res = self.stack.evaluate_pkh(&mut self.verify_sig, pkh);
if res.is_some() {
return res;
}
}
Terminal::After(ref n) => {
debug_assert_eq!(node_state.n_evaluated, 0);
debug_assert_eq!(node_state.n_satisfied, 0);
let res = self.stack.evaluate_after(n, self.age);
if res.is_some() {
return res;
}
}
Terminal::Older(ref n) => {
debug_assert_eq!(node_state.n_evaluated, 0);
debug_assert_eq!(node_state.n_satisfied, 0);
let res = self.stack.evaluate_older(n, self.height);
if res.is_some() {
return res;
}
}
Terminal::Sha256(ref hash) => {
debug_assert_eq!(node_state.n_evaluated, 0);
debug_assert_eq!(node_state.n_satisfied, 0);
let res = self.stack.evaluate_sha256(hash);
if res.is_some() {
return res;
}
}
Terminal::Hash256(ref hash) => {
debug_assert_eq!(node_state.n_evaluated, 0);
debug_assert_eq!(node_state.n_satisfied, 0);
let res = self.stack.evaluate_hash256(hash);
if res.is_some() {
return res;
}
}
Terminal::Hash160(ref hash) => {
debug_assert_eq!(node_state.n_evaluated, 0);
debug_assert_eq!(node_state.n_satisfied, 0);
let res = self.stack.evaluate_hash160(hash);
if res.is_some() {
return res;
}
}
Terminal::Ripemd160(ref hash) => {
debug_assert_eq!(node_state.n_evaluated, 0);
debug_assert_eq!(node_state.n_satisfied, 0);
let res = self.stack.evaluate_ripemd160(hash);
if res.is_some() {
return res;
}
}
Terminal::Ext(ref ext) => {
let res = ext.evaluate(self.stack);
match res {
Some(Ok(())) => return Some(Ok(SatisfiedConstraint::Ext { ext: ext })),
Some(Err(e)) => return Some(Err(e)),
None => {}
}
}
Terminal::Alt(ref sub) | Terminal::Swap(ref sub) | Terminal::Check(ref sub) => {
debug_assert_eq!(node_state.n_evaluated, 0);
debug_assert_eq!(node_state.n_satisfied, 0);
self.push_evaluation_state(sub, 0, 0);
}
Terminal::DupIf(ref sub) if node_state.n_evaluated == 0 => match self.stack.pop() {
Some(stack::Element::Dissatisfied) => {
self.stack.push(stack::Element::Dissatisfied);
}
Some(stack::Element::Satisfied) => {
self.push_evaluation_state(node_state.node, 1, 1);
self.push_evaluation_state(sub, 0, 0);
}
Some(stack::Element::Push(_v)) => {
return Some(Err(Error::UnexpectedStackElementPush))
}
None => return Some(Err(Error::UnexpectedStackEnd)),
},
Terminal::DupIf(ref _sub) if node_state.n_evaluated == 1 => {
self.stack.push(stack::Element::Satisfied);
}
Terminal::ZeroNotEqual(ref sub) | Terminal::Verify(ref sub)
if node_state.n_evaluated == 0 =>
{
self.push_evaluation_state(node_state.node, 1, 0);
self.push_evaluation_state(sub, 0, 0);
}
Terminal::Verify(ref _sub) if node_state.n_evaluated == 1 => {
match self.stack.pop() {
Some(stack::Element::Satisfied) => (),
Some(_) => return Some(Err(Error::VerifyFailed)),
None => return Some(Err(Error::UnexpectedStackEnd)),
}
}
Terminal::ZeroNotEqual(ref _sub) if node_state.n_evaluated == 1 => {
match self.stack.pop() {
Some(stack::Element::Dissatisfied) => {
self.stack.push(stack::Element::Dissatisfied)
}
Some(_) => self.stack.push(stack::Element::Satisfied),
None => return Some(Err(Error::UnexpectedStackEnd)),
}
}
Terminal::NonZero(ref sub) => {
debug_assert_eq!(node_state.n_evaluated, 0);
debug_assert_eq!(node_state.n_satisfied, 0);
match self.stack.last() {
Some(&stack::Element::Dissatisfied) => (),
Some(_) => self.push_evaluation_state(sub, 0, 0),
None => return Some(Err(Error::UnexpectedStackEnd)),
}
}
Terminal::AndV(ref left, ref right) => {
debug_assert_eq!(node_state.n_evaluated, 0);
debug_assert_eq!(node_state.n_satisfied, 0);
self.push_evaluation_state(right, 0, 0);
self.push_evaluation_state(left, 0, 0);
}
Terminal::OrB(ref left, ref _right) | Terminal::AndB(ref left, ref _right)
if node_state.n_evaluated == 0 =>
{
self.push_evaluation_state(node_state.node, 1, 0);
self.push_evaluation_state(left, 0, 0);
}
Terminal::OrB(ref _left, ref right) | Terminal::AndB(ref _left, ref right)
if node_state.n_evaluated == 1 =>
{
match self.stack.pop() {
Some(stack::Element::Dissatisfied) => {
self.push_evaluation_state(node_state.node, 2, 0);
self.push_evaluation_state(right, 0, 0);
}
Some(stack::Element::Satisfied) => {
self.push_evaluation_state(node_state.node, 2, 1);
self.push_evaluation_state(right, 0, 0);
}
Some(stack::Element::Push(_v)) => {
return Some(Err(Error::UnexpectedStackElementPush))
}
None => return Some(Err(Error::UnexpectedStackEnd)),
}
}
Terminal::AndB(ref _left, ref _right) if node_state.n_evaluated == 2 => {
match self.stack.pop() {
Some(stack::Element::Satisfied) if node_state.n_satisfied == 1 => {
self.stack.push(stack::Element::Satisfied)
}
Some(_) => self.stack.push(stack::Element::Dissatisfied),
None => return Some(Err(Error::UnexpectedStackEnd)),
}
}
Terminal::AndOr(ref left, ref _right, _)
| Terminal::OrC(ref left, ref _right)
| Terminal::OrD(ref left, ref _right)
if node_state.n_evaluated == 0 =>
{
self.push_evaluation_state(node_state.node, 1, 0);
self.push_evaluation_state(left, 0, 0);
}
Terminal::OrB(ref _left, ref _right) if node_state.n_evaluated == 2 => {
match self.stack.pop() {
Some(stack::Element::Dissatisfied) if node_state.n_satisfied == 0 => {
self.stack.push(stack::Element::Dissatisfied)
}
Some(_) => {
self.stack.push(stack::Element::Satisfied);
}
None => return Some(Err(Error::UnexpectedStackEnd)),
}
}
Terminal::OrC(ref _left, ref right) if node_state.n_evaluated == 1 => {
match self.stack.pop() {
Some(stack::Element::Satisfied) => (),
Some(stack::Element::Dissatisfied) => {
self.push_evaluation_state(right, 0, 0)
}
Some(stack::Element::Push(_v)) => {
return Some(Err(Error::UnexpectedStackElementPush))
}
None => return Some(Err(Error::UnexpectedStackEnd)),
}
}
Terminal::OrD(ref _left, ref right) if node_state.n_evaluated == 1 => {
match self.stack.pop() {
Some(stack::Element::Satisfied) => {
self.stack.push(stack::Element::Satisfied)
}
Some(stack::Element::Dissatisfied) => {
self.push_evaluation_state(right, 0, 0)
}
Some(stack::Element::Push(_v)) => {
return Some(Err(Error::UnexpectedStackElementPush))
}
None => return Some(Err(Error::UnexpectedStackEnd)),
}
}
Terminal::AndOr(_, ref left, ref right) | Terminal::OrI(ref left, ref right) => {
match self.stack.pop() {
Some(stack::Element::Satisfied) => self.push_evaluation_state(left, 0, 0),
Some(stack::Element::Dissatisfied) => {
self.push_evaluation_state(right, 0, 0)
}
Some(stack::Element::Push(_v)) => {
return Some(Err(Error::UnexpectedStackElementPush))
}
None => return Some(Err(Error::UnexpectedStackEnd)),
}
}
Terminal::Thresh(ref _k, ref subs) if node_state.n_evaluated == 0 => {
self.push_evaluation_state(node_state.node, 1, 0);
self.push_evaluation_state(&subs[0], 0, 0);
}
Terminal::Thresh(k, ref subs) if node_state.n_evaluated == subs.len() => {
match self.stack.pop() {
Some(stack::Element::Dissatisfied) if node_state.n_satisfied == k => {
self.stack.push(stack::Element::Satisfied)
}
Some(stack::Element::Satisfied) if node_state.n_satisfied == k - 1 => {
self.stack.push(stack::Element::Satisfied)
}
Some(stack::Element::Satisfied) | Some(stack::Element::Dissatisfied) => {
self.stack.push(stack::Element::Dissatisfied)
}
Some(stack::Element::Push(_v)) => {
return Some(Err(Error::UnexpectedStackElementPush))
}
None => return Some(Err(Error::UnexpectedStackEnd)),
}
}
Terminal::Thresh(ref _k, ref subs) if node_state.n_evaluated != 0 => {
match self.stack.pop() {
Some(stack::Element::Dissatisfied) => {
self.push_evaluation_state(
node_state.node,
node_state.n_evaluated + 1,
node_state.n_satisfied,
);
self.push_evaluation_state(&subs[node_state.n_evaluated], 0, 0);
}
Some(stack::Element::Satisfied) => {
self.push_evaluation_state(
node_state.node,
node_state.n_evaluated + 1,
node_state.n_satisfied + 1,
);
self.push_evaluation_state(&subs[node_state.n_evaluated], 0, 0);
}
Some(stack::Element::Push(_v)) => {
return Some(Err(Error::UnexpectedStackElementPush))
}
None => return Some(Err(Error::UnexpectedStackEnd)),
}
}
Terminal::Multi(ref k, ref subs) if node_state.n_evaluated == 0 => {
let len = self.stack.len();
if len < k + 1 {
return Some(Err(Error::InsufficientSignaturesMultiSig));
} else {
//Non-sat case. If the first sig is empty, others k elements must
//be empty.
match self.stack.last() {
Some(&stack::Element::Dissatisfied) => {
//Remove the extra zero from multi-sig check
let sigs = self.stack.split_off(len - (k + 1));
let nonsat = sigs
.iter()
.map(|sig| *sig == stack::Element::Dissatisfied)
.filter(|empty| *empty)
.count();
if nonsat == *k + 1 {
self.stack.push(stack::Element::Dissatisfied);
} else {
return Some(Err(Error::MissingExtraZeroMultiSig));
}
}
None => return Some(Err(Error::UnexpectedStackEnd)),
_ => {
match self
.stack
.evaluate_multi(&mut self.verify_sig, &subs[subs.len() - 1])
{
Some(Ok(x)) => {
self.push_evaluation_state(
node_state.node,
node_state.n_evaluated + 1,
node_state.n_satisfied + 1,
);
return Some(Ok(x));
}
None => self.push_evaluation_state(
node_state.node,
node_state.n_evaluated + 1,
node_state.n_satisfied,
),
x => return x, //forward errors as is
}
}
}
}
}
Terminal::Multi(k, ref subs) => {
if node_state.n_satisfied == k {
//multi-sig bug: Pop extra 0
if let Some(stack::Element::Dissatisfied) = self.stack.pop() {
self.stack.push(stack::Element::Satisfied);
} else {
return Some(Err(Error::MissingExtraZeroMultiSig));
}
} else if node_state.n_evaluated == subs.len() {
return Some(Err(Error::MultiSigEvaluationError));
} else {
match self.stack.evaluate_multi(
&mut self.verify_sig,
&subs[subs.len() - node_state.n_evaluated - 1],
) {
Some(Ok(x)) => {
self.push_evaluation_state(
node_state.node,
node_state.n_evaluated + 1,
node_state.n_satisfied + 1,
);
return Some(Ok(x));
}
None => self.push_evaluation_state(
node_state.node,
node_state.n_evaluated + 1,
node_state.n_satisfied,
),
x => return x, //forward errors as is
}
}
}
//All other match patterns should not be reached in any valid
//type checked Miniscript
_ => return Some(Err(Error::CouldNotEvaluate)),
};
}
//state empty implies that either the execution has terminated or we have a
//Pk based descriptor or a Covenant descriptor
if let Some(pk) = self.cov {
// First verify the top of Miniscript.
// At this point, the stack must contain 13 elements
// pop the satisfied top and verify the covenant code.
if self.stack.pop() != Some(stack::Element::Satisfied) {
return Some(Err(Error::IncorrectCovenantWitness));
}
if self.stack.len() != 12 {
return Some(Err(Error::UnexpectedStackEnd));
}
// safe to unwrap 12 times
for i in 0..12 {
if let Err(e) = self.stack[i].try_push() {
return Some(Err(e));
}
}
let mut ser_sig = Vec::new();
// 1.29 errors
{
let sighash_bytes = self.stack[1].as_push();
let sighash_u32 = util::slice_to_u32_le(sighash_bytes);
let sighash_ty = SigHashType::from_u32(sighash_u32);
let sig_vec = self.stack[0].as_push();
ser_sig.extend(sig_vec);
ser_sig.push(sighash_ty as u8);
}
if let Ok(sig) = verify_sersig(&mut self.verify_sig, &pk, &ser_sig) {
//Signature check successful, set cov to None to
//terminate the next() function in the subsequent call
self.cov = None;
// Do the checkSigFromStackCheck
let sighash_msg: Vec<u8> = self.stack.0[1..]
.into_iter()
.rev()
.map(|x| Vec::from(x.as_push()))
.flatten()
.collect();
let mut eng = SigHash::engine();
eng.input(&sighash_msg);
let sighash_u256 = SigHash::from_engine(eng);
let msg = elements::secp256k1_zkp::Message::from_slice(&sighash_u256[..]).unwrap();
// TODO: THIS SHOULD BE A SEPARATE PARAMETER TO THE FUNCTION, BUT SINCE
// IT MIGHT ELSEWHERE, CONSIDER MAKING IT A SEPARATE METHOD. RIGHT NOW,
// THIS IS CREATING A NEW CONTEXT WHICH IS EXPENSIVE
let secp = secp256k1_zkp::Secp256k1::verification_only();
if secp.verify(&msg, &sig, &pk.key).is_err() {
return Some(Err(Error::PkEvaluationError(pk.clone().to_public_key())));
}
self.stack.0.clear();
self.stack.push(stack::Element::Satisfied);
return Some(Ok(SatisfiedConstraint::PublicKey { key: pk, sig }));
} else {
return Some(Err(Error::PkEvaluationError(pk.clone().to_public_key())));
}
}
if let Some(pk) = self.public_key {
if let Some(stack::Element::Push(sig)) = self.stack.pop() {
if let Ok(sig) = verify_sersig(&mut self.verify_sig, &pk, &sig) {
//Signature check successful, set public_key to None to
//terminate the next() function in the subsequent call
self.public_key = None;
self.stack.push(stack::Element::Satisfied);
return Some(Ok(SatisfiedConstraint::PublicKey { key: pk, sig }));
} else {
return Some(Err(Error::PkEvaluationError(pk.clone().to_public_key())));
}
} else {
return Some(Err(Error::UnexpectedStackEnd));
}
} else {
//All the script has been executed.
//Check that the stack must contain exactly 1 satisfied element
if self.stack.pop() == Some(stack::Element::Satisfied) && self.stack.is_empty() {
return None;
} else {
return Some(Err(Error::ScriptSatisfactionError));
}
}
}
}
/// Helper function to verify serialized signature
fn verify_sersig<'txin, F>(
verify_sig: F,
pk: &PublicKey,
sigser: &[u8],
) -> Result<secp256k1_zkp::Signature, Error>
where
F: FnOnce(&PublicKey, ElementsSig) -> bool,
{
if let Some((sighash_byte, sig)) = sigser.split_last() {
let sighashtype = elements::SigHashType::from_u32(*sighash_byte as u32);
let sig = secp256k1_zkp::Signature::from_der(sig)?;
if verify_sig(pk, (sig, sighashtype)) {
Ok(sig)
} else {
Err(Error::InvalidSignature(*pk))
}
} else {
Err(Error::PkEvaluationError(*pk))
}
}
#[cfg(test)]
mod tests {
use CovenantExt;
use super::*;
use bitcoin;
use bitcoin::hashes::{hash160, ripemd160, sha256, sha256d, Hash};
use elements::secp256k1_zkp::{self, Secp256k1, VerifyOnly};
use miniscript::context::NoChecks;
use ElementsSig;
use Miniscript;
use MiniscriptKey;
use ToPublicKey;
fn setup_keys_sigs(
n: usize,
) -> (
Vec<bitcoin::PublicKey>,
Vec<Vec<u8>>,
Vec<secp256k1_zkp::Signature>,
secp256k1_zkp::Message,
Secp256k1<VerifyOnly>,
) {
let secp_sign = secp256k1_zkp::Secp256k1::signing_only();
let secp_verify = secp256k1_zkp::Secp256k1::verification_only();
let msg = secp256k1_zkp::Message::from_slice(&b"Yoda: btc, I trust. HODL I must!"[..])
.expect("32 bytes");
let mut pks = vec![];
let mut secp_sigs = vec![];
let mut der_sigs = vec![];
let mut sk = [0; 32];
for i in 1..n + 1 {
sk[0] = i as u8;
sk[1] = (i >> 8) as u8;
sk[2] = (i >> 16) as u8;
let sk = secp256k1_zkp::SecretKey::from_slice(&sk[..]).expect("secret key");
let pk = bitcoin::PublicKey {
key: secp256k1_zkp::PublicKey::from_secret_key(&secp_sign, &sk),
compressed: true,
};
let sig = secp_sign.sign(&msg, &sk);
secp_sigs.push(sig);
let mut sigser = sig.serialize_der().to_vec();
sigser.push(0x01); // sighash_all
pks.push(pk);
der_sigs.push(sigser);
}
(pks, der_sigs, secp_sigs, msg, secp_verify)
}
#[test]
fn sat_constraints() {
let (pks, der_sigs, secp_sigs, sighash, secp) = setup_keys_sigs(10);
let vfyfn_ =
|pk: &bitcoin::PublicKey, (sig, _)| secp.verify(&sighash, &sig, &pk.key).is_ok();
fn from_stack<'txin, 'elem, F>(
verify_fn: F,
stack: &'elem mut Stack<'txin>,
ms: &'elem Miniscript<bitcoin::PublicKey, NoChecks, CovenantExt>,
) -> Iter<'elem, 'txin, CovenantExt, F>
where
F: FnMut(&bitcoin::PublicKey, ElementsSig) -> bool,
{
Iter {
verify_sig: verify_fn,
stack: stack,
public_key: None,
state: vec![NodeEvaluationState {
node: ms,
n_evaluated: 0,
n_satisfied: 0,
}],
age: 1002,
height: 1002,
cov: None,
has_errored: false,
}
}
let pk = ms_str!("c:pk_k({})", pks[0]);
let pkh = ms_str!("c:pk_h({})", pks[1].to_pubkeyhash());
//Time
let after = ms_str!("after({})", 1000);
let older = ms_str!("older({})", 1000);
//Hashes
let preimage = vec![0xab as u8; 32];
let sha256_hash = sha256::Hash::hash(&preimage);
let sha256 = ms_str!("sha256({})", sha256_hash);
let sha256d_hash_rev = sha256d::Hash::hash(&preimage);
let mut sha256d_hash_bytes = sha256d_hash_rev.clone().into_inner();
sha256d_hash_bytes.reverse();
let sha256d_hash = sha256d::Hash::from_inner(sha256d_hash_bytes);
let hash256 = ms_str!("hash256({})", sha256d_hash);
let hash160_hash = hash160::Hash::hash(&preimage);
let hash160 = ms_str!("hash160({})", hash160_hash);
let ripemd160_hash = ripemd160::Hash::hash(&preimage);
let ripemd160 = ms_str!("ripemd160({})", ripemd160_hash);
let mut stack = Stack::from(vec![stack::Element::Push(&der_sigs[0])]);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &pk);
let pk_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
pk_satisfied.unwrap(),
vec![SatisfiedConstraint::PublicKey {
key: &pks[0],
sig: secp_sigs[0].clone(),
}]
);
//Check Pk failure with wrong signature
let mut stack = Stack::from(vec![stack::Element::Dissatisfied]);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &pk);
let pk_err: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> = constraints.collect();
assert!(pk_err.is_err());
//Check Pkh
let pk_bytes = pks[1].to_public_key().to_bytes();
let mut stack = Stack::from(vec![
stack::Element::Push(&der_sigs[1]),
stack::Element::Push(&pk_bytes),
]);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &pkh);
let pkh_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
pkh_satisfied.unwrap(),
vec![SatisfiedConstraint::PublicKeyHash {
keyhash: &pks[1].to_pubkeyhash(),
key: pks[1].clone(),
sig: secp_sigs[1].clone(),
}]
);
//Check After
let mut stack = Stack::from(vec![]);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &after);
let after_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
after_satisfied.unwrap(),
vec![SatisfiedConstraint::AbsoluteTimeLock { time: &1000 }]
);
//Check Older
let mut stack = Stack::from(vec![]);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &older);
let older_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
older_satisfied.unwrap(),
vec![SatisfiedConstraint::RelativeTimeLock { time: &1000 }]
);
//Check Sha256
let mut stack = Stack::from(vec![stack::Element::Push(&preimage)]);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &sha256);
let sah256_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
sah256_satisfied.unwrap(),
vec![SatisfiedConstraint::HashLock {
hash: HashLockType::Sha256(&sha256_hash),
preimage: &preimage,
}]
);
//Check Shad256
let mut stack = Stack::from(vec![stack::Element::Push(&preimage)]);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &hash256);
let sha256d_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
sha256d_satisfied.unwrap(),
vec![SatisfiedConstraint::HashLock {
hash: HashLockType::Hash256(&sha256d_hash_rev),
preimage: &preimage,
}]
);
//Check hash160
let mut stack = Stack::from(vec![stack::Element::Push(&preimage)]);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &hash160);
let hash160_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
hash160_satisfied.unwrap(),
vec![SatisfiedConstraint::HashLock {
hash: HashLockType::Hash160(&hash160_hash),
preimage: &preimage,
}]
);
//Check ripemd160
let mut stack = Stack::from(vec![stack::Element::Push(&preimage)]);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &ripemd160);
let ripemd160_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
ripemd160_satisfied.unwrap(),
vec![SatisfiedConstraint::HashLock {
hash: HashLockType::Ripemd160(&ripemd160_hash),
preimage: &preimage
}]
);
//Check AndV
let pk_bytes = pks[1].to_public_key().to_bytes();
let mut stack = Stack::from(vec![
stack::Element::Push(&der_sigs[1]),
stack::Element::Push(&pk_bytes),
stack::Element::Push(&der_sigs[0]),
]);
let elem = ms_str!(
"and_v(vc:pk_k({}),c:pk_h({}))",
pks[0],
pks[1].to_pubkeyhash()
);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &elem);
let and_v_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
and_v_satisfied.unwrap(),
vec![
SatisfiedConstraint::PublicKey {
key: &pks[0],
sig: secp_sigs[0].clone(),
},
SatisfiedConstraint::PublicKeyHash {
keyhash: &pks[1].to_pubkeyhash(),
key: pks[1].clone(),
sig: secp_sigs[1].clone(),
}
]
);
//Check AndB
let mut stack = Stack::from(vec![
stack::Element::Push(&preimage),
stack::Element::Push(&der_sigs[0]),
]);
let elem = ms_str!("and_b(c:pk_k({}),sjtv:sha256({}))", pks[0], sha256_hash);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &elem);
let and_b_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
and_b_satisfied.unwrap(),
vec![
SatisfiedConstraint::PublicKey {
key: &pks[0],
sig: secp_sigs[0].clone(),
},
SatisfiedConstraint::HashLock {
hash: HashLockType::Sha256(&sha256_hash),
preimage: &preimage,
}
]
);
//Check AndOr
let mut stack = Stack::from(vec![
stack::Element::Push(&preimage),
stack::Element::Push(&der_sigs[0]),
]);
let elem = ms_str!(
"andor(c:pk_k({}),jtv:sha256({}),c:pk_h({}))",
pks[0],
sha256_hash,
pks[1].to_pubkeyhash(),
);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &elem);
let and_or_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
and_or_satisfied.unwrap(),
vec![
SatisfiedConstraint::PublicKey {
key: &pks[0],
sig: secp_sigs[0].clone(),
},
SatisfiedConstraint::HashLock {
hash: HashLockType::Sha256(&sha256_hash),
preimage: &preimage,
}
]
);
//AndOr second satisfaction path
let pk_bytes = pks[1].to_public_key().to_bytes();
let mut stack = Stack::from(vec![
stack::Element::Push(&der_sigs[1]),
stack::Element::Push(&pk_bytes),
stack::Element::Dissatisfied,
]);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &elem);
let and_or_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
and_or_satisfied.unwrap(),
vec![SatisfiedConstraint::PublicKeyHash {
keyhash: &pks[1].to_pubkeyhash(),
key: pks[1].clone(),
sig: secp_sigs[1].clone(),
}]
);
//Check OrB
let mut stack = Stack::from(vec![
stack::Element::Push(&preimage),
stack::Element::Dissatisfied,
]);
let elem = ms_str!("or_b(c:pk_k({}),sjtv:sha256({}))", pks[0], sha256_hash);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &elem);
let or_b_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
or_b_satisfied.unwrap(),
vec![SatisfiedConstraint::HashLock {
hash: HashLockType::Sha256(&sha256_hash),
preimage: &preimage,
}]
);
//Check OrD
let mut stack = Stack::from(vec![stack::Element::Push(&der_sigs[0])]);
let elem = ms_str!("or_d(c:pk_k({}),jtv:sha256({}))", pks[0], sha256_hash);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &elem);
let or_d_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
or_d_satisfied.unwrap(),
vec![SatisfiedConstraint::PublicKey {
key: &pks[0],
sig: secp_sigs[0].clone(),
}]
);
//Check OrC
let mut stack = Stack::from(vec![
stack::Element::Push(&der_sigs[0]),
stack::Element::Dissatisfied,
]);
let elem = ms_str!("t:or_c(jtv:sha256({}),vc:pk_k({}))", sha256_hash, pks[0]);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &elem);
let or_c_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
or_c_satisfied.unwrap(),
vec![SatisfiedConstraint::PublicKey {
key: &pks[0],
sig: secp_sigs[0].clone(),
}]
);
//Check OrI
let mut stack = Stack::from(vec![
stack::Element::Push(&der_sigs[0]),
stack::Element::Dissatisfied,
]);
let elem = ms_str!("or_i(jtv:sha256({}),c:pk_k({}))", sha256_hash, pks[0]);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &elem);
let or_i_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
or_i_satisfied.unwrap(),
vec![SatisfiedConstraint::PublicKey {
key: &pks[0],
sig: secp_sigs[0].clone(),
}]
);
//Check Thres
let mut stack = Stack::from(vec![
stack::Element::Push(&der_sigs[0]),
stack::Element::Push(&der_sigs[1]),
stack::Element::Push(&der_sigs[2]),
stack::Element::Dissatisfied,
stack::Element::Dissatisfied,
]);
let elem = ms_str!(
"thresh(3,c:pk_k({}),sc:pk_k({}),sc:pk_k({}),sc:pk_k({}),sc:pk_k({}))",
pks[4],
pks[3],
pks[2],
pks[1],
pks[0],
);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &elem);
let thresh_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
thresh_satisfied.unwrap(),
vec![
SatisfiedConstraint::PublicKey {
key: &pks[2],
sig: secp_sigs[2].clone(),
},
SatisfiedConstraint::PublicKey {
key: &pks[1],
sig: secp_sigs[1].clone(),
},
SatisfiedConstraint::PublicKey {
key: &pks[0],
sig: secp_sigs[0].clone(),
}
]
);
// Check multi
let mut stack = Stack::from(vec![
stack::Element::Dissatisfied,
stack::Element::Push(&der_sigs[2]),
stack::Element::Push(&der_sigs[1]),
stack::Element::Push(&der_sigs[0]),
]);
let elem = ms_str!(
"multi(3,{},{},{},{},{})",
pks[4],
pks[3],
pks[2],
pks[1],
pks[0],
);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &elem);
let multi_satisfied: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert_eq!(
multi_satisfied.unwrap(),
vec![
SatisfiedConstraint::PublicKey {
key: &pks[0],
sig: secp_sigs[0].clone(),
},
SatisfiedConstraint::PublicKey {
key: &pks[1],
sig: secp_sigs[1].clone(),
},
SatisfiedConstraint::PublicKey {
key: &pks[2],
sig: secp_sigs[2].clone(),
},
]
);
// Error multi: Invalid order of sigs
let mut stack = Stack::from(vec![
stack::Element::Dissatisfied,
stack::Element::Push(&der_sigs[0]),
stack::Element::Push(&der_sigs[2]),
stack::Element::Push(&der_sigs[1]),
]);
let elem = ms_str!(
"multi(3,{},{},{},{},{})",
pks[4],
pks[3],
pks[2],
pks[1],
pks[0],
);
let mut vfyfn = vfyfn_.clone(); // sigh rust 1.29...
let constraints = from_stack(&mut vfyfn, &mut stack, &elem);
let multi_error: Result<Vec<SatisfiedConstraint<CovenantExt>>, Error> =
constraints.collect();
assert!(multi_error.is_err());
}
} | |
simple-todos.js | Tasks = new Mongo.Collection("tasks");
if (Meteor.isClient) {
// This code only runs on the client
Template.body.helpers({
tasks: function () {
// Show newest tasks first
return Tasks.find({}, {sort: {createdAt: -1}});
}
});
Template.body.events({
"submit .new-task": function (event) {
// This function is called when the new task form is submitted
var text = event.target.text.value;
Tasks.insert({
text: text,
createdAt: new Date() // current time
});
// Clear form
event.target.text.value = "";
// Prevent default form submit
return false;
}
});
Template.task.events({ | // Set the checked property to the opposite of its current value
Tasks.update(this._id, {$set: {checked: ! this.checked}});
},
"click .delete": function () {
Tasks.remove(this._id);
}
});
} | "click .toggle-checked": function () { |
diff-min.js | (function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})(function(a){a.defineMode("diff",function(){var a={"+":"positive","-":"negative","@":"meta"};return{token:function(b){var c=b.string.search(/[\t ]+?$/);if(!b.sol()||0===c)return b.skipToEnd(),("error "+(a[b.string.charAt(0)]||"")).replace(/ $/,"");var d=a[b.peek()]||b.skipToEnd();-1===c?b.skipToEnd():b.pos=c;return d}}});
a.defineMIME("text/x-diff","diff")}); |
||
client.rs | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Tools for starting or connecting to existing Fuchsia applications and services.
use {
crate::DEFAULT_SERVICE_INSTANCE,
anyhow::{format_err, Context as _, Error},
fidl::endpoints::{
DiscoverableService, MemberOpener, Proxy, ServerEnd, ServiceMarker, UnifiedServiceMarker,
UnifiedServiceProxy,
},
fidl_fuchsia_io::DirectoryProxy,
fidl_fuchsia_sys::{
ComponentControllerEvent, ComponentControllerEventStream, ComponentControllerProxy,
FileDescriptor, FlatNamespace, LaunchInfo, LauncherMarker, LauncherProxy, ServiceList,
TerminationReason,
},
fidl_fuchsia_sys2::{ChildRef, RealmMarker, RealmProxy},
fuchsia_async as fasync,
fuchsia_runtime::HandleType,
fuchsia_zircon::{self as zx, Socket, SocketOpts},
futures::{
future::{self, FutureExt, TryFutureExt},
stream::{StreamExt, TryStreamExt},
Future,
},
log::*,
std::{
borrow::Borrow,
fmt,
fs::File,
marker::PhantomData,
path::{Path, PathBuf},
sync::Arc,
},
thiserror::Error,
};
/// Path to the service directory in an application's root namespace.
const SVC_DIR: &'static str = "/svc";
/// A protocol connection request that allows checking if the protocol exists.
pub struct ProtocolConnector<D: Borrow<DirectoryProxy>, S: DiscoverableService> {
svc_dir: D,
_svc_marker: PhantomData<S>,
}
impl<D: Borrow<DirectoryProxy>, S: DiscoverableService> ProtocolConnector<D, S> {
/// Returns a new `ProtocolConnector` to `S` in the specified service directory.
fn new(svc_dir: D) -> ProtocolConnector<D, S> {
ProtocolConnector { svc_dir, _svc_marker: PhantomData }
}
/// Returns `true` if the protocol exists in the service directory.
///
/// This method requires a round trip to the service directory to check for
/// existence.
pub async fn exists(&self) -> Result<bool, Error> {
match files_async::dir_contains(self.svc_dir.borrow(), S::NAME).await {
Ok(v) => Ok(v),
// If the service directory is unavailable, then mask the error as if
// the protocol does not exist.
Err(files_async::Error::Fidl(
_,
fidl::Error::ClientChannelClosed { status, service_name: _ },
)) if status == zx::Status::PEER_CLOSED => Ok(false),
Err(e) => Err(Error::new(e).context("error checking for service entry in directory")),
}
}
/// Connect to the FIDL protocol using the provided server-end.
///
/// Note, this method does not check if the protocol exists. It is up to the
/// caller to call `exists` to check for existence.
pub fn connect_with(self, server_end: zx::Channel) -> Result<(), Error> {
self.svc_dir
.borrow()
.open(
fidl_fuchsia_io::OPEN_RIGHT_READABLE,
0, /* mode */
S::NAME,
fidl::endpoints::ServerEnd::new(server_end),
)
.context("error connecting to protocol")
}
/// Connect to the FIDL protocol.
///
/// Note, this method does not check if the protocol exists. It is up to the
/// caller to call `exists` to check for existence.
pub fn connect(self) -> Result<S::Proxy, Error> {
let (proxy, server) = zx::Channel::create().context("error creating zx channels")?;
let () = self.connect_with(server).context("error connecting with server channel")?;
let proxy =
fasync::Channel::from_channel(proxy).context("error creating proxy from channel")?;
Ok(S::Proxy::from_channel(proxy))
}
}
/// Clone the handle to the service directory in the application's root namespace.
pub fn clone_namespace_svc() -> Result<fidl_fuchsia_io::DirectoryProxy, Error> {
io_util::directory::open_in_namespace(SVC_DIR, fidl_fuchsia_io::OPEN_RIGHT_READABLE)
.context("error opening svc directory")
}
/// Return a FIDL protocol connector at the default service directory in the
/// application's root namespace.
pub fn new_protocol_connector<S: DiscoverableService>(
) -> Result<ProtocolConnector<DirectoryProxy, S>, Error> {
new_protocol_connector_at::<S>(SVC_DIR)
}
/// Return a FIDL protocol connector at the specified service directory in the
/// application's root namespace.
///
/// The service directory path must be an absolute path.
pub fn new_protocol_connector_at<S: DiscoverableService>(
service_directory_path: &str,
) -> Result<ProtocolConnector<DirectoryProxy, S>, Error> {
let dir = io_util::directory::open_in_namespace(
service_directory_path,
fidl_fuchsia_io::OPEN_RIGHT_READABLE,
)
.context("error opening service directory")?;
Ok(ProtocolConnector::new(dir))
}
/// Return a FIDL protocol connector at the specified service directory.
pub fn new_protocol_connector_in_dir<S: DiscoverableService>(
dir: &DirectoryProxy,
) -> ProtocolConnector<&DirectoryProxy, S> {
ProtocolConnector::new(dir)
}
/// Connect to a FIDL protocol using the provided channel.
pub fn connect_channel_to_protocol<S: DiscoverableService>(
server_end: zx::Channel,
) -> Result<(), Error> {
connect_channel_to_protocol_at::<S>(server_end, SVC_DIR)
}
/// Connect to a FIDL protocol using the provided channel and namespace prefix.
pub fn connect_channel_to_protocol_at<S: DiscoverableService>(
server_end: zx::Channel,
service_directory_path: &str,
) -> Result<(), Error> {
let protocol_path = format!("{}/{}", service_directory_path, S::SERVICE_NAME);
connect_channel_to_protocol_at_path(server_end, &protocol_path)
}
/// Connect to a FIDL protocol using the provided channel and namespace path.
pub fn connect_channel_to_protocol_at_path(
server_end: zx::Channel,
protocol_path: &str,
) -> Result<(), Error> {
fdio::service_connect(&protocol_path, server_end)
.with_context(|| format!("Error connecting to protocol path: {}", protocol_path))
}
/// Connect to a FIDL protocol using the application root namespace.
pub fn connect_to_protocol<S: DiscoverableService>() -> Result<S::Proxy, Error> {
connect_to_protocol_at::<S>(SVC_DIR)
}
/// Connect to a FIDL protocol using the provided namespace prefix.
pub fn connect_to_protocol_at<S: DiscoverableService>(
service_prefix: &str,
) -> Result<S::Proxy, Error> {
let (proxy, server) = zx::Channel::create()?;
connect_channel_to_protocol_at::<S>(server, service_prefix)?;
let proxy = fasync::Channel::from_channel(proxy)?;
Ok(S::Proxy::from_channel(proxy))
}
/// Connect to a FIDL protocol using the provided path.
pub fn connect_to_protocol_at_path<S: ServiceMarker>(
protocol_path: &str,
) -> Result<S::Proxy, Error> {
let (proxy, server) = zx::Channel::create()?;
connect_channel_to_protocol_at_path(server, protocol_path)?;
let proxy = fasync::Channel::from_channel(proxy)?;
Ok(S::Proxy::from_channel(proxy))
}
/// Connect to an instance of a FIDL protocol hosted in `directory`.
pub fn connect_to_protocol_at_dir_root<S: DiscoverableService>(
directory: &DirectoryProxy,
) -> Result<S::Proxy, Error> {
connect_to_named_protocol_at_dir_root::<S>(directory, S::SERVICE_NAME)
}
/// Connect to an instance of a FIDL protocol hosted in `directory` using the given `filename`.
pub fn connect_to_named_protocol_at_dir_root<S: DiscoverableService>(
directory: &DirectoryProxy,
filename: &str,
) -> Result<S::Proxy, Error> {
let proxy = io_util::open_node(
directory,
&PathBuf::from(filename),
fidl_fuchsia_io::OPEN_RIGHT_READABLE | fidl_fuchsia_io::OPEN_RIGHT_WRITABLE,
fidl_fuchsia_io::MODE_TYPE_SERVICE,
)
.context("Failed to open protocol in directory")?;
let proxy = S::Proxy::from_channel(proxy.into_channel().unwrap());
Ok(proxy)
}
/// Connect to an instance of a FIDL protocol hosted in `directory`, in the `svc/` subdir.
pub fn connect_to_protocol_at_dir_svc<S: DiscoverableService>(
directory: &DirectoryProxy,
) -> Result<S::Proxy, Error> {
let proxy = io_util::open_node(
directory,
&PathBuf::from(format!("svc/{}", S::SERVICE_NAME)),
fidl_fuchsia_io::OPEN_RIGHT_READABLE | fidl_fuchsia_io::OPEN_RIGHT_WRITABLE,
fidl_fuchsia_io::MODE_TYPE_SERVICE,
)
.context("Failed to open protocol in directory")?;
let proxy = S::Proxy::from_channel(proxy.into_channel().unwrap());
Ok(proxy)
}
struct DirectoryProtocolImpl(DirectoryProxy);
impl MemberOpener for DirectoryProtocolImpl {
fn open_member(&self, member: &str, server_end: zx::Channel) -> Result<(), fidl::Error> {
let flags = fidl_fuchsia_io::OPEN_RIGHT_READABLE | fidl_fuchsia_io::OPEN_RIGHT_WRITABLE;
self.0.open(
flags,
fidl_fuchsia_io::MODE_TYPE_SERVICE,
member,
ServerEnd::new(server_end),
)?;
Ok(())
}
}
/// Connect to the "default" instance of a FIDL service in the `/svc` directory of
/// the application's root namespace.
pub fn connect_to_service<US: UnifiedServiceMarker>() -> Result<US::Proxy, Error> {
connect_to_service_instance_at::<US>(SVC_DIR, DEFAULT_SERVICE_INSTANCE)
}
/// Connect to an instance of a FIDL service in the `/svc` directory of
/// the application's root namespace.
/// `instance` is a path of one or more components.
// NOTE: We would like to use impl AsRef<T> to accept a wide variety of string-like
// inputs but Rust limits specifying explicit generic parameters when `impl-traits`
// are present.
pub fn connect_to_service_instance<US: UnifiedServiceMarker>(
instance: &str,
) -> Result<US::Proxy, Error> {
connect_to_service_instance_at::<US>(SVC_DIR, instance)
}
/// Connect to an instance of a FIDL service using the provided path prefix.
/// `path_prefix` should not contain any slashes.
/// `instance` is a path of one or more components.
// NOTE: We would like to use impl AsRef<T> to accept a wide variety of string-like
// inputs but Rust limits specifying explicit generic parameters when `impl-traits`
// are present.
pub fn connect_to_service_instance_at<US: UnifiedServiceMarker>(
path_prefix: &str,
instance: &str,
) -> Result<US::Proxy, Error> {
let mut service_path = PathBuf::new();
service_path.push(path_prefix);
service_path.push(US::SERVICE_NAME);
service_path.push(instance);
let directory_proxy = io_util::open_directory_in_namespace(
service_path.to_str().unwrap(),
io_util::OPEN_RIGHT_READABLE | io_util::OPEN_RIGHT_WRITABLE,
)?;
Ok(US::Proxy::from_member_opener(Box::new(DirectoryProtocolImpl(directory_proxy))))
}
/// Connect to the "default" instance of a FIDL service hosted on the directory protocol
/// channel `directory`.
pub fn connect_to_service_at_dir<US: UnifiedServiceMarker>(
directory: &zx::Channel,
) -> Result<US::Proxy, Error> {
connect_to_service_instance_at_dir::<US>(directory, DEFAULT_SERVICE_INSTANCE)
}
/// Connect to an instance of a FIDL service hosted on the directory protocol channel `directory`.
/// `instance` is a path of one or more components.
// NOTE: We would like to use impl AsRef<T> to accept a wide variety of string-like
// inputs but Rust limits specifying explicit generic parameters when `impl-traits`
// are present.
pub fn connect_to_service_instance_at_dir<US: UnifiedServiceMarker>(
directory: &zx::Channel,
instance: &str,
) -> Result<US::Proxy, Error> {
let service_path = Path::new(US::SERVICE_NAME).join(instance);
let (directory_proxy, server_end) =
fidl::endpoints::create_proxy::<fidl_fuchsia_io::DirectoryMarker>()?;
let flags = fidl_fuchsia_io::OPEN_FLAG_DIRECTORY
| fidl_fuchsia_io::OPEN_RIGHT_READABLE
| fidl_fuchsia_io::OPEN_RIGHT_WRITABLE;
fdio::open_at(directory, service_path.to_str().unwrap(), flags, server_end.into_channel())?;
Ok(US::Proxy::from_member_opener(Box::new(DirectoryProtocolImpl(directory_proxy))))
}
/// Opens a FIDL service as a directory so that its instances can be listed.
pub fn open_service<US: UnifiedServiceMarker>() -> Result<DirectoryProxy, Error> {
let service_path = Path::new(SVC_DIR).join(US::SERVICE_NAME);
Ok(io_util::directory::open_in_namespace(
service_path.to_str().unwrap(),
io_util::OPEN_RIGHT_READABLE | io_util::OPEN_RIGHT_WRITABLE,
)?)
}
/// Opens the exposed directory from a child. Only works in CFv2, and only works if this component
/// uses `fuchsia.sys2.Realm`.
pub async fn open_childs_exposed_directory(
child_name: impl Into<String>,
collection_name: Option<String>,
) -> Result<DirectoryProxy, Error> {
let realm_proxy = connect_to_protocol::<RealmMarker>()?;
let (directory_proxy, server_end) =
fidl::endpoints::create_proxy::<fidl_fuchsia_io::DirectoryMarker>()?;
let name: String = child_name.into();
realm_proxy
.bind_child(
&mut ChildRef { name: name.clone(), collection: collection_name.clone() },
server_end,
)
.await?
.map_err(|e| {
format_err!(
"failed to bind to child {} in collection {:?}: {:?}",
name,
collection_name,
e
)
})?;
Ok(directory_proxy)
}
/// Connects to a FIDL protocol exposed by a child that's within the `/svc` directory. Only works in
/// CFv2, and only works if this component uses `fuchsia.sys2.Realm`.
pub async fn connect_to_childs_protocol<S: DiscoverableService>(
child_name: String,
collection_name: Option<String>,
) -> Result<S::Proxy, Error> {
let child_exposed_directory =
open_childs_exposed_directory(child_name, collection_name).await?;
connect_to_protocol_at_dir_root::<S>(&child_exposed_directory)
}
/// Adds a new directory handle to the namespace for the new process.
pub fn add_handle_to_namespace(namespace: &mut FlatNamespace, path: String, dir: zx::Handle) {
namespace.paths.push(path);
namespace.directories.push(zx::Channel::from(dir));
}
/// Adds a new directory to the namespace for the new process.
pub fn add_dir_to_namespace(
namespace: &mut FlatNamespace,
path: String,
dir: File,
) -> Result<(), Error> {
let handle = fdio::transfer_fd(dir)?;
Ok(add_handle_to_namespace(namespace, path, handle))
}
/// Returns a connection to the application launcher protocol. Components v1 only.
pub fn launcher() -> Result<LauncherProxy, Error> {
connect_to_protocol::<LauncherMarker>()
}
/// Launch an application at the specified URL. Components v1 only.
pub fn launch(
launcher: &LauncherProxy,
url: String,
arguments: Option<Vec<String>>,
) -> Result<App, Error> {
launch_with_options(launcher, url, arguments, LaunchOptions::new())
}
/// Options for the launcher when starting an applications.
pub struct LaunchOptions {
namespace: Option<Box<FlatNamespace>>,
out: Option<Box<FileDescriptor>>,
additional_services: Option<Box<ServiceList>>,
}
impl LaunchOptions {
/// Creates default launch options.
pub fn new() -> LaunchOptions {
LaunchOptions { namespace: None, out: None, additional_services: None }
}
/// Adds a new directory handle to the namespace for the new process.
pub fn add_handle_to_namespace(&mut self, path: String, dir: zx::Handle) -> &mut Self {
let namespace = self
.namespace
.get_or_insert_with(|| Box::new(FlatNamespace { paths: vec![], directories: vec![] }));
add_handle_to_namespace(namespace, path, dir);
self
}
/// Adds a new directory to the namespace for the new process.
pub fn add_dir_to_namespace(&mut self, path: String, dir: File) -> Result<&mut Self, Error> {
let handle = fdio::transfer_fd(dir)?;
Ok(self.add_handle_to_namespace(path, handle))
}
/// Sets the out handle.
pub fn set_out(&mut self, f: FileDescriptor) -> &mut Self {
self.out = Some(Box::new(f));
self
}
/// Set additional services to add the new component's namespace under /svc, in addition to
/// those coming from the environment. 'host_directory' should be a channel to the directory
/// hosting the services in 'names'. Subsequent calls will override previous calls.
pub fn set_additional_services(
&mut self,
names: Vec<String>,
host_directory: zx::Channel,
) -> &mut Self {
let list = ServiceList { names, host_directory: Some(host_directory), provider: None };
self.additional_services = Some(Box::new(list));
self
}
}
/// Launch an application at the specified URL. Components v1 only.
pub fn launch_with_options(
launcher: &LauncherProxy,
url: String,
arguments: Option<Vec<String>>,
options: LaunchOptions,
) -> Result<App, Error> {
let (controller, controller_server_end) = fidl::endpoints::create_proxy()?;
let (directory_request, directory_server_chan) = zx::Channel::create()?;
let directory_request = Arc::new(directory_request);
let mut launch_info = LaunchInfo {
url,
arguments,
out: options.out,
err: None,
directory_request: Some(directory_server_chan),
flat_namespace: options.namespace,
additional_services: options.additional_services,
};
launcher
.create_component(&mut launch_info, Some(controller_server_end.into()))
.context("Failed to start a new Fuchsia application.")?;
Ok(App { directory_request, controller, stdout: None, stderr: None })
}
/// Returns a connection to the Realm protocol. Components v2 only.
pub fn realm() -> Result<RealmProxy, Error> {
connect_to_protocol::<RealmMarker>()
}
/// `App` represents a launched application.
///
/// When `App` is dropped, launched application will be terminated.
#[must_use = "Dropping `App` will cause the application to be terminated."]
pub struct App {
// directory_request is a directory protocol channel
directory_request: Arc<zx::Channel>,
// Keeps the component alive until `App` is dropped.
controller: ComponentControllerProxy,
//TODO pub accessors to take stdout/stderr in wrapper types that implement AsyncRead.
stdout: Option<fasync::Socket>,
stderr: Option<fasync::Socket>,
}
impl App {
/// Returns a reference to the directory protocol channel of the application.
#[inline]
pub fn directory_channel(&self) -> &zx::Channel {
&self.directory_request
}
/// Returns reference of directory request which can be passed to `ServiceFs::add_proxy_service_to`.
#[inline]
pub fn directory_request(&self) -> &Arc<zx::Channel> {
&self.directory_request
}
/// Returns a reference to the component controller.
#[inline]
pub fn controller(&self) -> &ComponentControllerProxy {
&self.controller
}
/// Connect to a protocol provided by the `App`.
#[inline]
pub fn connect_to_protocol<S: DiscoverableService>(&self) -> Result<S::Proxy, Error> {
let (client_channel, server_channel) = zx::Channel::create()?;
self.pass_to_protocol::<S>(server_channel)?;
Ok(S::Proxy::from_channel(fasync::Channel::from_channel(client_channel)?))
}
/// Connect to a protocol provided by the `App`.
#[inline]
pub fn connect_to_named_protocol<S: DiscoverableService>(
&self,
protocol_name: &str,
) -> Result<S::Proxy, Error> {
let (client_channel, server_channel) = zx::Channel::create()?;
self.pass_to_named_protocol(protocol_name, server_channel)?;
Ok(S::Proxy::from_channel(fasync::Channel::from_channel(client_channel)?))
}
/// Connect to a FIDL service provided by the `App`.
#[inline]
pub fn connect_to_service<US: UnifiedServiceMarker>(&self) -> Result<US::Proxy, Error> {
connect_to_service_at_dir::<US>(&self.directory_request)
}
/// Connect to a protocol by passing a channel for the server.
#[inline]
pub fn pass_to_protocol<S: DiscoverableService>(
&self,
server_channel: zx::Channel,
) -> Result<(), Error> {
self.pass_to_named_protocol(S::SERVICE_NAME, server_channel)
}
/// Connect to a protocol by name.
#[inline]
pub fn pass_to_named_protocol(
&self,
protocol_name: &str,
server_channel: zx::Channel,
) -> Result<(), Error> {
fdio::service_connect_at(&self.directory_request, protocol_name, server_channel)?;
Ok(())
}
/// Forces the component to exit.
pub fn kill(&mut self) -> Result<(), fidl::Error> {
self.controller.kill()
}
/// Wait for the component to terminate and return its exit status.
pub fn wait(&mut self) -> impl Future<Output = Result<ExitStatus, Error>> {
ExitStatus::from_event_stream(self.controller.take_event_stream())
}
/// Wait for the component to terminate and return its exit status, stdout, and stderr.
pub fn wait_with_output(mut self) -> impl Future<Output = Result<Output, Error>> {
let drain = |pipe: Option<fasync::Socket>| match pipe {
None => future::ready(Ok(vec![])).left_future(),
Some(pipe) => pipe.into_datagram_stream().try_concat().err_into().right_future(),
};
future::try_join3(self.wait(), drain(self.stdout), drain(self.stderr))
.map_ok(|(exit_status, stdout, stderr)| Output { exit_status, stdout, stderr })
}
}
/// A component builder, providing a simpler interface to
/// [`fidl_fuchsia_sys::LauncherProxy::create_component`].
///
/// `AppBuilder`s interface matches
/// [`std:process:Command`](https://doc.rust-lang.org/std/process/struct.Command.html) as
/// closely as possible, except where the semantics of spawning a process differ from the
/// semantics of spawning a Fuchsia component:
///
/// * Fuchsia components do not support stdin, a current working directory, or environment
/// variables.
///
/// * `AppBuilder` will move certain handles into the spawned component (see
/// [`AppBuilder::add_dir_to_namespace`]), so a single instance of `AppBuilder` can only be
/// used to create a single component.
#[derive(Debug)]
pub struct AppBuilder {
launch_info: LaunchInfo,
directory_request: Option<Arc<zx::Channel>>,
stdout: Option<Stdio>,
stderr: Option<Stdio>,
}
impl AppBuilder {
/// Creates a new `AppBuilder` for the component referenced by the given `url`.
pub fn new(url: impl Into<String>) -> Self {
Self {
launch_info: LaunchInfo {
url: url.into(),
arguments: None,
out: None,
err: None,
directory_request: None,
flat_namespace: None,
additional_services: None,
},
directory_request: None,
stdout: None,
stderr: None,
}
}
/// Returns a reference to the local end of the component's directory_request channel,
/// creating it if necessary.
pub fn directory_request(&mut self) -> Result<&Arc<zx::Channel>, Error> {
Ok(match self.directory_request {
Some(ref channel) => channel,
None => {
let (directory_request, directory_server_chan) = zx::Channel::create()?;
let directory_request = Arc::new(directory_request);
self.launch_info.directory_request = Some(directory_server_chan);
self.directory_request = Some(directory_request);
self.directory_request.as_ref().unwrap()
}
})
}
/// Configures stdout for the new process.
pub fn stdout(mut self, cfg: impl Into<Stdio>) -> Self {
self.stdout = Some(cfg.into());
self
}
/// Configures stderr for the new process.
pub fn stderr(mut self, cfg: impl Into<Stdio>) -> Self {
self.stderr = Some(cfg.into());
self
}
/// Mounts a handle to a directory in the namespace of the component.
pub fn add_handle_to_namespace(mut self, path: String, handle: zx::Handle) -> Self {
let namespace = self
.launch_info
.flat_namespace
.get_or_insert_with(|| Box::new(FlatNamespace { paths: vec![], directories: vec![] }));
add_handle_to_namespace(namespace, path, handle);
self
}
/// Mounts an opened directory in the namespace of the component.
pub fn add_dir_to_namespace(self, path: String, dir: File) -> Result<Self, Error> {
let handle = fdio::transfer_fd(dir)?;
Ok(self.add_handle_to_namespace(path, handle))
}
/// Append the given `arg` to the sequence of arguments passed to the new process.
pub fn arg(mut self, arg: impl Into<String>) -> Self {
self.launch_info.arguments.get_or_insert_with(Vec::new).push(arg.into());
self
}
/// Append all the given `args` to the sequence of arguments passed to the new process.
pub fn args(mut self, args: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.launch_info
.arguments
.get_or_insert_with(Vec::new)
.extend(args.into_iter().map(|arg| arg.into()));
self
}
/// Launch the component using the provided `launcher` proxy, returning the launched
/// application or the error encountered while launching it.
///
/// By default:
/// * when the returned [`App`] is dropped, the launched application will be terminated.
/// * stdout and stderr will use the the default stdout and stderr for the environment.
pub fn spawn(self, launcher: &LauncherProxy) -> Result<App, Error> {
self.launch(launcher)
}
/// Launches the component using the provided `launcher` proxy, waits for it to finish, and
/// collects all of its output.
///
/// By default, stdout and stderr are captured (and used to provide the resulting output).
pub fn output(
mut self,
launcher: &LauncherProxy,
) -> Result<impl Future<Output = Result<Output, Error>>, Error> {
self.stdout = self.stdout.or(Some(Stdio::MakePipe));
self.stderr = self.stderr.or(Some(Stdio::MakePipe));
Ok(self.launch(launcher)?.wait_with_output())
}
/// Launches the component using the provided `launcher` proxy, waits for it to finish, and
/// collects its exit status.
///
/// By default, stdout and stderr will use the default stdout and stderr for the
/// environment.
pub fn status(
self,
launcher: &LauncherProxy,
) -> Result<impl Future<Output = Result<ExitStatus, Error>>, Error> {
Ok(self.launch(launcher)?.wait())
}
fn launch(mut self, launcher: &LauncherProxy) -> Result<App, Error> {
let (controller, controller_server_end) = fidl::endpoints::create_proxy()?;
let directory_request = if let Some(directory_request) = self.directory_request.take() {
directory_request
} else {
let (directory_request, directory_server_chan) = zx::Channel::create()?;
self.launch_info.directory_request = Some(directory_server_chan);
Arc::new(directory_request)
};
let (stdout, remote_stdout) =
self.stdout.unwrap_or(Stdio::Inherit).to_local_and_remote()?;
if let Some(fd) = remote_stdout {
self.launch_info.out = Some(Box::new(fd));
}
let (stderr, remote_stderr) =
self.stderr.unwrap_or(Stdio::Inherit).to_local_and_remote()?;
if let Some(fd) = remote_stderr {
self.launch_info.err = Some(Box::new(fd));
}
launcher
.create_component(&mut self.launch_info, Some(controller_server_end.into()))
.context("Failed to start a new Fuchsia application.")?;
Ok(App { directory_request, controller, stdout, stderr })
}
}
/// Describes what to do with a standard I/O stream for a child component.
#[derive(Debug)]
pub enum Stdio {
/// Use the default output sink for the environment.
Inherit,
/// Capture the component's output in a new socket.
MakePipe,
/// Provide a handle (that is valid in a `fidl_fuchsia_sys::FileDescriptor`) to the component to
/// write output to.
Handle(zx::Handle),
}
impl Stdio {
fn to_local_and_remote(
self,
) -> Result<(Option<fasync::Socket>, Option<FileDescriptor>), Error> {
match self {
Stdio::Inherit => Ok((None, None)),
Stdio::MakePipe => {
let (local, remote) = Socket::create(SocketOpts::STREAM)?;
// local end is read-only
local.half_close()?;
let local = fasync::Socket::from_socket(local)?;
let remote = FileDescriptor {
type0: HandleType::FileDescriptor as i32,
type1: 0,
type2: 0,
handle0: Some(remote.into()),
handle1: None,
handle2: None,
};
Ok((Some(local), Some(remote)))
}
Stdio::Handle(handle) => Ok((
None,
Some(FileDescriptor {
type0: HandleType::FileDescriptor as i32,
type1: 0,
type2: 0,
handle0: Some(handle),
handle1: None,
handle2: None,
}),
)),
}
}
}
impl<T: Into<zx::Handle>> From<T> for Stdio {
fn from(t: T) -> Self {
Self::Handle(t.into())
}
}
/// Describes the result of a component after it has terminated.
#[derive(Debug, Clone, Error)]
pub struct ExitStatus {
return_code: i64,
termination_reason: TerminationReason,
}
impl ExitStatus {
/// Consumes an `event_stream`, returning the `ExitStatus` of the component when it exits, or
/// the error encountered while waiting for the component to terminate.
pub fn from_event_stream(
event_stream: ComponentControllerEventStream,
) -> impl Future<Output = Result<Self, Error>> {
event_stream
.try_filter_map(|event| {
future::ready(match event {
ComponentControllerEvent::OnTerminated { return_code, termination_reason } => {
Ok(Some(ExitStatus { return_code, termination_reason }))
}
_ => Ok(None),
})
})
.into_future()
.map(|(next, _rest)| match next {
Some(result) => result.map_err(|err| err.into()),
_ => Ok(ExitStatus {
return_code: -1,
termination_reason: TerminationReason::Unknown,
}),
})
}
/// Did the component exit without an error? Success is defined as a reason of exited and
/// a code of 0.
#[inline]
pub fn success(&self) -> bool {
self.exited() && self.return_code == 0
}
/// Returns true if the component exited, as opposed to not starting at all due to some
/// error or terminating with any reason other than `EXITED`.
#[inline]
pub fn exited(&self) -> bool {
self.termination_reason == TerminationReason::Exited
}
/// The reason the component was terminated.
#[inline]
pub fn reason(&self) -> TerminationReason {
self.termination_reason
}
/// The return code from the component. Guaranteed to be non-zero if termination reason is
/// not `EXITED`. | pub fn code(&self) -> i64 {
self.return_code
}
/// Converts the `ExitStatus` to a `Result<(), ExitStatus>`, mapping to `Ok(())` if the
/// component exited with status code 0, or to `Err(ExitStatus)` otherwise.
pub fn ok(&self) -> Result<(), Self> {
if self.success() {
Ok(())
} else {
Err(self.clone())
}
}
}
impl fmt::Display for ExitStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.exited() {
write!(f, "Exited with {}", self.code())
} else {
write!(f, "Terminated with reason {:?}", self.reason())
}
}
}
/// The output of a finished component.
pub struct Output {
/// The exit status of the component.
pub exit_status: ExitStatus,
/// The data that the component wrote to stdout.
pub stdout: Vec<u8>,
/// The data that the component wrote to stderr.
pub stderr: Vec<u8>,
}
/// The output of a component that terminated with a failure.
#[derive(Clone, Error)]
#[error("{}", exit_status)]
pub struct OutputError {
#[source]
exit_status: ExitStatus,
stdout: String,
stderr: String,
}
impl Output {
/// Converts the `Output` to a `Result<(), OutputError>`, mapping to `Ok(())` if the component
/// exited with status code 0, or to `Err(OutputError)` otherwise.
pub fn ok(&self) -> Result<(), OutputError> {
if self.exit_status.success() {
Ok(())
} else {
let stdout = String::from_utf8_lossy(&self.stdout).into_owned();
let stderr = String::from_utf8_lossy(&self.stderr).into_owned();
Err(OutputError { exit_status: self.exit_status.clone(), stdout, stderr })
}
}
}
impl fmt::Debug for OutputError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
struct RawMultilineString<'a>(&'a str);
impl<'a> fmt::Debug for RawMultilineString<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.0.is_empty() {
f.write_str(r#""""#)
} else {
f.write_str("r#\"")?;
f.write_str(self.0)?;
f.write_str("\"#")
}
}
}
f.debug_struct("OutputError")
.field("exit_status", &self.exit_status)
.field("stdout", &RawMultilineString(&self.stdout))
.field("stderr", &RawMultilineString(&self.stderr))
.finish()
}
}
#[cfg(test)]
mod tests {
use fidl::endpoints::DiscoverableService as _;
use fidl_fuchsia_component_client_test::{
ServiceAMarker, ServiceAProxy, ServiceBMarker, ServiceBProxy,
};
use vfs::{
directory::entry::DirectoryEntry, execution_scope::ExecutionScope,
file::vmo::read_only_static, pseudo_directory,
};
use super::*;
#[fasync::run_singlethreaded(test)]
async fn test_svc_connector_svc_does_not_exist() -> Result<(), Error> {
let req = new_protocol_connector::<ServiceAMarker>().context("error probing service")?;
matches::assert_matches!(req.exists().await.context("error checking service"), Ok(false));
let _: ServiceAProxy = req.connect().context("error connecting to service")?;
let req = new_protocol_connector_at::<ServiceAMarker>(SVC_DIR)
.context("error probing service at svc dir")?;
matches::assert_matches!(
req.exists().await.context("error checking service at svc dir"),
Ok(false)
);
let _: ServiceAProxy = req.connect().context("error connecting to service at svc dir")?;
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn test_svc_connector_connect_with_dir() -> Result<(), Error> {
let dir = pseudo_directory! {
ServiceBMarker::SERVICE_NAME => read_only_static("read_only"),
};
let (dir_proxy, dir_server) =
fidl::endpoints::create_proxy::<fidl_fuchsia_io::DirectoryMarker>()?;
let scope = ExecutionScope::new();
dir.open(
scope,
fidl_fuchsia_io::OPEN_RIGHT_READABLE,
fidl_fuchsia_io::MODE_TYPE_DIRECTORY,
vfs::path::Path::empty(),
ServerEnd::new(dir_server.into_channel()),
);
let req = new_protocol_connector_in_dir::<ServiceAMarker>(&dir_proxy);
matches::assert_matches!(
req.exists().await.context("error probing invalid service"),
Ok(false)
);
let _: ServiceAProxy = req.connect().context("error connecting to invalid service")?;
let req = new_protocol_connector_in_dir::<ServiceBMarker>(&dir_proxy);
matches::assert_matches!(req.exists().await.context("error probing service"), Ok(true));
let _: ServiceBProxy = req.connect().context("error connecting to service")?;
Ok(())
}
} | #[inline] |
day15.rs | use crate::utils::read_file;
use anyhow::Result;
use itertools::iproduct;
use itertools::Itertools;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
// https://adventofcode.com/2021/day/15
pub type Point = (usize, usize);
pub type Map = Vec<Vec<u8>>;
pub fn read_input(args: &crate::File) -> Result<Map> {
let file = read_file(&args.file)?;
let input = file
.lines()
.map(|l| l.chars().map(|c| c as u8 - b'0').collect_vec())
.collect_vec();
// Expand it 5x
let (w, h) = (input[0].len(), input.len());
let mut xmap = vec![vec![0; w * 5]; h * 5];
for (y, x) in iproduct!(0..h * 5, 0..w * 5) {
let xtra = y / h + x / w;
let v = ((input[y % h][x % w] as usize + xtra - 1) % 9) as u8 + 1;
xmap[y][x] = v;
}
Ok(xmap)
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
struct Node {
pub cost: u16,
pub pos: Point,
}
impl Ord for Node {
fn cmp(&self, other: &Self) -> Ordering {
other.cost.cmp(&self.cost)
}
}
// `PartialOrd` needs to be implemented as well.
impl PartialOrd for Node {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(other.cost.cmp(&self.cost))
}
}
pub fn run(input: &[Vec<u8>]) -> (usize, usize) {
let (w, h) = (input[0].len(), input.len());
let (p1w, p1h) = (w / 5, h / 5);
let mut open = BinaryHeap::<Node>::new();
let mut costs = vec![vec![u16::MAX; w]; h];
open.push(Node {
cost: 0,
pos: (0, 0),
});
costs[0][0] = 0;
let mut insert = |x: usize, y: usize, cost: u16, open: &mut BinaryHeap<Node>| {
let cost = cost + input[y][x] as u16;
if costs[y][x] > cost {
costs[y][x] = cost;
open.push(Node { cost, pos: (x, y) });
}
};
let mut prio_max = 0;
let mut r1 = usize::MAX;
while let Some(node) = open.pop() {
prio_max = prio_max.max(open.len());
if node.pos == (p1w - 1, p1h - 1) {
r1 = r1.min(node.cost as usize);
}
if node.pos == (w - 1, h - 1) {
return (r1, node.cost as usize);
}
if node.pos.0 < w - 1 {
insert(node.pos.0 + 1, node.pos.1, node.cost, &mut open);
} | if node.pos.1 < h - 1 {
insert(node.pos.0, node.pos.1 + 1, node.cost, &mut open);
}
if node.pos.1 > 0 {
insert(node.pos.0, node.pos.1 - 1, node.cost, &mut open);
}
}
(r1, 0)
}
pub fn day15(args: &crate::File) -> Result<()> {
let map = read_input(args)?;
let result = run(&map);
println!("Result of Part 1 is {}", result.0);
println!("Result of Part 2 is {}", result.1);
Ok(())
} | if node.pos.0 > 0 {
insert(node.pos.0 - 1, node.pos.1, node.cost, &mut open);
} |
jquery-1.7.2.min.js | /*! jQuery v1.7.2 jquery.com | jquery.org/license */
(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"<!doctype html>":"")+"<html><body>"),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function ca(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function b_(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bD.test(a)?d(a,e):b_(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&f.type(b)==="object")for(var e in b)b_(a+"["+e+"]",b[e],c,d);else d(a,b)}function b$(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function bZ(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bS,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bZ(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bZ(a,c,d,e,"*",g));return l}function bY(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bO),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bB(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?1:0,g=4;if(d>0){if(c!=="border")for(;e<g;e+=2)c||(d-=parseFloat(f.css(a,"padding"+bx[e]))||0),c==="margin"?d+=parseFloat(f.css(a,c+bx[e]))||0:d-=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0;return d+"px"}d=by(a,b);if(d<0||d==null)d=a.style[b];if(bt.test(d))return d;d=parseFloat(d)||0;if(c)for(;e<g;e+=2)d+=parseFloat(f.css(a,"padding"+bx[e]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+bx[e]))||0);return d+"px"}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;b.nodeType===1&&(b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?b.outerHTML=a.outerHTML:c!=="input"||a.type!=="checkbox"&&a.type!=="radio"?c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text):(a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value)),b.removeAttribute(f.expando),b.removeAttribute("_submit_attached"),b.removeAttribute("_change_attached"))}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c,i[c][d])}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h,i){var j,k=d==null,l=0,m=a.length;if(d&&typeof d=="object"){for(l in d)e.access(a,c,l,d[l],1,h,f);g=1}else if(f!==b){j=i===b&&e.isFunction(f),k&&(j?(j=c,c=function(a,b,c){return j.call(e(a),c)}):(c.call(a,f),c=null));if(c)for(;l<m;l++)c(a[l],d,j?f.call(a[l],l,c(a[l],d)):f,i);g=1}return g?a:k?c.call(a):m?c(a[0],d):h},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test("聽")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m,n=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?n(g):h==="function"&&(!a.unique||!p.has(g))&&c.push(g)},o=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,j=!0,m=k||0,k=0,l=c.length;for(;c&&m<l;m++)if(c[m].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}j=!1,c&&(a.once?e===!0?p.disable():c=[]:d&&d.length&&(e=d.shift(),p.fireWith(e[0],e[1])))},p={add:function(){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){j&&f<=l&&(l--,f<=m&&m--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&p.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(j?a.once||d.push([b,c]):(!a.once||!e)&&o(b,c));return this},fire:function(){p.fireWith(this,arguments);return this},fired:function(){return!!i}};return p};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p=c.createElement("div"),q=c.documentElement;p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="<div "+n+"display:block;'><div style='"+t+"0;display:block;overflow:hidden;'></div></div>"+"<table "+n+"' cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="<table><tr><td style='"+t+"0;display:none'></td><td>t</td></tr></table>",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="<div style='width:5px;'></div>",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h,i,j=this[0],k=0,m=null;if(a===b){if(this.length){m=f.data(j);if(j.nodeType===1&&!f._data(j,"parsedAttrs")){g=j.attributes;for(i=g.length;k<i;k++)h=g[k].name,h.indexOf("data-")===0&&(h=f.camelCase(h.substring(5)),l(j,h,m[h]));f._data(j,"parsedAttrs",!0)}}return m}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!";return f.access(this,function(c){if(c===b){m=this.triggerHandler("getData"+e,[d[0]]),m===b&&j&&(m=f.data(j,a),m=l(j,a,m));return m===b&&d[1]?this.data(d[0]):m}d[1]=c,this.each(function(){var b=f(this);b.triggerHandler("setData"+e,d),f.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length<d)return f.queue(this[0],a);return c===b?this:this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise(c)}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,f.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i<g;i++)e=d[i],e&&(c=f.propFix[e]||e,h=u.test(e),h||f.attr(a,e,""),a.removeAttribute(v?e:c),h&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0,coords:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function( | a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:g&&G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=f.event.special[c.type]||{},j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(!i.preDispatch||i.preDispatch.call(this,c)!==!1){if(e&&(!c.button||c.type!=="click")){n=f(this),n.context=this.ownerDocument||this;for(m=c.target;m!=this;m=m.parentNode||this)if(m.disabled!==!0){p={},r=[],n[0]=m;for(k=0;k<e;k++)s=d[k],t=s.selector,p[t]===b&&(p[t]=s.quick?H(m,s.quick):n.is(t)),p[t]&&r.push(s);r.length&&j.push({elem:m,matches:r})}}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){q=j[k],c.currentTarget=q.elem;for(l=0;l<q.matches.length&&!c.isImmediatePropagationStopped();l++){s=q.matches[l];if(h||!c.namespace&&!s.namespace||c.namespace_re&&c.namespace_re.test(s.namespace))c.data=s.data,c.handleObj=s,o=((f.event.special[s.origType]||{}).handle||s.handler).apply(q.elem,g),o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()))}}i.postDispatch&&i.postDispatch.call(this,c);return c.result}},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),d._submit_attached=!0)})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9||d===11){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.globalPOS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")[\\s/>]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f
.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(f.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(g){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,function(a,b){b.src?f.ajax({type:"GET",global:!1,url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1></$2>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]==="<table>"&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i<u;i++)bn(l[i]);else bn(l);l.nodeType?j.push(l):j=f.merge(j,l)}if(d){g=function(a){return!a.type||be.test(a.type)};for(k=0;j[k];k++){h=j[k];if(e&&f.nodeName(h,"script")&&(!h.type||be.test(h.type)))e.push(h.parentNode?h.parentNode.removeChild(h):h);else{if(h.nodeType===1){var v=f.grep(h.getElementsByTagName("script"),g);j.splice.apply(j,[k+1,0].concat(v))}d.appendChild(h)}}}return j},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bp=/alpha\([^)]*\)/i,bq=/opacity=([^)]*)/,br=/([A-Z]|^ms)/g,bs=/^[\-+]?(?:\d*\.)?\d+$/i,bt=/^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,bu=/^([\-+])=([\-+.\de]+)/,bv=/^margin/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Top","Right","Bottom","Left"],by,bz,bA;f.fn.css=function(a,c){return f.access(this,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)},a,c,arguments.length>1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),(e===""&&f.css(d,"display")==="none"||!f.contains(d.ownerDocument.documentElement,d))&&f._data(d,"olddisplay",cu(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ct("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(ct("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o,p,q;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]);if((k=f.cssHooks[g])&&"expand"in k){l=k.expand(a[g]),delete a[g];for(i in l)i in a||(a[i]=l[i])}}for(g in a){h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cu(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cm.test(h)?(q=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),q?(f._data(this,"toggle"+i,q==="show"?"hide":"show"),j[q]()):j[h]()):(m=cn.exec(h),n=j.cur(),m?(o=parseFloat(m[2]),p=m[3]||(f.cssNumber[i]?"":"px"),p!=="px"&&(f.style(this,i,(o||1)+p),n=(o||1)/j.cur()*n,f.style(this,i,n+p)),m[1]&&(o=(m[1]==="-="?-1:1)*o+n),j.custom(n,o,p)):j.custom(n,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:ct("show",1),slideUp:ct("hide",1),slideToggle:ct("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a){return a},swing:function(a){return-Math.cos(a*Math.PI)/2+.5}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cq||cr(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){f._data(e.elem,"fxshow"+e.prop)===b&&(e.options.hide?f._data(e.elem,"fxshow"+e.prop,e.start):e.options.show&&f._data(e.elem,"fxshow"+e.prop,e.end))},h()&&f.timers.push(h)&&!co&&(co=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cq||cr(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(co),co=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(cp.concat.apply([],cp),function(a,b){b.indexOf("margin")&&(f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)})}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cv,cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?cv=function(a,b,c,d){try{d=a.getBoundingClientRect()}catch(e){}if(!d||!f.contains(c,a))return d?{top:d.top,left:d.left}:{top:0,left:0};var g=b.body,h=cy(b),i=c.clientTop||g.clientTop||0,j=c.clientLeft||g.clientLeft||0,k=h.pageYOffset||f.support.boxModel&&c.scrollTop||g.scrollTop,l=h.pageXOffset||f.support.boxModel&&c.scrollLeft||g.scrollLeft,m=d.top+k-i,n=d.left+l-j;return{top:m,left:n}}:cv=function(a,b,c){var d,e=a.offsetParent,g=a,h=b.body,i=b.defaultView,j=i?i.getComputedStyle(a,null):a.currentStyle,k=a.offsetTop,l=a.offsetLeft;while((a=a.parentNode)&&a!==h&&a!==c){if(f.support.fixedPosition&&j.position==="fixed")break;d=i?i.getComputedStyle(a,null):a.currentStyle,k-=a.scrollTop,l-=a.scrollLeft,a===e&&(k+=a.offsetTop,l+=a.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(a.nodeName))&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),g=e,e=a.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),j=d}if(j.position==="relative"||j.position==="static")k+=h.offsetTop,l+=h.offsetLeft;f.support.fixedPosition&&j.position==="fixed"&&(k+=Math.max(c.scrollTop,h.scrollTop),l+=Math.max(c.scrollLeft,h.scrollLeft));return{top:k,left:l}},f.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){f.offset.setOffset(this,a,b)});var c=this[0],d=c&&c.ownerDocument;if(!d)return null;if(c===d.body)return f.offset.bodyOffset(c);return cv(c,d,d.documentElement)},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); | |
edit.test.tsx | import { writeStorage } from "@rehooks/local-storage";
import { OperationsResponse } from "common-ui";
import { DEFAULT_GROUP_STORAGE_KEY } from "../../../../components/group-select/useStoredDefaultGroup";
import { PcrProfileEditPage } from "../../../../pages/seqdb/pcr-profile/edit";
import { mountWithAppContext } from "../../../../test-util/mock-app-context";
import { PcrProfile } from "../../../../types/seqdb-api/resources/PcrProfile";
// Mock out the Link component, which normally fails when used outside of a Next app.
jest.mock("next/link", () => ({ children }) => <div>{children}</div>);
/** Mock Kitsu "get" method. */
const mockGet = jest.fn(async path => {
// The get request will return the existing profile.
if (path === "seqdb-api/thermocycler-profile/100") {
// The request for the profile returns the test profile.
return { data: TEST_PROFILE };
} else {
// Requests for the selectable resources (linked group, region, etc.) return an empty array.
return { data: [] };
}
});
/** Mock axios for operations requests. */
const mockPatch = jest.fn();
/** Mock next.js' router "push" function for navigating pages. */
const mockPush = jest.fn();
const apiContext: any = {
apiClient: { get: mockGet, axios: { patch: mockPatch } }
};
describe("PcrProfile edit page", () => {
beforeEach(() => {
// Set the deault group selection:
writeStorage(DEFAULT_GROUP_STORAGE_KEY, "aafc");
jest.clearAllMocks();
});
it("Provides a form to add a PcrProfile.", done => {
mockPatch.mockReturnValueOnce({
data: [
{
data: {
id: "1",
type: "thermocycler-profile"
},
status: 201
}
] as OperationsResponse
});
const wrapper = mountWithAppContext(
<PcrProfileEditPage router={{ query: {}, push: mockPush } as any} />,
{ apiContext }
);
// Edit the profile name.
wrapper.find(".name-field input").simulate("change", {
target: { name: "name", value: "New PcrProfile" }
});
// Submit the form.
wrapper.find("form").simulate("submit");
setImmediate(() => {
expect(mockPatch).lastCalledWith(
"/seqdb-api/operations",
[
{
op: "POST",
path: "thermocycler-profile",
value: {
attributes: {
group: "aafc",
name: "New PcrProfile"
},
id: "00000000-0000-0000-0000-000000000000",
type: "thermocycler-profile"
}
} | // The user should be redirected to the new profile's details page.
expect(mockPush).lastCalledWith("/seqdb/pcr-profile/view?id=1");
done();
});
});
it("Renders an error after form submit if one is returned from the back-end.", done => {
// The patch request will return an error.
mockPatch.mockImplementationOnce(() => ({
data: [
{
errors: [
{
detail: "name size must be between 1 and 10",
status: "422",
title: "Constraint violation"
}
],
status: 422
}
] as OperationsResponse
}));
const wrapper = mountWithAppContext(
<PcrProfileEditPage router={{ query: {}, push: mockPush } as any} />,
{ apiContext }
);
// Submit the form.
wrapper.find("form").simulate("submit");
setImmediate(() => {
wrapper.update();
expect(wrapper.find(".alert.alert-danger").text()).toEqual(
"Constraint violation: name size must be between 1 and 10"
);
expect(mockPush).toBeCalledTimes(0);
done();
});
});
it("Provides a form to edit a PcrProfile.", async () => {
// The patch request will be successful.
mockPatch.mockReturnValueOnce({
data: [
{
data: {
id: "1",
type: "thermocycler-profile"
},
status: 201
}
] as OperationsResponse
});
const wrapper = mountWithAppContext(
<PcrProfileEditPage
router={{ query: { id: 100 }, push: mockPush } as any}
/>,
{ apiContext }
);
// The page should load initially with a loading spinner.
expect(wrapper.find(".spinner-border").exists()).toEqual(true);
// Wait for the profile form to load.
await new Promise(setImmediate);
wrapper.update();
// // Check that the existing profile's app value is in the field.
expect(wrapper.find(".application-field input").prop("value")).toEqual(
"PCR of ITS regions"
);
// Modify the application value.
wrapper.find(".application-field input").simulate("change", {
target: { name: "application", value: "new app value" }
});
// Submit the form.
wrapper.find("form").simulate("submit");
await new Promise(setImmediate);
// "patch" should have been called with a jsonpatch request containing the existing values
// and the modified one.
expect(mockPatch).lastCalledWith(
"/seqdb-api/operations",
[
{
op: "PATCH",
path: "thermocycler-profile/1",
value: {
attributes: expect.objectContaining({
application: "new app value",
group: "aafc",
name: "PROF1"
}),
id: "1",
relationships: {
region: {
data: expect.objectContaining({ id: "2", type: "region" })
}
},
type: "thermocycler-profile"
}
}
],
expect.anything()
);
// The user should be redirected to the existing profile's details page.
expect(mockPush).lastCalledWith("/seqdb/pcr-profile/view?id=1");
});
});
/** Test Profile with all fields defined. */
const TEST_PROFILE: Required<PcrProfile> = {
application: "PCR of ITS regions",
cycles: "cycles",
group: "aafc",
id: "1",
lastModified: "2013-03-19T04:00:00.000+0000",
name: "PROF1",
region: {
description: "ITS Region",
id: "2",
name: "Internal Transcribed Spacer",
symbol: "ITS",
type: "region"
},
step1: "step1",
step10: null,
step11: null,
step12: null,
step13: null,
step14: null,
step15: null,
step2: "step2",
step3: "step3",
step4: null,
step5: null,
step6: null,
step7: null,
step8: null,
step9: null,
type: "thermocycler-profile"
}; | ],
expect.anything()
);
|
fifth.rs | //unsafe magic deque
//
use std::ptr;
pub struct List<T> {
head: Link<T>,
tail: *mut Node<T>, // DANGER DANGER
}
type Link<T> = Option<Box<Node<T>>>;
struct Node<T> {
elem: T,
next: Link<T>,
}
impl<T> List<T> {
pub fn new() -> Self {
List {
head: None,
tail: ptr::null_mut(), //0 as *mut_
}
}
pub fn push(&mut self, elem: T) {
let mut new_node = Box::new(Node {
elem: elem,
next: None,
});
let raw_tail: *mut _ = &mut *new_node;
// tail is not null
if !self.tail.is_null() {
unsafe {
(*(self.tail)).next = Some(new_node);
}
} else {
//末端如果是空,则表示没有数据,从头部插入
self.head = Some(new_node);
}
//将指针赋值给tail
self.tail = raw_tail;
}
pub fn pop(&mut self) -> Option<T> {
self.head.take().map(|head| {
let head = *head;
self.head = head.next;
if self.head.is_none() {
self.tail = ptr::null_mut();
}
head.elem
})
}
pub fn peek(&self) -> Option<&T> {
self.head.as_ref().map(|node| &node.elem)
}
pub fn peek_mut(&mut self) -> Option<&mut T> {
self.head.as_mut().map(|node| &mut node.el | r {
// deref roadmap ( as_ref() -> Box ) to Node<T> and use & to ref Node<T>
next: self.head.as_ref().map(|n| &**n),
}
}
pub fn into_iter(self) -> IntoIter<T> {
IntoIter(self)
}
pub fn iter_mut(&mut self) -> IterMut<'_, T> {
IterMut {
next: self.head.as_mut().map(|n| &mut **n),
}
}
}
pub struct IntoIter<T>(List<T>);
impl<T> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.0.pop()
}
}
pub struct Iter<'a, T> {
next: Option<&'a Node<T>>,
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.next.map(|n| {
self.next = n.next.as_ref().map(|node| &**node);
&n.elem
})
}
}
pub struct IterMut<'a, T> {
next: Option<&'a mut Node<T>>,
}
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
self.next.take().map(|n| {
self.next = n.next.as_mut().map(|node| &mut **node);
&mut n.elem
})
}
}
impl<T> Drop for List<T> {
fn drop(&mut self) {
let mut curl_link = self.head.take();
while let Some(mut boxed_node) = curl_link {
curl_link = boxed_node.next.take();
}
}
}
#[cfg(test)]
mod test {
use super::List;
#[test]
fn basics() {
let mut list = List::new();
// Check empty list behaves right
assert_eq!(list.pop(), None);
// Populate list
list.push(1);
list.push(2);
list.push(3);
// Check normal removal
assert_eq!(list.pop(), Some(1));
assert_eq!(list.pop(), Some(2));
// Push some more just to make sure nothing's corrupted
list.push(4);
list.push(5);
// Check normal removal
assert_eq!(list.pop(), Some(3));
assert_eq!(list.pop(), Some(4));
// Check exhaustion
assert_eq!(list.pop(), Some(5));
assert_eq!(list.pop(), None);
// Check the exhaustion case fixed the pointer right
list.push(6);
list.push(7);
// Check normal removal
assert_eq!(list.pop(), Some(6));
assert_eq!(list.pop(), Some(7));
assert_eq!(list.pop(), None);
}
#[test]
fn into_iter() {
let mut list = List::new();
list.push(1);
list.push(2);
list.push(3);
let mut iter = list.into_iter();
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), Some(3));
assert_eq!(iter.next(), None);
}
#[test]
fn iter() {
let mut list = List::new();
list.push(1);
list.push(2);
list.push(3);
let mut iter = list.iter();
assert_eq!(iter.next(), Some(&1));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), Some(&3));
assert_eq!(iter.next(), None);
}
#[test]
fn iter_mut() {
let mut list = List::new();
list.push(1);
list.push(2);
list.push(3);
let mut iter_mut = list.iter_mut();
assert_eq!(iter_mut.next(), Some(&mut 1));
assert_eq!(iter_mut.next(), Some(&mut 2));
assert_eq!(iter_mut.next(), Some(&mut 3));
assert_eq!(iter_mut.next(), None);
}
}
| em)
}
pub fn iter(&self) -> Iter<'_, T> {
Ite |
mute_user_test.go | package build_test
import (
"github.com/memocash/index/ref/bitcoin/tx/build"
"github.com/memocash/index/ref/bitcoin/util/testing/test_tx"
"testing"
)
type MuteTest struct {
Request build.MuteUserRequest
Error string
TxHashes []test_tx.TxHash
}
func (tst MuteTest) Test(t *testing.T) {
txs, err := build.MuteUser(tst.Request)
test_tx.Checker{
Txs: txs,
Error: tst.Error,
TxHashes: tst.TxHashes,
}.Check(err, t)
}
func TestMuteSimple(t *testing.T) {
MuteTest{
Request: build.MuteUserRequest{
Wallet: test_tx.GetAddress1WalletSingle100k(),
MutePkHash: test_tx.Address2pkHash,
},
TxHashes: []test_tx.TxHash{{
TxHash: "2b297840d2aa91df997388a10409961156663001dd3599996abdc6ff80767a65",
TxRaw: "0100000001290c9e545233529c68f1efac662cb3370df17d08cdbaa7e63e04284e670ffef4000000006b483045022100be7216bc619a8517fee8293b85e4d08f2dea50af670ffe6f6dead832fecedbdd02205771c4f5bcdfbf1073b87951e2a75e8fef7886e4585c96942ee4cbe88bc71204412103065e9c67d6ef37c1b08f88d74a4b2090aa8d69f2e6ab5c116f60f05a78f2ededffffffff020000000000000000196a026d16140d4cd6490ddf863bbdf5c34d8ef1aebfd45c2105be850100000000001976a914fc393e225549da044ed2c0011fd6c8a799806b6288ac00000000",
}},
}.Test(t)
}
func | (t *testing.T) {
MuteTest{
Request: build.MuteUserRequest{
Wallet: test_tx.GetAddress1WalletSingle100k(),
MutePkHash: test_tx.Address2pkHash,
Unmute: true,
},
TxHashes: []test_tx.TxHash{{
TxHash: "1016ecca958fcfdfa7070b01427c375aefd7ee4c9f89180efd7ecf48345cb6e4",
TxRaw: "0100000001290c9e545233529c68f1efac662cb3370df17d08cdbaa7e63e04284e670ffef4000000006a4730440220234a5b82dd12627294eef6c99b98070483b2858e036b4d50dcd4b34e04fe4274022038ba7162094c587e4bd388f9c3843e7a62e36ae96f6c3e8fe6dd17d2a9e7681f412103065e9c67d6ef37c1b08f88d74a4b2090aa8d69f2e6ab5c116f60f05a78f2ededffffffff020000000000000000196a026d17140d4cd6490ddf863bbdf5c34d8ef1aebfd45c2105be850100000000001976a914fc393e225549da044ed2c0011fd6c8a799806b6288ac00000000",
}},
}.Test(t)
}
| TestUnmuteSimple |
output.tsx | import { __styles } from '@griffel/react';
import { createModule } from './module';
export const useStyles = __styles(
{
container: {
sj55zd: 'fe3e8s9', | },
);
createModule().baz(); | },
},
{
d: ['.fe3e8s9{color:red;}'], |
part_2.rs | pub fn solution() {
let file_input = std::fs::read_to_string("./src/day_2/input.txt").unwrap();
let input: Vec<usize> = file_input
.trim()
.split(',')
.map(|line| line.parse().unwrap())
.collect();
println!("{:?}", noun_verb_result(input, 19_690_720));
}
pub fn opcode_output(instruction_pointer: usize, mut input: Vec<usize>) -> Vec<usize> |
pub fn noun_verb_result(input: Vec<usize>, expected_result: usize) -> Option<usize> {
for noun in 0..=99 {
for verb in 0..=99 {
let mut input_copy = input.clone();
input_copy[1] = noun;
input_copy[2] = verb;
let input_copy = opcode_output(0, input_copy);
if input_copy[0] == expected_result {
return Some(100 * input_copy[1] + input_copy[2]);
}
}
}
None
}
| {
let opcode = input[instruction_pointer];
if opcode == 1 || opcode == 2 {
let position_input_1 = input[instruction_pointer + 1];
let position_input_2 = input[instruction_pointer + 2];
let position_output = input[instruction_pointer + 3];
let output = if opcode == 1 {
input[position_input_1] + input[position_input_2]
} else {
input[position_input_1] * input[position_input_2]
};
input[position_output] = output;
opcode_output(instruction_pointer + 4, input)
} else {
input
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.