file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
interfaces.ts
export type IMiddlewareFunc = (x: any) => any; export interface IMapDependency { [key: string]: any; } export type IDependencies = string[] | string | IMapDependency; export interface IBaseOptions { depends?: IDependencies; function?: boolean; } export interface IEntityMiddleware { before: any[]; after: any[]; } export interface IGlobalMiddlewares { [key: string]: any[]; }
export interface IMiddlewares { [key: string]: IEntityMiddleware; } export interface IRegisterable { name: string; options: IBaseOptions; } export interface IInstance<T = any> extends IRegisterable { name: string; instance?: T; depends: IDependencies; /** * Origin Factory */ factory?: IInstanceConstructor | IInstanceCreatingFunction; } export interface IFactory<T = any> extends IInstance, IRegisterable { instance?: T; depends: IDependencies; } export interface IFunctionalFactory extends IFactory, IRegisterable { factory: IInstanceCreatingFunction; } export interface IConstructorFactory extends IFactory, IRegisterable { factory: IInstanceConstructor; } export type IInstanceCreatingFunction = (...any) => IInstance; export type IInstanceConstructor = new (...any) => IInstance;
common.rs
use std::hash::{Hash, Hasher}; use std::str::FromStr; use std::time::Duration; use chrono::{Local, TimeZone, Utc}; use itertools::izip; use serde::Deserialize; use tickrs_api::Interval; use crate::api::model::ChartData; use crate::api::Range; #[derive(PartialEq, Clone, Copy, Debug, Hash)] pub enum ChartType { Line, Candlestick, } impl ChartType { pub fn toggle(self) -> Self { match self { ChartType::Line => ChartType::Candlestick, ChartType::Candlestick => ChartType::Line, } } } #[derive(Clone, Copy, PartialOrd, Debug, Hash, PartialEq, Eq, Deserialize)] pub enum TimeFrame { #[serde(alias = "1D")] Day1, #[serde(alias = "1W")] Week1, #[serde(alias = "1M")] Month1, #[serde(alias = "3M")] Month3, #[serde(alias = "6M")] Month6, #[serde(alias = "1Y")] Year1, #[serde(alias = "5Y")] Year5, } impl FromStr for TimeFrame { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { use TimeFrame::*; match s { "1D" => Ok(Day1), "1W" => Ok(Week1), "1M" => Ok(Month1), "3M" => Ok(Month3), "6M" => Ok(Month6), "1Y" => Ok(Year1), "5Y" => Ok(Year5), _ => Err("Valid time frames are: '1D', '1W', '1M', '3M', '6M', '1Y', '5Y'"), } } } impl TimeFrame { pub fn idx(self) -> usize { match self { TimeFrame::Day1 => 0, TimeFrame::Week1 => 1, TimeFrame::Month1 => 2, TimeFrame::Month3 => 3, TimeFrame::Month6 => 4, TimeFrame::Year1 => 5, TimeFrame::Year5 => 6, } } pub const fn tab_names() -> [&'static str; 7] { ["1D", "1W", "1M", "3M", "6M", "1Y", "5Y"] } pub const ALL: [TimeFrame; 7] = [ TimeFrame::Day1, TimeFrame::Week1, TimeFrame::Month1, TimeFrame::Month3, TimeFrame::Month6, TimeFrame::Year1, TimeFrame::Year5, ]; pub fn update_interval(self) -> Duration { match self { TimeFrame::Day1 => Duration::from_secs(60), TimeFrame::Week1 => Duration::from_secs(60 * 5), TimeFrame::Month1 => Duration::from_secs(60 * 30), TimeFrame::Month3 => Duration::from_secs(60 * 60), TimeFrame::Month6 => Duration::from_secs(60 * 60), TimeFrame::Year1 => Duration::from_secs(60 * 60 * 24), TimeFrame::Year5 => Duration::from_secs(60 * 60 * 24), } } pub fn up(self) -> TimeFrame { match self { TimeFrame::Day1 => TimeFrame::Week1, TimeFrame::Week1 => TimeFrame::Month1, TimeFrame::Month1 => TimeFrame::Month3, TimeFrame::Month3 => TimeFrame::Month6, TimeFrame::Month6 => TimeFrame::Year1, TimeFrame::Year1 => TimeFrame::Year5, TimeFrame::Year5 => TimeFrame::Day1, } } pub fn down(self) -> TimeFrame { match self { TimeFrame::Day1 => TimeFrame::Year5, TimeFrame::Week1 => TimeFrame::Day1, TimeFrame::Month1 => TimeFrame::Week1, TimeFrame::Month3 => TimeFrame::Month1, TimeFrame::Month6 => TimeFrame::Month3, TimeFrame::Year1 => TimeFrame::Month6, TimeFrame::Year5 => TimeFrame::Year1, } } pub fn as_range(self) -> Range { match self { TimeFrame::Day1 => Range::Day1, TimeFrame::Week1 => Range::Day5, TimeFrame::Month1 => Range::Month1, TimeFrame::Month3 => Range::Month3, TimeFrame::Month6 => Range::Month6, TimeFrame::Year1 => Range::Year1, TimeFrame::Year5 => Range::Year5, } } pub fn api_interval(self) -> Interval { match self { TimeFrame::Day1 => Interval::Minute1, TimeFrame::Week1 => Interval::Minute5, TimeFrame::Month1 => Interval::Minute30, TimeFrame::Month3 => Interval::Minute60, TimeFrame::Month6 => Interval::Minute60, _ => Interval::Day1, } } pub fn round_by(self) -> i64 { match self { TimeFrame::Day1 => 60, TimeFrame::Week1 => 60 * 5, TimeFrame::Month1 => 60 * 30, TimeFrame::Month3 => 60 * 60, TimeFrame::Month6 => 60 * 60, _ => 60 * 60 * 24, } } pub fn format_time(&self, timestamp: i64) -> String { let utc_date = Utc.timestamp(timestamp, 0); let local_date = utc_date.with_timezone(&Local); let fmt = match self { TimeFrame::Day1 => "%H:%M", TimeFrame::Week1 => "%m-%d %H:%M", _ => "%F", }; local_date.format(fmt).to_string() } } #[derive(Debug, Clone, Copy)] pub struct MarketHours(pub i64, pub i64); impl Default for MarketHours { fn default() -> Self { MarketHours(52200, 75600) } } impl Iterator for MarketHours { type Item = i64; fn next(&mut self) -> Option<Self::Item> { let min_rounded_0 = self.0 - self.0 % 60; let min_rounded_1 = self.1 - self.1 % 60; if min_rounded_0 == min_rounded_1 { None } else { let result = Some(min_rounded_0); self.0 = min_rounded_0 + 60; result } } } #[derive(Debug, Clone, Copy, PartialEq)] pub enum TradingPeriod { Pre, Regular, Post, } #[derive(Debug, Clone, Copy, Default)] pub struct Price { pub close: f64, pub volume: u64, pub high: f64, pub low: f64, pub open: f64, pub date: i64, } impl Hash for Price { fn hash<H: Hasher>(&self, state: &mut H) { self.close.to_bits().hash(state); self.volume.hash(state); self.high.to_bits().hash(state); self.low.to_bits().hash(state); self.open.to_bits().hash(state); self.date.hash(state); } } pub fn chart_data_to_prices(mut chart_data: ChartData) -> Vec<Price> { if chart_data.indicators.quote.len() != 1 { return vec![]; } let quote = chart_data.indicators.quote.remove(0); let timestamps = chart_data.timestamp; izip!( &quote.close, &quote.volume, &quote.high, &quote.low, &quote.open, &timestamps, ) .map(|(c, v, h, l, o, t)| Price { close: *c, volume: *v, high: *h, low: *l, open: *o, date: *t, }) .collect() } pub fn cast_as_dataset(input: (usize, &f64)) -> (f64, f64) { ((input.0 + 1) as f64, *input.1) } pub fn cast_historical_as_price(input: &Price) -> f64 { input.close } pub fn zeros_as_pre(prices: &mut [f64]) { if prices.len() <= 1 { return; } let zero_indexes = prices .iter() .enumerate() .filter_map(|(idx, price)| if *price == 0.0 { Some(idx) } else { None }) .collect::<Vec<usize>>(); for idx in zero_indexes { if idx == 0 { prices[0] = prices[1]; } else {
} } }
prices[idx] = prices[idx - 1];
server.dev.js
/**服务器设置 * 开发*/ var gulp = require('gulp'), connect = require('gulp-connect'), option = require('../config.js').serverDev;//服务器 function devServer() { // connect.server(option); } module.exports = devServer; /* var gulp = require('gulp'), connect = require('gulp-connect'), option = require('../config.js').serverDev;//服务器 var browserSync = require('browser-sync').get("My Server"); function devServer() { // //connect.server(option); browserSync.init({
reloadDebounce: 500, browser: "chrome", notify: false, //port: 666,//端口 }); /!* browserSync.init({ proxy: 'http://localhost:3000', browser: 'chrome', port: 7000*!/ } module.exports = devServer;*/
server: option,
worker.rs
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use std::{mem, net, time}; use actix_rt::{spawn, Arbiter}; use futures::sync::mpsc::{UnboundedReceiver, UnboundedSender}; use futures::sync::oneshot; use futures::{future, Async, Future, Poll, Stream}; use log::{error, info, trace}; use tokio_timer::{sleep, Delay}; use crate::accept::AcceptNotify; use crate::counter::Counter; use crate::services::{BoxedServerService, InternalServiceFactory, ServerMessage}; use crate::Token; pub(crate) struct WorkerCommand(Conn); /// Stop worker message. Returns `true` on successful shutdown /// and `false` if some connections still alive. pub(crate) struct StopCommand { graceful: bool, result: oneshot::Sender<bool>, } #[derive(Debug)] pub(crate) struct Conn { pub io: net::TcpStream, pub token: Token, pub peer: Option<net::SocketAddr>, } static MAX_CONNS: AtomicUsize = AtomicUsize::new(25600); /// Sets the maximum per-worker number of concurrent connections. /// /// All socket listeners will stop accepting connections when this limit is /// reached for each worker. /// /// By default max connections is set to a 25k per worker. pub fn max_concurrent_connections(num: usize) { MAX_CONNS.store(num, Ordering::Relaxed); } pub(crate) fn num_connections() -> usize { MAX_CONNS_COUNTER.with(|conns| conns.total()) } thread_local! { static MAX_CONNS_COUNTER: Counter = Counter::new(MAX_CONNS.load(Ordering::Relaxed)); } #[derive(Clone)] pub(crate) struct WorkerClient { pub idx: usize, tx1: UnboundedSender<WorkerCommand>, tx2: UnboundedSender<StopCommand>, avail: WorkerAvailability, } impl WorkerClient { pub fn new( idx: usize, tx1: UnboundedSender<WorkerCommand>, tx2: UnboundedSender<StopCommand>, avail: WorkerAvailability, ) -> Self { WorkerClient { idx, tx1, tx2, avail, } } pub fn send(&self, msg: Conn) -> Result<(), Conn> { self.tx1 .unbounded_send(WorkerCommand(msg)) .map_err(|msg| msg.into_inner().0) } pub fn available(&self) -> bool { self.avail.available() } pub fn stop(&self, graceful: bool) -> oneshot::Receiver<bool> { let (result, rx) = oneshot::channel(); let _ = self.tx2.unbounded_send(StopCommand { graceful, result }); rx } } #[derive(Clone)] pub(crate) struct WorkerAvailability { notify: AcceptNotify, available: Arc<AtomicBool>, } impl WorkerAvailability { pub fn new(notify: AcceptNotify) -> Self { WorkerAvailability { notify, available: Arc::new(AtomicBool::new(false)), } } pub fn available(&self) -> bool
pub fn set(&self, val: bool) { let old = self.available.swap(val, Ordering::Release); if !old && val { self.notify.notify() } } } /// Service worker /// /// Worker accepts Socket objects via unbounded channel and starts stream /// processing. pub(crate) struct Worker { rx: UnboundedReceiver<WorkerCommand>, rx2: UnboundedReceiver<StopCommand>, services: Vec<Option<(usize, BoxedServerService)>>, availability: WorkerAvailability, conns: Counter, factories: Vec<Box<InternalServiceFactory>>, state: WorkerState, shutdown_timeout: time::Duration, } impl Worker { pub(crate) fn start( rx: UnboundedReceiver<WorkerCommand>, rx2: UnboundedReceiver<StopCommand>, factories: Vec<Box<InternalServiceFactory>>, availability: WorkerAvailability, shutdown_timeout: time::Duration, ) { availability.set(false); let mut wrk = MAX_CONNS_COUNTER.with(|conns| Worker { rx, rx2, availability, factories, shutdown_timeout, services: Vec::new(), conns: conns.clone(), state: WorkerState::Unavailable(Vec::new()), }); let mut fut = Vec::new(); for (idx, factory) in wrk.factories.iter().enumerate() { fut.push(factory.create().map(move |res| { res.into_iter() .map(|(t, s)| (idx, t, s)) .collect::<Vec<_>>() })); } spawn( future::join_all(fut) .map_err(|e| { error!("Can not start worker: {:?}", e); Arbiter::current().stop(); }) .and_then(move |services| { for item in services { for (idx, token, service) in item { while token.0 >= wrk.services.len() { wrk.services.push(None); } wrk.services[token.0] = Some((idx, service)); } } wrk }), ); } fn shutdown(&mut self, force: bool) { if force { self.services.iter_mut().for_each(|h| { if let Some(h) = h { let _ = h.1.call((None, ServerMessage::ForceShutdown)); } }); } else { let timeout = self.shutdown_timeout; self.services.iter_mut().for_each(move |h| { if let Some(h) = h { let _ = h.1.call((None, ServerMessage::Shutdown(timeout))); } }); } } fn check_readiness(&mut self, trace: bool) -> Result<bool, (Token, usize)> { let mut ready = self.conns.available(); let mut failed = None; for (token, service) in &mut self.services.iter_mut().enumerate() { if let Some(service) = service { match service.1.poll_ready() { Ok(Async::Ready(_)) => { if trace { trace!( "Service {:?} is available", self.factories[service.0].name(Token(token)) ); } } Ok(Async::NotReady) => ready = false, Err(_) => { error!( "Service {:?} readiness check returned error, restarting", self.factories[service.0].name(Token(token)) ); failed = Some((Token(token), service.0)); } } } } if let Some(idx) = failed { Err(idx) } else { Ok(ready) } } } enum WorkerState { None, Available, Unavailable(Vec<Conn>), Restarting( usize, Token, Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>>, ), Shutdown(Delay, Delay, oneshot::Sender<bool>), } impl Future for Worker { type Item = (); type Error = (); fn poll(&mut self) -> Poll<Self::Item, Self::Error> { // `StopWorker` message handler if let Ok(Async::Ready(Some(StopCommand { graceful, result }))) = self.rx2.poll() { self.availability.set(false); let num = num_connections(); if num == 0 { info!("Shutting down worker, 0 connections"); let _ = result.send(true); return Ok(Async::Ready(())); } else if graceful { self.shutdown(false); let num = num_connections(); if num != 0 { info!("Graceful worker shutdown, {} connections", num); self.state = WorkerState::Shutdown( sleep(time::Duration::from_secs(1)), sleep(self.shutdown_timeout), result, ); } else { let _ = result.send(true); return Ok(Async::Ready(())); } } else { info!("Force shutdown worker, {} connections", num); self.shutdown(true); let _ = result.send(false); return Ok(Async::Ready(())); } } let state = mem::replace(&mut self.state, WorkerState::None); match state { WorkerState::Unavailable(mut conns) => { match self.check_readiness(true) { Ok(true) => { self.state = WorkerState::Available; // process requests from wait queue while let Some(msg) = conns.pop() { match self.check_readiness(false) { Ok(true) => { let guard = self.conns.get(); let _ = self.services[msg.token.0] .as_mut() .expect("actix net bug") .1 .call((Some(guard), ServerMessage::Connect(msg.io))); } Ok(false) => { trace!("Worker is unavailable"); self.state = WorkerState::Unavailable(conns); return self.poll(); } Err((token, idx)) => { trace!( "Service {:?} failed, restarting", self.factories[idx].name(token) ); self.state = WorkerState::Restarting( idx, token, self.factories[idx].create(), ); return self.poll(); } } } self.availability.set(true); return self.poll(); } Ok(false) => { self.state = WorkerState::Unavailable(conns); return Ok(Async::NotReady); } Err((token, idx)) => { trace!( "Service {:?} failed, restarting", self.factories[idx].name(token) ); self.state = WorkerState::Restarting(idx, token, self.factories[idx].create()); return self.poll(); } } } WorkerState::Restarting(idx, token, mut fut) => { match fut.poll() { Ok(Async::Ready(item)) => { for (token, service) in item { trace!( "Service {:?} has been restarted", self.factories[idx].name(token) ); self.services[token.0] = Some((idx, service)); self.state = WorkerState::Unavailable(Vec::new()); } } Ok(Async::NotReady) => { self.state = WorkerState::Restarting(idx, token, fut); return Ok(Async::NotReady); } Err(_) => { panic!( "Can not restart {:?} service", self.factories[idx].name(token) ); } } return self.poll(); } WorkerState::Shutdown(mut t1, mut t2, tx) => { let num = num_connections(); if num == 0 { let _ = tx.send(true); Arbiter::current().stop(); return Ok(Async::Ready(())); } // check graceful timeout match t2.poll().unwrap() { Async::NotReady => (), Async::Ready(_) => { self.shutdown(true); let _ = tx.send(false); Arbiter::current().stop(); return Ok(Async::Ready(())); } } // sleep for 1 second and then check again match t1.poll().unwrap() { Async::NotReady => (), Async::Ready(_) => { t1 = sleep(time::Duration::from_secs(1)); let _ = t1.poll(); } } self.state = WorkerState::Shutdown(t1, t2, tx); return Ok(Async::NotReady); } WorkerState::Available => { loop { match self.rx.poll() { // handle incoming tcp stream Ok(Async::Ready(Some(WorkerCommand(msg)))) => { match self.check_readiness(false) { Ok(true) => { let guard = self.conns.get(); let _ = self.services[msg.token.0] .as_mut() .expect("actix-server bug") .1 .call((Some(guard), ServerMessage::Connect(msg.io))); continue; } Ok(false) => { trace!("Worker is unavailable"); self.availability.set(false); self.state = WorkerState::Unavailable(vec![msg]); } Err((token, idx)) => { trace!( "Service {:?} failed, restarting", self.factories[idx].name(token) ); self.availability.set(false); self.state = WorkerState::Restarting( idx, token, self.factories[idx].create(), ); } } return self.poll(); } Ok(Async::NotReady) => { self.state = WorkerState::Available; return Ok(Async::NotReady); } Ok(Async::Ready(None)) | Err(_) => return Ok(Async::Ready(())), } } } WorkerState::None => panic!(), }; } }
{ self.available.load(Ordering::Acquire) }
json.py
# Copyright 2019 Wilhelm Putz # 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 json import dumps as json_dumps, loads as json_loads def dumps(data): """helper for jinja2""" return json_dumps(data, sort_keys=True, indent=2) def
(data): return json_loads(data)
loads
running.py
# Copyright 2016-2021 The Van Valen Lab at the California Institute of # Technology (Caltech), with support from the Paul Allen Family Foundation, # Google, & National Institutes of Health (NIH) under Grant U24CA224309-01. # All rights reserved. # # Licensed under a modified 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.github.com/vanvalenlab/deepcell-tf/LICENSE # # The Work provided may be used for non-commercial academic purposes only. # For any other use of the Work, including commercial use, please contact: # [email protected] # # Neither the name of Caltech nor the names of its contributors may be used # to endorse or promote products derived from this software without specific # prior written permission. # # 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. # ============================================================================== """Functions for running convolutional neural networks""" from __future__ import absolute_import from __future__ import print_function
from __future__ import division import numpy as np from tensorflow.keras import backend as K from tensorflow.keras.models import Model from deepcell.utils.data_utils import trim_padding def get_cropped_input_shape(images, num_crops=4, receptive_field=61, data_format=None): """Calculate the input_shape for models to process cropped sub-images. Args: images (numpy.array): numpy array of original data num_crops (int): number of slices for the x and y axis to create sub-images receptive_field (int): the receptive field of the neural network. data_format (str): "channels_first" or "channels_last" Returns: tuple: new ``input_shape`` for model to process sub-images. """ if data_format is None: data_format = K.image_data_format() if data_format == 'channels_first': channel_axis = 1 row_axis = len(images.shape) - 2 col_axis = len(images.shape) - 1 else: channel_axis = len(images.shape) - 1 row_axis = len(images.shape) - 3 col_axis = len(images.shape) - 2 channel_dim = images.shape[channel_axis] # Split the frames into quarters, as the full image size is too large crop_x = images.shape[row_axis] // num_crops + (receptive_field - 1) crop_y = images.shape[col_axis] // num_crops + (receptive_field - 1) if images.ndim == 5: input_shape = (images.shape[row_axis - 1], crop_x, crop_y, channel_dim) else: input_shape = (crop_x, crop_y, channel_dim) # switch to channels_first if necessary if channel_axis == 1: input_shape = tuple([input_shape[-1]] + list(input_shape[:-1])) return input_shape def get_padding_layers(model): """Get all names of padding layers in a model Args: model (tensorflow.keras.Model): Keras model Returns: list: list of names of padding layers inside model """ padding_layers = [] for layer in model.layers: if 'padding' in layer.name: padding_layers.append(layer.name) elif isinstance(layer, Model): padding_layers.extend(get_padding_layers(layer)) return padding_layers def process_whole_image(model, images, num_crops=4, receptive_field=61, padding=None): """Slice images into num_crops * num_crops pieces, and use the model to process each small image. Args: model (tensorflow.keras.Model): model that will process each small image images (numpy.array): numpy array that is too big for model.predict num_crops (int): number of slices for the x and y axis to create sub-images receptive_field (int): receptive field used by model, required to pad images padding (str): type of padding for input images, one of {'reflect', 'zero'}. Returns: numpy.array: model outputs for each sub-image Raises: ValueError: invalid padding value ValueError: model input shape is different than expected_input_shape """ if K.image_data_format() == 'channels_first': channel_axis = 1 row_axis = len(images.shape) - 2 col_axis = len(images.shape) - 1 else: channel_axis = len(images.shape) - 1 row_axis = len(images.shape) - 3 col_axis = len(images.shape) - 2 if not padding: padding_layers = get_padding_layers(model) if padding_layers: padding = 'reflect' if 'reflect' in padding_layers[0] else 'zero' if str(padding).lower() not in {'reflect', 'zero'}: raise ValueError('Expected `padding_mode` to be either `zero` or ' '`reflect`. Got ', padding) # Split the frames into quarters, as the full image size is too large crop_x = images.shape[row_axis] // num_crops crop_y = images.shape[col_axis] // num_crops # Set up receptive field window for padding win_x, win_y = (receptive_field - 1) // 2, (receptive_field - 1) // 2 # instantiate matrix for model output model_output_shape = tuple(list(model.layers[-1].output_shape)[1:]) if channel_axis == 1: output = np.zeros(tuple([images.shape[0], model_output_shape[0]] + list(images.shape[2:]))) else: output = np.zeros(tuple(list(images.shape[0:-1]) + [model_output_shape[-1]])) expected_input_shape = get_cropped_input_shape( images, num_crops, receptive_field) if expected_input_shape != model.input_shape[1:]: raise ValueError('Expected model.input_shape to be {}. Got {}. Use ' '`get_cropped_input_shape()` to recreate your model ' ' with the proper input_shape'.format( expected_input_shape, model.input_shape[1:])) # pad the images only in the x and y axes pad_width = [] for i in range(len(images.shape)): if i == row_axis: pad_width.append((win_x, win_x)) elif i == col_axis: pad_width.append((win_y, win_y)) else: pad_width.append((0, 0)) if str(padding).lower() == 'reflect': padded_images = np.pad(images, pad_width, mode='reflect') else: padded_images = np.pad(images, pad_width, mode='constant', constant_values=0) for i in range(num_crops): for j in range(num_crops): e, f = i * crop_x, (i + 1) * crop_x + 2 * win_x g, h = j * crop_y, (j + 1) * crop_y + 2 * win_y if images.ndim == 5: if channel_axis == 1: predicted = model.predict(padded_images[:, :, :, e:f, g:h]) else: predicted = model.predict(padded_images[:, :, e:f, g:h, :]) else: if channel_axis == 1: predicted = model.predict(padded_images[:, :, e:f, g:h]) else: predicted = model.predict(padded_images[:, e:f, g:h, :]) # if using skip_connections, get the final model output if isinstance(predicted, list): predicted = predicted[-1] # if the model uses padding, trim the output images to proper shape # if model does not use padding, images should already be correct if padding: predicted = trim_padding(predicted, win_x, win_y) a, b = i * crop_x, (i + 1) * crop_x c, d = j * crop_y, (j + 1) * crop_y if images.ndim == 5: if channel_axis == 1: output[:, :, :, a:b, c:d] = predicted else: output[:, :, a:b, c:d, :] = predicted else: if channel_axis == 1: output[:, :, a:b, c:d] = predicted else: output[:, a:b, c:d, :] = predicted return output
mod.rs
/* * Copyright 2018-2020 TON DEV SOLUTIONS LTD. * * Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use * this file except in compliance with the License. * * 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 TON DEV software governing permissions and * limitations under the License. */ use serde_json::Value; use ton_sdk::Contract; use crate::client::ClientContext; use crate::types::{ApiResult, ApiError}; use crate::dispatch::DispatchTable; use ton_block::MsgAddressInt; #[derive(Serialize, Deserialize)] #[allow(non_snake_case)] pub(crate) struct ParamsOfLocalRunGet { pub bocBase64: Option<String>, pub codeBase64: Option<String>, pub dataBase64: Option<String>, pub functionName: String, pub input: Option<Value>, pub address: Option<String>, pub balance: Option<String>, pub last_paid: Option<u32>, } #[allow(non_snake_case)] #[derive(Serialize, Deserialize)] pub(crate) struct ResultOfLocalRunGet { pub output: Value, } const DEFAULT_ADDRESS: &str = "0:0000000000000000000000000000000000000000000000000000000000000000"; const DEFAULT_BALANCE: &str = "0xffffffffffffffff"; pub(crate) fn
( context: &mut ClientContext, params: ParamsOfLocalRunGet, ) -> ApiResult<ResultOfLocalRunGet> { trace!("-> contracts.run.get({})", params.functionName, ); let (code_base64, data_base64) = Contract::resolve_code_and_data( &params.bocBase64, &params.codeBase64, &params.dataBase64, ).map_err( |_| { let address = params.address.as_ref().map(|a| crate::crypto::keys::account_decode(a) .unwrap_or(MsgAddressInt::default() )).unwrap_or(MsgAddressInt::default()); ApiError::account_code_missing(&address) } )?; let contract = match &code_base64 { // load contract data from node manually #[cfg(feature = "node_interaction")] None => { trace!("load contract"); let address = params.address.ok_or_else(|| ApiError::address_reqired_for_runget())?; let address = crate::crypto::keys::account_decode(&address)?; let mut runtime = context.take_runtime()?; let result = runtime.block_on(crate::contracts::run::load_contract(context, &address, true)); context.runtime = Some(runtime); result? } // can't load #[cfg(not(feature = "node_interaction"))] None => { trace!("no account provided"); let _context = context; return Err(ApiError::invalid_params("", "No account provided")); } Some(code) => { let last_paid = params.last_paid.unwrap_or(Contract::now()); let contract_json = json!({ "id": params.address.unwrap_or(DEFAULT_ADDRESS.to_string()), "acc_type": 1, "balance": params.balance.unwrap_or(DEFAULT_BALANCE.to_string()), "code": code, "data": data_base64, "last_paid": last_paid, }); Contract::from_json(contract_json.to_string().as_str()) .map_err(|err| ApiError::contracts_local_run_failed(err))? } }; let output = contract.local_call_tvm_get_json( &params.functionName, params.input.as_ref(), ).map_err(|err| ApiError::contracts_local_run_failed(err))?; Ok(ResultOfLocalRunGet { output }) } pub(crate) fn register(handlers: &mut DispatchTable) { handlers.spawn("tvm.get", get); }
get
file_deprecated.go
package validator import ( "io/ioutil" "os" "github.com/teragrid/dgrid/pkg/crypto" cmn "github.com/teragrid/dgrid/pkg/common" "github.com/teragrid/dgrid/core/types" ) // OldFilePV is the old version of the FilePV, pre v0.28.0. // Deprecated: Use FilePV instead. type OldFilePV struct { Address types.Address `json:"address"` PubKey crypto.PubKey `json:"pub_key"` LastHeight int64 `json:"last_height"` LastRound int `json:"last_round"` LastStep int8 `json:"last_step"` LastSignature []byte `json:"last_signature,omitempty"` LastSignBytes cmn.HexBytes `json:"last_signbytes,omitempty"` PrivKey crypto.PrivKey `json:"priv_key"` filePath string } // LoadOldFilePV loads an OldFilePV from the filePath. func LoadOldFilePV(filePath string) (*OldFilePV, error) { pvJSONBytes, err := ioutil.ReadFile(filePath) if err != nil { return nil, err } pv := &OldFilePV{} err = cdc.UnmarshalJSON(pvJSONBytes, &pv) if err != nil { return nil, err } // overwrite pubkey and address for convenience pv.PubKey = pv.PrivKey.PubKey() pv.Address = pv.PubKey.Address() pv.filePath = filePath return pv, nil } // Upgrade convets the OldFilePV to the new FilePV, separating the immutable and mutable components, // and persisting them to the keyFilePath and stateFilePath, respectively. // It renames the original file by adding ".bak". func (oldFilePV *OldFilePV) Upgrade(keyFilePath, stateFilePath string) *FilePV { privKey := oldFilePV.PrivKey pvKey := FilePVKey{ PrivKey: privKey, PubKey: privKey.PubKey(), Address: privKey.PubKey().Address(), filePath: keyFilePath, } pvState := FilePVLastSignState{ Height: oldFilePV.LastHeight, Round: oldFilePV.LastRound, Step: oldFilePV.LastStep, Signature: oldFilePV.LastSignature, SignBytes: oldFilePV.LastSignBytes,
} // Save the new PV files pv := &FilePV{ Key: pvKey, LastSignState: pvState, } pv.Save() // Rename the old PV file err := os.Rename(oldFilePV.filePath, oldFilePV.filePath+".bak") if err != nil { panic(err) } return pv }
filePath: stateFilePath,
controller.go
// Copyright (c) 2018 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package controller import ( "encoding/json" "errors" "fmt" "reflect" "sort" "strconv" "sync" "github.com/m3db/m3db-operator/pkg/apis/m3dboperator" myspec "github.com/m3db/m3db-operator/pkg/apis/m3dboperator/v1alpha1" clientset "github.com/m3db/m3db-operator/pkg/client/clientset/versioned" samplescheme "github.com/m3db/m3db-operator/pkg/client/clientset/versioned/scheme" clusterlisters "github.com/m3db/m3db-operator/pkg/client/listers/m3dboperator/v1alpha1" "github.com/m3db/m3db-operator/pkg/k8sops/annotations" "github.com/m3db/m3db-operator/pkg/k8sops/labels" "github.com/m3db/m3db-operator/pkg/k8sops/m3db" "github.com/m3db/m3db-operator/pkg/k8sops/podidentity" "github.com/m3db/m3db-operator/pkg/m3admin" "github.com/m3db/m3db-operator/pkg/util/eventer" m3placement "github.com/m3db/m3/src/cluster/placement" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" kerrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" klabels "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/selection" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/clock" "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" appslisters "k8s.io/client-go/listers/apps/v1" corelisters "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" "k8s.io/client-go/util/workqueue" "k8s.io/utils/pointer" jsonpatch "github.com/evanphx/json-patch" pkgerrors "github.com/pkg/errors" "github.com/uber-go/tally" "go.uber.org/zap" ) const ( controllerName = "m3db-controller" clusterWorkQueueName = "m3dbcluster-work-queue" podWorkQueueName = "pods-work-queue" ) var ( errOrphanedPod = errors.New("pod does not belong to an m3db cluster") errInvalidNumIsoGroups = errors.New("number of isolationgroups not equal to replication factor") errNonUniqueIsoGroups = errors.New("isolation group names are not unique") ) // Configuration contains parameters for the controller. type Configuration struct { // ManageCRD indicates whether the controller should create and update specs // of the CRDs it controls. ManageCRD bool // EnableValidation controls whether OpenAPI validation is enabled on the CRD. EnableValidation bool } type controllerBase struct { lock *sync.Mutex logger *zap.Logger clock clock.Clock scope tally.Scope config Configuration doneCh chan struct{} adminClient *multiAdminClient kubeClient kubernetes.Interface crdClient clientset.Interface statefulSetLister appslisters.StatefulSetLister statefulSetsSynced cache.InformerSynced podLister corelisters.PodLister podsSynced cache.InformerSynced podWorkQueue workqueue.RateLimitingInterface recorder eventer.Poster } // M3DBController object type M3DBController struct { controllerBase k8sclient m3db.K8sops podIDProvider podidentity.Provider clusterLister clusterlisters.M3DBClusterLister clustersSynced cache.InformerSynced clusterWorkQueue workqueue.RateLimitingInterface } // NewM3DBController creates new instance of Controller func NewM3DBController(opts ...Option) (*M3DBController, error) { options := &options{} for _, o := range opts { o.execute(options) } if err := options.validate(); err != nil { return nil, err } kclient := options.kclient kubeClient := options.kubeClient crdClient := options.crdClient scope := options.scope logger := options.logger if logger == nil { logger = zap.NewNop() } adminOpts := []m3admin.Option{m3admin.WithLogger(logger)} multiClient := newMultiAdminClient(adminOpts, logger) if options.kubectlProxy { multiClient.clusterURLFn = clusterURLProxy } statefulSetInformer := options.filteredInformerFactory.Apps().V1().StatefulSets() podInformer := options.filteredInformerFactory.Core().V1().Pods() m3dbClusterInformer := options.m3dbClusterInformerFactory.Operator().V1alpha1().M3DBClusters() samplescheme.AddToScheme(scheme.Scheme) clusterWorkQueue := workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), clusterWorkQueueName) podWorkQueue := workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), podWorkQueueName) r, err := eventer.NewEventRecorder(eventer.WithClient(kubeClient), eventer.WithLogger(logger), eventer.WithComponent(controllerName)) if err != nil { return nil, err } p := &M3DBController{ controllerBase: controllerBase{ lock: &sync.Mutex{}, logger: logger, scope: scope, config: options.config, clock: clock.RealClock{}, adminClient: multiClient, doneCh: make(chan struct{}), kubeClient: kubeClient, crdClient: crdClient, statefulSetLister: statefulSetInformer.Lister(), statefulSetsSynced: statefulSetInformer.Informer().HasSynced, podLister: podInformer.Lister(), podsSynced: podInformer.Informer().HasSynced, podWorkQueue: podWorkQueue, // TODO(celina): figure out if we actually need a recorder for each namespace recorder: r, }, k8sclient: kclient, podIDProvider: options.podIDProvider, clusterLister: m3dbClusterInformer.Lister(), clustersSynced: m3dbClusterInformer.Informer().HasSynced, clusterWorkQueue: clusterWorkQueue, } m3dbClusterInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: p.enqueueCluster, UpdateFunc: func(old, new interface{}) { p.enqueueCluster(new) }, DeleteFunc: func(obj interface{}) { // TODO(schallert): what do we want to do on delete? clean up the etcd // data? we don't need to do anything w/ the sts + pods, we set owner refs // so kubernetes will GC them for us logger.Info("deleted cluster") }, }) statefulSetInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: p.handleStatefulSetUpdate, UpdateFunc: func(old, new interface{}) { oldSts := old.(*appsv1.StatefulSet) newSts := new.(*appsv1.StatefulSet) // TODO(schallert): version vs. observed generation? if newSts.ResourceVersion == oldSts.ResourceVersion { // don't have to reprocess on periodic resync return } p.handleStatefulSetUpdate(new) }, DeleteFunc: p.handleStatefulSetUpdate, }) podInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: p.enqueuePod, UpdateFunc: func(old, new interface{}) { p.enqueuePod(new) }, DeleteFunc: func(obj interface{}) { // No-op }, }) return p, nil } // Run drives the controller event loop. func (c *M3DBController) Run(nWorkers int, stopCh <-chan struct{}) error { defer runtime.HandleCrash() defer c.clusterWorkQueue.ShutDown() c.logger.Info("starting Operator controller") if c.config.ManageCRD { if err := c.k8sclient.CreateOrUpdateCRD(m3dboperator.M3DBClustersName, c.config.EnableValidation); err != nil { return pkgerrors.WithMessage(err, "could not create or update CRD") } } c.logger.Info("waiting for informer caches to sync") if ok := cache.WaitForCacheSync(stopCh, c.clustersSynced, c.statefulSetsSynced, c.podsSynced); !ok { return errors.New("caches failed to sync") } c.logger.Info("starting workers") for i := 0; i < nWorkers; i++ { go c.runClusterLoop() go c.runPodLoop() } c.logger.Info("workers started") <-stopCh c.logger.Info("shutting down workers") return nil } func (c *M3DBController) enqueueCluster(obj interface{}) { var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { runtime.HandleError(err) return } c.clusterWorkQueue.AddRateLimited(key) c.scope.Counter("enqueued_event").Inc(int64(1)) } func (c *M3DBController) runClusterLoop() { for c.processClusterQueueItem() { } } func (c *M3DBController) processClusterQueueItem() bool { obj, shutdown := c.clusterWorkQueue.Get() c.scope.Counter("dequeued_event").Inc(int64(1)) if shutdown { return false } // Closure so we can defer workQueue.Done. err := func(obj interface{}) error { defer c.clusterWorkQueue.Done(obj) var key string var ok bool if key, ok = obj.(string); !ok { c.clusterWorkQueue.Forget(obj) runtime.HandleError(fmt.Errorf("expected string from queue, got %#v", obj)) return nil } if err := c.handleClusterEvent(key); err != nil { return fmt.Errorf("error syncing cluster '%s': %v", key, err) } c.clusterWorkQueue.Forget(obj) c.logger.Info("successfully synced item", zap.String("key", key)) return nil }(obj) if err != nil { runtime.HandleError(err) } return true } func (c *M3DBController) handleClusterEvent(key string) error { namespace, name, err := cache.SplitMetaNamespaceKey(key) if err != nil { runtime.HandleError(fmt.Errorf("invalid resource key: %s", key)) return nil } cluster, err := c.clusterLister.M3DBClusters(namespace).Get(name) if err != nil { if kerrors.IsNotFound(err) { // give up processing if this cluster doesn't exist runtime.HandleError(fmt.Errorf("clusters '%s' no longer exists", key)) return nil } return err } if cluster == nil { return errors.New("got nil cluster for " + key) } return c.handleClusterUpdate(cluster) } // We are guaranteed by handleClusterEvent that we will never be passed a nil // cluster here. func (c *M3DBController) handleClusterUpdate(cluster *myspec.M3DBCluster) error { // MUST create a deep copy of the cluster or risk corrupting cache! Technically // only need if we modify, but we frequently do that so let's deep copy to // start and remove unnecessary calls later to optimize if we want. cluster = cluster.DeepCopy() clusterLogger := c.logger.With(zap.String("cluster", cluster.Name)) if cluster.Spec.Frozen { clusterLogger.Info("cluster is frozen so no changes will be made") return nil } // https://v1-12.docs.kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ // // If deletion timestamp is zero (cluster hasn't been deleted), make sure our // finalizer is present. If the cluster has been marked for deletion, delete // the placement and namespace. if dts := cluster.ObjectMeta.DeletionTimestamp; dts != nil && !dts.IsZero() { if !stringArrayContains(cluster.Finalizers, labels.EtcdDeletionFinalizer) { clusterLogger.Info("no etcd finalizer on cluster, nothing to do") return nil } // If cluster is set to preserve data, jump straight to removing the // finalizer. if cluster.Spec.KeepEtcdDataOnDelete { clusterLogger.Info("skipping etcd deletion due to keepEtcdDataOnDelete") } else { if err := c.deleteAllNamespaces(cluster); err != nil { clusterLogger.Error("error deleting cluster namespaces", zap.Error(err)) return err } if err := c.deletePlacement(cluster); err != nil { clusterLogger.Error("error deleting cluster placement", zap.Error(err)) return err } } if _, err := c.removeEtcdFinalizer(cluster); err != nil { clusterLogger.Error("error deleting etcd finalizer", zap.Error(err)) return pkgerrors.WithMessage(err, "error removing etcd cluster finalizer") } // Exit the control loop once the cluster is deleted and cleaned up. clusterLogger.Info("completed finalizer cleanup") return nil } if err := validateIsolationGroups(cluster); err != nil { clusterLogger.Error("failed validating isolationgroups", zap.Error(err)) c.recorder.WarningEvent(cluster, eventer.ReasonFailSync, err.Error()) return err } if !cluster.Spec.KeepEtcdDataOnDelete { var err error cluster, err = c.ensureEtcdFinalizer(cluster) if err != nil { return err } } if err := c.ensureConfigMap(cluster); err != nil { clusterLogger.Error("failed to ensure configmap", zap.Error(err)) c.recorder.WarningEvent(cluster, eventer.ReasonFailSync, "failed to ensure configmap: %s", err.Error()) return err } // Per https://v1-10.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.10/#statefulsetspec-v1-apps, // headless service MUST exist before statefulset. if err := c.ensureServices(cluster); err != nil { return err } if len(cluster.Spec.IsolationGroups) == 0 { // nothing to do, no groups to create in return nil } // copy since we sort the array isoGroups := make([]myspec.IsolationGroup, len(cluster.Spec.IsolationGroups)) copy(isoGroups, cluster.Spec.IsolationGroups) sort.Sort(myspec.IsolationGroups(isoGroups)) childrenSets, err := c.getChildStatefulSets(cluster) if err != nil { return err } childrenSetsByName := make(map[string]*appsv1.StatefulSet) for _, sts := range childrenSets { childrenSetsByName[sts.Name] = sts } // Create any missing statefulsets, at this point all existing stateful sets are bootstrapped. for i := 0; i < len(isoGroups); i++ { name := m3db.StatefulSetName(cluster.Name, i) _, exists := childrenSetsByName[name] if !exists { sts, err := m3db.GenerateStatefulSet(cluster, isoGroups[i].Name, isoGroups[i].NumInstances) if err != nil { return err } _, err = c.kubeClient.AppsV1().StatefulSets(cluster.Namespace).Create(sts) if err != nil { if kerrors.IsAlreadyExists(err) { // There may be a delay between when a StatefulSet is created and when it is // returned in calls to List because of the caching that the k8s client does. // So if we receive an error because the StatefulSet already exists that's not // indicative of a real problem. c.logger.Info("statefulset already exists", zap.String("name", name)) return nil } c.logger.Error(err.Error()) return err } c.logger.Info("created statefulset", zap.String("name", name)) return nil } } // For all statefulsets, ensure their observered generation is up to date. // This means that the k8s statefulset controller has updated Status (and // therefore ready replicas + updated replicas). If observed generation != // generation, it means Status will contain stale info. for _, sts := range childrenSets { if sts.Generation != sts.Status.ObservedGeneration { c.logger.Warn("stateful set not up to date", zap.String("namespace", sts.Namespace), zap.String("name", sts.Name), zap.Int32("readyReplicas", sts.Status.ReadyReplicas), zap.Int32("updatedReplicas", sts.Status.UpdatedReplicas), zap.String("currentRevision", sts.Status.CurrentRevision), zap.String("updateRevision", sts.Status.UpdateRevision), zap.Int64("generation", sts.Generation), zap.Int64("observed", sts.Status.ObservedGeneration), ) return fmt.Errorf("set %s generation is not up to date (current: %d, observed: %d)", sts.Name, sts.Generation, sts.Status.ObservedGeneration) } } // If any of the statefulsets aren't ready, wait until they are as we'll get // another event (ready == bootstrapped) for _, sts := range childrenSets { c.logger.Debug("processing set", zap.String("namespace", sts.Namespace), zap.String("name", sts.Name), zap.Int32("readyReplicas", sts.Status.ReadyReplicas), zap.Int32("updatedReplicas", sts.Status.UpdatedReplicas), zap.String("currentRevision", sts.Status.CurrentRevision), zap.String("updateRevision", sts.Status.UpdateRevision), zap.Int64("generation", sts.Generation), zap.Int64("observed", sts.Status.ObservedGeneration), ) if sts.Spec.Replicas == nil { c.logger.Warn("skip check for statefulset, replicas is nil", zap.String("name", sts.Name), zap.Int32("readyReplicas", sts.Status.ReadyReplicas), zap.Int32("updatedReplicas", sts.Status.UpdatedReplicas), zap.String("currentRevision", sts.Status.CurrentRevision), zap.String("updateRevision", sts.Status.UpdateRevision)) continue } replicas := *sts.Spec.Replicas ready := replicas == sts.Status.ReadyReplicas if sts.Status.UpdateRevision != "" && sts.Spec.UpdateStrategy.Type == appsv1.RollingUpdateStatefulSetStrategyType { // If there is an update revision, ensure all pods are updated // otherwise there is a rollout in progress. // Note: This ensures there is no race condition between // updating a stateful set and it seemingly being "ready" and // all pods healthy immediately after the update, since the // updated replicas will not match the desired replicas // and avoid the race condition of proceeding to another update // before a stateful set has had a chance to update the pods // but otherwise seemingly is healthy. ready = ready && replicas == sts.Status.UpdatedReplicas } if !ready { c.logger.Info("waiting for statefulset to be ready", zap.String("namespace", sts.Namespace), zap.String("name", sts.Name), zap.Int32("replicas", replicas), zap.Int32("readyReplicas", sts.Status.ReadyReplicas), zap.Int32("updatedReplicas", sts.Status.UpdatedReplicas), zap.String("currentRevision", sts.Status.CurrentRevision), zap.String("updateRevision", sts.Status.UpdateRevision)) return nil } } // Now that we know the cluster is healthy, iterate over each isolation group and check // if it should be updated. for i := 0; i < len(isoGroups); i++ { name := m3db.StatefulSetName(cluster.Name, i) // This StatefulSet is guaranteed to exist since if it didn't originally it would be // created above when we first iterate over the isolation groups. actual := childrenSetsByName[name] expected, update, err := updatedStatefulSet(actual, cluster, isoGroups[i]) if err != nil { c.logger.Error(err.Error()) return err } // If we're not updating the statefulset AND we're not using the OnDelete update // strategy, then move to the next statefulset. When using the OnDelete update // strategy, we still may want to restart nodes for this particular statefulset, // so don't continue yet. onDeleteUpdateStrategy := actual.Spec.UpdateStrategy.Type == appsv1.OnDeleteStatefulSetStrategyType if !update && !onDeleteUpdateStrategy { continue } if update { _, err = c.applyStatefulSetUpdate(cluster, actual, expected) if err != nil { c.logger.Error(err.Error()) return err } return nil } // Using an OnDelete strategy, we have to update nodes if: // - a statefulset update has happened OR // - we're already in the middle of a rollout // * because nodes are rolled out in chunks, this can happen over many iterations // Therefore, check to see if pods need to be updated and return from this loop // if pods were updated. If a rollout is finished or there has not // been a change, this call is a no-op. if onDeleteUpdateStrategy { nodesUpdated, err := c.updateStatefulSetPods(cluster, actual) if err != nil { c.logger.Error("error performing update", zap.Error(err), zap.String("namespace", cluster.Namespace), zap.String("name", actual.Name)) return err } // If we've performed any updates at all, do not process the next statefulset. // Wait for the updated pods to become healthy. if nodesUpdated { return nil } } } if !cluster.Status.HasInitializedPlacement() { cluster, err = c.validatePlacementWithStatus(cluster) if err != nil { return err } } if err := c.reconcileNamespaces(cluster); err != nil { c.recorder.WarningEvent(cluster, eventer.ReasonFailedCreate, "failed to create namespace: %s", err) c.logger.Error("error reconciling namespaces", zap.Error(err)) return err } if len(cluster.Spec.Namespaces) == 0 { c.logger.Warn("cluster has no namespaces defined", zap.String("cluster", cluster.Name)) c.recorder.WarningEvent(cluster, eventer.ReasonUnknown, "cluster %s has no namespaces", cluster.Name) } // At this point we have the desired number of statefulsets, and every pod // across those sets is bootstrapped. However some may be bootstrapped because // they own no shards. Check to see that all pods are in the placement. clusterPodsSelector := klabels.SelectorFromSet(labels.BaseLabels(cluster)) pods, err := c.podLister.Pods(cluster.Namespace).List(clusterPodsSelector) if err != nil { return fmt.Errorf("error listing pods to construct placement: %v", err) } placement, err := c.adminClient.placementClientForCluster(cluster).Get() if err != nil { return fmt.Errorf("error fetching active placement: %v", err) } c.logger.Info("found placement", zap.Int("currentPods", len(pods)), zap.Int("placementInsts", placement.NumInstances())) unavailInsts := []string{} for _, inst := range placement.Instances() { if !inst.IsAvailable() { unavailInsts = append(unavailInsts, inst.ID()) } } if ln := len(unavailInsts); ln > 0 { c.logger.Warn("waiting for instances to be available", zap.Strings("instances", unavailInsts)) c.recorder.WarningEvent(cluster, eventer.ReasonLongerThanUsual, "current unavailable instances: %d", ln) return nil } // Determine if any sets aren't at their desired replica count. Maybe we can // reuse the set objects from above but being paranoid for now. childrenSets, err = c.getChildStatefulSets(cluster) if err != nil { return err } // check if any pods inside the cluster need to be swapped in leavingInstanceID, podToReplace, err := c.checkPodsForReplacement(cluster, pods, placement) if err != nil { return err } if podToReplace != nil { err = c.replacePodInPlacement(cluster, placement, leavingInstanceID, podToReplace) if err != nil { c.recorder.WarningEvent(cluster, eventer.ReasonFailedToUpdate, "could not replace instance: "+leavingInstanceID) return err } c.recorder.NormalEvent(cluster, eventer.ReasonSuccessfulUpdate, "successfully replaced instance: "+leavingInstanceID) } for _, set := range childrenSets { zone, ok := set.Labels[labels.IsolationGroup] if !ok { return fmt.Errorf("statefulset %s has no isolation-group label", set.Name) } group, ok := myspec.IsolationGroups(isoGroups).GetByName(zone) if !ok { return fmt.Errorf("zone %s not found in cluster isoGroups %v", zone, isoGroups) } if set.Spec.Replicas == nil { return fmt.Errorf("set %s has unset spec replica", set.Name) } // Number of pods we want in the group. desired := group.NumInstances // Number of pods currently in the group. current := *set.Spec.Replicas // Number of instances in the group AND currently in the placement. inPlacement := int32(len(instancesInIsoGroup(placement, group.Name))) setLogger := c.logger.With( zap.String("statefulSet", set.Name), zap.Int32("inPlacement", inPlacement), zap.Int32("current", current), zap.Int32("desired", desired), ) if desired == current { // If the set is at its desired size, and all pods in the set are in the // placement, there's nothing we need to do for this set. if current == inPlacement { continue } // If the set is at its desired size but there's pods in the set that are // absent from the placement, add pods to placement. if inPlacement < current { setLogger.Info("expanding placement for set") return c.expandPlacementForSet(cluster, set, group, placement) } } // If there are more pods in the placement than we want in the group, // trigger a remove so that we can shrink the set. if inPlacement > desired { setLogger.Info("remove instance from placement for set") return c.shrinkPlacementForSet(cluster, set, placement) } var newCount int32 if current < desired { newCount = current + 1 } else { newCount = current - 1 } setLogger.Info("resizing set, desired != current", zap.Int32("newSize", newCount)) if err = c.patchStatefulSet(set, func(set *appsv1.StatefulSet) { set.Spec.Replicas = pointer.Int32Ptr(newCount) }); err != nil { c.logger.Error("error patching statefulset", zap.Error(err)) return err } return nil } placement, err = c.adminClient.placementClientForCluster(cluster).Get() if err != nil { return fmt.Errorf("error fetching placement: %v", err) } // TODO(celina): possibly do a replacement check here // See if we need to clean up the pod bootstrapping status. cluster, err = c.reconcileBootstrappingStatus(cluster, placement) if err != nil { return fmt.Errorf("error reconciling bootstrap status: %v", err) } c.logger.Info("nothing to do", zap.Int("childrensets", len(childrenSets)), zap.Int("zones", len(isoGroups)), zap.Int64("generation", cluster.ObjectMeta.Generation), zap.String("rv", cluster.ObjectMeta.ResourceVersion)) return nil } func (c *M3DBController) patchStatefulSet( set *appsv1.StatefulSet, action func(set *appsv1.StatefulSet), ) error { setBytes, err := json.Marshal(set) if err != nil { return err } action(set) setModifiedBytes, err := json.Marshal(set) if err != nil { return err } patchBytes, err := jsonpatch.CreateMergePatch(setBytes, setModifiedBytes) if err != nil { return err } set, err = c.kubeClient. AppsV1(). StatefulSets(set.Namespace). Patch(set.Name, types.MergePatchType, patchBytes) if err != nil { return fmt.Errorf("error updating statefulset %s: %w", set.Name, err) } return nil } func (c *M3DBController) applyStatefulSetUpdate( cluster *myspec.M3DBCluster, actual *appsv1.StatefulSet, expected *appsv1.StatefulSet, ) (*appsv1.StatefulSet, error) { updated, err := c.kubeClient.AppsV1().StatefulSets(cluster.Namespace).Update(expected) if err != nil { c.logger.Error(err.Error()) return nil, err } c.logger.Info("updated statefulset", zap.String("name", expected.Name), zap.Int32("actual_readyReplicas", actual.Status.ReadyReplicas), zap.Int32("actual_updatedReplicas", actual.Status.UpdatedReplicas), zap.String("actual_currentRevision", actual.Status.CurrentRevision), zap.String("actual_updateRevision", actual.Status.UpdateRevision), zap.Int32("expected_readyReplicas", expected.Status.ReadyReplicas), zap.Int32("expected_updatedReplicas", expected.Status.UpdatedReplicas), zap.String("expected_currentRevision", expected.Status.CurrentRevision), zap.String("expected_updateRevision", expected.Status.UpdateRevision), zap.Int64("generation", expected.Generation), zap.Int64("observed", expected.Status.ObservedGeneration), ) return updated, nil } // updateStatefulSetPods returns true if it updates any pods func (c *M3DBController) updateStatefulSetPods( cluster *myspec.M3DBCluster, sts *appsv1.StatefulSet, ) (bool, error) { logger := c.logger.With( zap.String("namespace", cluster.Namespace), zap.String("name", sts.Name), ) if _, ok := sts.Annotations[annotations.ParallelUpdateInProgress]; !ok { logger.Debug("no update and no rollout in progress so move to next statefulset") return false, nil } numPods, err := getMaxPodsToUpdate(sts) if err != nil { return false, err } if numPods == 0 { return false, errors.New("parallel update annotation set to 0. will not perform pod updates") } pods, err := c.podsToUpdate(cluster.Namespace, sts, numPods) if err != nil { return false, err } if len(pods) > 0 { names := make([]string, 0, len(pods)) for _, pod := range pods { if err := c.kubeClient.CoreV1(). Pods(pod.Namespace). Delete(pod.Name, &metav1.DeleteOptions{}); err != nil { return false, err } names = append(names, pod.Name) } logger.Info("restarting pods", zap.Strings("pods", names)) return true, nil } // If there are no pods to update, we're fully rolled out so remove // the update annotation and update status. // // NB(nate): K8s handles this for you when using the RollingUpdate update strategy. // However, since OnDelete removes k8s from the pod update process, it's our // responsibility to set this once done rolling out. sts.Status.CurrentReplicas = sts.Status.UpdatedReplicas sts.Status.CurrentRevision = sts.Status.UpdateRevision if sts, err = c.kubeClient.AppsV1().StatefulSets(cluster.Namespace).UpdateStatus(sts); err != nil { return false, err } if err = c.patchStatefulSet(sts, func(set *appsv1.StatefulSet) { delete(set.Annotations, annotations.ParallelUpdateInProgress) }); err != nil { return false, err } logger.Info("update complete") return false, nil } func getMaxPodsToUpdate(actual *appsv1.StatefulSet) (int, error) { var ( rawVal string ok bool ) if rawVal, ok = actual.Annotations[annotations.ParallelUpdateInProgress]; !ok { return 0, errors.New("parallel update annotation missing during statefulset update") } var ( maxPodsPerUpdate int err error ) if maxPodsPerUpdate, err = strconv.Atoi(rawVal); err != nil { return 0, fmt.Errorf("failed to parse parallel update annotation: %v", rawVal) } return maxPodsPerUpdate, nil } func (c *M3DBController) podsToUpdate( namespace string, sts *appsv1.StatefulSet, numPods int, ) ([]*corev1.Pod, error) { var ( currRev = sts.Status.CurrentRevision updateRev = sts.Status.UpdateRevision ) // nolint:gocritic if currRev == "" { return nil, errors.New("currentRevision empty") } else if updateRev == "" { return nil, errors.New("updateRevision empty") } else if currRev == updateRev { // No pods to update because current and update revision are the same return nil, nil } // Get any pods not on the updateRevision for this statefulset podSelector, err := generatePodSelector(updateRev, sts) if err != nil { return nil, err } pods, err := c.podLister.Pods(namespace).List(podSelector) if err != nil { return nil, err } else if len(pods) == 0 { return nil, nil } // NB(nate): Sort here so updates are always done in a consistent order. // Statefulset 0 -> N: Pod 0 -> N sortedPods, err := sortPods(pods) if err != nil { return nil, err } toUpdate := make([]*corev1.Pod, 0, len(sortedPods)) for _, pod := range sortedPods { toUpdate = append(toUpdate, pod.pod) if len(toUpdate) == numPods { break } } return toUpdate, nil } func generatePodSelector(updateRev string, sts *appsv1.StatefulSet) (klabels.Selector, error) { revReq, err := klabels.NewRequirement( "controller-revision-hash", selection.NotEquals, []string{updateRev}, ) if err != nil { return nil, err } stsReq, err := klabels.NewRequirement( labels.StatefulSet, selection.Equals, []string{sts.Name}, ) if err != nil { return nil, err } podSelector := klabels.NewSelector().Add(*revReq, *stsReq) return podSelector, nil } func instancesInIsoGroup(pl m3placement.Placement, isoGroup string) []m3placement.Instance { insts := []m3placement.Instance{} for _, inst := range pl.Instances() { if inst.IsolationGroup() == isoGroup { insts = append(insts, inst) } } return insts } // This func is currently read-only, but if we end up modifying statefulsets // we'll have to deepcopy. func (c *M3DBController) getChildStatefulSets(cluster *myspec.M3DBCluster) ([]*appsv1.StatefulSet, error) { labels := labels.BaseLabels(cluster) statefulSets, err := c.statefulSetLister.StatefulSets(cluster.Namespace).List(klabels.Set(labels).AsSelector()) if err != nil { runtime.HandleError(fmt.Errorf("error listing statefulsets: %v", err)) return nil, err } childrenSets := make([]*appsv1.StatefulSet, 0) for _, sts := range statefulSets { if metav1.IsControlledBy(sts, cluster) { childrenSets = append(childrenSets, sts.DeepCopy()) } } return childrenSets, nil } func (c *M3DBController) handleStatefulSetUpdate(obj interface{}) { var object metav1.Object var ok bool if object, ok = obj.(metav1.Object); !ok { tombstone, ok := obj.(cache.DeletedFinalStateUnknown) if !ok { runtime.HandleError(fmt.Errorf("error decoding object, invalid type")) return } object, ok = tombstone.Obj.(metav1.Object) if !ok { runtime.HandleError(fmt.Errorf("error decoding tombstone, invalid type")) return } c.logger.Info("recovered object from tombstone", zap.String("name", object.GetName())) } c.logger.Info("processing statefulset", zap.String("statefulset.namespace", object.GetNamespace()), zap.String("statefulset.name", object.GetName())) owner := metav1.GetControllerOf(object) // TODO(schallert): const if owner == nil || owner.Kind != "m3dbcluster" { return } cluster, err := c.clusterLister.M3DBClusters(object.GetNamespace()).Get(owner.Name) if err != nil { c.logger.Info("ignoring orphaned object", zap.String("m3dbcluster", owner.Name), zap.String("namespace", object.GetNamespace()), zap.String("statefulset", object.GetName())) return } // enqueue the cluster for processing c.enqueueCluster(cluster) } func (c *M3DBController) enqueuePod(obj interface{}) { var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { c.logger.Error("error splitting pod cache key", zap.Error(err)) return } c.podWorkQueue.AddRateLimited(key) c.scope.Counter("enqueued_event").Inc(int64(1)) } func (c *M3DBController) runPodLoop() { for c.processPodQueueItem() { } } func (c *M3DBController) processPodQueueItem() bool { obj, shutdown := c.podWorkQueue.Get() c.scope.Counter("dequeued_event").Inc(int64(1)) if shutdown { return false } // Closure so we can defer workQueue.Done. err := func(obj interface{}) error { defer c.podWorkQueue.Done(obj) var key string var ok bool if key, ok = obj.(string); !ok { c.podWorkQueue.Forget(obj) runtime.HandleError(fmt.Errorf("expected string from queue, got %#v", obj)) return nil } if err := c.handlePodEvent(key); err != nil { return fmt.Errorf("error syncing cluster '%s': %v", key, err) } c.podWorkQueue.Forget(obj) c.logger.Debug("successfully synced item", zap.String("key", key)) return nil }(obj) if err != nil { runtime.HandleError(err) } return true } func (c *M3DBController) handlePodEvent(key string) error { namespace, name, err := cache.SplitMetaNamespaceKey(key) if err != nil { c.logger.Error("invalid resource key", zap.Error(err)) return nil } pod, err := c.podLister.Pods(namespace).Get(name) if err != nil { if kerrors.IsNotFound(err) { c.logger.Debug("pod no longer exists", zap.String("pod", name)) return nil } c.logger.Error("error listing pods in pod handle", zap.String("pod", name), zap.Error(err)) return err } if pod == nil { return errors.New("got nil pod for key " + key) } return c.handlePodUpdate(pod) } func (c *M3DBController) handlePodUpdate(pod *corev1.Pod) error { // We only process pods that are members of m3db clusters. if _, err := getClusterValue(pod); err != nil { return nil } pod = pod.DeepCopy() podBytes, err := json.Marshal(pod) if err != nil { return err } podLogger := c.logger.With(zap.String("pod.namespace", pod.Namespace), zap.String("pod.name", pod.Name)) podLogger.Info("processing pod") cluster, err := c.getParentCluster(pod) if err != nil { podLogger.Error("error getting parent cluster", zap.Error(err)) return err } id, err := c.podIDProvider.Identity(pod, cluster) if err != nil { podLogger.Error("error getting pod ID", zap.Error(err)) return err } podLogger.Debug("pod ID", zap.Any("id", id)) idStr, err := podidentity.IdentityJSON(id) if err != nil { podLogger.Error("error marshaling pod ID", zap.Error(err)) return err } currentID, ok := pod.Annotations[podidentity.AnnotationKeyPodIdentity] if ok { if currentID != idStr { podLogger.Warn("pod ID mismatch", zap.String("currentID", currentID), zap.String("newID", idStr)) } // TODO(schallert): decide how to enforce updated pod identity (need to // determine ramnifications of changing). Will likely need to do a replace. return nil } if pod.Annotations == nil { pod.Annotations = make(map[string]string) } pod.Annotations[podidentity.AnnotationKeyPodIdentity] = idStr podModifiedBytes, err := json.Marshal(pod) if err != nil { return err } // NB(r): See reference of use in the AddLabelToPod of postgres operator: // https://github.com/CrunchyData/postgres-operator/blob/7e867ebf211b488def26dfaf10d7b2b5bbd6f5f6/kubeapi/pod.go#L108 patchBytes, err := jsonpatch.CreateMergePatch(podBytes, podModifiedBytes) if err != nil { return err } _, err = c.kubeClient.CoreV1(). Pods(pod.Namespace). Patch(pod.Name, types.MergePatchType, patchBytes) if err != nil { podLogger.Error("error updating pod annotation", zap.Error(err)) return err } podLogger.Info("updated pod ID", zap.Any("id", id)) c.recorder.NormalEvent(pod, eventer.ReasonSuccessSync, "updated pod %s with ID annotation", pod.Name) return nil } func
(pod *corev1.Pod) (string, error) { cluster, ok := pod.Labels[labels.Cluster] if !ok { return "", errOrphanedPod } return cluster, nil } func (c *M3DBController) getParentCluster(pod *corev1.Pod) (*myspec.M3DBCluster, error) { clusterName, err := getClusterValue(pod) if err != nil { return nil, err } cluster, err := c.clusterLister.M3DBClusters(pod.Namespace).Get(clusterName) if err != nil { return nil, err } return cluster, nil } func validateIsolationGroups(cluster *myspec.M3DBCluster) error { groups := cluster.Spec.IsolationGroups if cluster.Spec.ReplicationFactor != int32(len(groups)) { return pkgerrors.WithMessagef(errInvalidNumIsoGroups, "replication factor is %d but number of isogroups is %d", cluster.Spec.ReplicationFactor, len(groups)) } names := make(map[string]struct{}, len(groups)) for _, g := range groups { names[g.Name] = struct{}{} } if len(names) != len(groups) { return pkgerrors.WithMessagef(errNonUniqueIsoGroups, "found %d isolationGroups but %d unique names", len(groups), len(names)) } return nil } // updatedStatefulSet checks if we should update the actual StatefulSet to match it's // expected state. If so, it returns true and the updated StatefulSet and if not, it // return false. func updatedStatefulSet( actual *appsv1.StatefulSet, cluster *myspec.M3DBCluster, isoGroup myspec.IsolationGroup, ) (*appsv1.StatefulSet, bool, error) { // The operator will only perform an update if the current StatefulSet has been // annotated to indicate that it is okay to update it. if val, ok := actual.Annotations[annotations.Update]; !ok || val != annotations.EnabledVal { str, ok := actual.Annotations[annotations.ParallelUpdate] if !ok { return nil, false, nil } if parallelVal, err := strconv.Atoi(str); err != nil { return nil, false, err } else if parallelVal < 1 { return nil, false, fmt.Errorf("parallel update value invalid: %v", str) } } expected, err := m3db.GenerateStatefulSet(cluster, isoGroup.Name, isoGroup.NumInstances) if err != nil { return nil, false, err } var update bool // The Kubernetes API server sets various default values for fields so instead of comparing // if the desired spec is equal to the actual spec, which may have fail because the desired // spec hasn't yet been transformed by the API server, we use DeepDerivative to only compare // those fields in the desired spec which are actually set. The controller has special logic // for handling changes to the number of replicas in the cluster since such changes also // require updates to the placement so we can safely ignore the replicas here. expected.Spec.Replicas = actual.Spec.Replicas if !equality.Semantic.DeepDerivative(expected.Spec, actual.Spec) { update = true } // We also want to check if the labels in the cluster spec have changed and update the // StatefulSet if so. if !reflect.DeepEqual(expected.Labels, actual.Labels) { update = true } // If we don't need to perform an update to the StatefulSet's spec, but the StatefulSet // has an update annotation, we'll still update the StatefulSet to remove the update // annotation. This ensures that users can always set an update annotation and then // wait for it to be removed to know if the operator has processed a StatefulSet. if !update { delete(actual.Annotations, annotations.Update) delete(actual.Annotations, annotations.ParallelUpdate) return actual, true, nil } // Ensure we keep old object meta so that resource version info can be used by // K8s API for conflict resolution. expected.ObjectMeta = *actual.ObjectMeta.DeepCopy() // Reset expected annotations since we ensure their final state below. expected.ObjectMeta.Annotations = map[string]string{} expected.Status = actual.DeepCopy().Status copyAnnotations(expected, actual) return expected, true, nil } func copyAnnotations(expected, actual *appsv1.StatefulSet) { // It's okay for users to add annotations to a StatefulSet after it has been created so // we'll want to copy over any that exist on the actual StatefulSet but not the expected // one. The only exception is we don't want to copy over the update annotation so users // will always have to explicitly trigger updates. Note that this means removing an // annotation will require users to delete the annotation from the StatefulSet as well as // the cluster spec. for k, v := range actual.Annotations { if k == annotations.Update { // NB(nate): add this check for backwards compatibility. Existing components // may be using the old update annotation. We want to ensure rollouts still work as // expected. if expected.Spec.UpdateStrategy.Type == appsv1.OnDeleteStatefulSetStrategyType { expected.Annotations[annotations.ParallelUpdateInProgress] = "1" } continue } // For parallel updates, remove the initial annotation added by the client and add rollout // in progress annotation. This will ensure that in future passes we don't attempt to // update the statefulset again unnecessarily and simply roll pods that need to pick up // updates. if k == annotations.ParallelUpdate { expected.Annotations[annotations.ParallelUpdateInProgress] = v continue } if _, ok := expected.Annotations[k]; !ok { expected.Annotations[k] = v } } }
getClusterValue
drop.py
# Copyright 1999-2021 Alibaba Group Holding Ltd. # # 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 warnings from collections import OrderedDict import numpy as np from ... import opcodes from ...core import Entity, Chunk, CHUNK_TYPE, OutputType, recursive_tile from ...serialization.serializables import AnyField, StringField from ..core import IndexValue, DATAFRAME_TYPE, SERIES_TYPE, INDEX_CHUNK_TYPE from ..operands import DataFrameOperand, DataFrameOperandMixin from ..utils import parse_index, validate_axis class DataFrameDrop(DataFrameOperandMixin, DataFrameOperand): _op_type_ = opcodes.DATAFRAME_DROP _index = AnyField('index') _columns = AnyField('columns') _level = AnyField('level') _errors = StringField('errors') def __init__(self, index=None, columns=None, level=None, errors=None, **kw): super().__init__(_index=index, _columns=columns, _level=level, _errors=errors, **kw) @property def index(self):
@property def columns(self): return self._columns @property def level(self): return self._level @property def errors(self): return self._errors def _filter_dtypes(self, dtypes, ignore_errors=False): if self._columns: return dtypes.drop(index=self._columns, level=self._level, errors='ignore' if ignore_errors else self._errors) else: return dtypes def _set_inputs(self, inputs): super()._set_inputs(inputs) inputs_iter = iter(self._inputs[1:]) if len(self._inputs) > 1: self._index = next(inputs_iter) def __call__(self, df_or_series): params = df_or_series.params.copy() shape_list = list(df_or_series.shape) if self._index is not None: if isinstance(df_or_series.index_value.value, IndexValue.RangeIndex): params['index_value'] = parse_index(None, (df_or_series.key, df_or_series.index_value.key)) shape_list[0] = np.nan if isinstance(df_or_series, DATAFRAME_TYPE): new_dtypes = self._filter_dtypes(df_or_series.dtypes) params['columns_value'] = parse_index(new_dtypes.index, store_data=True) params['dtypes'] = new_dtypes shape_list[1] = len(new_dtypes) self.output_types = [OutputType.dataframe] elif isinstance(df_or_series, SERIES_TYPE): self.output_types = [OutputType.series] else: self.output_types = [OutputType.index] params['shape'] = tuple(shape_list) inputs = [df_or_series] if isinstance(self._index, Entity): inputs.append(self._index) return self.new_tileable(inputs, **params) @classmethod def tile(cls, op: 'DataFrameDrop'): inp = op.inputs[0] out = op.outputs[0] if len(op.inputs) > 1: rechunked = yield from recursive_tile( op.index.rechunk({0: (op.index.shape[0],)})) index_chunk = rechunked.chunks[0] else: index_chunk = op.index col_to_args = OrderedDict() chunks = [] for c in inp.chunks: params = c.params.copy() if isinstance(inp, DATAFRAME_TYPE): new_dtypes, new_col_id = col_to_args.get(c.index[1], (None, None)) if new_dtypes is None: new_col_id = len(col_to_args) new_dtypes = op._filter_dtypes(c.dtypes, ignore_errors=True) if len(new_dtypes) == 0: continue col_to_args[c.index[1]] = (new_dtypes, new_col_id) params.update(dict(dtypes=new_dtypes, index=(c.index[0], new_col_id), index_value=c.index_value, columns_value=parse_index(new_dtypes.index, store_data=True))) if op.index is not None: params.update(dict(shape=(np.nan, len(new_dtypes)), index_value=parse_index(None, (c.key, c.index_value.key)))) else: params['shape'] = (c.shape[0], len(new_dtypes)) elif op.index is not None: params.update(dict(shape=(np.nan,), index_value=parse_index(None, (c.key, c.index_value.key)))) chunk_inputs = [c] if isinstance(index_chunk, Chunk): chunk_inputs.append(index_chunk) new_op = op.copy().reset_key() new_op._index = index_chunk chunks.append(new_op.new_chunk(chunk_inputs, **params)) new_op = op.copy().reset_key() params = out.params.copy() if op.index is not None: nsplits_list = [(np.nan,) * inp.chunk_shape[0]] else: nsplits_list = [inp.nsplits[0]] if isinstance(inp, DATAFRAME_TYPE): nsplits_list.append(tuple(len(dt) for dt, _ in col_to_args.values())) params.update(dict(chunks=chunks, nsplits=tuple(nsplits_list))) return new_op.new_tileables(op.inputs, **params) @classmethod def execute(cls, ctx, op: 'DataFrameDrop'): inp = op.inputs[0] if isinstance(op.index, CHUNK_TYPE): index_val = ctx[op.index.key] else: index_val = op.index if isinstance(inp, INDEX_CHUNK_TYPE): ctx[op.outputs[0].key] = ctx[inp.key].drop(index_val, errors='ignore') else: ctx[op.outputs[0].key] = ctx[inp.key].drop( index=index_val, columns=op.columns, level=op.level, errors='ignore') def _drop(df_or_series, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise'): axis = validate_axis(axis, df_or_series) if labels is not None: if axis == 0: index = labels else: columns = labels if index is not None and errors == 'raise': warnings.warn('Errors will not raise for non-existing indices') if isinstance(columns, Entity): raise NotImplementedError('Columns cannot be Mars objects') op = DataFrameDrop(index=index, columns=columns, level=level, errors=errors) df = op(df_or_series) if inplace: df_or_series.data = df.data else: return df def df_drop(df, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise'): """ Drop specified labels from rows or columns. Remove rows or columns by specifying label names and corresponding axis, or by specifying directly index or column names. When using a multi-index, labels on different levels can be removed by specifying the level. Parameters ---------- labels : single label or list-like Index or column labels to drop. axis : {0 or 'index', 1 or 'columns'}, default 0 Whether to drop labels from the index (0 or 'index') or columns (1 or 'columns'). index : single label or list-like Alternative to specifying axis (``labels, axis=0`` is equivalent to ``index=labels``). columns : single label or list-like Alternative to specifying axis (``labels, axis=1`` is equivalent to ``columns=labels``). level : int or level name, optional For MultiIndex, level from which the labels will be removed. inplace : bool, default False If True, do operation inplace and return None. errors : {'ignore', 'raise'}, default 'raise' If 'ignore', suppress error and only existing labels are dropped. Note that errors for missing indices will not raise. Returns ------- DataFrame DataFrame without the removed index or column labels. Raises ------ KeyError If any of the labels is not found in the selected axis. See Also -------- DataFrame.loc : Label-location based indexer for selection by label. DataFrame.dropna : Return DataFrame with labels on given axis omitted where (all or any) data are missing. DataFrame.drop_duplicates : Return DataFrame with duplicate rows removed, optionally only considering certain columns. Series.drop : Return Series with specified index labels removed. Examples -------- >>> import numpy as np >>> import pandas as pd >>> import mars.dataframe as md >>> df = md.DataFrame(np.arange(12).reshape(3, 4), ... columns=['A', 'B', 'C', 'D']) >>> df.execute() A B C D 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 Drop columns >>> df.drop(['B', 'C'], axis=1).execute() A D 0 0 3 1 4 7 2 8 11 >>> df.drop(columns=['B', 'C']).execute() A D 0 0 3 1 4 7 2 8 11 Drop a row by index >>> df.drop([0, 1]).execute() A B C D 2 8 9 10 11 Drop columns and/or rows of MultiIndex DataFrame >>> midx = pd.MultiIndex(levels=[['lama', 'cow', 'falcon'], ... ['speed', 'weight', 'length']], ... codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], ... [0, 1, 2, 0, 1, 2, 0, 1, 2]]) >>> df = md.DataFrame(index=midx, columns=['big', 'small'], ... data=[[45, 30], [200, 100], [1.5, 1], [30, 20], ... [250, 150], [1.5, 0.8], [320, 250], ... [1, 0.8], [0.3, 0.2]]) >>> df.execute() big small lama speed 45.0 30.0 weight 200.0 100.0 length 1.5 1.0 cow speed 30.0 20.0 weight 250.0 150.0 length 1.5 0.8 falcon speed 320.0 250.0 weight 1.0 0.8 length 0.3 0.2 >>> df.drop(index='cow', columns='small').execute() big lama speed 45.0 weight 200.0 length 1.5 falcon speed 320.0 weight 1.0 length 0.3 >>> df.drop(index='length', level=1).execute() big small lama speed 45.0 30.0 weight 200.0 100.0 cow speed 30.0 20.0 weight 250.0 150.0 falcon speed 320.0 250.0 weight 1.0 0.8 """ return _drop(df, labels=labels, axis=axis, index=index, columns=columns, level=level, inplace=inplace, errors=errors) def df_pop(df, item): """ Return item and drop from frame. Raise KeyError if not found. Parameters ---------- item : str Label of column to be popped. Returns ------- Series Examples -------- >>> import numpy as np >>> import mars.dataframe as md >>> df = md.DataFrame([('falcon', 'bird', 389.0), ... ('parrot', 'bird', 24.0), ... ('lion', 'mammal', 80.5), ... ('monkey', 'mammal', np.nan)], ... columns=('name', 'class', 'max_speed')) >>> df.execute() name class max_speed 0 falcon bird 389.0 1 parrot bird 24.0 2 lion mammal 80.5 3 monkey mammal NaN >>> df.pop('class').execute() 0 bird 1 bird 2 mammal 3 mammal Name: class, dtype: object >>> df.execute() name max_speed 0 falcon 389.0 1 parrot 24.0 2 lion 80.5 3 monkey NaN """ series = df.data[item] df_drop(df, item, axis=1, inplace=True) return series def series_drop(series, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise'): """ Return Series with specified index labels removed. Remove elements of a Series based on specifying the index labels. When using a multi-index, labels on different levels can be removed by specifying the level. Parameters ---------- labels : single label or list-like Index labels to drop. axis : 0, default 0 Redundant for application on Series. index : single label or list-like Redundant for application on Series, but 'index' can be used instead of 'labels'. .. versionadded:: 0.21.0 columns : single label or list-like No change is made to the Series; use 'index' or 'labels' instead. .. versionadded:: 0.21.0 level : int or level name, optional For MultiIndex, level for which the labels will be removed. inplace : bool, default False If True, do operation inplace and return None. errors : {'ignore', 'raise'}, default 'raise' Note that this argument is kept only for compatibility, and errors will not raise even if ``errors=='raise'``. Returns ------- Series Series with specified index labels removed. Raises ------ KeyError If none of the labels are found in the index. See Also -------- Series.reindex : Return only specified index labels of Series. Series.dropna : Return series without null values. Series.drop_duplicates : Return Series with duplicate values removed. DataFrame.drop : Drop specified labels from rows or columns. Examples -------- >>> import numpy as np >>> import pandas as pd >>> import mars.dataframe as md >>> s = md.Series(data=np.arange(3), index=['A', 'B', 'C']) >>> s.execute() A 0 B 1 C 2 dtype: int64 Drop labels B en C >>> s.drop(labels=['B', 'C']).execute() A 0 dtype: int64 Drop 2nd level label in MultiIndex Series >>> midx = pd.MultiIndex(levels=[['lama', 'cow', 'falcon'], ... ['speed', 'weight', 'length']], ... codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], ... [0, 1, 2, 0, 1, 2, 0, 1, 2]]) >>> s = md.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], ... index=midx) >>> s.execute() lama speed 45.0 weight 200.0 length 1.2 cow speed 30.0 weight 250.0 length 1.5 falcon speed 320.0 weight 1.0 length 0.3 dtype: float64 >>> s.drop(labels='weight', level=1).execute() lama speed 45.0 length 1.2 cow speed 30.0 length 1.5 falcon speed 320.0 length 0.3 dtype: float64 """ return _drop(series, labels=labels, axis=axis, index=index, columns=columns, level=level, inplace=inplace, errors=errors) def index_drop(index, labels, errors='raise'): """ Make new Index with passed list of labels deleted. Parameters ---------- labels : array-like errors : {'ignore', 'raise'}, default 'raise' Note that this argument is kept only for compatibility, and errors will not raise even if ``errors=='raise'``. Returns ------- dropped : Index Raises ------ KeyError If not all of the labels are found in the selected axis """ return _drop(index, labels=labels, errors=errors)
return self._index
rbac.go
// Copyright 2020 Red Hat, Inc. and/or its affiliates // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package kogitoruntime import ( "github.com/kiegroup/kogito-cloud-operator/pkg/client/meta" v1 "k8s.io/api/core/v1" rbac "k8s.io/api/rbac/v1" v12 "k8s.io/apimachinery/pkg/apis/meta/v1" ) const ( serviceAccountName = "kogito-service-viewer" roleName = "kogito-service-viewer" roleBindingName = "kogito-service-viewer" roleAPIGroup = "rbac.authorization.k8s.io" ) var serviceViewerRoleVerbs = []string{"list", "get", "watch", "update", "patch"} var serviceViewerRoleAPIGroups = []string{""} var serviceViewerRoleResources = []string{"services", "configmaps"} func getServiceViewerServiceAccount(namespace string) meta.ResourceObject { return &v1.ServiceAccount{ ObjectMeta: v12.ObjectMeta{ Name: serviceAccountName, Namespace: namespace, }, } } func getServiceViewerRole(namespace string) meta.ResourceObject { return &rbac.Role{ ObjectMeta: v12.ObjectMeta{ Name: roleName, Namespace: namespace, }, Rules: []rbac.PolicyRule{ { Verbs: serviceViewerRoleVerbs, APIGroups: serviceViewerRoleAPIGroups, Resources: serviceViewerRoleResources, }, }, } } func getServiceViewerRoleBinding(namespace string) meta.ResourceObject { return &rbac.RoleBinding{ ObjectMeta: v12.ObjectMeta{ Name: roleBindingName,
Namespace: namespace, }, Subjects: []rbac.Subject{ { Kind: "ServiceAccount", Name: serviceAccountName, }, }, RoleRef: rbac.RoleRef{ APIGroup: roleAPIGroup, Name: roleName, Kind: "Role", }, } }
_data_masking_rules_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. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class DataMaskingRulesOperations(object): """DataMaskingRulesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.synapse.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def create_or_update( self, resource_group_name, # type: str workspace_name, # type: str sql_pool_name, # type: str data_masking_rule_name, # type: str parameters, # type: "_models.DataMaskingRule" **kwargs # type: Any ): # type: (...) -> "_models.DataMaskingRule" """Creates or updates a Sql pool data masking rule. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param workspace_name: The name of the workspace. :type workspace_name: str :param sql_pool_name: SQL pool name. :type sql_pool_name: str :param data_masking_rule_name: The name of the data masking rule. :type data_masking_rule_name: str :param parameters: The required parameters for creating or updating a data masking rule. :type parameters: ~azure.mgmt.synapse.models.DataMaskingRule :keyword callable cls: A custom type or function that will be passed the direct response :return: DataMaskingRule, or the result of cls(response) :rtype: ~azure.mgmt.synapse.models.DataMaskingRule :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.DataMaskingRule"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-03-01" data_masking_policy_name = "Default" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.create_or_update.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str'), 'sqlPoolName': self._serialize.url("sql_pool_name", sql_pool_name, 'str'), 'dataMaskingPolicyName': self._serialize.url("data_masking_policy_name", data_masking_policy_name, 'str'), 'dataMaskingRuleName': self._serialize.url("data_masking_rule_name", data_masking_rule_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'DataMaskingRule') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(_models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('DataMaskingRule', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('DataMaskingRule', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Synapse/workspaces/{workspaceName}/sqlPools/{sqlPoolName}/dataMaskingPolicies/{dataMaskingPolicyName}/rules/{dataMaskingRuleName}'} # type: ignore def get( self, resource_group_name, # type: str workspace_name, # type: str sql_pool_name, # type: str data_masking_rule_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.DataMaskingRule"
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Synapse/workspaces/{workspaceName}/sqlPools/{sqlPoolName}/dataMaskingPolicies/{dataMaskingPolicyName}/rules/{dataMaskingRuleName}'} # type: ignore def list_by_sql_pool( self, resource_group_name, # type: str workspace_name, # type: str sql_pool_name, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["_models.DataMaskingRuleListResult"] """Gets a list of Sql pool data masking rules. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param workspace_name: The name of the workspace. :type workspace_name: str :param sql_pool_name: SQL pool name. :type sql_pool_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either DataMaskingRuleListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.synapse.models.DataMaskingRuleListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.DataMaskingRuleListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-03-01" data_masking_policy_name = "Default" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_sql_pool.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str'), 'sqlPoolName': self._serialize.url("sql_pool_name", sql_pool_name, 'str'), 'dataMaskingPolicyName': self._serialize.url("data_masking_policy_name", data_masking_policy_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('DataMaskingRuleListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: error = self._deserialize(_models.ErrorResponse, response) map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_sql_pool.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Synapse/workspaces/{workspaceName}/sqlPools/{sqlPoolName}/dataMaskingPolicies/{dataMaskingPolicyName}/rules'} # type: ignore
"""Gets the specific Sql pool data masking rule. :param resource_group_name: The name of the resource group. The name is case insensitive. :type resource_group_name: str :param workspace_name: The name of the workspace. :type workspace_name: str :param sql_pool_name: SQL pool name. :type sql_pool_name: str :param data_masking_rule_name: The name of the data masking rule. :type data_masking_rule_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: DataMaskingRule, or the result of cls(response) :rtype: ~azure.mgmt.synapse.models.DataMaskingRule :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.DataMaskingRule"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-03-01" data_masking_policy_name = "Default" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str'), 'sqlPoolName': self._serialize.url("sql_pool_name", sql_pool_name, 'str'), 'dataMaskingPolicyName': self._serialize.url("data_masking_policy_name", data_masking_policy_name, 'str'), 'dataMaskingRuleName': self._serialize.url("data_masking_rule_name", data_masking_rule_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize(_models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('DataMaskingRule', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized
day05.rs
use std::io::{self, Read}; fn main() -> io::Result<()> { let mut buffer = String::new(); io::stdin().read_to_string(&mut buffer)?; let input: Vec<&str> = buffer.lines().collect(); println!("Part 1: {:?}", first_part(&input).unwrap()); println!("Part 2: {:?}", second_part(&input).unwrap()); Ok(()) } fn first_part(input: &Vec<&str>) -> Option<u32> { let mut max_seat_id = 0; for boarding_pass in input { let seat_id = calculate_seat_id(boarding_pass); if seat_id > max_seat_id { max_seat_id = seat_id } } Some(max_seat_id) } fn second_part(input: &Vec<&str>) -> Option<u32> { let mut all_seats: Vec<u32> = Vec::new(); for boarding_pass in input { let seat_id = calculate_seat_id(boarding_pass); all_seats.push(seat_id); } all_seats.sort(); let my_seat_id: Option<u32> = find_my_seat_id(&all_seats); my_seat_id } fn find_my_seat_id(seat_ids: &Vec<u32>) -> Option<u32>
fn calculate_seat_id(boarding_pass: &str) -> u32 { let mut idx: u32 = 0; let mut min_row: u32 = 0; let mut max_row: u32 = 127; let mut min_col: u32 = 0; let mut max_col: u32 = 7; for chr in boarding_pass.chars() { if idx < 7 { let res: (u32, u32) = helper(chr, min_row, max_row); min_row = res.0; max_row = res.1; } else { let res: (u32, u32) = helper(chr, min_col, max_col); min_col = res.0; max_col = res.1; } idx += 1; } let seat_id = max_row * 8 + max_col; seat_id } fn helper(direction: char, min: u32, max: u32) -> (u32, u32) { let half: u32 = max - (max - min) / 2; if direction == 'B' || direction == 'R' { (half, max) } else { (min, half - 1) } } #[cfg(test)] mod tests { use super::*; #[test] fn it_runs_first_part_right() { let example_input: Vec<&str> = vec!["BFFFBBFRRR", "FFFBBBFRRR", "BBFFBBFRLL"]; assert_eq!(first_part(&example_input).unwrap(), 820); } #[test] fn it_runs_second_part_right() { let example_input: Vec<&str> = vec!["FFFBBBFRRR", "FFFBBBFRRL", "FFFBBBFRLL"]; assert_eq!(second_part(&example_input).unwrap(), 117); } #[test] fn it_calculates_id_correctly() { assert_eq!(calculate_seat_id("BFFFBBFRRR"), 567); assert_eq!(calculate_seat_id("FFFBBBFRRR"), 119); assert_eq!(calculate_seat_id("BBFFBBFRLL"), 820); } #[test] fn it_helpers_correctly() { assert_eq!(helper('F', 0, 128), (0, 63)); assert_eq!(helper('B', 0, 63), (32, 63)); assert_eq!(helper('F', 32, 63), (32, 47)); assert_eq!(helper('B', 32, 47), (40, 47)); assert_eq!(helper('B', 40, 47), (44, 47)); assert_eq!(helper('F', 44, 47), (44, 45)); assert_eq!(helper('F', 44, 45), (44, 44)); } }
{ for idx in 0..(seat_ids.len() - 1) { if !(seat_ids[idx] == seat_ids[idx + 1] - 1) { return Some(seat_ids[idx] + 1); } } None }
test_functional.py
import errno from http import client as httplib import logging import multiprocessing import os import signal import socket import string import subprocess import sys import time import unittest from waitress import server from waitress.compat import WIN from waitress.utilities import cleanup_unix_socket dn = os.path.dirname here = dn(__file__) class NullHandler(logging.Handler): # pragma: no cover """A logging handler that swallows all emitted messages.""" def emit(self, record): pass def start_server(app, svr, queue, **kwargs): # pragma: no cover """Run a fixture application.""" logging.getLogger("waitress").addHandler(NullHandler()) try_register_coverage() svr(app, queue, **kwargs).run() def try_register_coverage(): # pragma: no cover # Hack around multiprocessing exiting early and not triggering coverage's # atexit handler by always registering a signal handler if "COVERAGE_PROCESS_START" in os.environ: def sigterm(*args): sys.exit(0) signal.signal(signal.SIGTERM, sigterm) class FixtureTcpWSGIServer(server.TcpWSGIServer): """A version of TcpWSGIServer that relays back what it's bound to.""" family = socket.AF_INET # Testing def __init__(self, application, queue, **kw): # pragma: no cover # Coverage doesn't see this as it's ran in a separate process. kw["host"] = "127.0.0.1" kw["port"] = 0 # Bind to any available port. super().__init__(application, **kw) host, port = self.socket.getsockname() if os.name == "nt": host = "127.0.0.1" queue.put((host, port)) class SubprocessTests: exe = sys.executable server = None def start_subprocess(self, target, **kw): # Spawn a server process. self.queue = multiprocessing.Queue() if "COVERAGE_RCFILE" in os.environ: os.environ["COVERAGE_PROCESS_START"] = os.environ["COVERAGE_RCFILE"] if not WIN: ctx = multiprocessing.get_context("fork") else: ctx = multiprocessing.get_context("spawn") self.proc = ctx.Process( target=start_server, args=(target, self.server, self.queue), kwargs=kw, ) self.proc.start() if self.proc.exitcode is not None: # pragma: no cover raise RuntimeError("%s didn't start" % str(target)) # Get the socket the server is listening on. self.bound_to = self.queue.get(timeout=5) self.sock = self.create_socket() def stop_subprocess(self): if self.proc.exitcode is None: self.proc.terminate() self.sock.close() # This give us one FD back ... self.proc.join() self.proc.close() self.queue.close() self.queue.join_thread() # The following is for the benefit of PyPy 3, for some reason it is # holding on to some resources way longer than necessary causing tests # to fail with file desctriptor exceeded errors on macOS which defaults # to 256 file desctriptors per process. While we could use ulimit to # increase the limits before running tests, this works as well and # means we don't need to remember to do that. import gc gc.collect() def assertline(self, line, status, reason, version): v, s, r = (x.strip() for x in line.split(None, 2)) self.assertEqual(s, status.encode("latin-1")) self.assertEqual(r, reason.encode("latin-1")) self.assertEqual(v, version.encode("latin-1")) def create_socket(self): return socket.socket(self.server.family, socket.SOCK_STREAM) def connect(self): self.sock.connect(self.bound_to) def make_http_connection(self): raise NotImplementedError # pragma: no cover def send_check_error(self, to_send): self.sock.send(to_send) class TcpTests(SubprocessTests): server = FixtureTcpWSGIServer def make_http_connection(self): return httplib.HTTPConnection(*self.bound_to) class SleepyThreadTests(TcpTests, unittest.TestCase): # test that sleepy thread doesnt block other requests def setUp(self): from tests.fixtureapps import sleepy self.start_subprocess(sleepy.app) def tearDown(self): self.stop_subprocess() def test_it(self): getline = os.path.join(here, "fixtureapps", "getline.py") cmds = ( [self.exe, getline, "http://%s:%d/sleepy" % self.bound_to], [self.exe, getline, "http://%s:%d/" % self.bound_to], ) r, w = os.pipe() procs = [] for cmd in cmds: procs.append(subprocess.Popen(cmd, stdout=w)) time.sleep(3) for proc in procs: if proc.returncode is not None: # pragma: no cover proc.terminate() proc.wait() # the notsleepy response should always be first returned (it sleeps # for 2 seconds, then returns; the notsleepy response should be # processed in the meantime) result = os.read(r, 10000) os.close(r) os.close(w) self.assertEqual(result, b"notsleepy returnedsleepy returned") class EchoTests: def setUp(self): from tests.fixtureapps import echo self.start_subprocess( echo.app, trusted_proxy="*", trusted_proxy_count=1, trusted_proxy_headers={"x-forwarded-for", "x-forwarded-proto"}, clear_untrusted_proxy_headers=True, ) def tearDown(self): self.stop_subprocess() def _read_echo(self, fp): from tests.fixtureapps import echo line, headers, body = read_http(fp) return line, headers, echo.parse_response(body) def test_date_and_server(self): to_send = b"GET / HTTP/1.0\r\nContent-Length: 0\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, echo = self._read_echo(fp) self.assertline(line, "200", "OK", "HTTP/1.0") self.assertEqual(headers.get("server"), "waitress") self.assertTrue(headers.get("date")) def test_bad_host_header(self): # https://corte.si/posts/code/pathod/pythonservers/index.html to_send = b"GET / HTTP/1.0\r\n Host: 0\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "400", "Bad Request", "HTTP/1.0") self.assertEqual(headers.get("server"), "waitress") self.assertTrue(headers.get("date")) def test_send_with_body(self): to_send = b"GET / HTTP/1.0\r\nContent-Length: 5\r\n\r\n" to_send += b"hello" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, echo = self._read_echo(fp) self.assertline(line, "200", "OK", "HTTP/1.0") self.assertEqual(echo.content_length, "5") self.assertEqual(echo.body, b"hello") def test_send_empty_body(self): to_send = b"GET / HTTP/1.0\r\nContent-Length: 0\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, echo = self._read_echo(fp) self.assertline(line, "200", "OK", "HTTP/1.0") self.assertEqual(echo.content_length, "0") self.assertEqual(echo.body, b"") def test_multiple_requests_with_body(self): orig_sock = self.sock for x in range(3): self.sock = self.create_socket() self.test_send_with_body() self.sock.close() self.sock = orig_sock def test_multiple_requests_without_body(self): orig_sock = self.sock for x in range(3): self.sock = self.create_socket() self.test_send_empty_body() self.sock.close() self.sock = orig_sock def test_without_crlf(self): data = b"Echo\r\nthis\r\nplease" s = ( b"GET / HTTP/1.0\r\n" b"Connection: close\r\n" b"Content-Length: %d\r\n" b"\r\n" b"%s" % (len(data), data) ) self.connect() self.sock.send(s) with self.sock.makefile("rb", 0) as fp: line, headers, echo = self._read_echo(fp) self.assertline(line, "200", "OK", "HTTP/1.0") self.assertEqual(int(echo.content_length), len(data)) self.assertEqual(len(echo.body), len(data)) self.assertEqual(echo.body, (data)) def test_large_body(self): # 1024 characters. body = b"This string has 32 characters.\r\n" * 32 s = b"GET / HTTP/1.0\r\nContent-Length: %d\r\n\r\n%s" % (len(body), body) self.connect() self.sock.send(s) with self.sock.makefile("rb", 0) as fp: line, headers, echo = self._read_echo(fp) self.assertline(line, "200", "OK", "HTTP/1.0") self.assertEqual(echo.content_length, "1024") self.assertEqual(echo.body, body) def test_many_clients(self): conns = [] for n in range(50): h = self.make_http_connection() h.request("GET", "/", headers={"Accept": "text/plain"}) conns.append(h) responses = [] for h in conns: response = h.getresponse() self.assertEqual(response.status, 200) responses.append(response) for response in responses: response.read() for h in conns: h.close() def test_chunking_request_without_content(self): header = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" self.connect() self.sock.send(header) self.sock.send(b"0\r\n\r\n") with self.sock.makefile("rb", 0) as fp: line, headers, echo = self._read_echo(fp) self.assertline(line, "200", "OK", "HTTP/1.1") self.assertEqual(echo.body, b"") self.assertEqual(echo.content_length, "0") self.assertFalse("transfer-encoding" in headers) def test_chunking_request_with_content(self): control_line = b"20;\r\n" # 20 hex = 32 dec s = b"This string has 32 characters.\r\n" expected = s * 12 header = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" self.connect() self.sock.send(header) with self.sock.makefile("rb", 0) as fp: for n in range(12): self.sock.send(control_line) self.sock.send(s) self.sock.send(b"\r\n") # End the chunk self.sock.send(b"0\r\n\r\n") line, headers, echo = self._read_echo(fp) self.assertline(line, "200", "OK", "HTTP/1.1") self.assertEqual(echo.body, expected) self.assertEqual(echo.content_length, str(len(expected))) self.assertFalse("transfer-encoding" in headers) def test_broken_chunked_encoding(self): control_line = b"20;\r\n" # 20 hex = 32 dec s = b"This string has 32 characters.\r\n" to_send = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" to_send += control_line + s + b"\r\n" # garbage in input to_send += b"garbage\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) # receiver caught garbage and turned it into a 400 self.assertline(line, "400", "Bad Request", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertEqual( sorted(headers.keys()), ["connection", "content-length", "content-type", "date", "server"], ) self.assertEqual(headers["content-type"], "text/plain") # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_broken_chunked_encoding_missing_chunk_end(self): control_line = b"20;\r\n" # 20 hex = 32 dec s = b"This string has 32 characters.\r\n" to_send = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" to_send += control_line + s # garbage in input to_send += b"garbage" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) # receiver caught garbage and turned it into a 400 self.assertline(line, "400", "Bad Request", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertTrue(b"Chunk not properly terminated" in response_body) self.assertEqual( sorted(headers.keys()), ["connection", "content-length", "content-type", "date", "server"], ) self.assertEqual(headers["content-type"], "text/plain") # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_keepalive_http_10(self): # Handling of Keep-Alive within HTTP 1.0 data = b"Default: Don't keep me alive" s = b"GET / HTTP/1.0\r\nContent-Length: %d\r\n\r\n%s" % (len(data), data) self.connect() self.sock.send(s) response = httplib.HTTPResponse(self.sock) response.begin() self.assertEqual(int(response.status), 200) connection = response.getheader("Connection", "") # We sent no Connection: Keep-Alive header # Connection: close (or no header) is default. self.assertTrue(connection != "Keep-Alive") def test_keepalive_http10_explicit(self): # If header Connection: Keep-Alive is explicitly sent, # we want to keept the connection open, we also need to return # the corresponding header data = b"Keep me alive" s = ( b"GET / HTTP/1.0\r\n" b"Connection: Keep-Alive\r\n" b"Content-Length: %d\r\n" b"\r\n" b"%s" % (len(data), data) ) self.connect() self.sock.send(s) response = httplib.HTTPResponse(self.sock) response.begin() self.assertEqual(int(response.status), 200) connection = response.getheader("Connection", "") self.assertEqual(connection, "Keep-Alive") def test_keepalive_http_11(self): # Handling of Keep-Alive within HTTP 1.1 # All connections are kept alive, unless stated otherwise data = b"Default: Keep me alive" s = b"GET / HTTP/1.1\r\nContent-Length: %d\r\n\r\n%s" % (len(data), data) self.connect() self.sock.send(s) response = httplib.HTTPResponse(self.sock) response.begin() self.assertEqual(int(response.status), 200) self.assertTrue(response.getheader("connection") != "close") def test_keepalive_http11_explicit(self): # Explicitly set keep-alive data = b"Default: Keep me alive" s = ( b"GET / HTTP/1.1\r\n" b"Connection: keep-alive\r\n" b"Content-Length: %d\r\n" b"\r\n" b"%s" % (len(data), data) ) self.connect() self.sock.send(s) response = httplib.HTTPResponse(self.sock) response.begin() self.assertEqual(int(response.status), 200) self.assertTrue(response.getheader("connection") != "close") def test_keepalive_http11_connclose(self): # specifying Connection: close explicitly data = b"Don't keep me alive" s = ( b"GET / HTTP/1.1\r\n" b"Connection: close\r\n" b"Content-Length: %d\r\n" b"\r\n" b"%s" % (len(data), data) ) self.connect() self.sock.send(s) response = httplib.HTTPResponse(self.sock) response.begin() self.assertEqual(int(response.status), 200) self.assertEqual(response.getheader("connection"), "close") def test_proxy_headers(self): to_send = ( b"GET / HTTP/1.0\r\n" b"Content-Length: 0\r\n" b"Host: www.google.com:8080\r\n" b"X-Forwarded-For: 192.168.1.1\r\n" b"X-Forwarded-Proto: https\r\n" b"X-Forwarded-Port: 5000\r\n\r\n" ) self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, echo = self._read_echo(fp) self.assertline(line, "200", "OK", "HTTP/1.0") self.assertEqual(headers.get("server"), "waitress") self.assertTrue(headers.get("date")) self.assertIsNone(echo.headers.get("X_FORWARDED_PORT")) self.assertEqual(echo.headers["HOST"], "www.google.com:8080") self.assertEqual(echo.scheme, "https") self.assertEqual(echo.remote_addr, "192.168.1.1") self.assertEqual(echo.remote_host, "192.168.1.1") class PipeliningTests: def setUp(self): from tests.fixtureapps import echo self.start_subprocess(echo.app_body_only) def tearDown(self): self.stop_subprocess() def test_pipelining(self): s = ( b"GET / HTTP/1.0\r\n" b"Connection: %s\r\n" b"Content-Length: %d\r\n" b"\r\n" b"%s" ) to_send = b"" count = 25 for n in range(count): body = b"Response #%d\r\n" % (n + 1) if n + 1 < count: conn = b"keep-alive" else: conn = b"close" to_send += s % (conn, len(body), body) self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: for n in range(count): expect_body = b"Response #%d\r\n" % (n + 1) line = fp.readline() # status line version, status, reason = (x.strip() for x in line.split(None, 2)) headers = parse_headers(fp) length = int(headers.get("content-length")) or None response_body = fp.read(length) self.assertEqual(int(status), 200) self.assertEqual(length, len(response_body)) self.assertEqual(response_body, expect_body) class ExpectContinueTests: def setUp(self): from tests.fixtureapps import echo self.start_subprocess(echo.app_body_only) def tearDown(self): self.stop_subprocess() def test_expect_continue(self): # specifying Connection: close explicitly data = b"I have expectations" to_send = ( b"GET / HTTP/1.1\r\n" b"Connection: close\r\n" b"Content-Length: %d\r\n" b"Expect: 100-continue\r\n" b"\r\n" b"%s" % (len(data), data) ) self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line = fp.readline() # continue status line version, status, reason = (x.strip() for x in line.split(None, 2)) self.assertEqual(int(status), 100) self.assertEqual(reason, b"Continue") self.assertEqual(version, b"HTTP/1.1") fp.readline() # blank line line = fp.readline() # next status line version, status, reason = (x.strip() for x in line.split(None, 2)) headers = parse_headers(fp) length = int(headers.get("content-length")) or None response_body = fp.read(length) self.assertEqual(int(status), 200) self.assertEqual(length, len(response_body)) self.assertEqual(response_body, data) class BadContentLengthTests: def setUp(self): from tests.fixtureapps import badcl self.start_subprocess(badcl.app) def tearDown(self): self.stop_subprocess() def test_short_body(self): # check to see if server closes connection when body is too short # for cl header to_send = ( b"GET /short_body HTTP/1.0\r\n" b"Connection: Keep-Alive\r\n" b"Content-Length: 0\r\n" b"\r\n" ) self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line = fp.readline() # status line version, status, reason = (x.strip() for x in line.split(None, 2)) headers = parse_headers(fp) content_length = int(headers.get("content-length")) response_body = fp.read(content_length) self.assertEqual(int(status), 200) self.assertNotEqual(content_length, len(response_body)) self.assertEqual(len(response_body), content_length - 1) self.assertEqual(response_body, b"abcdefghi") # remote closed connection (despite keepalive header); not sure why # first send succeeds self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_long_body(self): # check server doesnt close connection when body is too short # for cl header to_send = ( b"GET /long_body HTTP/1.0\r\n" b"Connection: Keep-Alive\r\n" b"Content-Length: 0\r\n" b"\r\n" ) self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line = fp.readline() # status line version, status, reason = (x.strip() for x in line.split(None, 2)) headers = parse_headers(fp) content_length = int(headers.get("content-length")) or None response_body = fp.read(content_length) self.assertEqual(int(status), 200) self.assertEqual(content_length, len(response_body)) self.assertEqual(response_body, b"abcdefgh") # remote does not close connection (keepalive header) self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line = fp.readline() # status line version, status, reason = (x.strip() for x in line.split(None, 2)) headers = parse_headers(fp) content_length = int(headers.get("content-length")) or None response_body = fp.read(content_length) self.assertEqual(int(status), 200) class NoContentLengthTests: def setUp(self): from tests.fixtureapps import nocl self.start_subprocess(nocl.app) def tearDown(self): self.stop_subprocess() def test_http10_generator(self): body = string.ascii_letters.encode("latin-1") to_send = ( b"GET / HTTP/1.0\r\n" b"Connection: Keep-Alive\r\n" b"Content-Length: %d\r\n\r\n" % len(body) ) to_send += body self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") self.assertEqual(headers.get("content-length"), None) self.assertEqual(headers.get("connection"), "close") self.assertEqual(response_body, body) # remote closed connection (despite keepalive header), because # generators cannot have a content-length divined self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_http10_list(self): body = string.ascii_letters.encode("latin-1") to_send = ( b"GET /list HTTP/1.0\r\n" b"Connection: Keep-Alive\r\n" b"Content-Length: %d\r\n\r\n" % len(body) ) to_send += body self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") self.assertEqual(headers["content-length"], str(len(body))) self.assertEqual(headers.get("connection"), "Keep-Alive") self.assertEqual(response_body, body) # remote keeps connection open because it divined the content length # from a length-1 list self.sock.send(to_send) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") def test_http10_listlentwo(self): body = string.ascii_letters.encode("latin-1") to_send = ( b"GET /list_lentwo HTTP/1.0\r\n" b"Connection: Keep-Alive\r\n" b"Content-Length: %d\r\n\r\n" % len(body) ) to_send += body self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") self.assertEqual(headers.get("content-length"), None) self.assertEqual(headers.get("connection"), "close") self.assertEqual(response_body, body) # remote closed connection (despite keepalive header), because # lists of length > 1 cannot have their content length divined self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_http11_generator(self): body = string.ascii_letters body = body.encode("latin-1") to_send = b"GET / HTTP/1.1\r\nContent-Length: %d\r\n\r\n" % len(body) to_send += body self.connect() self.sock.send(to_send) with self.sock.makefile("rb") as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") expected = b"" for chunk in chunks(body, 10): expected += b"%s\r\n%s\r\n" % ( hex(len(chunk))[2:].upper().encode("latin-1"), chunk, ) expected += b"0\r\n\r\n" self.assertEqual(response_body, expected) # connection is always closed at the end of a chunked response self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_http11_list(self): body = string.ascii_letters.encode("latin-1") to_send = b"GET /list HTTP/1.1\r\nContent-Length: %d\r\n\r\n" % len(body) to_send += body self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") self.assertEqual(headers["content-length"], str(len(body))) self.assertEqual(response_body, body) # remote keeps connection open because it divined the content length # from a length-1 list self.sock.send(to_send) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") def test_http11_listlentwo(self): body = string.ascii_letters.encode("latin-1") to_send = b"GET /list_lentwo HTTP/1.1\r\nContent-Length: %d\r\n\r\n" % len(body) to_send += body self.connect() self.sock.send(to_send) with self.sock.makefile("rb") as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") expected = b"" for chunk in (body[:1], body[1:]): expected += b"%s\r\n%s\r\n" % ( (hex(len(chunk))[2:].upper().encode("latin-1")), chunk, ) expected += b"0\r\n\r\n" self.assertEqual(response_body, expected) # connection is always closed at the end of a chunked response self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) class WriteCallbackTests: def setUp(self): from tests.fixtureapps import writecb self.start_subprocess(writecb.app) def tearDown(self): self.stop_subprocess() def test_short_body(self): # check to see if server closes connection when body is too short # for cl header to_send = ( b"GET /short_body HTTP/1.0\r\n" b"Connection: Keep-Alive\r\n" b"Content-Length: 0\r\n" b"\r\n" ) self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) # server trusts the content-length header (5) self.assertline(line, "200", "OK", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, 9) self.assertNotEqual(cl, len(response_body)) self.assertEqual(len(response_body), cl - 1) self.assertEqual(response_body, b"abcdefgh") # remote closed connection (despite keepalive header) self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_long_body(self): # check server doesnt close connection when body is too long # for cl header to_send = ( b"GET /long_body HTTP/1.0\r\n" b"Connection: Keep-Alive\r\n" b"Content-Length: 0\r\n" b"\r\n" ) self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) content_length = int(headers.get("content-length")) or None self.assertEqual(content_length, 9) self.assertEqual(content_length, len(response_body)) self.assertEqual(response_body, b"abcdefghi") # remote does not close connection (keepalive header) self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") def test_equal_body(self): # check server doesnt close connection when body is equal to # cl header to_send = ( b"GET /equal_body HTTP/1.0\r\n" b"Connection: Keep-Alive\r\n" b"Content-Length: 0\r\n" b"\r\n" ) self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) content_length = int(headers.get("content-length")) or None self.assertEqual(content_length, 9) self.assertline(line, "200", "OK", "HTTP/1.0") self.assertEqual(content_length, len(response_body)) self.assertEqual(response_body, b"abcdefghi") # remote does not close connection (keepalive header) self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") def test_no_content_length(self): # wtf happens when there's no content-length to_send = ( b"GET /no_content_length HTTP/1.0\r\n" b"Connection: Keep-Alive\r\n" b"Content-Length: 0\r\n" b"\r\n" ) self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line = fp.readline() # status line line, headers, response_body = read_http(fp) content_length = headers.get("content-length") self.assertEqual(content_length, None) self.assertEqual(response_body, b"abcdefghi") # remote closed connection (despite keepalive header) self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) class TooLargeTests: toobig = 1050 def setUp(self): from tests.fixtureapps import toolarge self.start_subprocess( toolarge.app, max_request_header_size=1000, max_request_body_size=1000 ) def tearDown(self): self.stop_subprocess()
body = b"" bad_headers = b"X-Random-Header: 100\r\n" * int(self.toobig / 20) to_send = b"GET / HTTP/1.1\r\nContent-Length: 0\r\n" to_send += bad_headers to_send += b"\r\n\r\n" to_send += body self.connect() self.sock.send(to_send) with self.sock.makefile("rb") as fp: response_line, headers, response_body = read_http(fp) self.assertline( response_line, "431", "Request Header Fields Too Large", "HTTP/1.0" ) self.assertEqual(headers["connection"], "close") def test_request_body_too_large_with_wrong_cl_http10(self): body = b"a" * self.toobig to_send = b"GET / HTTP/1.0\r\nContent-Length: 5\r\n\r\n" to_send += body self.connect() self.sock.send(to_send) with self.sock.makefile("rb") as fp: # first request succeeds (content-length 5) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # server trusts the content-length header; no pipelining, # so request fulfilled, extra bytes are thrown away # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_request_body_too_large_with_wrong_cl_http10_keepalive(self): body = b"a" * self.toobig to_send = ( b"GET / HTTP/1.0\r\nContent-Length: 5\r\nConnection: Keep-Alive\r\n\r\n" ) to_send += body self.connect() self.sock.send(to_send) with self.sock.makefile("rb") as fp: # first request succeeds (content-length 5) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) line, headers, response_body = read_http(fp) self.assertline(line, "431", "Request Header Fields Too Large", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_request_body_too_large_with_no_cl_http10(self): body = b"a" * self.toobig to_send = b"GET / HTTP/1.0\r\n\r\n" to_send += body self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # extra bytes are thrown away (no pipelining), connection closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_request_body_too_large_with_no_cl_http10_keepalive(self): body = b"a" * self.toobig to_send = b"GET / HTTP/1.0\r\nConnection: Keep-Alive\r\n\r\n" to_send += body self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) # server trusts the content-length header (assumed zero) self.assertline(line, "200", "OK", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) line, headers, response_body = read_http(fp) # next response overruns because the extra data appears to be # header data self.assertline(line, "431", "Request Header Fields Too Large", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_request_body_too_large_with_wrong_cl_http11(self): body = b"a" * self.toobig to_send = b"GET / HTTP/1.1\r\nContent-Length: 5\r\n\r\n" to_send += body self.connect() self.sock.send(to_send) with self.sock.makefile("rb") as fp: # first request succeeds (content-length 5) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # second response is an error response line, headers, response_body = read_http(fp) self.assertline(line, "431", "Request Header Fields Too Large", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_request_body_too_large_with_wrong_cl_http11_connclose(self): body = b"a" * self.toobig to_send = b"GET / HTTP/1.1\r\nContent-Length: 5\r\nConnection: close\r\n\r\n" to_send += body self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) # server trusts the content-length header (5) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_request_body_too_large_with_no_cl_http11(self): body = b"a" * self.toobig to_send = b"GET / HTTP/1.1\r\n\r\n" to_send += body self.connect() self.sock.send(to_send) with self.sock.makefile("rb") as fp: # server trusts the content-length header (assumed 0) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # server assumes pipelined requests due to http/1.1, and the first # request was assumed c-l 0 because it had no content-length header, # so entire body looks like the header of the subsequent request # second response is an error response line, headers, response_body = read_http(fp) self.assertline(line, "431", "Request Header Fields Too Large", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_request_body_too_large_with_no_cl_http11_connclose(self): body = b"a" * self.toobig to_send = b"GET / HTTP/1.1\r\nConnection: close\r\n\r\n" to_send += body self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) # server trusts the content-length header (assumed 0) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_request_body_too_large_chunked_encoding(self): control_line = b"20;\r\n" # 20 hex = 32 dec s = b"This string has 32 characters.\r\n" to_send = b"GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" repeat = control_line + s to_send += repeat * ((self.toobig // len(repeat)) + 1) self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) # body bytes counter caught a max_request_body_size overrun self.assertline(line, "413", "Request Entity Too Large", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertEqual(headers["content-type"], "text/plain") # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) class InternalServerErrorTests: def setUp(self): from tests.fixtureapps import error self.start_subprocess(error.app, expose_tracebacks=True) def tearDown(self): self.stop_subprocess() def test_before_start_response_http_10(self): to_send = b"GET /before_start_response HTTP/1.0\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "500", "Internal Server Error", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertTrue(response_body.startswith(b"Internal Server Error")) self.assertEqual(headers["connection"], "close") # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_before_start_response_http_11(self): to_send = b"GET /before_start_response HTTP/1.1\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "500", "Internal Server Error", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertTrue(response_body.startswith(b"Internal Server Error")) self.assertEqual( sorted(headers.keys()), ["connection", "content-length", "content-type", "date", "server"], ) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_before_start_response_http_11_close(self): to_send = b"GET /before_start_response HTTP/1.1\r\nConnection: close\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "500", "Internal Server Error", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertTrue(response_body.startswith(b"Internal Server Error")) self.assertEqual( sorted(headers.keys()), ["connection", "content-length", "content-type", "date", "server"], ) self.assertEqual(headers["connection"], "close") # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_after_start_response_http10(self): to_send = b"GET /after_start_response HTTP/1.0\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "500", "Internal Server Error", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertTrue(response_body.startswith(b"Internal Server Error")) self.assertEqual( sorted(headers.keys()), ["connection", "content-length", "content-type", "date", "server"], ) self.assertEqual(headers["connection"], "close") # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_after_start_response_http11(self): to_send = b"GET /after_start_response HTTP/1.1\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "500", "Internal Server Error", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertTrue(response_body.startswith(b"Internal Server Error")) self.assertEqual( sorted(headers.keys()), ["connection", "content-length", "content-type", "date", "server"], ) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_after_start_response_http11_close(self): to_send = b"GET /after_start_response HTTP/1.1\r\nConnection: close\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "500", "Internal Server Error", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertTrue(response_body.startswith(b"Internal Server Error")) self.assertEqual( sorted(headers.keys()), ["connection", "content-length", "content-type", "date", "server"], ) self.assertEqual(headers["connection"], "close") # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_after_write_cb(self): to_send = b"GET /after_write_cb HTTP/1.1\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") self.assertEqual(response_body, b"") # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_in_generator(self): to_send = b"GET /in_generator HTTP/1.1\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") self.assertEqual(response_body, b"") # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) class FileWrapperTests: def setUp(self): from tests.fixtureapps import filewrapper self.start_subprocess(filewrapper.app) def tearDown(self): self.stop_subprocess() def test_filelike_http11(self): to_send = b"GET /filelike HTTP/1.1\r\n\r\n" self.connect() for t in range(0, 2): self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body) # connection has not been closed def test_filelike_nocl_http11(self): to_send = b"GET /filelike_nocl HTTP/1.1\r\n\r\n" self.connect() for t in range(0, 2): self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body) # connection has not been closed def test_filelike_shortcl_http11(self): to_send = b"GET /filelike_shortcl HTTP/1.1\r\n\r\n" self.connect() for t in range(0, 2): self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, 1) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377" in response_body) # connection has not been closed def test_filelike_longcl_http11(self): to_send = b"GET /filelike_longcl HTTP/1.1\r\n\r\n" self.connect() for t in range(0, 2): self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body) # connection has not been closed def test_notfilelike_http11(self): to_send = b"GET /notfilelike HTTP/1.1\r\n\r\n" self.connect() for t in range(0, 2): self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body) # connection has not been closed def test_notfilelike_iobase_http11(self): to_send = b"GET /notfilelike_iobase HTTP/1.1\r\n\r\n" self.connect() for t in range(0, 2): self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body) # connection has not been closed def test_notfilelike_nocl_http11(self): to_send = b"GET /notfilelike_nocl HTTP/1.1\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body) # connection has been closed (no content-length) self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_notfilelike_shortcl_http11(self): to_send = b"GET /notfilelike_shortcl HTTP/1.1\r\n\r\n" self.connect() for t in range(0, 2): self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, 1) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377" in response_body) # connection has not been closed def test_notfilelike_longcl_http11(self): to_send = b"GET /notfilelike_longcl HTTP/1.1\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body) + 10) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_filelike_http10(self): to_send = b"GET /filelike HTTP/1.0\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_filelike_nocl_http10(self): to_send = b"GET /filelike_nocl HTTP/1.0\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_notfilelike_http10(self): to_send = b"GET /notfilelike HTTP/1.0\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) def test_notfilelike_nocl_http10(self): to_send = b"GET /notfilelike_nocl HTTP/1.0\r\n\r\n" self.connect() self.sock.send(to_send) with self.sock.makefile("rb", 0) as fp: line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body) # connection has been closed (no content-length) self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp) class TcpEchoTests(EchoTests, TcpTests, unittest.TestCase): pass class TcpPipeliningTests(PipeliningTests, TcpTests, unittest.TestCase): pass class TcpExpectContinueTests(ExpectContinueTests, TcpTests, unittest.TestCase): pass class TcpBadContentLengthTests(BadContentLengthTests, TcpTests, unittest.TestCase): pass class TcpNoContentLengthTests(NoContentLengthTests, TcpTests, unittest.TestCase): pass class TcpWriteCallbackTests(WriteCallbackTests, TcpTests, unittest.TestCase): pass class TcpTooLargeTests(TooLargeTests, TcpTests, unittest.TestCase): pass class TcpInternalServerErrorTests( InternalServerErrorTests, TcpTests, unittest.TestCase ): pass class TcpFileWrapperTests(FileWrapperTests, TcpTests, unittest.TestCase): pass if hasattr(socket, "AF_UNIX"): class FixtureUnixWSGIServer(server.UnixWSGIServer): """A version of UnixWSGIServer that relays back what it's bound to.""" family = socket.AF_UNIX # Testing def __init__(self, application, queue, **kw): # pragma: no cover # Coverage doesn't see this as it's ran in a separate process. # To permit parallel testing, use a PID-dependent socket. kw["unix_socket"] = "/tmp/waitress.test-%d.sock" % os.getpid() super().__init__(application, **kw) queue.put(self.socket.getsockname()) class UnixTests(SubprocessTests): server = FixtureUnixWSGIServer def make_http_connection(self): return UnixHTTPConnection(self.bound_to) def stop_subprocess(self): super().stop_subprocess() cleanup_unix_socket(self.bound_to) def send_check_error(self, to_send): # Unlike inet domain sockets, Unix domain sockets can trigger a # 'Broken pipe' error when the socket it closed. try: self.sock.send(to_send) except OSError as exc: valid_errors = {errno.EPIPE, errno.ENOTCONN} self.assertIn(get_errno(exc), valid_errors) class UnixEchoTests(EchoTests, UnixTests, unittest.TestCase): pass class UnixPipeliningTests(PipeliningTests, UnixTests, unittest.TestCase): pass class UnixExpectContinueTests(ExpectContinueTests, UnixTests, unittest.TestCase): pass class UnixBadContentLengthTests( BadContentLengthTests, UnixTests, unittest.TestCase ): pass class UnixNoContentLengthTests(NoContentLengthTests, UnixTests, unittest.TestCase): pass class UnixWriteCallbackTests(WriteCallbackTests, UnixTests, unittest.TestCase): pass class UnixTooLargeTests(TooLargeTests, UnixTests, unittest.TestCase): pass class UnixInternalServerErrorTests( InternalServerErrorTests, UnixTests, unittest.TestCase ): pass class UnixFileWrapperTests(FileWrapperTests, UnixTests, unittest.TestCase): pass def parse_headers(fp): """Parses only RFC2822 headers from a file pointer.""" headers = {} while True: line = fp.readline() if line in (b"\r\n", b"\n", b""): break line = line.decode("iso-8859-1") name, value = line.strip().split(":", 1) headers[name.lower().strip()] = value.lower().strip() return headers class UnixHTTPConnection(httplib.HTTPConnection): """Patched version of HTTPConnection that uses Unix domain sockets.""" def __init__(self, path): httplib.HTTPConnection.__init__(self, "localhost") self.path = path def connect(self): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(self.path) self.sock = sock def close(self): self.sock.close() class ConnectionClosed(Exception): pass # stolen from gevent def read_http(fp): # pragma: no cover try: response_line = fp.readline() except OSError as exc: fp.close() # errno 104 is ENOTRECOVERABLE, In WinSock 10054 is ECONNRESET if get_errno(exc) in (errno.ECONNABORTED, errno.ECONNRESET, 104, 10054): raise ConnectionClosed raise if not response_line: raise ConnectionClosed header_lines = [] while True: line = fp.readline() if line in (b"\r\n", b"\r\n", b""): break else: header_lines.append(line) headers = dict() for x in header_lines: x = x.strip() if not x: continue key, value = x.split(b": ", 1) key = key.decode("iso-8859-1").lower() value = value.decode("iso-8859-1") assert key not in headers, "%s header duplicated" % key headers[key] = value if "content-length" in headers: num = int(headers["content-length"]) body = b"" left = num while left > 0: data = fp.read(left) if not data: break body += data left -= len(data) else: # read until EOF body = fp.read() return response_line, headers, body # stolen from gevent def get_errno(exc): # pragma: no cover """Get the error code out of socket.error objects. socket.error in <2.5 does not have errno attribute socket.error in 3.x does not allow indexing access e.args[0] works for all. There are cases when args[0] is not errno. i.e. http://bugs.python.org/issue6471 Maybe there are cases when errno is set, but it is not the first argument? """ try: if exc.errno is not None: return exc.errno except AttributeError: pass try: return exc.args[0] except IndexError: return None def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i : i + n]
def test_request_headers_too_large_http11(self):
E0451.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. mod Bar { pub struct Foo { pub a: isize, b: isize, } pub struct FooTuple ( pub isize, isize, ); } fn
(foo: Bar::Foo) { let Bar::Foo{a:a, b:b} = foo; //~ ERROR E0451 //~^ NOTE field `b` is private } fn pat_match_tuple(foo: Bar::FooTuple) { let Bar::FooTuple(a,b) = foo; //~ ERROR E0451 //~^ NOTE field `1` is private } fn main() { let f = Bar::Foo{ a: 0, b: 0 }; //~ ERROR E0451 //~^ NOTE field `b` is private }
pat_match
cache.go
package dnsproxy import ( "sync" "time" ) var ( lock = sync.RWMutex{} Cachsed = make(map[string]*Cache) ) type Cache struct { data []byte create time.Time // client *net.UDPAddr } func
() { lock.Lock() defer lock.Unlock() Cachsed = make(map[string]*Cache) } func RegistDNS(host string, replyDNS []byte) { if replyDNS == nil || len(replyDNS) == 0 { return } lock.Lock() defer lock.Unlock() c := &Cache{ data: replyDNS, create: time.Now(), // client: client, } Cachsed[host] = c } func FindCache(host string) (c *Cache, found bool) { c, found = Cachsed[host] // c.create.After(1 * ) return }
CleanCache
basic_project_stats.py
#Python 2.7.9 (default, Apr 5 2015, 22:21:35) # the full environment I used to test this is in basic_project_stats.yml import sys # file with raw classifications (csv) # put this way up here so if there are no inputs we exit quickly before even trying to load everything else try: classfile_in = sys.argv[1] except: print("\nUsage: %s classifications_infile" % sys.argv[0]) print(" classifications_infile is a Zooniverse (Panoptes) classifications data export CSV.\n") print(" Optional inputs:") print(" workflow_id=N") print(" specify the program should only consider classifications from workflow id N") print(" workflow_version=M") print(" specify the program should only consider classifications from workflow version M") print(" (note the program will only consider the major version, i.e. the integer part)") print(" outfile_csv=filename.csv") print(" if you want the program to save a sub-file with only classification info from the workflow specified, give the filename here") print(" --time_elapsed") print(" specify the program should compute classification durations and total classification work effort") print(" --remove_duplicates") print(" remove duplicate classifications (subject-user pairs) before analysis.") print(" memory-intensive for big files; probably best to pair with outfile_csv so you save the output.") print(" --keep_nonlive") print(" by default the program ignores classifications made while the project wasn't 'Live'; setting this will keep them in.") print(" --keep_allcols") print(" by default the program only keeps columns required for stats; use this with a specified outfile_csv to save all columns, including annotations. (If you're not using outfile_csv this will just waste memory.)") print("\nAll output will be to stdout (about 1-2 paragraphs' worth).\n") sys.exit(0) import numpy as np # works in 1.10.1 import pandas as pd # works in 0.13.1 import datetime import dateutil.parser import json, ujson import gc # default value is not to care about workflow ID or version workflow_id = -1 workflow_version = -1 # by default we won't worry about computing how much time effort the volunteers cumulatively spent time_elapsed = False # by default we won't write the subset of classifications we used to a new csv file output_csv = False # by default we'll ignore the possibility of duplicate classifications # note duplicates are relatively rare, usually <2% of all classifications # the Zooniverse has squashed several bugs related to this, but some still # happen client-side and there's nothing we can do about that. remove_duplicates = False # by default, restrict the analysis to "Live" classifications keep_nonlive = False # by default, don't keep every column of the classifications when writing to an outfile keep_allcols = False # check for other command-line arguments if len(sys.argv) > 2: # if there are additional arguments, loop through them for i_arg, argstr in enumerate(sys.argv[2:]): arg = argstr.split('=') if arg[0] == "workflow_id": workflow_id = int(arg[1]) elif arg[0] == "workflow_version": workflow_version = float(arg[1]) elif (arg[0] == "outfile_csv") | (arg[0] == "outfile"): outfile_csv = arg[1] output_csv = True elif arg[0] == "--keep_allcols": keep_allcols = True elif arg[0] == "--time_elapsed": time_elapsed = True elif arg[0] == "--remove_duplicates": remove_duplicates = True elif arg[0] == "--keep_nonlive": keep_nonlive = True # columns currently in an exported Panoptes classification file: # classification_id,user_name,user_id,user_ip,workflow_id,workflow_name,workflow_version,created_at,gold_standard,expert,metadata,annotations,subject_data,subject_ids # classification_id identifies the specific classification - should be unique for each row in this file # user_name is either their registered name or "not-logged-in"+their hashed IP # user_id is their numeric Zooniverse ID or blank if they're unregistered # user_ip is a hashed version of their IP # workflow_id is the numeric ID of this workflow, which you can find in the project builder URL for managing the workflow: # https://www.zooniverse.org/lab/[project_id]/workflow/[workflow_id]/ # workflow_name is the name you gave your workflow (for sanity checks) # workflow_version is [bigchangecount].[smallchangecount] and is probably pretty big # created_at is the date the entry for the classification was recorded # gold_standard is 1 if this classification was done in gold standard mode # expert is 1 if this classification was done in expert mode... I think # metadata (json) is the data the browser sent along with the classification. # Includes browser information, language, started_at and finished_at # note started_at and finished_at are perhaps the easiest way to calculate the length of a classification # (the duration elapsed between consecutive created_at by the same user is another way) # the difference here is back-end vs front-end # annotations (json) contains the actual classification information # which for this analysis we will ignore completely, for now # subject_data is cross-matched from the subjects table and is for convenience in data reduction # subject_ids has just the subject ids in the given classification # here we will ignore this too, except to count subjects once. # we'll also ignore classification_id, user_ip, workflow information, gold_standard, and expert. # # Print out the input parameters just as a sanity check print("Computing project stats using:") print(" infile: %s" % classfile_in) ################################################################################# ################################################################################# ################################################################################# # Get the Gini coefficient - https://en.wikipedia.org/wiki/Gini_coefficient # # The Gini coefficient measures inequality in distributions of things. # It was originally conceived for economics (e.g. where is the wealth in a country? # in the hands of many citizens or a few?), but it's just as applicable to many # other fields. In this case we'll use it to see how classifications are # distributed among classifiers. # G = 0 is a completely even distribution (everyone does the same number of # classifications), and ~1 is uneven (~all the classifications are done # by one classifier). # Typical values of the Gini for healthy Zooniverse projects (Cox et al. 2015) are # in the range of 0.7-0.9. # That range is generally indicative of a project with a loyal core group of # volunteers who contribute the bulk of the classification effort, but balanced # out by a regular influx of new classifiers trying out the project, from which # you continue to draw to maintain a core group of prolific classifiers. # Once your project is fairly well established, you can compare it to past Zooniverse # projects to see how you're doing. # If your G is << 0.7, you may be having trouble recruiting classifiers into a loyal # group of volunteers. People are trying it, but not many are staying. # If your G is > 0.9, it's a little more complicated. If your total classification # count is lower than you'd like it to be, you may be having trouble recruiting # classifiers to the project, such that your classification counts are # dominated by a few people. # But if you have G > 0.9 and plenty of classifications, this may be a sign that your # loyal users are -really- committed, so a very high G is not necessarily a bad thing. # # Of course the Gini coefficient is a simplified measure that doesn't always capture # subtle nuances and so forth, but it's still a useful broad metric. def
(list_of_values): sorted_list = sorted(list_of_values) height, area = 0, 0 for value in sorted_list: height += value area += height - value / 2. fair_area = height * len(list_of_values) / 2 return (fair_area - area) / fair_area ################################################################################# ################################################################################# ################################################################################# def get_duplicate_ids(grp): # groupbys and dfs have slightly different indexing and just NOPE #thegrp = pd.DataFrame(grp) thegrp = grp if len(thegrp) == 1: return else: # we have a duplicate set, so return the details return thegrp def get_live_project(meta_json): try: return meta_json['live_project'] except: # apparently some subject metadata doesn't have this? dunno? return False def get_live_project_incl_missing(meta_json): try: return meta_json['live_project'] except: return -1 # Begin the main stuff print("Reading classifications from %s" % classfile_in) #classifications = pd.read_csv(classfile_in) # the above will work but uses a LOT of memory for projects with > 1 million # classifications. Nothing here uses the actual classification data so don't read it ''' If you are using this code on an older project, where the data export is from before subject_ids were exported as their own column, change "subject_id" below to "subject_data", and then when you define the groupby "by_subject" and count subjects, you'll need to use subject_data instead of subject_ids. Apologies for doing this, but subject_data contains the whole manifest so for big projects with big catalogs it can take up a lot of memory, so we don't want to use it if we don't have to. ''' cols_keep = ["classification_id", "user_name", "user_id", "user_ip", "workflow_id", "workflow_version", "created_at", "metadata", "subject_ids"] if not keep_allcols: try: classifications = pd.read_csv(classfile_in, usecols=cols_keep) except: print("Some columns missing from classifications infile, reading without specifying columns (uses more memory)... ") classifications = pd.read_csv(classfile_in) else: try: classifications = pd.read_csv(classfile_in, low_memory=False) except: classifications = pd.read_csv(classfile_in) cols_used = classifications.columns.tolist() cols_out = classifications.columns.tolist() if not 'created_day' in cols_used: cols_used.append('created_day') if not 'meta_json' in cols_used: cols_used.append('meta_json') n_class_raw = len(classifications) # now restrict classifications to a particular workflow id/version if requested if (workflow_id > 0) | (workflow_version > 0): # only keep the stuff that matches these workflow properties if (workflow_id > 0): print("Considering only workflow id %d" % workflow_id) in_workflow = classifications.workflow_id == workflow_id else: # the workflow id wasn't specified, so just make an array of true in_workflow = np.array([True for q in classifications.workflow_id]) if (workflow_version > 0): classifications['version_int'] = [int(q) for q in classifications.workflow_version] print("Considering only major workflow version %d" % int(workflow_version)) # we only care about the major workflow version, not the minor version in_version = classifications.version_int == int(workflow_version) else: in_version = np.array([True for q in classifications.workflow_version]) if (sum(in_workflow & in_version) == 0): print("ERROR: your combination of workflow_id and workflow_version does not exist!\nIgnoring workflow id/version request and computing stats for ALL classifications instead.") #classifications = classifications_all else: # select the subset of classifications classifications = classifications[in_workflow & in_version] del in_workflow del in_version else: # just use everything #classifications = classifications_all workflow_ids = classifications.workflow_id.unique() # this takes too much CPU time just for a print statement. Just use float versions #classifications['version_int'] = [int(q) for q in classifications.workflow_version] version_ints = classifications.workflow_version.unique() print("Considering all classifications in workflow ids:") print(workflow_ids) print(" and workflow_versions:") print(version_ints) # Remove classifications collected before the project went Live # note: it makes logical sense to do this *before* we extract the classifications # from the workflow we care about, *but* the meta_json setting step (which we # need in order to extract Live project status) can take a while (up to ~minutes) # and adds to memory usage, so I'd rather do it after we've already culled # the table of potentially a lot of unused rows. # OTOH culling duplicates takes more time and memory than culling unused workflow # versions, so wait to do that until after we've removed non-Live classifications # first, extract the metadata column into a json we can read entries for # # ujson is quite a bit faster than json but seems to use a bit more memory as it works classifications['meta_json'] = [ujson.loads(q) for q in classifications.metadata] if keep_nonlive: print("Retaining all non-live classifications in analysis.") else: # would that we could just do q['live_project'] but if that tag is missing for # any classifications (which it is in some cases) it crashes classifications['live_project'] = [get_live_project(q) for q in classifications.meta_json] # if this line gives you an error you've read in this boolean as a string # so need to convert "True" --> True and "False" --> False class_live = classifications[classifications.live_project].copy() n_class_thiswf = len(classifications) n_live = sum(classifications.live_project) n_notlive = n_class_thiswf - n_live print(" Removing %d non-live classifications..." % n_notlive) # don't make a slice but also save memory classifications = pd.DataFrame(class_live) del class_live gc.collect() # if we've been asked to remove duplicates, do that now if remove_duplicates: ''' a duplicate can be that the classification id is submitted twice by the client but it can also be that the classifier classified the same subject twice in different classification_ids. So identify duplicates based on username + subject id + workflow info, not based on classification_id. ''' subj_classifications = classifications.groupby('user_name subject_ids workflow_id workflow_version'.split()) n_class = len(classifications) # just take the first of each of the groups classifications_nodups = subj_classifications.head(1) n_class_nodup = len(classifications_nodups) n_dups = n_class - n_class_nodup if n_dups == 0: print("Searched for duplicate classifications; none found.") else: duplicate_outfile = classfile_in.replace(".csv", "_duplicated_only.csv") if duplicate_outfile == classfile_in: duplicate_outfile += "_duplicated_only.csv" print("Found %d duplicate classifications (%.2f percent of total)." % (n_dups, float(n_dups)/float(n_class)*100.0)) # get the duplicate classifications and save them before we remove them #class_dups = pd.DataFrame(subj_classifications.apply(get_duplicate_ids)) # if you want to keep a record of everything with just the dups flagged, # this is your thing #dups_flagged = pd.merge(classifications, classifications_nodups['classification_id subject_id'.split()], how='outer', on='classification_id', suffixes=('', '_2'), indicator=True) # if you just need something that has only the dups in it, here you go dups_only = classifications[~classifications.isin(classifications_nodups)].dropna(how='all') # dups_only has the duplicates only - not the original classification in each set # i.e. if classifications 123, 456, and 789 are all from the same user # classifying the same subject, dups_only will only contain classifications # 456 and 789. When we save the duplicate classifications we want to save # the initial classification (that was later duplicated) as well, so we # need to retrieve those. # I don't see a really easy way to do it based on the groupby we already did # (subj_classifications) # so let's just define what identifies the duplicate (user_name + subject_ids) # and pick them out. # even for a reasonably big dataset this is relatively fast (seconds, not minutes) try: dups_only['user_subj_pair'] = dups_only['user_name']+'_'+dups_only['subject_ids'].astype(int).astype(str)+'_'+dups_only['workflow_id'].astype(str)+'v'+dups_only['workflow_version'].astype(str) except: dups_only['user_subj_pair'] = dups_only['user_name']+'_'+dups_only['subject_ids'].astype(str)+'_'+dups_only['workflow_id'].astype(str)+'v'+dups_only['workflow_version'].astype(str) # n_dup_pairs tracks unique user-subject pairs that were duplicated dup_pairs = dups_only['user_subj_pair'].unique() n_dup_pairs = len(dup_pairs) try: classifications['user_subj_pair'] = classifications['user_name']+'_'+classifications['subject_ids'].astype(int).astype(str)+'_'+classifications['workflow_id'].astype(str)+'v'+classifications['workflow_version'].astype(str) except: classifications['user_subj_pair'] = classifications['user_name']+'_'+classifications['subject_ids'].astype(str)+'_'+classifications['workflow_id'].astype(str)+'v'+classifications['workflow_version'].astype(str) # this keeps things that are any part of a duplicate set, including first is_a_dup = classifications['user_subj_pair'].isin(dup_pairs) class_dups = classifications[is_a_dup].copy() # counts any classification that is any part of a duplicate set n_partofdup = len(class_dups) class_dups.to_csv(duplicate_outfile) #print(class_dups.head(3)) # now throw away the duplicates (but keep the first of each set) from # the main classifications table classifications = pd.DataFrame(classifications_nodups) del class_dups del is_a_dup print("Duplicates removed from analysis (%d unique user-subject-workflow groups)." % n_dup_pairs) del subj_classifications del classifications_nodups gc.collect() classifications['created_day'] = [q[:10] for q in classifications.created_at] first_class_day = min(classifications.created_day).replace(' ', '') last_class_day = max(classifications.created_day).replace(' ', '') # save processing time and memory in the groupby.apply(); only keep the columns we're going to use or want to save if output_csv: if not keep_allcols: # if we'll be writing to a file at the end of this we need to save a few extra columns cols_used = ["classification_id", "user_name", "user_id", "user_ip", "created_at", "created_day", "metadata", "meta_json", "subject_ids", "workflow_id", "workflow_version"] else: if not keep_allcols: cols_used = ["classification_id", "user_name", "user_id", "user_ip", "created_at", "created_day", "meta_json", "subject_ids"] classifications = classifications[cols_used] # collect() calls PyInt_ClearFreeList(), so explicitly helps free some active memory gc.collect() # grab the subject counts n_subj_tot = len(classifications.subject_ids.unique()) by_subject = classifications.groupby('subject_ids') subj_class = by_subject.created_at.aggregate('count') # basic stats on how classified the subjects are subj_class_mean = np.mean(subj_class) subj_class_med = np.median(subj_class) subj_class_min = np.min(subj_class) subj_class_max = np.max(subj_class) # free up some memory - note calling this does take CPU time but # can free up GBs of active memory for big classification files del by_subject gc.collect() # index by created_at as a timeseries # note: this means things might not be uniquely indexed # but it makes a lot of things easier and faster. # update: it's not really needed in the main bit, but will do it on each group later. #classifications.set_index('created_at_ts', inplace=True) # get some user information all_users = classifications.user_name.unique() by_user = classifications.groupby('user_name') # also count IP addresses n_ip = len(classifications.user_ip.unique()) # get total classification and user counts n_class_tot = len(classifications) n_users_tot = len(all_users) unregistered = [q.startswith("not-logged-in") for q in all_users] n_unreg = sum(unregistered) n_reg = n_users_tot - n_unreg is_unreg_class = [q.startswith("not-logged-in") for q in classifications.user_name] n_unreg_class = sum(is_unreg_class) n_reg_class = n_class_tot - n_unreg_class # for the leaderboard, which I recommend project builders never make public because # Just Say No to gamification # But it's still interesting to see who your most prolific classifiers are, and # e.g. whether they're also your most prolific Talk users nclass_byuser = by_user.created_at.aggregate('count') nclass_byuser_ranked = nclass_byuser.copy() nclass_byuser_ranked.sort_values(inplace=True, ascending=False) # rename the columns properly so they'll print as useful csv headers nclass_byuser_ranked.name = 'user_name' nc = pd.DataFrame(nclass_byuser_ranked) nc.columns = ['n_class'] # write this to a file, so you don't have to re-calculate it later nclass_byuser_outfile = classfile_in.replace(".csv", "_nclass_byuser_ranked.csv") # don't accidentally overwrite the classifications file just because someone # renamed it to not end in .csv if nclass_byuser_outfile == classfile_in: nclass_byuser_outfile = "project_nclass_byuser_ranked.csv" nc.to_csv(nclass_byuser_outfile) # very basic stats nclass_med = np.median(nclass_byuser) nclass_mean = np.mean(nclass_byuser) # Gini coefficient - see the comments above the gini() function for more notes nclass_gini = gini(nclass_byuser) print("\nOverall:\n\n%d classifications of %d subjects by %d classifiers," % (n_class_tot,n_subj_tot,n_users_tot)) print("%d logged in and %d not logged in, from %d unique IP addresses." % (n_reg,n_unreg,n_ip)) print("%d classifications were from logged-in users, %d from not-logged-in users.\n" % (n_reg_class, n_unreg_class)) print("That's %.2f classifications per subject on average (median = %.1f)." % (subj_class_mean, subj_class_med)) print("The most classified subject has %d classifications; the least-classified subject has %d.\n" % (subj_class_max,subj_class_min)) print("Median number of classifications per user: %.2f" %nclass_med) print("Mean number of classifications per user: %.2f" % nclass_mean) print("\nTop 10 most prolific classifiers:") print(nclass_byuser_ranked.head(10)) print("\n\nGini coefficient for classifications by user: %.2f" % nclass_gini) print("\nClassifications were collected between %s and %s." % (first_class_day, last_class_day)) print("The highest classification id considered here is %d.\n" % max(classifications.classification_id)) # if the input specified we should compute total time spent by classifiers, compute it if time_elapsed: # free up some memory # do this inside the if because if we're not computing times then the program # is about to end so this memory will be freed up anyway del unregistered del by_user gc.collect() classifications['started_at_str'] = [q['started_at'].replace('T',' ').replace('Z', '') for q in classifications.meta_json] classifications['finished_at_str'] = [q['finished_at'].replace('T',' ').replace('Z', '') for q in classifications.meta_json] sa_temp = classifications['started_at_str'] fa_temp = classifications['finished_at_str'] #print("Creating timeseries...")#,datetime.datetime.now().strftime('%H:%M:%S.%f') try: classifications['started_at'] = pd.to_datetime(sa_temp, format='%Y-%m-%d %H:%M:%S.%f') except Exception as the_error: print("Oops:\n%s" % the_error) try: classifications['started_at'] = pd.to_datetime(sa_temp, format='%Y-%m-%d %H:%M:%S %Z') except Exception as the_error: print("Oops:\n%s" % the_error) classifications['started_at'] = pd.to_datetime(sa_temp) try: classifications['finished_at'] = pd.to_datetime(fa_temp, format='%Y-%m-%d %H:%M:%S.%f') except Exception as the_error: print("Oops:\n%s" % the_error) try: classifications['finished_at'] = pd.to_datetime(fa_temp, format='%Y-%m-%d %H:%M:%S %Z') except Exception as the_error: print("Oops:\n%s" % the_error) classifications['finished_at'] = pd.to_datetime(fa_temp) # we did all that above so that this would only take one line and be quite fast classifications['class_t_length'] = (classifications.finished_at - classifications.started_at) # throw away absurd time counts: accept lengths between 0 < dt < 30 minutes # anything outside that is either a wrongly reported time or the user walked away from their computer ok_times = (classifications.class_t_length > np.timedelta64(0, 's')) & (classifications.class_t_length < np.timedelta64(30, 'm')) # how many turned out to be okay? n_t_ok = sum(ok_times) # compute total times time_spent_classifying = np.sum(classifications['class_t_length'][ok_times]) days_spent_classifying = time_spent_classifying / np.timedelta64(1, 'D') frac_good_durations = float(n_t_ok)/float(n_class_tot) print("Based on %d classifications (%.1f percent) where we can probably\ntrust the classification durations, the classifiers spent a total of %.2f days\n(or %.2f years) classifying in the project.\n" % (n_t_ok, frac_good_durations*100., days_spent_classifying, days_spent_classifying / 365.)) mean_t_class = np.mean(classifications['class_t_length'][ok_times]) median_t_class = np.median(classifications['class_t_length'][ok_times]) human_effort_extrap = float(n_class_tot)*float(mean_t_class / np.timedelta64(1, 'D')) / 365. # in years print("Mean classification length: %8.1f seconds" % float(mean_t_class / np.timedelta64(1, 's'))) print("Median classification length: %6.1f seconds" % float(median_t_class / np.timedelta64(1, 's'))) print("\nIf we use the mean to extrapolate and include the %.1f percent of\nclassifications where the reported duration had an error, that means\nthe total time spent is equivalent to %.2f years of human effort, or\n%.2f years of FTE (1 person working 40 hours/week, no holiday.)\n" % ((1-frac_good_durations)*100., human_effort_extrap, human_effort_extrap * (24.*7.)/40.)) if output_csv: # free up what memory we can before doing this (matters for big files) if time_elapsed: del ok_times del sa_temp del fa_temp del nclass_byuser del all_users del subj_class gc.collect() if keep_allcols: classifications[cols_out].to_csv(outfile_csv) else: classifications.to_csv(outfile_csv) print("File with used subset of classification info written to %s ." % outfile_csv) print("File with ranked list of user classification counts written to %s ." % nclass_byuser_outfile) if remove_duplicates: if (n_dups > 0): print("Saved info for all classifications that have duplicates to %s ." % duplicate_outfile) #end
gini
sugar.py
""" Collection of old doppyo functions and useful tidbits for internal dcfp use Authors: Dougie Squire and Thomas Moore Date created: 01/10/2018 Python Version: 3.6 """ # =================================================================================================== # Packages # =================================================================================================== import numpy as np import pandas as pd import xarray as xr import cartopy from collections import Sequence from itertools import chain, count import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as mticker from cartopy.util import add_cyclic_point from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER # Load doppyo packages ----- from doppyo import utils # =================================================================================================== def rank_gufunc(x): ''' Returns ranked data along specified dimension ''' import bottleneck ranks = bottleneck.nanrankdata(x,axis=-1) ranks = ranks[...,0] return ranks def compute_rank(da_1, da_2, over_dim): ''' Feeds forecast and observation data to ufunc that ranks data along specified dimension''' # Add 'ensemble' coord to obs if one does not exist ----- if over_dim not in da_2.coords: da_2_pass = da_2.copy() da_2_pass.coords[over_dim] = -1 da_2_pass = da_2_pass.expand_dims(over_dim) else: da_2_pass = da_2.copy() # Only keep and combine instances that appear in both dataarrays (excluding the ensemble dim) ----- aligned = xr.align(da_2_pass, da_1, join='inner', exclude=over_dim) combined = xr.concat(aligned, dim=over_dim) return xr.apply_ufunc(rank_gufunc, combined, input_core_dims=[[over_dim]], dask='allowed', output_dtypes=[int]).rename('rank') # =================================================================================================== def categorize(da, bin_edges): """ Returns the indices of the bins to which each value in input array belongs Output indices are such that bin_edges[i-1] <= x < bin_edges[i] """ return xr.apply_ufunc(np.digitize, da, bin_edges, input_core_dims=[[],[]], dask='allowed', output_dtypes=[int]).rename('categorized') # =================================================================================================== def unstack_and_count(da, dims): """ Unstacks provided xarray object and returns the total number of elements along dims """ try: unstacked = da.unstack(da.dims[0]) except ValueError: unstacked = da if dims is None: return ((0 * unstacked) + 1) else: return ((0 * unstacked) + 1).sum(dim=dims, skipna=True) def compute_histogram(da, bin_edges, over_dims): """ Returns the histogram of data over the specified dimensions """ # To use groupby_bins, da must have a name ----- da = da.rename('data') hist = da.groupby_bins(da, bins=bin_edges, squeeze=False) \ .apply(unstack_and_count, dims=over_dims) \ .fillna(0) \ .rename({'data_bins' : 'bins'}) hist['bins'] = (bin_edges[0:-1]+bin_edges[1:])/2 # Add nans where data did not fall in any bin ----- return hist.astype(int).where(hist.sum('bins') != 0) # =================================================================================================== def calc_gradient(da, dim, x=None): """ Returns the gradient computed using second order accurate central differences in the interior points and either first order accurate one-sided (forward or backwards) differences at the boundaries See https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.gradient.html """ # Replace dimension values if specified ----- da_n = da.copy() if x is None: x = da_n[dim] centre_chunk = range(len(x[dim])-2) f_hd = da_n.shift(**{dim:-2}) f = da_n.shift(**{dim:-1}) f_hs = da_n hs = x.shift(**{dim:-1}) - x hd = x.shift(**{dim:-2}) - x.shift(**{dim:-1}) c = (hs ** 2 * f_hd + (hd ** 2 - hs ** 2) * f - hd ** 2 * f_hs) / \ (hs * hd * (hd + hs)).isel(**{dim : centre_chunk}) c[dim] = x[dim][1:-1] l = (da_n.shift(**{dim:-1}) - da_n).isel(**{dim : 0}) / \ (x.shift(**{dim:-1}) - x).isel(**{dim : 0}) r = (-da_n.shift(**{dim:1}) + da_n).isel(**{dim : -1}) / \ (-x.shift(**{dim:1}) + x).isel(**{dim : -1}) grad = xr.concat([l, c, r], dim=dim) grad[dim] = da[dim] return grad # =================================================================================================== def bias_correct_ms(da_biased, da_target, da_target_clim=None, init_date_name='init_date', lead_time_name='lead_time'): """ Adjusts, per month and lead time, the mean and standard deviation of da_biased to match that of da_target. Author: Dougie Squire Date: 01/09/2018 Parameters ---------- da_biased : xarray DataArray Array containing values to be corrected. The time information of this array is anticipated in a lead_time/inital_date format da_target : xarray DataArray Array containing values to use for the correction. da_target_clim : xarray DataArray, optional Array containing a climatology of da_target. If da_target_clim is provided, this function returns both the corrected full field and the anomalies. Otherwise, returns only the anomalies init_date_name : str, optional Name of initial date dimension lead_time_name : str, optional Name of lead time dimension Returns ------- corrected : xarray DataArray Bias corrected array Examples -------- >>> biased = xr.DataArray(np.random.normal(size=(48,6)), ... coords=[('init_date', pd.date_range(start='1/1/2018', periods=48, freq='M')), ... ('lead_time', np.arange(6))]) >>> biased['lead_time'].attrs['units'] = 'M' >>> target = xr.DataArray(np.random.normal(size=(48)), ... coords=[('time', pd.date_range(start='1/1/2000', periods=48, freq='M'))]) >>> doppyo.utils.bias_correct_ms(biased, target) <xarray.DataArray (init_date: 48, lead_time: 6)> array([[ 9.336394e-02, 1.133997e-01, -5.851293e-01, -4.908594e-02, 7.952765e-01, 5.325052e-01], [-1.131123e+00, 1.603380e-01, -1.626906e+00, -1.811439e+00, -1.653359e-01, -1.871170e-01], [ 6.515435e-01, -1.064662e+00, 2.249610e+00, 6.881682e-01, -1.831233e-01, -1.159470e+00], ..., [-2.096226e+00, 3.143062e-04, 3.603787e-01, -1.515535e+00, 5.421578e-02, -6.446119e-01], [-8.186274e-01, -9.858171e-01, 1.933307e+00, 5.227265e-02, 5.443201e-01, -7.059492e-01], [ 2.253396e-02, 2.238470e+00, 1.138728e-01, -3.617103e-01, 1.678223e+00, -2.413158e+00]]) Coordinates: * lead_time (lead_time) int64 0 1 2 3 4 5 * init_date (init_date) datetime64[ns] 2018-01-31 2018-02-28 ... 2021-12-31 Notes ----------- Many years of initial dates (in da_biased) and times (in da_target) must exist for the mean and standard deviation to be computed reliably """ def _groupby_lead_and_mean(da, over_dims, init_date_name, lead_time_name): """ Groups provided array by lead time and computes mean """ return da.unstack('stacked_' + init_date_name + '_' + lead_time_name).groupby(lead_time_name).mean(over_dims, skipna=True) def _groupby_lead_and_std(da, over_dims, init_date_name, lead_time_name): """ Groups provided array by lead time and computes standard deviation """ return da.unstack('stacked_' + init_date_name + '_' + lead_time_name).groupby(lead_time_name).std(over_dims, skipna=True) def _unstack_and_shift_per_month(da, shift, init_date_name, lead_time_name): """ Unstacks and adjusts input array by a constant shift as a function of month """ da_us = da.unstack('stacked_' + init_date_name + '_' + lead_time_name) the_month = np.ndarray.flatten(da_us.month.values) the_month = int(np.unique(the_month[~np.isnan(the_month)])) return da_us - shift.sel(month=the_month) def _unstack_and_scale_per_month(da, scale, init_date_name, lead_time_name): """ Unstacks and scales input array by a constant value as a function of month """ da_us = da.unstack('stacked_' + init_date_name + '_' + lead_time_name) the_month = np.ndarray.flatten(da_us.month.values) the_month = int(np.unique(the_month[~np.isnan(the_month)])) return da_us * scale.sel(month=the_month) def _scale_per_month(da, scale): """ Scales input array by a constant value as a function of month """ return da.groupby('time.month') * scale _anomalize = lambda data, clim: datetime_to_leadtime( anomalize( leadtime_to_datetime(data),clim)) _rescale = lambda da, scale : datetime_to_leadtime( _scale_per_month( leadtime_to_datetime(da), scale)) da_biased = da_biased.copy() da_target = da_target.copy() month = (da_biased[init_date_name].dt.month + da_biased[lead_time_name]) % 12 month = month.where(month != 0, 12) # Correct the mean ----- da_biased.coords['month'] = month try: da_biased_mean = da_biased.groupby('month').apply(_groupby_lead_and_mean, over_dims=[init_date_name,'ensemble'], init_date_name=init_date_name, lead_time_name=lead_time_name) except ValueError: da_biased_mean = da_biased.groupby('month').apply(_groupby_lead_and_mean, over_dims=init_date_name, init_date_name=init_date_name, lead_time_name=lead_time_name) if da_target_clim is not None: da_target_mean = da_target.groupby('time.month').mean('time') da_meancorr = da_biased.groupby('month').apply(_unstack_and_shift_per_month, shift=(da_biased_mean - da_target_mean), init_date_name=init_date_name, lead_time_name=lead_time_name) \ .mean('month', skipna=True) da_meancorr[lead_time_name] = da_biased[lead_time_name] da_meancorr.coords['month'] = month # Compute the corrected anomalies ----- da_anom_meancorr = da_meancorr.groupby(init_date_name).apply(_anomalize, clim=da_target_clim) da_anom_meancorr.coords['month'] = month else: da_anom_meancorr = da_biased.groupby('month').apply(_unstack_and_shift_per_month, shift=(da_biased_mean), init_date_name=init_date_name, lead_time_name=lead_time_name) \ .mean('month', skipna=True) da_anom_meancorr[lead_time_name] = da_anom_meancorr[lead_time_name] da_anom_meancorr.coords['month'] = month # Correct the standard deviation ----- try: da_biased_std_tmp = da_anom_meancorr.groupby('month').apply(_groupby_lead_and_std, over_dims=[init_date_name,'ensemble'], init_date_name=init_date_name, lead_time_name=lead_time_name) except ValueError: da_biased_std_tmp = da_anom_meancorr.groupby('month').apply(_groupby_lead_and_std, over_dims=init_date_name, init_date_name=init_date_name, lead_time_name=lead_time_name) try: da_target_std = da_target.sel(lat=da_biased.lat, lon=da_biased.lon).groupby('time.month').std('time') except: da_target_std = da_target.groupby('time.month').std('time') da_anom_stdcorr_tmp = da_anom_meancorr.groupby('month').apply(_unstack_and_scale_per_month, scale=(da_target_std / da_biased_std_tmp), init_date_name=init_date_name, lead_time_name=lead_time_name) \ .mean('month', skipna=True) da_anom_stdcorr_tmp[lead_time_name] = da_biased[lead_time_name] da_anom_stdcorr_tmp.coords['month'] = month # This will "squeeze" each pdf at each lead time appropriately. However, the total variance across all leads for # a given month will now be incorrect. Thus, we now rescale as a function of month only try: da_biased_std = concat_times(da_anom_stdcorr_tmp).groupby('time.month').std(['time','ensemble']) except ValueError: da_biased_std = concat_times(da_anom_stdcorr_tmp).groupby('time.month').std('time') da_anom_stdcorr = da_anom_stdcorr_tmp.groupby(init_date_name).apply(_rescale, scale=(da_target_std / da_biased_std)) if da_target_clim is not None: da_stdcorr = da_anom_stdcorr.groupby(init_date_name).apply(_anomalize, clim=-da_target_clim) return da_stdcorr.drop('month'), da_anom_stdcorr.drop('month') else: return da_anom_stdcorr.drop('month') # =================================================================================================== def bias_correct_m(da_biased, da_target, da_target_clim=None, init_date_name='init_date', lead_time_name='lead_time'): """ Adjusts, per month and lead time, the mean of da_biased to match that of da_target Author: Dougie Squire Date: 01/09/2018 Parameters ---------- da_biased : xarray DataArray Array containing values to be corrected. The time information of this array is anticipated in a lead_time/inital_date format da_target : xarray DataArray Array containing values to use for the correction. da_target_clim : xarray DataArray, optional Array containing a climatology of da_target. If da_target_clim is provided, this function returns both the corrected full field and the anomalies. Otherwise, returns only the anomalies init_date_name : str, optional Name of initial date dimension lead_time_name : str, optional Name of lead time dimension Returns ------- corrected : xarray DataArray Bias corrected array Examples -------- >>> biased = xr.DataArray(np.random.normal(size=(48,6)), ... coords=[('init_date', pd.date_range(start='1/1/2018', periods=48, freq='M')), ... ('lead_time', np.arange(6))]) >>> biased['lead_time'].attrs['units'] = 'M' >>> target = xr.DataArray(np.random.normal(size=(48)), ... coords=[('time', pd.date_range(start='1/1/2000', periods=48, freq='M'))]) >>> doppyo.utils.bias_correct_m(biased, target) <xarray.DataArray (init_date: 48, lead_time: 6)> array([[ 0.541226, 0.693622, -0.367322, 0.820282, 0.111487, 0.078355], [-0.299829, 0.164297, -0.976883, 0.463365, -0.26428 , -0.536119], [ 0.078832, -0.260615, -0.235059, -0.349185, 0.567183, -1.543395], ..., [ 0.335494, -1.121158, 1.313004, 0.604279, 0.135053, 0.031851], [ 0.33103 , 0.876521, -0.980873, 0.640328, 1.053691, 0.166768], [ 1.207329, 0.021916, 0.210883, -0.189922, 0.075786, 0.047616]]) Coordinates: * init_date (init_date) datetime64[ns] 2018-01-31 2018-02-28 ... 2021-12-31 * lead_time (lead_time) int64 0 1 2 3 4 5 Notes ----------- Many years of initial dates (in da_biased) and times (in da_target) must exist for the mean to be computed reliably """ def _groupby_lead_and_mean(da, over_dims, init_date_name, lead_time_name): """ Groups provided array by lead time and computes mean """ return da.unstack('stacked_' + init_date_name + '_' + lead_time_name).groupby(lead_time_name).mean(over_dims, skipna=True) def _unstack_and_shift_per_month(da, shift, init_date_name, lead_time_name): """ Unstacks and adjusts input array by a constant shift as a function of month """ da_us = da.unstack('stacked_' + init_date_name + '_' + lead_time_name) the_month = np.ndarray.flatten(da_us.month.values) the_month = int(np.unique(the_month[~np.isnan(the_month)])) return da_us - shift.sel(month=the_month) _anomalize = lambda data, clim: datetime_to_leadtime( anomalize( leadtime_to_datetime(data),clim)) da_biased = da_biased.copy() da_target = da_target.copy() month = (da_biased[init_date_name].dt.month + da_biased[lead_time_name]) % 12 month = month.where(month != 0, 12) # Correct the mean ----- da_biased.coords['month'] = month try: da_biased_mean = da_biased.groupby('month').apply(_groupby_lead_and_mean, over_dims=[init_date_name,'ensemble'], init_date_name=init_date_name, lead_time_name=lead_time_name) except ValueError: da_biased_mean = da_biased.groupby('month').apply(_groupby_lead_and_mean, over_dims=init_date_name, init_date_name=init_date_name, lead_time_name=lead_time_name) if da_target_clim is not None: da_target_mean = da_target.groupby('time.month').mean('time') da_meancorr = da_biased.groupby('month').apply(_unstack_and_shift_per_month, shift=(da_biased_mean - da_target_mean), init_date_name=init_date_name, lead_time_name=lead_time_name) \ .mean('month', skipna=True) da_meancorr[lead_time_name] = da_biased[lead_time_name] da_meancorr.coords['month'] = month # Compute the corrected anomalies ----- da_anom_meancorr = da_meancorr.groupby(init_date_name).apply(_anomalize, clim=da_target_clim) da_anom_meancorr.coords['month'] = month else: da_anom_meancorr = da_biased.groupby('month').apply(_unstack_and_shift_per_month, shift=(da_biased_mean), init_date_name=init_date_name, lead_time_name=lead_time_name) \ .mean('month', skipna=True) da_anom_meancorr[lead_time_name] = da_anom_meancorr[lead_time_name] da_anom_meancorr.coords['month'] = month if da_target_clim is not None: da_meancorrr = da_anom_meancorr.groupby(init_date_name).apply(_anomalize, clim=-da_target_clim) return da_meancorr.drop('month'), da_anom_meancorr.drop('month') else: return da_anom_meancorr.drop('month') # =================================================================================================== def conditional_bias_correct(da_cmp, da_ref, over_dims): """ Return conditional bias corrected data using the approach of Goddard et al. 2013 """ cc = skill.compute_Pearson_corrcoef(da_cmp.mean('ensemble'), da_ref, over_dims=over_dims, subtract_local_mean=False) correct_cond_bias = (da_ref.std(over_dims) / da_cmp.mean('ensemble').std(over_dims)) * cc return da_cmp * correct_cond_bias # =================================================================================================== def trunc_time(time, freq): """ Truncates values in provided time array to provided frequency. E.g. 2018-01-15T12:00 with freq = 'M' becomes 2018-01-01. """ return time.astype('<M8[' + freq + ']') # =================================================================================================== def month_delta(date_in, delta, trunc_to_start=False): """ Increments provided datetime64 array by delta months """ date_mod = pd.Timestamp(date_in) m, y = (date_mod.month + delta) % 12, date_mod.year + ((date_mod.month) + delta - 1) // 12 if not m: m = 12 d = min(date_mod.day, [31, 29 if y % 4 == 0 and not y % 400 == 0 else 28,31,30,31,30,31,31,30,31,30,31][m - 1]) if trunc_to_start: date_out = trunc_time(np.datetime64(date_mod.replace(day=d,month=m, year=y)),'M') else: date_out = np.datetime64(date_mod.replace(day=d,month=m, year=y)) return np.datetime64(date_out,'ns') # =================================================================================================== def year_delta(date_in, delta, trunc_to_start=False): """ Increments provided datetime64 array by delta years """ date_mod = month_delta(date_in, 12 * delta) if trunc_to_start: date_out = trunc_time(date_mod,'Y') else: date_out = date_mod return date_out # =================================================================================================== def datetime_to_leadtime(data_in): """ Converts time information from single datetime dimension to init_date/lead_time dimension pair """ init_date = data_in.time.values[0] lead_times = range(len(data_in.time)) try: freq = pd.infer_freq(data_in.time.values) # If pandas tries to assign start time to frequency (e.g. QS-OCT), remove this ----- if '-' in freq: freq = freq[:freq.find('-')] # Split frequency into numbers and strings ----- incr_string = ''.join([i for i in freq if i.isdigit()]) freq_incr = [int(incr_string) if incr_string else 1][0] freq_type = ''.join([i for i in freq if not i.isdigit()]) # Specify all lengths great than 1 month in months ----- if 'QS' in freq_type: freq = str(3*freq_incr) + 'MS' elif 'Q' in freq_type: freq = str(3*freq_incr) + 'M' elif ('YS' in freq_type) | ('AS' in freq_type): freq = str(12*freq_incr) + 'MS' elif ('Y' in freq_type) | ('A' in freq_type): freq = str(12*freq_incr) + 'M' except ValueError: dt = (data_in.time.values[1] - data_in.time.values[0]) / np.timedelta64(1, 's') month = data_in.time.dt.month[0] if dt == 60*60*24: freq = 'D' elif ((month == 1) | (month == 3) | (month == 5) | (month == 7) | (month == 8) | (month == 10) | (month == 12)) & (dt == 31*60*60*24): freq = 'MS' elif ((month == 4) | (month == 6) | (month == 9) | (month == 11)) & (dt == 30*60*60*24): freq = 'MS' elif (month == 2) & ((dt == 28*60*60*24) | (dt == 29*60*60*24)): freq = 'MS' elif (dt == 365*60*60*24) | (dt == 366*60*60*24): freq = 'A' else: freq = 'NA' data_out = data_in.rename({'time' : 'lead_time'}) data_out['lead_time'] = lead_times data_out['lead_time'].attrs['units'] = freq data_out.coords['init_date'] = init_date return data_out # =================================================================================================== def leadtime_to_datetime(data_in, init_date_name='init_date', lead_time_name='lead_time'): """ Converts time information from lead time/initial date dimension pair to single datetime dimension """ try: init_date = data_in[init_date_name].values[0] except IndexError: init_date = data_in[init_date_name].values lead_times = list(map(int, data_in[lead_time_name].values)) freq = data_in[lead_time_name].attrs['units'] # # Split frequency into numbers and strings ----- # incr_string = ''.join([i for i in freq if i.isdigit()]) # freq_incr = [int(incr_string) if incr_string else 1][0] # freq_type = ''.join([i for i in freq if not i.isdigit()]) # Deal with special cases of monthly and yearly frequencies ----- # if 'M' in freq_type: # datetimes = np.array([month_delta(init_date, freq_incr * ix) for ix in lead_times]) # elif ('A' in freq_type) | ('Y' in freq_type): # datetimes = np.array([year_delta(init_date, freq_incr * ix) for ix in lead_times]) # else: # datetimes = (pd.date_range(init_date, periods=len(lead_times), freq=freq)).values datetimes = (pd.date_range(init_date, periods=len(lead_times), freq=freq)).values data_out = data_in.drop(init_date_name) data_out = data_out.rename({lead_time_name : 'time'}) data_out['time'] = datetimes return prune(data_out) # =================================================================================================== def get_nearest_point(da, lat, lon): """ Returns the nearest grid point to the specified lat/lon location """ return da.sel(lat=lat,lon=lon,method='nearest') # =================================================================================================== # visualization tools # =================================================================================================== def plot_fields(data, title=None, headings=None, ncol=2, contour=False, vlims=None, clims=None, squeeze_row=1, squeeze_col=1, squeeze_cbar=1, shift_cbar=1, cmap='viridis', fontsize=12, invert=False): """ Plots tiles of figures """ def
(seq): for level in count(): if not seq: return level seq = list(chain.from_iterable(s for s in seq if isinstance(s, Sequence))) matplotlib.rc('font', family='sans-serif') matplotlib.rc('font', serif='Helvetica') matplotlib.rc('text', usetex='false') matplotlib.rcParams.update({'font.size': fontsize}) nrow = int(np.ceil(len(data)/ncol)); fig = plt.figure(figsize=(11*squeeze_col, nrow*4*squeeze_row)) if (clims is not None) & (np.shape(vlims) != np.shape(clims)): raise ValueError('The input clims must be equal in size to vlims') # Check if vlims are given per figure or for all figures ----- one_cbar = False if vlims is None: vlims = [[None, None]] * len(data) if _depth(vlims) == 1: one_cbar = True over_count = 1 for idx,dat in enumerate(data): if one_cbar: vmin, vmax = vlims if clims is not None: cmin, cmax = clims else: vmin, vmax = vlims[idx] if clims is not None: cmin, cmax = clims[idx] if ('lat' in dat.dims) and ('lon' in dat.dims): trans = cartopy.crs.PlateCarree() ax = plt.subplot(nrow, ncol, over_count, projection=cartopy.crs.PlateCarree(central_longitude=180)) extent = [dat.lon.min(), dat.lon.max(), dat.lat.min(), dat.lat.max()] if contour is True: if clims is not None: ax.coastlines(color='gray') im = ax.contourf(dat.lon, dat.lat, dat, levels=np.linspace(vmin,vmax,12), origin='lower', transform=trans, vmin=vmin, vmax=vmax, cmap=cmap) ax.contour(dat.lon, dat.lat, dat, levels=np.linspace(cmin,cmax,12), origin='lower', transform=trans, vmin=vmin, vmax=vmax, colors='w', linewidths=2) ax.contour(dat.lon, dat.lat, dat, levels=np.linspace(cmin,cmax,12), origin='lower', transform=trans, vmin=vmin, vmax=vmax, colors='k', linewidths=1) else: ax.coastlines(color='black') im = ax.contourf(dat.lon, dat.lat, dat, origin='lower', transform=trans, vmin=vmin, vmax=vmax, cmap=cmap) else: ax.coastlines(color='black') im = ax.imshow(dat, origin='lower', extent=extent, transform=trans, vmin=vmin, vmax=vmax, cmap=cmap) gl = ax.gridlines(crs=cartopy.crs.PlateCarree(), draw_labels=True) gl.xlines = False gl.ylines = False gl.xlabels_top = False if over_count % ncol == 0: gl.ylabels_left = False elif (over_count+ncol-1) % ncol == 0: gl.ylabels_right = False else: gl.ylabels_left = False gl.ylabels_right = False gl.xlocator = mticker.FixedLocator([-90, 0, 90, 180]) gl.ylocator = mticker.FixedLocator([-90, -60, 0, 60, 90]) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER if not one_cbar: cbar = plt.colorbar(im, ax=ax, orientation="horizontal", aspect=30/squeeze_cbar, pad=shift_cbar*0.1) tick_locator = mticker.MaxNLocator(nbins=6) cbar.locator = tick_locator cbar.update_ticks() if headings is not None: cbar.set_label(headings[idx], labelpad=5, fontsize=fontsize); elif headings is not None: ax.set_title(headings[idx], fontsize=fontsize) else: ax = plt.subplot(nrow, ncol, over_count) if 'lat' in dat.dims: x_plt = dat['lat'] y_plt = dat[utils.get_other_dims(dat,'lat')[0]] # if dat.get_axis_num('lat') > 0: # dat = dat.transpose() elif 'lon' in dat.dims: x_plt = dat['lon'] y_plt = dat[utils.get_other_dims(dat,'lon')[0]] # if dat.get_axis_num('lon') > 0: # dat = dat.transpose() else: x_plt = dat[dat.dims[1]] y_plt = dat[dat.dims[0]] extent = [x_plt.min(), x_plt.max(), y_plt.min(), y_plt.max()] if contour is True: if clims is not None: im = ax.contourf(x_plt, y_plt, dat, levels=np.linspace(vmin,vmax,12), vmin=vmin, vmax=vmax, cmap=cmap) ax.contour(x_plt, y_plt, dat, levels=np.linspace(cmin,cmax,12), colors='w', linewidths=2) ax.contour(x_plt, y_plt, dat, levels=np.linspace(cmin,cmax,12), colors='k', linewidths=1) else: im = ax.contourf(x_plt, y_plt, dat, vmin=vmin, vmax=vmax, cmap=cmap) else: im = ax.imshow(dat, origin='lower', extent=extent, vmin=vmin, vmax=vmax, cmap=cmap) if over_count % ncol == 0: ax.yaxis.tick_right() elif (over_count+ncol-1) % ncol == 0: ax.set_ylabel(y_plt.dims[0], fontsize=fontsize) else: ax.set_yticks([]) if idx / ncol >= nrow - 1: ax.set_xlabel(x_plt.dims[0], fontsize=fontsize) if not one_cbar: cbar = plt.colorbar(im, ax=ax, orientation="horizontal", aspect=30/squeeze_cbar, pad=shift_cbar*0.1) tick_locator = mticker.MaxNLocator(nbins=6) cbar.locator = tick_locator cbar.update_ticks() if headings is not None: cbar.set_label(headings[idx], labelpad=5, fontsize=fontsize); elif headings is not None: ax.set_title(headings[idx], fontsize=fontsize) if invert: ax.invert_yaxis() over_count += 1 plt.tight_layout() if one_cbar: vmin, vmax = vlims fig.subplots_adjust(bottom=shift_cbar*0.16) cbar_ax = fig.add_axes([0.15, 0.13, 0.7, squeeze_cbar*0.020]) cbar = fig.colorbar(im, cax=cbar_ax, orientation='horizontal'); cbar_ax.set_xlabel(title, rotation=0, labelpad=15, fontsize=fontsize); cbar.set_ticks(np.linspace(vmin,vmax,5)) elif title is not None: fig.suptitle(title, y=1) # =================================================================================================== def size_GB(xr_object): """ How many GB (or GiB) is your xarray object? // Requires an xarray object // Returns: * equivalent GB (GBytes) - 10^9 conversion * equivalent GiB (GiBytes) - 2^ 30 conversion < Thomas Moore - [email protected] - 10102018 > """ bytes = xr_object.nbytes Ten2the9 = 10**9 Two2the30 = 2**30 GBytes = bytes / Ten2the9 GiBytes = bytes / Two2the30 #print out results print(xr_object.name, "is", GBytes, "GB", 'which is', GiBytes,"GiB") return GBytes,GiBytes # =================================================================================================== def get_pres_name(da): """ Returns name of pressure dimension in input array Author: Dougie Squire Date: 03/03/2018 Parameters ---------- da : xarray DataArray Array with coordinate corresponding to pressure Returns ------- name : str Name of dimension corresponding to pressure Examples -------- >>> A = xr.DataArray(np.random.normal(size=(2,2,2,2,2)), ... coords=[('lat', np.arange(2)), ('lon', np.arange(2)), ... ('depth', np.arange(2)), ('level', np.arange(2)), ... ('pfull', np.arange(2))]) >>> doppyo.utils.get_pres_name(A) 'pfull' """ if 'pfull' in da.dims: return 'pfull' elif 'phalf' in da.dims: return 'phalf' else: raise KeyError('Unable to determine pressure dimension') pass # =================================================================================================== def did_event(da, event): """ Returns array containing True/False where event occurs/does not occur Notes ----- See http://www.cawcr.gov.au/projects/verification/ """ eval_expr = event.replace(">", "da >").replace("<", "da <").replace("==", "da ==") \ .replace("=", "da ==").replace('&&', '&').replace('||', '|') \ .replace("and", "&").replace("or", "|") eval_expr = '(' + eval_expr + ').rename("event_logical")' return eval(eval_expr) # =================================================================================================== def compute_likelihood(da_logical, dim='ensemble'): """ Returns array of likelihoods computed along dim from logical event data Notes ----- See http://www.cawcr.gov.au/projects/verification/ """ if dim == None: likelihood = da_logical else: likelihood = da_logical.mean(dim=dim).rename('likelihood') return likelihood # =================================================================================================== def atmos_energy_cycle(temp, u, v, omega, gh, terms=None, vgradz=False, spectral=False, n_wavenumbers=20, integrate=True, loop_triple_terms=False, lat_name=None, lon_name=None, plevel_name=None): """ Returns all terms in the Lorenz energy cycle. Follows formulae and notation used in `Marques et al. 2011 Global diagnostic energetics of five state-of-the-art climate models. Climate Dynamics`. Note that this decomposition is in the space domain. A space-time decomposition can also be carried out (though not in Fourier space, but this is not implemented here (see `Oort. 1964 On Estimates of the atmospheric energy cycle. Monthly Weather Review`). Parameters ---------- temp : xarray DataArray Array containing fields of temperature with at least coordinates latitude, longitude and level (following standard naming - see Limitations) u : xarray DataArray Array containing fields of zonal velocity with at least coordinates latitude, longitude and level (following standard naming - see Limitations) v : xarray DataArray Array containing fields of meridional velocity with at least coordinates latitude, longitude and level (following standard naming - see Limitations) omega : xarray DataArray Array containing fields of vertical velocity (pressure coordinates) with at least coordinates latitude, longitude and level (following standard naming - see Limitations) gh : xarray DataArray Array containing fields of geopotential height with at least coordinates latitude, longitude and level (following standard naming - see Limitations) terms : str or sequence of str List of terms to compute. If None, returns all terms. Available options are: Pz; total available potential energy in the zonally averaged temperature distribution Kz; total kinetic energy in zonally averaged motion Pe; total eddy available potential energy [= sum_n Pn (n > 0 only) for spectral=True] (Note that for spectral=True, an additional term, Sn, quantifying the rate of transfer of available potential energy to eddies of wavenumber n from eddies of all other wavenumbers is also returned) Ke; total eddy kinetic energy [= sum_n Kn (n > 0 only) for spectral=True] (Note that for spectral=True, an additional term, Ln, quantifying the rate of transfer of kinetic energy to eddies of wavenumber n from eddies of all other wavenumbers is also returned) Cz; rate of conversion of zonal available potential energy to zonal kinetic energy Ca; rate of transfer of total available potential energy in the zonally averaged temperature distribution (Pz) to total eddy available potential energy (Pe) [= sum_n Rn (n > 0 only) for spectral=True] Ce; rate of transfer of total eddy available potential energy (Pe) to total eddy kinetic energy (Ke) [= sum_n Cn (n > 0 only) for spectral=True] Ck; rate of transfer of total eddy kinetic energy (Ke) to total kinetic energy in zonally averaged motion (Kz) [= sum_n Mn (n > 0 only) for spectral=True] Gz; rate of generation of zonal available potential energy due to the zonally averaged heating (Pz). Note that this term is computed as a residual (Cz + Ca) and cannot be returned in spectral space. If Gz is requested with spectral=True, Gz is returned in real-space only Ge; rate of generation of eddy available potential energy (Pe). Note that this term is computed as a residual (Ce - Ca) and cannot be returned in spectral space. If Ge is requested with spectral=True, Ge is returned in real-space only Dz; rate of viscous dissipation of zonal kinetic energy (Kz). Note that this term is computed as a residual (Cz - Ck) and cannot be returned in spectral space. If Dz is requested with spectral=True, Dz is returned in real-space only De; rate of dissipation of eddy kinetic energy (Ke). Note that this term is computed as a residual (Ce - Ck) and cannot be returned in spectral space. If De is requested with spectral=True, De is returned in real-space only vgradz : bool, optional If True, uses `v-grad-z` approach for computing terms relating to conversion of potential energy to kinetic energy. Otherwise, defaults to using the `omaga-alpha` approach (see reference above for details) spectral : bool, optional If True, computes all terms as a function of wavenumber on longitudinal bands. To use this option, longitudes must be regularly spaced. Note that Ge and De are computed as residuals and cannot be computed in spectral space n_wavenumbers : int, optional Number of wavenumbers to retain either side of wavenumber=0. Obviously only does anything if spectral=True integrate : bool, optional If True, computes and returns the integral of each term over the mass of the atmosphere. Otherwise, only the integrands are returned. Returns ------- atmos_energy_cycle : xarray Dataset Limitations ----------- All input array coordinates must follow standard naming (see doppyo.utils.get_lat_name(), doppyo.utils.get_lon_name(), etc) Pressure levels must be provided in units of hPa Notes ----- The following notation is used below (stackable, e.g. *_ZT indicates the time average of the zonal average): *_A -> area average over an isobaric surface *_a -> departure from area average *_Z -> zonal average *_z -> departure from zonal average *_T -> time average *_t -> departure from time average Additionally, capital variables indicate Fourier transforms: F(u) = U F(v) = V F(omega) = O F(gh) = A F(temp) = B """ def _flip_n(da): """ Flips data along wavenumber coordinate """ daf = da.copy() daf['n'] = -daf['n'] return daf.sortby(daf['n']) def _truncate(F, n_truncate, dim): """ Converts spatial frequency dim to wavenumber, n, and truncates all wavenumbers greater than n_truncate """ F[dim] = 360 * F[dim] F = F.rename({dim : 'n'}) F = F.where(abs(F.n) <= n_truncate, drop=True) return F, _flip_n(F) def _triple_terms(A, B, C): """ Calculate triple term summation of the form \int_{m=-inf}^{inf} A(m) * B(n) * C(n - m) """ # Use rolling operator to build shifted terms ----- Am = A.rename({'n' : 'm'}) Cnm = C.rolling(n=len(C.n), center=True).construct('m', fill_value=0) Cnm['m'] = -C['n'].values # Drop m = 0 and n < 0 ----- Am = Am.where(Am['m'] != 0, drop=True) Cnm = Cnm.where(Cnm['m'] != 0, drop=True) return (B * (Am * Cnm)).sum(dim='m', skipna=False) def _triple_terms_loop(A, B, C): """ Calculate triple term summation of the form \int_{m=-inf}^{inf} A(m) * B(n) * C(n - m) """ # Loop over all m's and perform rolling sum ----- ms = A['n'].where(A['n'] != 0, drop=True).values ABC = A.copy() * 0 for m in ms: Am = A.sel(n=m) Cnm = C.shift(n=int(m)).fillna(0) ABC = ABC + (Am * B * Cnm) return ABC if terms is None: terms = ['Pz', 'Kz', 'Pe', 'Ke', 'Cz', 'Ca', 'Ce', 'Ck', 'Gz', 'Ge', 'Dz', 'De'] if isinstance(terms, str): terms = [terms] # Initialize some things ----- if lat_name is None: lat_name = utils.get_lat_name(temp) if lon_name is None: lon_name = utils.get_lon_name(temp) if plevel_name is None: plevel_name = utils.get_plevel_name(temp) degtorad = utils.constants().pi / 180 tan_lat = xr.ufuncs.tan(temp[lat_name] * degtorad) cos_lat = xr.ufuncs.cos(temp[lat_name] * degtorad) # Determine the stability parameter using Saltzman's approach ----- kappa = utils.constants().R_d / utils.constants().C_pd p_kap = (1000 / temp[plevel_name]) ** kappa theta_A = utils.average(temp * p_kap, [lat_name, lon_name], weights=cos_lat) dtheta_Adp = utils.differentiate_wrt(theta_A, dim=plevel_name, x=(theta_A[plevel_name] * 100)) gamma = - p_kap * (utils.constants().R_d) / ((temp[plevel_name] * 100) * utils.constants().C_pd) / dtheta_Adp # [1/K] energies = gamma.rename('gamma').to_dataset() # Compute zonal terms # ======================== if ('Pz' in terms): # Compute the total available potential energy in the zonally averaged temperature # distribution, Pz [also commonly called Az] ----- temp_A = utils.average(temp, [lat_name, lon_name], weights=cos_lat) temp_Z = temp.mean(dim=lon_name) temp_Za = temp_Z - temp_A Pz_int = gamma * utils.constants().C_pd / 2 * temp_Za ** 2 # [J/kg] energies['Pz_int'] = Pz_int if integrate: Pz = _int_over_atmos(Pz_int, lat_name, lon_name, plevel_name, lon_dim=temp[lon_name]) # [J/m^2] energies['Pz'] = Pz if ('Kz' in terms): # Compute the total kinetic energy in zonally averaged motion, Kz [also commonly # called Kz] ----- u_Z = u.mean(dim=lon_name) v_Z = v.mean(dim=lon_name) Kz_int = 0.5 * (u_Z ** 2 + v_Z ** 2) # [J/kg] energies['Kz_int'] = Kz_int if integrate: Kz = _int_over_atmos(Kz_int, lat_name, lon_name, plevel_name, lon_dim=u[lon_name]) # [J/m^2] energies['Kz'] = Kz if ('Cz' in terms): # Compute the rate of conversion of zonal available potential energy (Pz) to zonal kinetic # energy (Kz), Cz [also commonly called Cz] ----- if vgradz: if 'v_Z' not in locals(): v_Z = v.mean(dim=lon_name) gh_Z = gh.mean(dim=lon_name) dghdlat = utils.differentiate_wrt(gh_Z, dim=lat_name, x=(gh_Z[lat_name] * degtorad)) Cz_int = - (utils.constants().g / utils.constants().R_earth) * v_Z * dghdlat # [W/kg] energies['Cz_int'] = Cz_int if integrate: Cz = _int_over_atmos(Cz_int, lat_name, lon_name, plevel_name, lon_dim=gh[lon_name]) # [W/m^2] energies['Cz'] = Cz else: if 'temp_Za' not in locals(): temp_A = utils.average(temp, [lat_name, lon_name], weights=cos_lat) temp_Z = temp.mean(dim=lon_name) temp_Za = temp_Z - temp_A omega_A = utils.average(omega, [lat_name, lon_name], weights=cos_lat) omega_Z = omega.mean(dim=lon_name) omega_Za = omega_Z - omega_A Cz_int = - (utils.constants().R_d / (temp[plevel_name] * 100)) * omega_Za * temp_Za # [W/kg] energies['Cz_int'] = Cz_int if integrate: Cz = _int_over_atmos(Cz_int, lat_name, lon_name, plevel_name, lon_dim=omega[lon_name]) # [W/m^2] energies['Cz'] = Cz # Compute eddy terms in Fourier space if spectral=True # ========================================================== if spectral: if ('Pe' in terms): # Compute the total available potential energy eddies of wavenumber n, Pn ----- Bp, Bn = _truncate(utils.fft(temp, dim=lon_name, nfft=len(temp[lon_name]), twosided=True, shift=True) / len(temp[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) Pn_int = (gamma * utils.constants().C_pd * abs(Bp) ** 2) energies['Pn_int'] = Pn_int if integrate: Pn = _int_over_atmos(Pn_int, lat_name, lon_name, plevel_name, lon_dim=temp[lon_name]) # [J/m^2] energies['Pn'] = Pn # Compute the rate of transfer of available potential energy to eddies of # wavenumber n from eddies of all other wavenumbers, Sn ----- Up, Un = _truncate(utils.fft(u, dim=lon_name, nfft=len(u[lon_name]), twosided=True, shift=True) / len(u[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) Vp, Vn = _truncate(utils.fft(v, dim=lon_name, nfft=len(v[lon_name]), twosided=True, shift=True) / len(v[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) Op, On = _truncate(utils.fft(omega, dim=lon_name, nfft=len(omega[lon_name]), twosided=True, shift=True) / len(omega[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) dBpdlat = utils.differentiate_wrt(Bp, dim=lat_name, x=(Bp[lat_name] * degtorad)) dBndlat = utils.differentiate_wrt(Bn, dim=lat_name, x=(Bn[lat_name] * degtorad)) dBpdp = utils.differentiate_wrt(Bp, dim=plevel_name, x=(Bp[plevel_name] * 100)) dBndp = utils.differentiate_wrt(Bn, dim=plevel_name, x=(Bn[plevel_name] * 100)) if loop_triple_terms: BpBnUp = _triple_terms_loop(Bp, Bn, Up) BpBpUn = _triple_terms_loop(Bp, Bp, Un) BpglBnVp = _triple_terms_loop(Bp, dBndlat, Vp) BpglBpVn = _triple_terms_loop(Bp, dBpdlat, Vn) BpgpBnOp = _triple_terms_loop(Bp, dBndp, Op) BpgpBpOn = _triple_terms_loop(Bp, dBpdp, On) BpBnOp = _triple_terms_loop(Bp, Bn, Op) BpBpOn = _triple_terms_loop(Bp, Bp, On) else: BpBnUp = _triple_terms(Bp, Bn, Up) BpBpUn = _triple_terms(Bp, Bp, Un) BpglBnVp = _triple_terms(Bp, dBndlat, Vp) BpglBpVn = _triple_terms(Bp, dBpdlat, Vn) BpgpBnOp = _triple_terms(Bp, dBndp, Op) BpgpBpOn = _triple_terms(Bp, dBpdp, On) BpBnOp = _triple_terms(Bp, Bn, Op) BpBpOn = _triple_terms(Bp, Bp, On) Sn_int = -gamma * utils.constants().C_pd * (1j * Bp['n']) / \ (utils.constants().R_earth * xr.ufuncs.cos(Bp[lat_name] * degtorad)) * \ (BpBnUp + BpBpUn) + \ gamma * utils.constants().C_pd / utils.constants().R_earth * \ (BpglBnVp + BpglBpVn) + \ gamma * utils.constants().C_pd * (BpgpBnOp + BpgpBpOn) + \ gamma * utils.constants().R_d / Bp[plevel_name] * \ (BpBnOp + BpBpOn) energies['Sn_int'] = Sn_int if integrate: Sn = abs(_int_over_atmos(Sn_int, lat_name, lon_name, plevel_name, lon_dim=temp[lon_name])) # [W/m^2] energies['Sn'] = Sn if ('Ke' in terms): # Compute the total kinetic energy in eddies of wavenumber n, Kn ----- if 'U' not in locals(): Up, Un = _truncate(utils.fft(u, dim=lon_name, nfft=len(u[lon_name]), twosided=True, shift=True) / len(u[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) if 'V' not in locals(): Vp, Vn = _truncate(utils.fft(v, dim=lon_name, nfft=len(v[lon_name]), twosided=True, shift=True) / len(v[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) Kn_int = abs(Up) ** 2 + abs(Vp) ** 2 energies['Kn_int'] = Kn_int if integrate: Kn = _int_over_atmos(Kn_int, lat_name, lon_name, plevel_name, lon_dim=u[lon_name]) # [J/m^2] energies['Kn'] = Kn # Compute the rate of transfer of kinetic energy to eddies of wavenumber n from # eddies of all other wavenumbers, Ln ----- if 'O' not in locals(): Op, On = _truncate(utils.fft(omega, dim=lon_name, nfft=len(omega[lon_name]), twosided=True, shift=True) / len(omega[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) dUpdp = utils.differentiate_wrt(Up, dim=plevel_name, x=(Up[plevel_name] * 100)) dVpdp = utils.differentiate_wrt(Vp, dim=plevel_name, x=(Vp[plevel_name] * 100)) dOpdp = utils.differentiate_wrt(Op, dim=plevel_name, x=(Op[plevel_name] * 100)) dOndp = utils.differentiate_wrt(On, dim=plevel_name, x=(On[plevel_name] * 100)) dVpcdl = utils.differentiate_wrt(Vp * cos_lat, dim=lat_name, x=(Vp[lat_name] * degtorad)) dVncdl = utils.differentiate_wrt(Vn * cos_lat, dim=lat_name, x=(Vn[lat_name] * degtorad)) dUpdl = utils.differentiate_wrt(Up, dim=lat_name, x=(Up[lat_name] * degtorad)) dVpdl = utils.differentiate_wrt(Vp, dim=lat_name, x=(Vp[lat_name] * degtorad)) if loop_triple_terms: UpUnUp = _triple_terms_loop(Up, Un, Up) UpUpUn = _triple_terms_loop(Up, Up, Un) VpVnUp = _triple_terms_loop(Vp, Vn, Up) VpVpUn = _triple_terms_loop(Vp, Vp, Un) VpUnUp = _triple_terms_loop(Vp, Un, Up) VpUpUn = _triple_terms_loop(Vp, Up, Un) UpVnUp = _triple_terms_loop(Up, Vn, Up) UpVpUn = _triple_terms_loop(Up, Vp, Un) gpUpUngpOp = _triple_terms_loop(dUpdp, Un, dOpdp) gpUpUpgpOn = _triple_terms_loop(dUpdp, Up, dOndp) gpVpVngpOp = _triple_terms_loop(dVpdp, Vn, dOpdp) gpVpVpgpOn = _triple_terms_loop(dVpdp, Vp, dOndp) glUpUnglVpc = _triple_terms_loop(dUpdl, Un, dVpcdl) glUpUpglVnc = _triple_terms_loop(dUpdl, Up, dVncdl) glVpVnglVpc = _triple_terms_loop(dVpdl, Vn, dVpcdl) glVpVpglVnc = _triple_terms_loop(dVpdl, Vp, dVncdl) else: UpUnUp = _triple_terms(Up, Un, Up) UpUpUn = _triple_terms(Up, Up, Un) VpVnUp = _triple_terms(Vp, Vn, Up) VpVpUn = _triple_terms(Vp, Vp, Un) VpUnUp = _triple_terms(Vp, Un, Up) VpUpUn = _triple_terms(Vp, Up, Un) UpVnUp = _triple_terms(Up, Vn, Up) UpVpUn = _triple_terms(Up, Vp, Un) gpUpUngpOp = _triple_terms(dUpdp, Un, dOpdp) gpUpUpgpOn = _triple_terms(dUpdp, Up, dOndp) gpVpVngpOp = _triple_terms(dVpdp, Vn, dOpdp) gpVpVpgpOn = _triple_terms(dVpdp, Vp, dOndp) glUpUnglVpc = _triple_terms(dUpdl, Un, dVpcdl) glUpUpglVnc = _triple_terms(dUpdl, Up, dVncdl) glVpVnglVpc = _triple_terms(dVpdl, Vn, dVpcdl) glVpVpglVnc = _triple_terms(dVpdl, Vp, dVncdl) Ln_int = -(1j * Up['n']) / (utils.constants().R_earth * cos_lat) * \ (UpUnUp - UpUpUn) + \ (1j * Vp['n']) / (utils.constants().R_earth * cos_lat) * \ (VpVnUp - VpVpUn) - \ tan_lat / utils.constants().R_earth * \ (VpUnUp + VpUpUn) + \ tan_lat / utils.constants().R_earth * \ (UpVnUp + UpVpUn) + \ (gpUpUngpOp + gpUpUpgpOn) + \ (gpVpVngpOp + gpVpVpgpOn) + \ 1 / (utils.constants().R_earth * cos_lat) * \ (glUpUnglVpc + glUpUpglVnc + glVpVnglVpc + glVpVpglVnc) energies['Ln_int'] = Ln_int if integrate: Ln = abs(_int_over_atmos(Ln_int, lat_name, lon_name, plevel_name, lon_dim=u[lon_name])) # [W/m^2] energies['Ln'] = Ln if ('Ca' in terms): # Compute the rate of transfer of zonal available potential energy to eddy # available potential energy in wavenumber n, Rn ----- if 'temp_Z' not in locals(): temp_Z = temp.mean(dim=lon_name) if 'V' not in locals(): Vp, Vn = _truncate(utils.fft(v, dim=lon_name, nfft=len(v[lon_name]), twosided=True, shift=True) / len(v[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) if 'B' not in locals(): Bp, Bn = _truncate(utils.fft(temp, dim=lon_name, nfft=len(temp[lon_name]), twosided=True, shift=True) / len(temp[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) if 'O' not in locals(): Op, On = _truncate(utils.fft(omega, dim=lon_name, nfft=len(omega[lon_name]), twosided=True, shift=True) / len(omega[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) dtemp_Zdlat = utils.differentiate_wrt(temp_Z, dim=lat_name, x=(temp_Z[lat_name] * degtorad)) theta = temp * p_kap theta_Z = theta.mean(dim=lon_name) theta_Za = theta_Z - theta_A dtheta_Zadp = utils.differentiate_wrt(theta_Za, dim=plevel_name, x=(theta_Za[plevel_name] * 100)) Rn_int = gamma * utils.constants().C_pd * ((dtemp_Zdlat / utils.constants().R_earth) * (Vp * Bn + Vn * Bp) + (p_kap * dtheta_Zadp) * (Op * Bn + On * Bp)) # [W/kg] energies['Rn_int'] = Rn_int if integrate: Rn = abs(_int_over_atmos(Rn_int, lat_name, lon_name, plevel_name, lon_dim=temp[lon_name])) # [W/m^2] energies['Rn'] = Rn if ('Ce' in terms): # Compute the rate of conversion of available potential energy of wavenumber n # to eddy kinetic energy of wavenumber n, Cn ----- if vgradz: if 'U' not in locals(): Up, Un = _truncate(utils.fft(u, dim=lon_name, nfft=len(u[lon_name]), twosided=True, shift=True) / len(u[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) if 'V' not in locals(): Vp, Vn = _truncate(utils.fft(v, dim=lon_name, nfft=len(v[lon_name]), twosided=True, shift=True) / len(v[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) Ap, An = _truncate(utils.fft(gh, dim=lon_name, nfft=len(gh[lon_name]), twosided=True, shift=True) / len(gh[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) dApdlat = utils.differentiate_wrt(Ap, dim=lat_name, x=(Ap[lat_name] * degtorad)) dAndlat = utils.differentiate_wrt(An, dim=lat_name, x=(An[lat_name] * degtorad)) Cn_int = (((-1j * utils.constants().g * Up['n']) / \ (utils.constants().R_earth * xr.ufuncs.cos(Up[lat_name] * degtorad))) * \ (Ap * Un - An * Up)) - \ ((utils.constants().g / utils.constants().R_earth) * \ (dApdlat * Vn + dAndlat * Vp)) # [W/kg] energies['Cn_int'] = Cn_int if integrate: Cn = abs(_int_over_atmos(Cn_int, lat_name, lon_name, plevel_name, lon_dim=u[lon_name])) # [W/m^2] energies['Cn'] = Cn else: if 'O' not in locals(): Op, On = _truncate(utils.fft(omega, dim=lon_name, nfft=len(omega[lon_name]), twosided=True, shift=True) / len(omega[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) if 'B' not in locals(): Bp, Bn = _truncate(utils.fft(temp, dim=lon_name, nfft=len(temp[lon_name]), twosided=True, shift=True) / len(temp[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) Cn_int = - (utils.constants().R_d / (omega[plevel_name] * 100)) * (Op * Bn + On * Bp) # [W/kg] energies['Cn_int'] = Cn_int if integrate: Cn = abs(_int_over_atmos(Cn_int, lat_name, lon_name, plevel_name, lon_dim=temp[lon_name])) # [W/m^2] energies['Cn'] = Cn if ('Ck' in terms): # Compute the rate of transfer of kinetic energy to the zonally averaged flow # from eddies of wavenumber n, Mn ----- if 'v_Z' not in locals(): v_Z = v.mean(dim=lon_name) if 'u_Z' not in locals(): u_Z = u.mean(dim=lon_name) if 'U' not in locals(): Up, Un = _truncate(utils.fft(u, dim=lon_name, nfft=len(u[lon_name]), twosided=True, shift=True) / len(u[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) if 'V' not in locals(): Vp, Vn = _truncate(utils.fft(v, dim=lon_name, nfft=len(v[lon_name]), twosided=True, shift=True) / len(v[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) if 'O' not in locals(): Op, On = _truncate(utils.fft(omega, dim=lon_name, nfft=len(omega[lon_name]), twosided=True, shift=True) / len(omega[lon_name]), n_truncate=n_wavenumbers, dim='f_'+lon_name) dv_Zdlat = utils.differentiate_wrt(v_Z, dim=lat_name, x=(v[lat_name] * degtorad)) du_Zndlat = utils.differentiate_wrt(u_Z / xr.ufuncs.cos(u[lat_name] * degtorad), dim=lat_name, x=(u[lat_name] * degtorad)) dv_Zdp = utils.differentiate_wrt(v_Z, dim=plevel_name, x=(v[plevel_name] * 100)) du_Zdp = utils.differentiate_wrt(u_Z, dim=plevel_name, x=(u[plevel_name] * 100)) Mn_int = (-2 * Up * Un * v_Z * tan_lat / utils.constants().R_earth) + \ (2 * Vp * Vn * dv_Zdlat / utils.constants().R_earth + (Vp * On + Vn * Op) * dv_Zdp) + \ ((Up * On + Un * Op) * du_Zdp) + \ ((Up * Vn + Un * Vp) * xr.ufuncs.cos(u[lat_name] * degtorad) / \ utils.constants().R_earth * du_Zndlat) # [W/kg] energies['Mn_int'] = Mn_int if integrate: Mn = abs(_int_over_atmos(Mn_int, lat_name, lon_name, plevel_name, lon_dim=u[lon_name])) # [W/m^2] energies['Mn'] = Mn else: if ('Pe' in terms): # Compute the total eddy available potential energy, Pe [also commonly called # Ae] ----- if 'temp_Z' not in locals(): temp_Z = temp.mean(dim=lon_name) temp_z = temp - temp_Z Pe_int = gamma * utils.constants().C_pd / 2 * (temp_z ** 2).mean(dim=lon_name) # [J/kg] energies['Pe_int'] = Pe_int if integrate: Pe = _int_over_atmos(Pe_int, lat_name, lon_name, plevel_name, lon_dim=temp[lon_name]) # [J/m^2] energies['Pe'] = Pe if ('Ke' in terms): # Compute the total eddy kinetic energy, Ke ----- if 'u_Z' not in locals(): u_Z = u.mean(dim=lon_name) if 'v_Z' not in locals(): v_Z = v.mean(dim=lon_name) u_z = u - u_Z v_z = v - v_Z Ke_int = 0.5 * (u_z ** 2 + v_z ** 2).mean(dim=lon_name) # [J/kg] energies['Ke_int'] = Ke_int if integrate: Ke = _int_over_atmos(Ke_int, lat_name, lon_name, plevel_name, lon_dim=u[lon_name]) # [J/m^2] energies['Ke'] = Ke if ('Ca' in terms): # Compute the rate of transfer of total available potential energy in the zonally # averaged temperature distribution (Pz) to total eddy available potential energy # (Pe), Ca ----- if 'v_Z' not in locals(): v_Z = v.mean(dim=lon_name) if 'temp_Z' not in locals(): temp_Z = temp.mean(dim=lon_name) if 'omega_Z' not in locals(): omega_Z = omega.mean(dim=lon_name) if 'theta_Z' not in locals(): theta = temp * p_kap theta_Z = theta.mean(dim=lon_name) if 'dtemp_Zdlat' not in locals(): dtemp_Zdlat = utils.differentiate_wrt(temp_Z, dim=lat_name, x=(temp_Z[lat_name] * degtorad)) v_z = v - v_Z temp_z = temp - temp_Z omega_z = omega - omega_Z oT_Z = (omega_z * temp_z).mean(dim=lon_name) oT_A = utils.average(omega_z * temp_z, [lat_name, lon_name], weights=cos_lat) oT_Za = oT_Z - oT_A theta_Za = theta_Z - theta_A dtheta_Zadp = utils.differentiate_wrt(theta_Za, dim=plevel_name, x=(theta_Za[plevel_name] * 100)) Ca_int = - gamma * utils.constants().C_pd * \ (((v_z * temp_z).mean(dim=lon_name) * dtemp_Zdlat / utils.constants().R_earth) + \ (p_kap * oT_Za * dtheta_Zadp)) # [W/kg] energies['Ca_int'] = Ca_int if integrate: Ca = _int_over_atmos(Ca_int, lat_name, lon_name, plevel_name, lon_dim=v[lon_name]) # [W/m^2] energies['Ca'] = Ca if ('Ce' in terms): # Compute the rate of transfer of total eddy available potential energy (Pe) to # total eddy kinetic energy (Ke), Ce ----- if 'temp_Z' not in locals(): temp_Z = temp.mean(dim=lon_name) if 'omega_Z' not in locals(): omega_Z = omega.mean(dim=lon_name) temp_z = temp - temp_Z omega_z = omega - omega_Z Ce_int = - (utils.constants().R_d / (temp[plevel_name] * 100)) * \ (omega_z * temp_z).mean(dim=lon_name) # [W/kg] energies['Ce_int'] = Ce_int if integrate: Ce = _int_over_atmos(Ce_int, lat_name, lon_name, plevel_name, lon_dim=temp[lon_name]) # [W/m^2] energies['Ce'] = Ce if ('Ck' in terms): # Compute the rate of transfer of total eddy kinetic energy (Ke) to total kinetic # energy in zonally averaged motion (Kz), Ck ----- if 'u_Z' not in locals(): u_Z = u.mean(dim=lon_name) if 'v_Z' not in locals(): v_Z = v.mean(dim=lon_name) if 'omega_Z' not in locals(): omega_Z = omega.mean(dim=lon_name) u_z = u - u_Z v_z = v - v_Z omega_z = omega - omega_Z du_Zndlat = utils.differentiate_wrt(u_Z / cos_lat, dim=lat_name, x=(u_Z[lat_name] * degtorad)) dv_Zdlat = utils.differentiate_wrt(v_Z, dim=lat_name, x=(v_Z[lat_name] * degtorad)) du_Zdp = utils.differentiate_wrt(u_Z, dim=plevel_name, x=(u_Z[plevel_name] * 100)) dv_Zdp = utils.differentiate_wrt(v_Z, dim=plevel_name, x=(v_Z[plevel_name] * 100)) Ck_int = (u_z * v_z).mean(dim=lon_name) * cos_lat * du_Zndlat / utils.constants().R_earth + \ (u_z * omega_z).mean(dim=lon_name) * du_Zdp + \ (v_z ** 2).mean(dim=lon_name) * dv_Zdlat / utils.constants().R_earth + \ (v_z * omega_z).mean(dim=lon_name) * dv_Zdp - \ (u_z ** 2).mean(dim=lon_name) * v_Z * tan_lat / utils.constants().R_earth energies['Ck_int'] = Ck_int if integrate: Ck = _int_over_atmos(Ck_int, lat_name, lon_name, plevel_name, lon_dim=temp[lon_name]) # [W/m^2] energies['Ck'] = Ck if ('Gz' in terms): # Compute the rate of generation of zonal available potential energy due to the zonally # averaged heating, Gz ----- if ('Cz' not in terms) | ('Ca' not in terms): raise ValueError('The rate of generation of zonal available potential energy, Gz, is computed from the sum of Cz and Ca. Please add these to the list, terms=[<terms>].') if spectral: warnings.warn('Rate of generation of zonal available potential energy is computed from the sum of Cz and Ca and cannot be computed in Fourier space. Returning Gz in real-space.') Ca_int = Rn_int.where(Rn_int.n > 0, drop=True).sum(dim='n').real # sum Rn to get Ca Gz_int = Cz_int + Ca_int energies['Gz_int'] = Gz_int if integrate: Gz = _int_over_atmos(Gz_int, lat_name, lon_name, plevel_name, lon_dim=temp[lon_name]) # [W/m^2] energies['Gz'] = Gz if ('Ge' in terms): # Compute the rate of generation of eddy available potential energy (Ae), Ge ----- if ('Ce' not in terms) | ('Ca' not in terms): raise ValueError('The rate of generation of eddy available potential energy, Ge, is computed from the residual of Ce and Ca. Please add these to the list, terms=[<terms>].') if spectral: warnings.warn('The rate of generation of eddy available potential energy is computed from the residual of Ce and Ca and cannot be computed in Fourier space. Returning Ge in real-space.') Ce_int = Cn_int.where(Cn_int.n > 0, drop=True).sum(dim='n').real # sum Cn to get Ce if 'Ca_int' not in locals(): Ca_int = Rn_int.where(Rn_int.n > 0, drop=True).sum(dim='n').real # sum Rn to get Ca Ge_int = Ce_int - Ca_int energies['Ge_int'] = Ge_int if integrate: Ge = _int_over_atmos(Ge_int, lat_name, lon_name, plevel_name, lon_dim=temp[lon_name]) # [W/m^2] energies['Ge'] = Ge if ('Dz' in terms): # Compute the rate of viscous dissipation of zonal kinetic energy, Dz ----- if ('Cz' not in terms) | ('Ck' not in terms): raise ValueError('The rate of viscous dissipation of zonal kinetic energy, Dz, is computed from the residual of Cz and Ck. Please add these to the list, terms=[<terms>].') if spectral: warnings.warn('The rate of viscous dissipation of zonal kinetic energy, Dz, is computed from the residual of Cz and Ck and cannot be computed in Fourier space. Returning De in real-space.') Ck_int = Mn_int.where(Mn_int.n > 0, drop=True).sum(dim='n').real # sum Mn to get Ck Dz_int = Cz_int - Ck_int energies['Dz_int'] = Dz_int if integrate: Dz = _int_over_atmos(Dz_int, lat_name, lon_name, plevel_name, lon_dim=temp[lon_name]) # [W/m^2] energies['Dz'] = Dz if ('De' in terms): # Compute the rate of dissipation of eddy kinetic energy (Ke), De ----- if ('Ce' not in terms) | ('Ck' not in terms): raise ValueError('The rate of viscous dissipation of eddy kinetic energy, De, is computed from the residual of Ce and Ck. Please add these to the list, terms=[<terms>].') if spectral: warnings.warn('The rate of viscous dissipation of eddy kinetic energy, De, is computed from the residual of Ce and Ck and cannot be computed in Fourier space. Returning De in real-space.') if 'Ce_int' not in locals(): Ce_int = Cn_int.where(Cn_int.n > 0, drop=True).sum(dim='n').real # sum Cn to get Ce if 'Ck_int' not in locals(): Ck_int = Mn_int.where(Mn_int.n > 0, drop=True).sum(dim='n').real # sum Mn to get Ck De_int = Ce_int - Ck_int energies['De_int'] = De_int if integrate: De = _int_over_atmos(De_int, lat_name, lon_name, plevel_name, lon_dim=temp[lon_name]) # [W/m^2] energies['De'] = De return energies # =================================================================================================== def auto_merge(paths, preprocess=None, parallel=True, **kwargs): """ Automatically merge a split xarray Dataset. This is designed to behave like `xarray.open_mfdataset`, except it supports concatenation along multiple dimensions. Parameters ---------- datasets : str or list of str or list of xarray.Dataset Either a glob expression or list of paths as you would pass to xarray.open_mfdataset, or a list of xarray datasets. If a list of datasets is passed, you should make sure that they are represented as dask arrays to avoid reading the whole dataset into memory. Returns ------- xarray.Dataset The merged dataset. """ if parallel: # wrap the open_dataset, getattr, and preprocess with delayed open_ = dask.delayed(xr.open_dataset) getattr_ = dask.delayed(getattr) if preprocess is not None: preprocess = dask.delayed(preprocess) else: open_ = open_dataset getattr_ = getattr datasets = [open_(p, **kwargs) for p in paths] file_objs = [getattr_(ds, '_file_obj') for ds in datasets] if preprocess is not None: datasets = [preprocess(ds) for ds in datasets] if parallel: # calling compute here will return the datasets/file_objs lists, # the underlying datasets will still be stored as dask arrays datasets, file_objs = dask.compute(datasets, file_objs) def _combine_along_last_dim(datasets): merged = [] # Determine the dimension along which the dataset is split split_dims = [d for d in datasets[0].dims if len(np.unique([ds[d].values[0] for ds in datasets])) > 1] # Concatenate along one of the split dimensions concat_dim = split_dims[-1] # Group along the remaining dimensions and concatenate within each # group. sorted_ds = sorted(datasets, key=lambda ds: tuple(ds[d].values[0] for d in split_dims)) for _, group in itertools.groupby( sorted_ds, key=lambda ds: tuple(ds[d].values[0] for d in split_dims[:-1]) ): merged.append(xr.auto_combine(group, concat_dim=concat_dim)) return merged merged = datasets while len(merged) > 1: merged = _combine_along_last_dim(merged) return merged[0]
_depth
test_example.py
from web.msnotifier.example import add def test_add_correct(): assert add(5, 7) == 12 def
(): assert add(15, 8) != 21
test_add_incorrect
parser_loader.py
import os import re import inspect def _get_parser_list(dirname):
def _import_parsers(parserfiles): m = re.compile('.+parsers',re.I) _modules = __import__('weatherterm.parsers',globals(),locals(),parserfiles,0) _parsers = [(k,v) for k,v in inspect.getmembers(_modules) if inspect.ismodule(v) and m.match(k)] _classes = dict() for k,v in _parsers: _classes.update({k:v for k,v in inspect.getmembers(v) if inspect.isclass(v) and m.match(k)}) return _classes def load(dirname): parserfiles = _get_parser_list(dirname) return _import_parsers(parserfiles)
files = [ f.replace('.py','') for f in os.listdir(dirname) if not f.startswith('__') ] return files
api_usage_controller.py
# -*- coding: utf-8 -*- """ meraki This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ). """ from meraki.api_helper import APIHelper from meraki.configuration import Configuration from meraki.controllers.base_controller import BaseController from meraki.http.auth.custom_header_auth import CustomHeaderAuth class APIUsageController(BaseController): """A Controller to access Endpoints in the meraki API.""" def get_organization_api_requests(self, options=dict()): """Does a GET request to /organizations/{organizationId}/apiRequests. List the API requests made by an organization Args: options (dict, optional): Key-value pairs for any of the parameters to this API Endpoint. All parameters to the endpoint are supplied through the dictionary with their names being the key and their desired values being the value. A list of parameters that can be used are:: organization_id -- string -- TODO: type description here. Example: t_0 -- string -- The beginning of the timespan for the data. The maximum lookback period is 31 days from
t_1 -- string -- The end of the timespan for the data. t1 can be a maximum of 31 days after t0. timespan -- float -- The timespan for which the information will be fetched. If specifying timespan, do not specify parameters t0 and t1. The value must be in seconds and be less than or equal to 31 days. The default is 31 days. per_page -- int -- The number of entries per page returned. Acceptable range is 3 - 1000. Default is 50. starting_after -- string -- A token used by the server to indicate the start of the page. Often this is a timestamp or an ID but it is not limited to those. This parameter should not be defined by client applications. The link for the first, last, prev, or next page in the HTTP Link header should define it. ending_before -- string -- A token used by the server to indicate the end of the page. Often this is a timestamp or an ID but it is not limited to those. This parameter should not be defined by client applications. The link for the first, last, prev, or next page in the HTTP Link header should define it. admin_id -- string -- Filter the results by the ID of the admin who made the API requests path -- string -- Filter the results by the path of the API requests method -- string -- Filter the results by the method of the API requests (must be 'GET', 'PUT', 'POST' or 'DELETE') response_code -- int -- Filter the results by the response code of the API requests Returns: mixed: Response from the API. Successful operation Raises: APIException: When an error occurs while fetching the data from the remote API. This exception includes the HTTP Response code, an error message, and the HTTP body that was received in the request. """ # Validate required parameters self.validate_parameters(organization_id=options.get("organization_id")) # Prepare query URL _url_path = '/organizations/{organizationId}/apiRequests' _url_path = APIHelper.append_url_with_template_parameters(_url_path, { 'organizationId': options.get('organization_id', None) }) _query_builder = Configuration.base_uri _query_builder += _url_path _query_parameters = { 't0': options.get('t_0', None), 't1': options.get('t_1', None), 'timespan': options.get('timespan', None), 'perPage': options.get('per_page', None), 'startingAfter': options.get('starting_after', None), 'endingBefore': options.get('ending_before', None), 'adminId': options.get('admin_id', None), 'path': options.get('path', None), 'method': options.get('method', None), 'responseCode': options.get('response_code', None) } _query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.array_serialization) _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'accept': 'application/json' } # Prepare and execute request _request = self.http_client.get(_query_url, headers=_headers) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) self.validate_response(_context) # Return appropriate type return APIHelper.json_deserialize(_context.response.raw_body)
today.
functions.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch def exclusive_cumprod(tensor, dim: int, eps: float = 1e-10):
def safe_cumprod(tensor, dim: int, eps: float = 1e-10): """ An implementation of cumprod to prevent precision issue. cumprod(x) = [x1, x1x2, x1x2x3, ....] = [exp(log(x1)), exp(log(x1) + log(x2)), exp(log(x1) + log(x2) + log(x3)), ...] = exp(cumsum(log(x))) """ if (tensor + eps < 0).any().item(): raise RuntimeError( "Safe cumprod can only take non-negative tensors as input." "Consider use torch.cumprod if you want to calculate negative values." ) log_tensor = torch.log(tensor + eps) cumsum_log_tensor = torch.cumsum(log_tensor, dim) exp_cumsum_log_tensor = torch.exp(cumsum_log_tensor) return exp_cumsum_log_tensor def lengths_to_mask(lengths, max_len: int, dim: int = 0, negative_mask: bool = False): """ Convert a tensor of lengths to mask For example, lengths = [[2, 3, 4]], max_len = 5 mask = [[1, 1, 1], [1, 1, 1], [0, 1, 1], [0, 0, 1], [0, 0, 0]] """ assert len(lengths.size()) <= 2 if len(lengths) == 2: if dim == 1: lengths = lengths.t() lengths = lengths else: lengths = lengths.unsqueeze(1) # lengths : batch_size, 1 lengths = lengths.view(-1, 1) batch_size = lengths.size(0) # batch_size, max_len mask = ( torch.arange(max_len, device="cuda") .expand(batch_size, max_len) .type_as(lengths) < lengths ) if negative_mask: mask = ~mask if dim == 0: # max_len, batch_size mask = mask.t() return mask def moving_sum(x, start_idx: int, end_idx: int): """ From MONOTONIC CHUNKWISE ATTENTION https://arxiv.org/pdf/1712.05382.pdf Equation (18) x = [x_1, x_2, ..., x_N] MovingSum(x, start_idx, end_idx)_n = Sigma_{m=n−(start_idx−1)}^{n+end_idx-1} x_m for n in {1, 2, 3, ..., N} x : src_len, batch_size start_idx : start idx end_idx : end idx Example src_len = 5 batch_size = 3 x = [[ 0, 5, 10], [ 1, 6, 11], [ 2, 7, 12], [ 3, 8, 13], [ 4, 9, 14]] MovingSum(x, 3, 1) = [[ 0, 5, 10], [ 1, 11, 21], [ 3, 18, 33], [ 6, 21, 36], [ 9, 24, 39]] MovingSum(x, 1, 3) = [[ 3, 18, 33], [ 6, 21, 36], [ 9, 24, 39], [ 7, 17, 27], [ 4, 9, 14]] """ assert start_idx > 0 and end_idx > 0 assert len(x.size()) == 2 src_len, batch_size = x.size() # batch_size, 1, src_len x = x.t().unsqueeze(1) # batch_size, 1, src_len moving_sum_weight = x.new_ones([1, 1, end_idx + start_idx - 1]) moving_sum = ( torch.nn.functional.conv1d( x, moving_sum_weight, padding=start_idx + end_idx - 1 ) .squeeze(1) .t() ) moving_sum = moving_sum[end_idx:-start_idx] assert src_len == moving_sum.size(0) assert batch_size == moving_sum.size(1) return moving_sum
""" Implementing exclusive cumprod. There is cumprod in pytorch, however there is no exclusive mode. cumprod(x) = [x1, x1x2, x2x3x4, ..., prod_{i=1}^n x_i] exclusive means cumprod(x) = [1, x1, x1x2, x1x2x3, ..., prod_{i=1}^{n-1} x_i] """ tensor_size = list(tensor.size()) tensor_size[dim] = 1 return_tensor = safe_cumprod( torch.cat([torch.ones(tensor_size, device=tensor.device), tensor], dim=dim), dim=dim, eps=eps, ) if dim == 0: return return_tensor[:-1] elif dim == 1: return return_tensor[:, :-1] elif dim == 2: return return_tensor[:, :, :-1] else: raise RuntimeError("Cumprod on dimension 3 and more is not implemented")
2pc_test.go
// Copyright 2016 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 tikv import ( "bytes" "context" "math" "math/rand" "strings" "sync/atomic" "time" . "github.com/pingcap/check" "github.com/pingcap/errors" "github.com/pingcap/failpoint" "github.com/pingcap/kvproto/pkg/kvrpcpb" "github.com/pingcap/tidb/store/mockstore/mocktikv" "github.com/shafreeck/tidbit/kv" "github.com/shafreeck/tidbit/tikv/oracle" "github.com/shafreeck/tidbit/tikv/tikvrpc" ) type testCommitterSuite struct { OneByOneSuite cluster *mocktikv.Cluster store *tikvStore } var _ = SerialSuites(&testCommitterSuite{}) func (s *testCommitterSuite) SetUpSuite(c *C) { atomic.StoreUint64(&ManagedLockTTL, 3000) // 3s s.OneByOneSuite.SetUpSuite(c) } func (s *testCommitterSuite) SetUpTest(c *C) { s.cluster = mocktikv.NewCluster() mocktikv.BootstrapWithMultiRegions(s.cluster, []byte("a"), []byte("b"), []byte("c")) mvccStore, err := mocktikv.NewMVCCLevelDB("") c.Assert(err, IsNil) client := mocktikv.NewRPCClient(s.cluster, mvccStore) pdCli := &codecPDClient{mocktikv.NewPDClient(s.cluster)} spkv := NewMockSafePointKV() store, err := newTikvStore("mocktikv-store", pdCli, spkv, client, false, nil) c.Assert(err, IsNil) store.EnableTxnLocalLatches(1024000) s.store = store CommitMaxBackoff = 1000 } func (s *testCommitterSuite) TearDownSuite(c *C) { CommitMaxBackoff = 20000 s.store.Close() s.OneByOneSuite.TearDownSuite(c) } func (s *testCommitterSuite) begin(c *C) *tikvTxn { txn, err := s.store.Begin() c.Assert(err, IsNil) return txn.(*tikvTxn)
func (s *testCommitterSuite) checkValues(c *C, m map[string]string) { txn := s.begin(c) for k, v := range m { val, err := txn.Get(context.TODO(), []byte(k)) c.Assert(err, IsNil) c.Assert(string(val), Equals, v) } } func (s *testCommitterSuite) mustCommit(c *C, m map[string]string) { txn := s.begin(c) for k, v := range m { err := txn.Set([]byte(k), []byte(v)) c.Assert(err, IsNil) } err := txn.Commit(context.Background()) c.Assert(err, IsNil) s.checkValues(c, m) } func randKV(keyLen, valLen int) (string, string) { const letters = "abc" k, v := make([]byte, keyLen), make([]byte, valLen) for i := range k { k[i] = letters[rand.Intn(len(letters))] } for i := range v { v[i] = letters[rand.Intn(len(letters))] } return string(k), string(v) } func (s *testCommitterSuite) TestCommitRollback(c *C) { s.mustCommit(c, map[string]string{ "a": "a", "b": "b", "c": "c", }) txn := s.begin(c) txn.Set([]byte("a"), []byte("a1")) txn.Set([]byte("b"), []byte("b1")) txn.Set([]byte("c"), []byte("c1")) s.mustCommit(c, map[string]string{ "c": "c2", }) err := txn.Commit(context.Background()) c.Assert(err, NotNil) s.checkValues(c, map[string]string{ "a": "a", "b": "b", "c": "c2", }) } func (s *testCommitterSuite) TestPrewriteRollback(c *C) { s.mustCommit(c, map[string]string{ "a": "a0", "b": "b0", }) ctx := context.Background() txn1 := s.begin(c) err := txn1.Set([]byte("a"), []byte("a1")) c.Assert(err, IsNil) err = txn1.Set([]byte("b"), []byte("b1")) c.Assert(err, IsNil) committer, err := newTwoPhaseCommitterWithInit(txn1, 0) c.Assert(err, IsNil) err = committer.prewriteKeys(NewBackoffer(ctx, PrewriteMaxBackoff), committer.keys) c.Assert(err, IsNil) txn2 := s.begin(c) v, err := txn2.Get(context.TODO(), []byte("a")) c.Assert(err, IsNil) c.Assert(v, BytesEquals, []byte("a0")) err = committer.prewriteKeys(NewBackoffer(ctx, PrewriteMaxBackoff), committer.keys) if err != nil { // Retry. txn1 = s.begin(c) err = txn1.Set([]byte("a"), []byte("a1")) c.Assert(err, IsNil) err = txn1.Set([]byte("b"), []byte("b1")) c.Assert(err, IsNil) committer, err = newTwoPhaseCommitterWithInit(txn1, 0) c.Assert(err, IsNil) err = committer.prewriteKeys(NewBackoffer(ctx, PrewriteMaxBackoff), committer.keys) c.Assert(err, IsNil) } committer.commitTS, err = s.store.oracle.GetTimestamp(ctx) c.Assert(err, IsNil) err = committer.commitKeys(NewBackoffer(ctx, CommitMaxBackoff), [][]byte{[]byte("a")}) c.Assert(err, IsNil) txn3 := s.begin(c) v, err = txn3.Get(context.TODO(), []byte("b")) c.Assert(err, IsNil) c.Assert(v, BytesEquals, []byte("b1")) } func (s *testCommitterSuite) TestContextCancel(c *C) { txn1 := s.begin(c) err := txn1.Set([]byte("a"), []byte("a1")) c.Assert(err, IsNil) err = txn1.Set([]byte("b"), []byte("b1")) c.Assert(err, IsNil) committer, err := newTwoPhaseCommitterWithInit(txn1, 0) c.Assert(err, IsNil) bo := NewBackoffer(context.Background(), PrewriteMaxBackoff) backoffer, cancel := bo.Fork() cancel() // cancel the context err = committer.prewriteKeys(backoffer, committer.keys) c.Assert(errors.Cause(err), Equals, context.Canceled) } func (s *testCommitterSuite) TestContextCancel2(c *C) { txn := s.begin(c) err := txn.Set([]byte("a"), []byte("a")) c.Assert(err, IsNil) err = txn.Set([]byte("b"), []byte("b")) c.Assert(err, IsNil) ctx, cancel := context.WithCancel(context.Background()) err = txn.Commit(ctx) c.Assert(err, IsNil) cancel() // Secondary keys should not be canceled. time.Sleep(time.Millisecond * 20) c.Assert(s.isKeyLocked(c, []byte("b")), IsFalse) } func (s *testCommitterSuite) TestContextCancelRetryable(c *C) { txn1, txn2, txn3 := s.begin(c), s.begin(c), s.begin(c) // txn1 locks "b" err := txn1.Set([]byte("b"), []byte("b1")) c.Assert(err, IsNil) committer, err := newTwoPhaseCommitterWithInit(txn1, 0) c.Assert(err, IsNil) err = committer.prewriteKeys(NewBackoffer(context.Background(), PrewriteMaxBackoff), committer.keys) c.Assert(err, IsNil) // txn3 writes "c" err = txn3.Set([]byte("c"), []byte("c3")) c.Assert(err, IsNil) err = txn3.Commit(context.Background()) c.Assert(err, IsNil) // txn2 writes "a"(PK), "b", "c" on different regions. // "c" will return a retryable error. // "b" will get a Locked error first, then the context must be canceled after backoff for lock. err = txn2.Set([]byte("a"), []byte("a2")) c.Assert(err, IsNil) err = txn2.Set([]byte("b"), []byte("b2")) c.Assert(err, IsNil) err = txn2.Set([]byte("c"), []byte("c2")) c.Assert(err, IsNil) err = txn2.Commit(context.Background()) c.Assert(err, NotNil) c.Assert(kv.ErrWriteConflictInTiDB.Equal(err), IsTrue, Commentf("err: %s", err)) } func (s *testCommitterSuite) mustGetRegionID(c *C, key []byte) uint64 { loc, err := s.store.regionCache.LocateKey(NewBackoffer(context.Background(), getMaxBackoff), key) c.Assert(err, IsNil) return loc.Region.id } func (s *testCommitterSuite) isKeyLocked(c *C, key []byte) bool { ver, err := s.store.CurrentVersion() c.Assert(err, IsNil) bo := NewBackoffer(context.Background(), getMaxBackoff) req := tikvrpc.NewRequest(tikvrpc.CmdGet, &kvrpcpb.GetRequest{ Key: key, Version: ver.Ver, }) loc, err := s.store.regionCache.LocateKey(bo, key) c.Assert(err, IsNil) resp, err := s.store.SendReq(bo, req, loc.Region, readTimeoutShort) c.Assert(err, IsNil) c.Assert(resp.Resp, NotNil) keyErr := (resp.Resp.(*kvrpcpb.GetResponse)).GetError() return keyErr.GetLocked() != nil } func (s *testCommitterSuite) TestPrewriteCancel(c *C) { // Setup region delays for key "b" and "c". delays := map[uint64]time.Duration{ s.mustGetRegionID(c, []byte("b")): time.Millisecond * 10, s.mustGetRegionID(c, []byte("c")): time.Millisecond * 20, } s.store.client = &slowClient{ Client: s.store.client, regionDelays: delays, } txn1, txn2 := s.begin(c), s.begin(c) // txn2 writes "b" err := txn2.Set([]byte("b"), []byte("b2")) c.Assert(err, IsNil) err = txn2.Commit(context.Background()) c.Assert(err, IsNil) // txn1 writes "a"(PK), "b", "c" on different regions. // "b" will return an error and cancel commit. err = txn1.Set([]byte("a"), []byte("a1")) c.Assert(err, IsNil) err = txn1.Set([]byte("b"), []byte("b1")) c.Assert(err, IsNil) err = txn1.Set([]byte("c"), []byte("c1")) c.Assert(err, IsNil) err = txn1.Commit(context.Background()) c.Assert(err, NotNil) // "c" should be cleaned up in reasonable time. for i := 0; i < 50; i++ { if !s.isKeyLocked(c, []byte("c")) { return } time.Sleep(time.Millisecond * 10) } c.Fail() } // slowClient wraps rpcClient and makes some regions respond with delay. type slowClient struct { Client regionDelays map[uint64]time.Duration } func (c *slowClient) SendReq(ctx context.Context, addr string, req *tikvrpc.Request, timeout time.Duration) (*tikvrpc.Response, error) { for id, delay := range c.regionDelays { reqCtx := &req.Context if reqCtx.GetRegionId() == id { time.Sleep(delay) } } return c.Client.SendRequest(ctx, addr, req, timeout) } func (s *testCommitterSuite) TestIllegalTso(c *C) { txn := s.begin(c) data := map[string]string{ "name": "aa", "age": "12", } for k, v := range data { err := txn.Set([]byte(k), []byte(v)) c.Assert(err, IsNil) } // make start ts bigger. txn.startTS = uint64(math.MaxUint64) err := txn.Commit(context.Background()) c.Assert(err, NotNil) errMsgMustContain(c, err, "invalid txnStartTS") } func errMsgMustContain(c *C, err error, msg string) { c.Assert(strings.Contains(err.Error(), msg), IsTrue) } func newTwoPhaseCommitterWithInit(txn *tikvTxn, connID uint64) (*twoPhaseCommitter, error) { c, err := newTwoPhaseCommitter(txn, connID) if err != nil { return nil, errors.Trace(err) } if err = c.initKeysAndMutations(); err != nil { return nil, errors.Trace(err) } return c, nil } func (s *testCommitterSuite) TestCommitBeforePrewrite(c *C) { txn := s.begin(c) err := txn.Set([]byte("a"), []byte("a1")) c.Assert(err, IsNil) committer, err := newTwoPhaseCommitterWithInit(txn, 0) c.Assert(err, IsNil) ctx := context.Background() err = committer.cleanupKeys(NewBackoffer(ctx, cleanupMaxBackoff), committer.keys) c.Assert(err, IsNil) err = committer.prewriteKeys(NewBackoffer(ctx, PrewriteMaxBackoff), committer.keys) c.Assert(err, NotNil) errMsgMustContain(c, err, "conflictCommitTS") } func (s *testCommitterSuite) TestPrewritePrimaryKeyFailed(c *C) { // commit (a,a1) txn1 := s.begin(c) err := txn1.Set([]byte("a"), []byte("a1")) c.Assert(err, IsNil) err = txn1.Commit(context.Background()) c.Assert(err, IsNil) // check a txn := s.begin(c) v, err := txn.Get(context.TODO(), []byte("a")) c.Assert(err, IsNil) c.Assert(v, BytesEquals, []byte("a1")) // set txn2's startTs before txn1's txn2 := s.begin(c) txn2.startTS = txn1.startTS - 1 err = txn2.Set([]byte("a"), []byte("a2")) c.Assert(err, IsNil) err = txn2.Set([]byte("b"), []byte("b2")) c.Assert(err, IsNil) // prewrite:primary a failed, b success err = txn2.Commit(context.Background()) c.Assert(err, NotNil) // txn2 failed with a rollback for record a. txn = s.begin(c) v, err = txn.Get(context.TODO(), []byte("a")) c.Assert(err, IsNil) c.Assert(v, BytesEquals, []byte("a1")) _, err = txn.Get(context.TODO(), []byte("b")) errMsgMustContain(c, err, "key not exist") // clean again, shouldn't be failed when a rollback already exist. ctx := context.Background() committer, err := newTwoPhaseCommitterWithInit(txn2, 0) c.Assert(err, IsNil) err = committer.cleanupKeys(NewBackoffer(ctx, cleanupMaxBackoff), committer.keys) c.Assert(err, IsNil) // check the data after rollback twice. txn = s.begin(c) v, err = txn.Get(context.TODO(), []byte("a")) c.Assert(err, IsNil) c.Assert(v, BytesEquals, []byte("a1")) // update data in a new txn, should be success. err = txn.Set([]byte("a"), []byte("a3")) c.Assert(err, IsNil) err = txn.Commit(context.Background()) c.Assert(err, IsNil) // check value txn = s.begin(c) v, err = txn.Get(context.TODO(), []byte("a")) c.Assert(err, IsNil) c.Assert(v, BytesEquals, []byte("a3")) } func (s *testCommitterSuite) TestWrittenKeysOnConflict(c *C) { // This test checks that when there is a write conflict, written keys is collected, // so we can use it to clean up keys. region, _ := s.cluster.GetRegionByKey([]byte("x")) newRegionID := s.cluster.AllocID() newPeerID := s.cluster.AllocID() s.cluster.Split(region.Id, newRegionID, []byte("y"), []uint64{newPeerID}, newPeerID) var totalTime time.Duration for i := 0; i < 10; i++ { txn1 := s.begin(c) txn2 := s.begin(c) txn2.Set([]byte("x1"), []byte("1")) committer2, err := newTwoPhaseCommitterWithInit(txn2, 2) c.Assert(err, IsNil) err = committer2.execute(context.Background()) c.Assert(err, IsNil) txn1.Set([]byte("x1"), []byte("1")) txn1.Set([]byte("y1"), []byte("2")) committer1, err := newTwoPhaseCommitterWithInit(txn1, 2) c.Assert(err, IsNil) err = committer1.execute(context.Background()) c.Assert(err, NotNil) committer1.cleanWg.Wait() txn3 := s.begin(c) start := time.Now() txn3.Get(context.TODO(), []byte("y1")) totalTime += time.Since(start) txn3.Commit(context.Background()) } c.Assert(totalTime, Less, time.Millisecond*200) } func (s *testCommitterSuite) TestPrewriteTxnSize(c *C) { // Prepare two regions first: (, 100) and [100, ) region, _ := s.cluster.GetRegionByKey([]byte{50}) newRegionID := s.cluster.AllocID() newPeerID := s.cluster.AllocID() s.cluster.Split(region.Id, newRegionID, []byte{100}, []uint64{newPeerID}, newPeerID) txn := s.begin(c) var val [1024]byte for i := byte(50); i < 120; i++ { err := txn.Set([]byte{i}, val[:]) c.Assert(err, IsNil) } committer, err := newTwoPhaseCommitterWithInit(txn, 1) c.Assert(err, IsNil) ctx := context.Background() err = committer.prewriteKeys(NewBackoffer(ctx, PrewriteMaxBackoff), committer.keys) c.Assert(err, IsNil) // Check the written locks in the first region (50 keys) for i := byte(50); i < 100; i++ { lock := s.getLockInfo(c, []byte{i}) c.Assert(int(lock.TxnSize), Equals, 50) } // Check the written locks in the second region (20 keys) for i := byte(100); i < 120; i++ { lock := s.getLockInfo(c, []byte{i}) c.Assert(int(lock.TxnSize), Equals, 20) } } func (s *testCommitterSuite) TestRejectCommitTS(c *C) { txn := s.begin(c) c.Assert(txn.Set([]byte("x"), []byte("v")), IsNil) committer, err := newTwoPhaseCommitterWithInit(txn, 1) c.Assert(err, IsNil) bo := NewBackoffer(context.Background(), getMaxBackoff) loc, err := s.store.regionCache.LocateKey(bo, []byte("x")) c.Assert(err, IsNil) batch := batchKeys{region: loc.Region, keys: [][]byte{[]byte("x")}} mutations := make([]*kvrpcpb.Mutation, len(batch.keys)) for i, k := range batch.keys { tmp := committer.mutations[string(k)] mutations[i] = &tmp.Mutation } prewrite := &kvrpcpb.PrewriteRequest{ Mutations: mutations, PrimaryLock: committer.primary(), StartVersion: committer.startTS, LockTtl: committer.lockTTL, MinCommitTs: committer.startTS + 100, // Set minCommitTS } req := tikvrpc.NewRequest(tikvrpc.CmdPrewrite, prewrite) _, err = s.store.SendReq(bo, req, loc.Region, readTimeoutShort) c.Assert(err, IsNil) // Make commitTS less than minCommitTS. committer.commitTS = committer.startTS + 1 // Ensure that the new commit ts is greater than minCommitTS when retry time.Sleep(3 * time.Millisecond) err = committer.commitKeys(bo, committer.keys) c.Assert(err, IsNil) // Use startTS+2 to read the data and get nothing. // Use max.Uint64 to read the data and success. // That means the final commitTS > startTS+2, it's not the one we provide. // So we cover the rety commitTS logic. txn1, err := s.store.BeginWithStartTS(committer.startTS + 2) c.Assert(err, IsNil) _, err = txn1.Get(bo.ctx, []byte("x")) c.Assert(kv.IsErrNotFound(err), IsTrue) txn2, err := s.store.BeginWithStartTS(math.MaxUint64) c.Assert(err, IsNil) val, err := txn2.Get(bo.ctx, []byte("x")) c.Assert(err, IsNil) c.Assert(bytes.Equal(val, []byte("v")), IsTrue) } func (s *testCommitterSuite) TestPessimisticPrewriteRequest(c *C) { // This test checks that the isPessimisticLock field is set in the request even when no keys are pessimistic lock. txn := s.begin(c) txn.SetOption(kv.Pessimistic, true) err := txn.Set([]byte("t1"), []byte("v1")) c.Assert(err, IsNil) committer, err := newTwoPhaseCommitterWithInit(txn, 0) c.Assert(err, IsNil) committer.forUpdateTS = 100 var batch batchKeys batch.keys = append(batch.keys, []byte("t1")) batch.region = RegionVerID{1, 1, 1} req := committer.buildPrewriteRequest(batch, 1) c.Assert(len(req.Prewrite().IsPessimisticLock), Greater, 0) c.Assert(req.Prewrite().ForUpdateTs, Equals, uint64(100)) } func (s *testCommitterSuite) TestUnsetPrimaryKey(c *C) { // This test checks that the isPessimisticLock field is set in the request even when no keys are pessimistic lock. key := kv.Key("key") txn := s.begin(c) c.Assert(txn.Set(key, key), IsNil) c.Assert(txn.Commit(context.Background()), IsNil) txn = s.begin(c) txn.SetOption(kv.Pessimistic, true) txn.SetOption(kv.PresumeKeyNotExists, nil) txn.SetOption(kv.PresumeKeyNotExistsError, kv.NewExistErrInfo("name", "value")) _, _ = txn.us.Get(context.TODO(), key) c.Assert(txn.Set(key, key), IsNil) txn.DelOption(kv.PresumeKeyNotExistsError) txn.DelOption(kv.PresumeKeyNotExists) lockCtx := &kv.LockCtx{ForUpdateTS: txn.startTS, WaitStartTime: time.Now()} err := txn.LockKeys(context.Background(), lockCtx, key) c.Assert(err, NotNil) c.Assert(txn.Delete(key), IsNil) key2 := kv.Key("key2") c.Assert(txn.Set(key2, key2), IsNil) err = txn.Commit(context.Background()) c.Assert(err, IsNil) } func (s *testCommitterSuite) TestPessimisticLockedKeysDedup(c *C) { txn := s.begin(c) txn.SetOption(kv.Pessimistic, true) lockCtx := &kv.LockCtx{ForUpdateTS: 100, WaitStartTime: time.Now()} err := txn.LockKeys(context.Background(), lockCtx, kv.Key("abc"), kv.Key("def")) c.Assert(err, IsNil) lockCtx = &kv.LockCtx{ForUpdateTS: 100, WaitStartTime: time.Now()} err = txn.LockKeys(context.Background(), lockCtx, kv.Key("abc"), kv.Key("def")) c.Assert(err, IsNil) c.Assert(txn.lockKeys, HasLen, 2) } func (s *testCommitterSuite) TestPessimisticTTL(c *C) { key := kv.Key("key") txn := s.begin(c) txn.SetOption(kv.Pessimistic, true) time.Sleep(time.Millisecond * 100) lockCtx := &kv.LockCtx{ForUpdateTS: txn.startTS, WaitStartTime: time.Now()} err := txn.LockKeys(context.Background(), lockCtx, key) c.Assert(err, IsNil) time.Sleep(time.Millisecond * 100) key2 := kv.Key("key2") lockCtx = &kv.LockCtx{ForUpdateTS: txn.startTS, WaitStartTime: time.Now()} err = txn.LockKeys(context.Background(), lockCtx, key2) c.Assert(err, IsNil) lockInfo := s.getLockInfo(c, key) msBeforeLockExpired := s.store.GetOracle().UntilExpired(txn.StartTS(), lockInfo.LockTtl) c.Assert(msBeforeLockExpired, GreaterEqual, int64(100)) lr := newLockResolver(s.store) bo := NewBackoffer(context.Background(), getMaxBackoff) status, err := lr.getTxnStatus(bo, txn.startTS, key2, 0, txn.startTS, true) c.Assert(err, IsNil) c.Assert(status.ttl, GreaterEqual, lockInfo.LockTtl) // Check primary lock TTL is auto increasing while the pessimistic txn is ongoing. for i := 0; i < 50; i++ { lockInfoNew := s.getLockInfo(c, key) if lockInfoNew.LockTtl > lockInfo.LockTtl { currentTS, err := lr.store.GetOracle().GetTimestamp(bo.ctx) c.Assert(err, IsNil) // Check that the TTL is update to a reasonable range. expire := oracle.ExtractPhysical(txn.startTS) + int64(lockInfoNew.LockTtl) now := oracle.ExtractPhysical(currentTS) c.Assert(expire > now, IsTrue) c.Assert(uint64(expire-now) <= atomic.LoadUint64(&ManagedLockTTL), IsTrue) return } time.Sleep(100 * time.Millisecond) } c.Assert(false, IsTrue, Commentf("update pessimistic ttl fail")) } // TestElapsedTTL tests that elapsed time is correct even if ts physical time is greater than local time. func (s *testCommitterSuite) TestElapsedTTL(c *C) { key := kv.Key("key") txn := s.begin(c) txn.startTS = oracle.ComposeTS(oracle.GetPhysical(time.Now().Add(time.Second*10)), 1) txn.SetOption(kv.Pessimistic, true) time.Sleep(time.Millisecond * 100) lockCtx := &kv.LockCtx{ ForUpdateTS: oracle.ComposeTS(oracle.ExtractPhysical(txn.startTS)+100, 1), WaitStartTime: time.Now(), } err := txn.LockKeys(context.Background(), lockCtx, key) c.Assert(err, IsNil) lockInfo := s.getLockInfo(c, key) c.Assert(lockInfo.LockTtl-atomic.LoadUint64(&ManagedLockTTL), GreaterEqual, uint64(100)) c.Assert(lockInfo.LockTtl-atomic.LoadUint64(&ManagedLockTTL), Less, uint64(150)) } // TestAcquireFalseTimeoutLock tests acquiring a key which is a secondary key of another transaction. // The lock's own TTL is expired but the primary key is still alive due to heartbeats. func (s *testCommitterSuite) TestAcquireFalseTimeoutLock(c *C) { // k1 is the primary lock of txn1 k1 := kv.Key("k1") // k2 is a secondary lock of txn1 and a key txn2 wants to lock k2 := kv.Key("k2") txn1 := s.begin(c) txn1.SetOption(kv.Pessimistic, true) // lock the primary key lockCtx := &kv.LockCtx{ForUpdateTS: txn1.startTS, WaitStartTime: time.Now()} err := txn1.LockKeys(context.Background(), lockCtx, k1) c.Assert(err, IsNil) // lock the secondary key lockCtx = &kv.LockCtx{ForUpdateTS: txn1.startTS, WaitStartTime: time.Now()} err = txn1.LockKeys(context.Background(), lockCtx, k2) c.Assert(err, IsNil) // Heartbeats will increase the TTL of the primary key // wait until secondary key exceeds its own TTL time.Sleep(time.Duration(atomic.LoadUint64(&ManagedLockTTL)) * time.Millisecond) txn2 := s.begin(c) txn2.SetOption(kv.Pessimistic, true) // test no wait lockCtx = &kv.LockCtx{ForUpdateTS: txn2.startTS, LockWaitTime: kv.LockNoWait, WaitStartTime: time.Now()} startTime := time.Now() err = txn2.LockKeys(context.Background(), lockCtx, k2) elapsed := time.Since(startTime) // cannot acquire lock immediately thus error c.Assert(err.Error(), Equals, ErrLockAcquireFailAndNoWaitSet.Error()) // it should return immediately c.Assert(elapsed, Less, 50*time.Millisecond) // test for wait limited time (300ms) lockCtx = &kv.LockCtx{ForUpdateTS: txn2.startTS, LockWaitTime: 300, WaitStartTime: time.Now()} startTime = time.Now() err = txn2.LockKeys(context.Background(), lockCtx, k2) elapsed = time.Since(startTime) // cannot acquire lock in time thus error c.Assert(err.Error(), Equals, ErrLockWaitTimeout.Error()) // it should return after about 300ms c.Assert(elapsed, Less, 350*time.Millisecond) } func (s *testCommitterSuite) getLockInfo(c *C, key []byte) *kvrpcpb.LockInfo { txn := s.begin(c) err := txn.Set(key, key) c.Assert(err, IsNil) committer, err := newTwoPhaseCommitterWithInit(txn, 1) c.Assert(err, IsNil) bo := NewBackoffer(context.Background(), getMaxBackoff) loc, err := s.store.regionCache.LocateKey(bo, key) c.Assert(err, IsNil) batch := batchKeys{region: loc.Region, keys: [][]byte{key}} req := committer.buildPrewriteRequest(batch, 1) resp, err := s.store.SendReq(bo, req, loc.Region, readTimeoutShort) c.Assert(err, IsNil) c.Assert(resp.Resp, NotNil) keyErrs := (resp.Resp.(*kvrpcpb.PrewriteResponse)).Errors c.Assert(keyErrs, HasLen, 1) locked := keyErrs[0].Locked c.Assert(locked, NotNil) return locked } func (s *testCommitterSuite) TestPkNotFound(c *C) { atomic.StoreUint64(&ManagedLockTTL, 100) // 100ms defer atomic.StoreUint64(&ManagedLockTTL, 3000) // restore default value // k1 is the primary lock of txn1 k1 := kv.Key("k1") // k2 is a secondary lock of txn1 and a key txn2 wants to lock k2 := kv.Key("k2") k3 := kv.Key("k3") txn1 := s.begin(c) txn1.SetOption(kv.Pessimistic, true) // lock the primary key lockCtx := &kv.LockCtx{ForUpdateTS: txn1.startTS, WaitStartTime: time.Now()} err := txn1.LockKeys(context.Background(), lockCtx, k1) c.Assert(err, IsNil) // lock the secondary key lockCtx = &kv.LockCtx{ForUpdateTS: txn1.startTS, WaitStartTime: time.Now()} err = txn1.LockKeys(context.Background(), lockCtx, k2) c.Assert(err, IsNil) // Stop txn ttl manager and remove primary key, like tidb server crashes and the priamry key lock does not exists actually, // while the secondary lock operation succeeded bo := NewBackoffer(context.Background(), pessimisticLockMaxBackoff) txn1.committer.ttlManager.close() err = txn1.committer.pessimisticRollbackKeys(bo, [][]byte{k1}) c.Assert(err, IsNil) // Txn2 tries to lock the secondary key k2, dead loop if the left secondary lock by txn1 not resolved txn2 := s.begin(c) txn2.SetOption(kv.Pessimistic, true) lockCtx = &kv.LockCtx{ForUpdateTS: txn2.startTS, WaitStartTime: time.Now()} err = txn2.LockKeys(context.Background(), lockCtx, k2) c.Assert(err, IsNil) // Using smaller forUpdateTS cannot rollback this lock, other lock will fail lockKey3 := &Lock{ Key: k3, Primary: k1, TxnID: txn1.startTS, TTL: ManagedLockTTL, TxnSize: txnCommitBatchSize, LockType: kvrpcpb.Op_PessimisticLock, LockForUpdateTS: txn1.startTS - 1, } cleanTxns := make(map[RegionVerID]struct{}) err = s.store.lockResolver.resolvePessimisticLock(bo, lockKey3, cleanTxns) c.Assert(err, IsNil) lockCtx = &kv.LockCtx{ForUpdateTS: txn1.startTS, WaitStartTime: time.Now()} err = txn1.LockKeys(context.Background(), lockCtx, k3) c.Assert(err, IsNil) txn3 := s.begin(c) txn3.SetOption(kv.Pessimistic, true) lockCtx = &kv.LockCtx{ForUpdateTS: txn1.startTS - 1, WaitStartTime: time.Now(), LockWaitTime: kv.LockNoWait} c.Assert(failpoint.Enable("github.com/shafreeck/tidbit/tikv/txnNotFoundRetTTL", "return"), IsNil) err = txn3.LockKeys(context.Background(), lockCtx, k3) c.Assert(err.Error(), Equals, ErrLockAcquireFailAndNoWaitSet.Error()) c.Assert(failpoint.Disable("github.com/shafreeck/tidbit/tikv/txnNotFoundRetTTL"), IsNil) } func (s *testCommitterSuite) TestPessimisticLockPrimary(c *C) { // a is the primary lock of txn1 k1 := kv.Key("a") // b is a secondary lock of txn1 and a key txn2 wants to lock, b is on another region k2 := kv.Key("b") txn1 := s.begin(c) txn1.SetOption(kv.Pessimistic, true) // txn1 lock k1 lockCtx := &kv.LockCtx{ForUpdateTS: txn1.startTS, WaitStartTime: time.Now()} err := txn1.LockKeys(context.Background(), lockCtx, k1) c.Assert(err, IsNil) // txn2 wants to lock k1, k2, k1(pk) is blocked by txn1, pessimisticLockKeys has been changed to // lock primary key first and then secondary keys concurrently, k2 should not be locked by txn2 doneCh := make(chan error) go func() { txn2 := s.begin(c) txn2.SetOption(kv.Pessimistic, true) lockCtx2 := &kv.LockCtx{ForUpdateTS: txn2.startTS, WaitStartTime: time.Now(), LockWaitTime: 200} waitErr := txn2.LockKeys(context.Background(), lockCtx2, k1, k2) doneCh <- waitErr }() time.Sleep(50 * time.Millisecond) // txn3 should locks k2 successfully using no wait txn3 := s.begin(c) txn3.SetOption(kv.Pessimistic, true) lockCtx3 := &kv.LockCtx{ForUpdateTS: txn3.startTS, WaitStartTime: time.Now(), LockWaitTime: kv.LockNoWait} c.Assert(failpoint.Enable("github.com/shafreeck/tidbit/tikv/txnNotFoundRetTTL", "return"), IsNil) err = txn3.LockKeys(context.Background(), lockCtx3, k2) c.Assert(failpoint.Disable("github.com/shafreeck/tidbit/tikv/txnNotFoundRetTTL"), IsNil) c.Assert(err, IsNil) waitErr := <-doneCh c.Assert(ErrLockWaitTimeout.Equal(waitErr), IsTrue) }
}
vms_test.go
package main import ( "fmt" "os" "os/exec" "testing" "github.com/stretchr/testify/assert" ) func TestGetGcloudvMs(t *testing.T) { execCommand = fakeVmsCommand defer func() { execCommand = exec.Command }() project := projectDetails{ ProjectID: "irrelevant", } expectedVMs := []vmDetails{ vmDetails{ Zone: "us-central-1", Name: "app-central-as72", }, } vms, _ := getGcloudVMs(project) assert.Equal(t, expectedVMs, vms) } func fakeVmsCommand(command string, args ...string) (cmd *exec.Cmd) { cs := []string{"-test.run=TestHelperVMs", "--", command} cs = append(cs, args...) cmd = exec.Command(os.Args[0], cs...) cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} return } func TestHelperVMs(t *testing.T) { if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { return } fmt.Fprintf(os.Stdout, "[{\"zone\":\"us-central-1\",\"name\":\"app-central-as72\"}]") os.Exit(0) } func TestGrtGcloudVMsError(t *testing.T) { execCommand = fakeVMsCommandError defer func() { execCommand = exec.Command }() project := projectDetails{ ProjectID: "irrelevant", } _, err := getGcloudVMs(project) assert.NotNil(t, err) } func fakeVMsCommandError(command string, args ...string) (cmd *exec.Cmd) { cs := []string{"-test.run=TestHelperVMsError", "--", command} cs = append(cs, args...) cmd = exec.Command(os.Args[0], cs...) cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} return } func TestHelperVMsError(t *testing.T)
func TestFilterVMs(t *testing.T) { vms := []vmDetails{ vmDetails{Zone: "us-central-1", Name: "app-central-as72"}, vmDetails{Zone: "us-west-1", Name: "db-west-09as"}, vmDetails{Zone: "eu-west-1", Name: "something-central-a7m2"}, } filtered := filterVMs(vms, "app") expectedVMs := []vmDetails{ vmDetails{Zone: "us-central-1", Name: "app-central-as72"}, } assert.Equal(t, expectedVMs, filtered) filtered = filterVMs(vms, "central") expectedVMs = []vmDetails{ vmDetails{Zone: "us-central-1", Name: "app-central-as72"}, vmDetails{Zone: "eu-west-1", Name: "something-central-a7m2"}, } assert.Equal(t, expectedVMs, filtered) } func TestVMDetailsToSurvey(t *testing.T) { vms := []vmDetails{ vmDetails{Zone: "us-central-1", Name: "app-central-as72"}, vmDetails{Zone: "us-west-1", Name: "db-west-09as"}, vmDetails{Zone: "eu-west-1", Name: "something-central-a7m2"}, } response := vmDetailsToSurvey(vms) expected := []string{ "(us-central-1) app-central-as72", "(us-west-1) db-west-09as", "(eu-west-1) something-central-a7m2", } assert.Equal(t, expected, response) } func TestStringToVMDetails(t *testing.T) { response := stringToVMDetails("(us-central-1) app-central-as72") expected := vmDetails{Zone: "us-central-1", Name: "app-central-as72"} assert.Equal(t, expected, response) }
{ if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { return } fmt.Fprintf(os.Stderr, "This is an error. Handle me!") os.Exit(1) }
dns.go
// Implement a basic DNS server for testing beacons and downloaders. This should // not be used in production. package main import ( "encoding/base64" "fmt" "io/ioutil" "log" "strconv" "github.com/miekg/dns" ) const payloadFile = "payload.bin" const payloadDns = "ns.domain.com" // The payload server DNS address. const domain = "domain.com" const port = ":5553" var chunks map[string]string // Base64 encode our payload and break it into 240 character chunks to be sent // over TXT lookups. Store the chunks in a map with the chunk count as the index. // // This excellent idea is courtesy of @breenmachine https://github.com/breenmachine/dnsftp func chunk(data []byte)
// Define a DNS server handler. type handler struct{} // ServeDNS will respond to the NS and TXT requests necessary for testing the // DNS beacon and downloader. func (this *handler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) { msg := dns.Msg{} name := r.Question[0].Name recType := r.Question[0].Qtype msg.SetReply(r) log.Printf("%s request for %s\n", dns.TypeToString[recType], name) switch r.Question[0].Qtype { case dns.TypeSOA: rr, err := dns.NewRR(fmt.Sprintf("%s 300 SOA %s %s 2015013001 86400 7200 604800 300", name, name, payloadDns)) if err != nil { log.Println(err) return } msg.Answer = append(msg.Answer, rr) case dns.TypeMX: rr, err := dns.NewRR(fmt.Sprintf("%s MX 10 %s", name, payloadDns)) if err != nil { log.Println(err) return } msg.Answer = append(msg.Answer, rr) case dns.TypeNS: rr, err := dns.NewRR(fmt.Sprintf("%s NS %s", name, payloadDns)) if err != nil { log.Println(err) return } msg.Answer = append(msg.Answer, rr) case dns.TypeTXT: if _, ok := dns.IsDomainName(name); !ok { log.Println("Invalid domain name") return } key := dns.SplitDomainName(name)[0] val, ok := chunks[key] if !ok { val = "" } rr, err := dns.NewRR(fmt.Sprintf("%s TXT %s", r.Question[0].Name, val)) if err != nil { log.Println(err) return } msg.Answer = append(msg.Answer, rr) } w.WriteMsg(&msg) } func main() { chunks = make(map[string]string) // Open our payload file and chunk it. data, err := ioutil.ReadFile(payloadFile) if err != nil { log.Print("Failed to read payload.") } else { chunk(data) } // Start our DNS server. srv := &dns.Server{Addr: port, Net: "udp"} srv.Handler = &handler{} if err := srv.ListenAndServe(); err != nil { log.Fatalf("Failed to set udp listener %s\n", err.Error()) } }
{ str := base64.StdEncoding.EncodeToString(data) size := 240 count := (len(str) / size) + 1 for i := 0; i < count; i++ { iStr := strconv.Itoa(i) begin := i * size end := begin + size if end > len(str) { end = len(str) } chunks[iStr] = str[begin:end] } }
blog.ts
export class
{ public title: string = ""; public subtitle: string = ""; public author: string = ""; public area: string = ""; public description: string = ""; public heroImage: string = ""; public gallery: Array<any> = []; }
Blog
mint.js
require("dotenv").config(); const HDWalletProvider = require("@truffle/hdwallet-provider"); const web3 = require("web3"); const PRIVATE_KEY = process.env.PRIVATE_KEY; const NODE_API_KEY = process.env.INFURA_KEY || process.env.ALCHEMY_KEY; const isInfura = !!process.env.INFURA_KEY; const FACTORY_CONTRACT_ADDRESS = process.env.FACTORY_CONTRACT_ADDRESS; const NFT_CONTRACT_ADDRESS = process.env.NFT_CONTRACT_ADDRESS; const OWNER_ADDRESS = process.env.OWNER_ADDRESS; const NETWORK = process.env.NETWORK; const NUM_CREATURES = 12; const NUM_LOOTBOXES = 4; const DEFAULT_OPTION_ID = 0; const LOOTBOX_OPTION_ID = 2; if (!PRIVATE_KEY || !NODE_API_KEY || !OWNER_ADDRESS || !NETWORK) { console.error( "Please set a mnemonic, Alchemy/Infura key, owner, network, and contract address." ); return; } const NFT_ABI = [ { constant: false, inputs: [ { name: "_to", type: "address", }, ], name: "mintTo", outputs: [], payable: false, stateMutability: "nonpayable", type: "function", }, ]; const FACTORY_ABI = [ { constant: false, inputs: [ { name: "_optionId", type: "uint256", }, { name: "_toAddress", type: "address", }, ], name: "mint", outputs: [], payable: false, stateMutability: "nonpayable", type: "function", }, ]; async function
() { const network = NETWORK === "mainnet" || NETWORK === "live" ? "mainnet" : "rinkeby"; const provider = new HDWalletProvider( PRIVATE_KEY, isInfura ? "https://" + network + ".infura.io/v3/" + NODE_API_KEY : "https://eth-" + network + ".alchemyapi.io/v2/" + NODE_API_KEY ); const web3Instance = new web3(provider); if (FACTORY_CONTRACT_ADDRESS) { const factoryContract = new web3Instance.eth.Contract( FACTORY_ABI, FACTORY_CONTRACT_ADDRESS, { gasLimit: "1000000" } ); // Creatures issued directly to the owner. for (var i = 0; i < NUM_CREATURES; i++) { const result = await factoryContract.methods .mint(DEFAULT_OPTION_ID, OWNER_ADDRESS) .send({ from: OWNER_ADDRESS }); console.log("Minted creature. Transaction: " + result.transactionHash); } // Lootboxes issued directly to the owner. for (var i = 0; i < NUM_LOOTBOXES; i++) { const result = await factoryContract.methods .mint(LOOTBOX_OPTION_ID, OWNER_ADDRESS) .send({ from: OWNER_ADDRESS }); console.log("Minted lootbox. Transaction: " + result.transactionHash); } console.log("Minting with factory is finished. 👏👏👏"); } else if (NFT_CONTRACT_ADDRESS) { const nftContract = new web3Instance.eth.Contract( NFT_ABI, NFT_CONTRACT_ADDRESS, { gasLimit: "1000000" } ); // Creatures issued directly to the owner. for (var i = 0; i < NUM_CREATURES; i++) { const result = await nftContract.methods .mintTo(OWNER_ADDRESS) .send({ from: OWNER_ADDRESS }); console.log("Minted creature. Transaction: " + result.transactionHash); } console.log("Minting is finished. 👏👏👏"); } else { console.error( "Add NFT_CONTRACT_ADDRESS or FACTORY_CONTRACT_ADDRESS to the environment variables" ); } } main();
main
highstock.js
/* Highstock JS v8.0.0 (2019-12-10) (c) 2009-2018 Torstein Honsi License: www.highcharts.com/license */ (function(S,K){"object"===typeof module&&module.exports?(K["default"]=K,module.exports=S.document?K(S):K):"function"===typeof define&&define.amd?define("highcharts/highstock",function(){return K(S)}):(S.Highcharts&&S.Highcharts.error(16,!0),S.Highcharts=K(S))})("undefined"!==typeof window?window:this,function(S){function K(d,g,M,F){d.hasOwnProperty(g)||(d[g]=F.apply(null,M))}var y={};K(y,"parts/Globals.js",[],function(){var d="undefined"!==typeof S?S:"undefined"!==typeof window?window:{},g=d.document, M=d.navigator&&d.navigator.userAgent||"",F=g&&g.createElementNS&&!!g.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect,E=/(edge|msie|trident)/i.test(M)&&!d.opera,D=-1!==M.indexOf("Firefox"),x=-1!==M.indexOf("Chrome"),v=D&&4>parseInt(M.split("Firefox/")[1],10);return{product:"Highcharts",version:"8.0.0",deg2rad:2*Math.PI/360,doc:g,hasBidiBug:v,hasTouch:!!d.TouchEvent,isMS:E,isWebKit:-1!==M.indexOf("AppleWebKit"),isFirefox:D,isChrome:x,isSafari:!x&&-1!==M.indexOf("Safari"),isTouchDevice:/(Mobile|Android|Windows Phone)/.test(M), SVG_NS:"http://www.w3.org/2000/svg",chartCount:0,seriesTypes:{},symbolSizes:{},svg:F,win:d,marginNames:["plotTop","marginRight","marginBottom","plotLeft"],noop:function(){},charts:[],dateFormats:{}}});K(y,"parts/Utilities.js",[y["parts/Globals.js"]],function(d){function g(a,l){return parseInt(a,l||10)}function M(a){return"string"===typeof a}function F(a){a=Object.prototype.toString.call(a);return"[object Array]"===a||"[object Array Iterator]"===a}function E(a,l){return!!a&&"object"===typeof a&&(!l|| !F(a))}function D(a){return E(a)&&"number"===typeof a.nodeType}function x(a){var l=a&&a.constructor;return!(!E(a,!0)||D(a)||!l||!l.name||"Object"===l.name)}function v(a){return"number"===typeof a&&!isNaN(a)&&Infinity>a&&-Infinity<a}function C(a){return"undefined"!==typeof a&&null!==a}function B(a,l,b){var c;M(l)?C(b)?a.setAttribute(l,b):a&&a.getAttribute&&((c=a.getAttribute(l))||"class"!==l||(c=a.getAttribute(l+"Name"))):h(l,function(l,b){a.setAttribute(b,l)});return c}function p(a,l){var b;a||(a= {});for(b in l)a[b]=l[b];return a}function z(){for(var a=arguments,l=a.length,b=0;b<l;b++){var c=a[b];if("undefined"!==typeof c&&null!==c)return c}}function m(a,l){var b=function(){};b.prototype=new a;p(b.prototype,l);return b}function q(a,l){return parseFloat(a.toPrecision(l||14))}function w(a,l,b,c){a=+a||0;l=+l;var n=d.defaultOptions.lang,f=(a.toString().split(".")[1]||"").split("e")[0].length,e=a.toString().split("e");if(-1===l)l=Math.min(f,20);else if(!v(l))l=2;else if(l&&e[1]&&0>e[1]){var k= l+ +e[1];0<=k?(e[0]=(+e[0]).toExponential(k).split("e")[0],l=k):(e[0]=e[0].split(".")[0]||0,a=20>l?(e[0]*Math.pow(10,e[1])).toFixed(l):0,e[1]=0)}var u=(Math.abs(e[1]?e[0]:a)+Math.pow(10,-Math.max(l,f)-1)).toFixed(l);f=String(g(u));k=3<f.length?f.length%3:0;b=z(b,n.decimalPoint);c=z(c,n.thousandsSep);a=(0>a?"-":"")+(k?f.substr(0,k)+c:"");a+=f.substr(k).replace(/(\d{3})(?=\d)/g,"$1"+c);l&&(a+=b+u.slice(-l));e[1]&&0!==+a&&(a+="e"+e[1]);return a}function h(a,l,b){for(var c in a)Object.hasOwnProperty.call(a, c)&&l.call(b||a[c],a[c],c,a)}d.timers=[];var f=d.charts,c=d.doc,b=d.win;d.error=function(a,l,c,f){var n=v(a),t=n?"Highcharts error #"+a+": www.highcharts.com/errors/"+a+"/":a.toString(),e=function(){if(l)throw Error(t);b.console&&console.log(t)};if("undefined"!==typeof f){var k="";n&&(t+="?");d.objectEach(f,function(a,e){k+="\n"+e+": "+a;n&&(t+=encodeURI(e)+"="+encodeURI(a))});t+=k}c?d.fireEvent(c,"displayError",{code:a,message:t,params:f},e):e()};d.Fx=function(a,l,b){this.options=l;this.elem=a;this.prop= b};d.Fx.prototype={dSetter:function(){var a=this.paths[0],b=this.paths[1],c=[],f=this.now,h=a.length;if(1===f)c=this.toD;else if(h===b.length&&1>f)for(;h--;){var r=parseFloat(a[h]);c[h]=isNaN(r)||"A"===b[h-4]||"A"===b[h-5]?b[h]:f*parseFloat(""+(b[h]-r))+r}else c=b;this.elem.attr("d",c,null,!0)},update:function(){var a=this.elem,b=this.prop,c=this.now,f=this.options.step;if(this[b+"Setter"])this[b+"Setter"]();else a.attr?a.element&&a.attr(b,c,null,!0):a.style[b]=c+this.unit;f&&f.call(a,c,this)},run:function(a, l,c){var f=this,n=f.options,r=function(a){return r.stopped?!1:f.step(a)},e=b.requestAnimationFrame||function(a){setTimeout(a,13)},k=function(){for(var a=0;a<d.timers.length;a++)d.timers[a]()||d.timers.splice(a--,1);d.timers.length&&e(k)};a!==l||this.elem["forceAnimate:"+this.prop]?(this.startTime=+new Date,this.start=a,this.end=l,this.unit=c,this.now=this.start,this.pos=0,r.elem=this.elem,r.prop=this.prop,r()&&1===d.timers.push(r)&&e(k)):(delete n.curAnim[this.prop],n.complete&&0===Object.keys(n.curAnim).length&& n.complete.call(this.elem))},step:function(a){var b=+new Date,c=this.options,f=this.elem,d=c.complete,r=c.duration,e=c.curAnim;if(f.attr&&!f.element)a=!1;else if(a||b>=r+this.startTime){this.now=this.end;this.pos=1;this.update();var k=e[this.prop]=!0;h(e,function(a){!0!==a&&(k=!1)});k&&d&&d.call(f);a=!1}else this.pos=c.easing((b-this.startTime)/r),this.now=this.start+(this.end-this.start)*this.pos,this.update(),a=!0;return a},initPath:function(a,b,c){function l(a){for(A=a.length;A--;){var e="M"=== a[A]||"L"===a[A];var k=/[a-zA-Z]/.test(a[A+3]);e&&k&&a.splice(A+1,0,a[A+1],a[A+2],a[A+1],a[A+2])}}function f(a,e){for(;a.length<m;){a[0]=e[m-a.length];var k=a.slice(0,h);[].splice.apply(a,[0,0].concat(k));J&&(k=a.slice(a.length-h),[].splice.apply(a,[a.length,0].concat(k)),A--)}a[0]="M"}function n(a,e){for(var k=(m-a.length)/h;0<k&&k--;)G=a.slice().splice(a.length/L-h,h*L),G[0]=e[m-h-k*h],u&&(G[h-6]=G[h-2],G[h-5]=G[h-1]),[].splice.apply(a,[a.length/L,0].concat(G)),J&&k--}b=b||"";var e=a.startX,k=a.endX, u=-1<b.indexOf("C"),h=u?7:3,G,A;b=b.split(" ");c=c.slice();var J=a.isArea,L=J?2:1;u&&(l(b),l(c));if(e&&k){for(A=0;A<e.length;A++)if(e[A]===k[0]){var d=A;break}else if(e[0]===k[k.length-e.length+A]){d=A;var q=!0;break}else if(e[e.length-1]===k[k.length-e.length+A]){d=e.length-A;break}"undefined"===typeof d&&(b=[])}if(b.length&&v(d)){var m=c.length+d*L*h;q?(f(b,c),n(c,b)):(f(c,b),n(b,c))}return[b,c]},fillSetter:function(){d.Fx.prototype.strokeSetter.apply(this,arguments)},strokeSetter:function(){this.elem.attr(this.prop, d.color(this.start).tweenTo(d.color(this.end),this.pos),null,!0)}};d.merge=function(){var a,b=arguments,c={},f=function(a,e){"object"!==typeof a&&(a={});h(e,function(k,b){!E(k,!0)||x(k)||D(k)?a[b]=e[b]:a[b]=f(a[b]||{},k)});return a};!0===b[0]&&(c=b[1],b=Array.prototype.slice.call(b,2));var d=b.length;for(a=0;a<d;a++)c=f(c,b[a]);return c};d.clearTimeout=function(a){C(a)&&clearTimeout(a)};d.css=function(a,b){d.isMS&&!d.svg&&b&&"undefined"!==typeof b.opacity&&(b.filter="alpha(opacity="+100*b.opacity+ ")");p(a.style,b)};d.createElement=function(a,b,f,t,h){a=c.createElement(a);var l=d.css;b&&p(a,b);h&&l(a,{padding:"0",border:"none",margin:"0"});f&&l(a,f);t&&t.appendChild(a);return a};d.datePropsToTimestamps=function(a){h(a,function(b,c){E(b)&&"function"===typeof b.getTime?a[c]=b.getTime():(E(b)||F(b))&&d.datePropsToTimestamps(b)})};d.formatSingle=function(a,b,c){var l=/\.([0-9])/,f=d.defaultOptions.lang,n=c&&c.time||d.time;c=c&&c.numberFormatter||w;/f$/.test(a)?(l=(l=a.match(l))?l[1]:-1,null!== b&&(b=c(b,l,f.decimalPoint,-1<a.indexOf(",")?f.thousandsSep:""))):b=n.dateFormat(a,b);return b};d.format=function(a,b,c){for(var l="{",f=!1,n,e,k,u,h=[],G;a;){l=a.indexOf(l);if(-1===l)break;n=a.slice(0,l);if(f){n=n.split(":");e=n.shift().split(".");u=e.length;G=b;for(k=0;k<u;k++)G&&(G=G[e[k]]);n.length&&(G=d.formatSingle(n.join(":"),G,c));h.push(G)}else h.push(n);a=a.slice(l+1);l=(f=!f)?"}":"{"}h.push(a);return h.join("")};d.getMagnitude=function(a){return Math.pow(10,Math.floor(Math.log(a)/Math.LN10))}; d.normalizeTickInterval=function(a,b,c,f,h){var l=a;c=z(c,1);var e=a/c;b||(b=h?[1,1.2,1.5,2,2.5,3,4,5,6,8,10]:[1,2,2.5,5,10],!1===f&&(1===c?b=b.filter(function(a){return 0===a%1}):.1>=c&&(b=[1/c])));for(f=0;f<b.length&&!(l=b[f],h&&l*c>=a||!h&&e<=(b[f]+(b[f+1]||b[f]))/2);f++);return l=q(l*c,-Math.round(Math.log(.001)/Math.LN10))};d.stableSort=function(a,b){var c=a.length,l,f;for(f=0;f<c;f++)a[f].safeI=f;a.sort(function(a,e){l=b(a,e);return 0===l?a.safeI-e.safeI:l});for(f=0;f<c;f++)delete a[f].safeI}; d.timeUnits={millisecond:1,second:1E3,minute:6E4,hour:36E5,day:864E5,week:6048E5,month:24192E5,year:314496E5};Math.easeInOutSine=function(a){return-.5*(Math.cos(Math.PI*a)-1)};d.getStyle=function(a,c,f){if("width"===c)return c=Math.min(a.offsetWidth,a.scrollWidth),f=a.getBoundingClientRect&&a.getBoundingClientRect().width,f<c&&f>=c-1&&(c=Math.floor(f)),Math.max(0,c-d.getStyle(a,"padding-left")-d.getStyle(a,"padding-right"));if("height"===c)return Math.max(0,Math.min(a.offsetHeight,a.scrollHeight)- d.getStyle(a,"padding-top")-d.getStyle(a,"padding-bottom"));b.getComputedStyle||d.error(27,!0);if(a=b.getComputedStyle(a,void 0))a=a.getPropertyValue(c),z(f,"opacity"!==c)&&(a=g(a));return a};d.inArray=function(a,b,c){return b.indexOf(a,c)};d.find=Array.prototype.find?function(a,b){return a.find(b)}:function(a,b){var c,l=a.length;for(c=0;c<l;c++)if(b(a[c],c))return a[c]};d.keys=Object.keys;d.stop=function(a,b){for(var c=d.timers.length;c--;)d.timers[c].elem!==a||b&&b!==d.timers[c].prop||(d.timers[c].stopped= !0)};h({map:"map",each:"forEach",grep:"filter",reduce:"reduce",some:"some"},function(a,b){d[b]=function(b){return Array.prototype[a].apply(b,[].slice.call(arguments,1))}});d.addEvent=function(a,b,c,f){void 0===f&&(f={});var l=a.addEventListener||d.addEventListenerPolyfill;var n="function"===typeof a&&a.prototype?a.prototype.protoEvents=a.prototype.protoEvents||{}:a.hcEvents=a.hcEvents||{};d.Point&&a instanceof d.Point&&a.series&&a.series.chart&&(a.series.chart.runTrackerClick=!0);l&&l.call(a,b,c, !1);n[b]||(n[b]=[]);n[b].push({fn:c,order:"number"===typeof f.order?f.order:Infinity});n[b].sort(function(a,b){return a.order-b.order});return function(){d.removeEvent(a,b,c)}};d.removeEvent=function(a,b,c){function
(e,b){var c=a.removeEventListener||d.removeEventListenerPolyfill;c&&c.call(a,e,b,!1)}function f(e){var c;if(a.nodeName){if(b){var f={};f[b]=!0}else f=e;h(f,function(a,b){if(e[b])for(c=e[b].length;c--;)l(b,e[b][c].fn)})}}var n;["protoEvents","hcEvents"].forEach(function(e,k){var u=(k= k?a:a.prototype)&&k[e];u&&(b?(n=u[b]||[],c?(u[b]=n.filter(function(a){return c!==a.fn}),l(b,c)):(f(u),u[b]=[])):(f(u),k[e]={}))})};d.fireEvent=function(a,b,f,h){var l;f=f||{};if(c.createEvent&&(a.dispatchEvent||a.fireEvent)){var n=c.createEvent("Events");n.initEvent(b,!0,!0);p(n,f);a.dispatchEvent?a.dispatchEvent(n):a.fireEvent(b,n)}else f.target||p(f,{preventDefault:function(){f.defaultPrevented=!0},target:a,type:b}),function(e,b){void 0===e&&(e=[]);void 0===b&&(b=[]);var c=0,k=0,n=e.length+b.length; for(l=0;l<n;l++)!1===(e[c]?b[k]?e[c].order<=b[k].order?e[c++]:b[k++]:e[c++]:b[k++]).fn.call(a,f)&&f.preventDefault()}(a.protoEvents&&a.protoEvents[b],a.hcEvents&&a.hcEvents[b]);h&&!f.defaultPrevented&&h.call(a,f)};d.animate=function(a,b,c){var l,f="",n,e;if(!E(c)){var k=arguments;c={duration:k[2],easing:k[3],complete:k[4]}}v(c.duration)||(c.duration=400);c.easing="function"===typeof c.easing?c.easing:Math[c.easing]||Math.easeInOutSine;c.curAnim=d.merge(b);h(b,function(k,h){d.stop(a,h);e=new d.Fx(a, c,h);n=null;"d"===h?(e.paths=e.initPath(a,a.d,b.d),e.toD=b.d,l=0,n=1):a.attr?l=a.attr(h):(l=parseFloat(d.getStyle(a,h))||0,"opacity"!==h&&(f="px"));n||(n=k);n&&n.match&&n.match("px")&&(n=n.replace(/px/g,""));e.run(l,n,f)})};d.seriesType=function(a,b,c,f,h){var l=d.getOptions(),e=d.seriesTypes;l.plotOptions[a]=d.merge(l.plotOptions[b],c);e[a]=m(e[b]||function(){},f);e[a].prototype.type=a;h&&(e[a].prototype.pointClass=m(d.Point,h));return e[a]};d.uniqueKey=function(){var a=Math.random().toString(36).substring(2, 9),b=0;return function(){return"highcharts-"+a+"-"+b++}}();d.isFunction=function(a){return"function"===typeof a};b.jQuery&&(b.jQuery.fn.highcharts=function(){var a=[].slice.call(arguments);if(this[0])return a[0]?(new (d[M(a[0])?a.shift():"Chart"])(this[0],a[0],a[1]),this):f[B(this[0],"data-highcharts-chart")]});return{animObject:function(a){return E(a)?d.merge(a):{duration:a?500:0}},arrayMax:function(a){for(var b=a.length,c=a[0];b--;)a[b]>c&&(c=a[b]);return c},arrayMin:function(a){for(var b=a.length, c=a[0];b--;)a[b]<c&&(c=a[b]);return c},attr:B,clamp:function(a,b,c){return a>b?a<c?a:c:b},correctFloat:q,defined:C,destroyObjectProperties:function(a,b){h(a,function(c,f){c&&c!==b&&c.destroy&&c.destroy();delete a[f]})},discardElement:function(a){var b=d.garbageBin;b||(b=d.createElement("div"));a&&b.appendChild(a);b.innerHTML=""},erase:function(a,b){for(var c=a.length;c--;)if(a[c]===b){a.splice(c,1);break}},extend:p,extendClass:m,isArray:F,isClass:x,isDOMElement:D,isNumber:v,isObject:E,isString:M, numberFormat:w,objectEach:h,offset:function(a){var f=c.documentElement;a=a.parentElement||a.parentNode?a.getBoundingClientRect():{top:0,left:0};return{top:a.top+(b.pageYOffset||f.scrollTop)-(f.clientTop||0),left:a.left+(b.pageXOffset||f.scrollLeft)-(f.clientLeft||0)}},pad:function(a,b,c){return Array((b||2)+1-String(a).replace("-","").length).join(c||"0")+a},pick:z,pInt:g,relativeLength:function(a,b,c){return/%$/.test(a)?b*parseFloat(a)/100+(c||0):parseFloat(a)},setAnimation:function(a,b){b.renderer.globalAnimation= z(a,b.options.chart.animation,!0)},splat:function(a){return F(a)?a:[a]},syncTimeout:function(a,b,c){if(0<b)return setTimeout(a,b,c);a.call(0,c);return-1},wrap:function(a,b,c){var f=a[b];a[b]=function(){var a=Array.prototype.slice.call(arguments),b=arguments,e=this;e.proceed=function(){f.apply(e,arguments.length?arguments:b)};a.unshift(f);a=c.apply(this,a);e.proceed=null;return a}}}});K(y,"parts/Color.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var M=g.isNumber,F=g.pInt,E=d.merge; d.Color=function(g){if(!(this instanceof d.Color))return new d.Color(g);this.init(g)};d.Color.prototype={parsers:[{regex:/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/,parse:function(d){return[F(d[1]),F(d[2]),F(d[3]),parseFloat(d[4],10)]}},{regex:/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/,parse:function(d){return[F(d[1]),F(d[2]),F(d[3]),1]}}],names:{white:"#ffffff",black:"#000000"},init:function(g){var x,v;if((this.input=g=this.names[g&& g.toLowerCase?g.toLowerCase():""]||g)&&g.stops)this.stops=g.stops.map(function(g){return new d.Color(g[1])});else{if(g&&g.charAt&&"#"===g.charAt()){var C=g.length;g=parseInt(g.substr(1),16);7===C?x=[(g&16711680)>>16,(g&65280)>>8,g&255,1]:4===C&&(x=[(g&3840)>>4|(g&3840)>>8,(g&240)>>4|g&240,(g&15)<<4|g&15,1])}if(!x)for(v=this.parsers.length;v--&&!x;){var D=this.parsers[v];(C=D.regex.exec(g))&&(x=D.parse(C))}}this.rgba=x||[]},get:function(d){var g=this.input,v=this.rgba;if(this.stops){var C=E(g);C.stops= [].concat(C.stops);this.stops.forEach(function(g,p){C.stops[p]=[C.stops[p][0],g.get(d)]})}else C=v&&M(v[0])?"rgb"===d||!d&&1===v[3]?"rgb("+v[0]+","+v[1]+","+v[2]+")":"a"===d?v[3]:"rgba("+v.join(",")+")":g;return C},brighten:function(d){var g,v=this.rgba;if(this.stops)this.stops.forEach(function(g){g.brighten(d)});else if(M(d)&&0!==d)for(g=0;3>g;g++)v[g]+=F(255*d),0>v[g]&&(v[g]=0),255<v[g]&&(v[g]=255);return this},setOpacity:function(d){this.rgba[3]=d;return this},tweenTo:function(d,g){var v=this.rgba, x=d.rgba;x.length&&v&&v.length?(d=1!==x[3]||1!==v[3],g=(d?"rgba(":"rgb(")+Math.round(x[0]+(v[0]-x[0])*(1-g))+","+Math.round(x[1]+(v[1]-x[1])*(1-g))+","+Math.round(x[2]+(v[2]-x[2])*(1-g))+(d?","+(x[3]+(v[3]-x[3])*(1-g)):"")+")"):g=d.input||"none";return g}};d.color=function(g){return new d.Color(g)}});K(y,"parts/SvgRenderer.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var M=g.animObject,F=g.attr,E=g.defined,D=g.destroyObjectProperties,x=g.erase,v=g.extend,C=g.isArray,B=g.isNumber, p=g.isObject,z=g.isString,m=g.objectEach,q=g.pick,w=g.pInt,h=g.splat,f=d.addEvent,c=d.animate,b=d.charts,a=d.color,l=d.css,n=d.createElement,t=d.deg2rad,I=d.doc,r=d.hasTouch,e=d.isFirefox,k=d.isMS,u=d.isWebKit,H=d.merge,G=d.noop,A=d.removeEvent,J=d.stop,L=d.svg,Q=d.SVG_NS,V=d.symbolSizes,U=d.win;var P=d.SVGElement=function(){return this};v(P.prototype,{opacity:1,SVG_NS:Q,textProps:"direction fontSize fontWeight fontFamily fontStyle color lineHeight width textAlign textDecoration textOverflow textOutline cursor".split(" "), init:function(a,e){this.element="span"===e?n(e):I.createElementNS(this.SVG_NS,e);this.renderer=a;d.fireEvent(this,"afterInit")},animate:function(a,e,b){var k=M(q(e,this.renderer.globalAnimation,!0));q(I.hidden,I.msHidden,I.webkitHidden,!1)&&(k.duration=0);0!==k.duration?(b&&(k.complete=b),c(this,a,k)):(this.attr(a,void 0,b),m(a,function(a,e){k.step&&k.step.call(this,a,{prop:e,pos:1})},this));return this},complexColor:function(a,e,b){var c=this.renderer,k,A,f,l,u,J,N,O,h,n,t,L=[],r;d.fireEvent(this.renderer, "complexColor",{args:arguments},function(){a.radialGradient?A="radialGradient":a.linearGradient&&(A="linearGradient");A&&(f=a[A],u=c.gradients,N=a.stops,n=b.radialReference,C(f)&&(a[A]=f={x1:f[0],y1:f[1],x2:f[2],y2:f[3],gradientUnits:"userSpaceOnUse"}),"radialGradient"===A&&n&&!E(f.gradientUnits)&&(l=f,f=H(f,c.getRadialAttr(n,l),{gradientUnits:"userSpaceOnUse"})),m(f,function(a,e){"id"!==e&&L.push(e,a)}),m(N,function(a){L.push(a)}),L=L.join(","),u[L]?t=u[L].attr("id"):(f.id=t=d.uniqueKey(),u[L]=J= c.createElement(A).attr(f).add(c.defs),J.radAttr=l,J.stops=[],N.forEach(function(a){0===a[1].indexOf("rgba")?(k=d.color(a[1]),O=k.get("rgb"),h=k.get("a")):(O=a[1],h=1);a=c.createElement("stop").attr({offset:a[0],"stop-color":O,"stop-opacity":h}).add(J);J.stops.push(a)})),r="url("+c.url+"#"+t+")",b.setAttribute(e,r),b.gradient=L,a.toString=function(){return r})})},applyTextOutline:function(a){var e=this.element,b;-1!==a.indexOf("contrast")&&(a=a.replace(/contrast/g,this.renderer.getContrast(e.style.fill))); a=a.split(" ");var c=a[a.length-1];if((b=a[0])&&"none"!==b&&d.svg){this.fakeTS=!0;a=[].slice.call(e.getElementsByTagName("tspan"));this.ySetter=this.xSetter;b=b.replace(/(^[\d\.]+)(.*?)$/g,function(a,e,b){return 2*e+b});this.removeTextOutline(a);var k=e.firstChild;a.forEach(function(a,f){0===f&&(a.setAttribute("x",e.getAttribute("x")),f=e.getAttribute("y"),a.setAttribute("y",f||0),null===f&&e.setAttribute("y",0));a=a.cloneNode(1);F(a,{"class":"highcharts-text-outline",fill:c,stroke:c,"stroke-width":b, "stroke-linejoin":"round"});e.insertBefore(a,k)})}},removeTextOutline:function(a){for(var e=a.length,b;e--;)b=a[e],"highcharts-text-outline"===b.getAttribute("class")&&x(a,this.element.removeChild(b))},symbolCustomAttribs:"x y width height r start end innerR anchorX anchorY rounded".split(" "),attr:function(a,e,b,c){var k=this.element,f,A=this,l,u,N=this.symbolCustomAttribs;if("string"===typeof a&&"undefined"!==typeof e){var O=a;a={};a[O]=e}"string"===typeof a?A=(this[a+"Getter"]||this._defaultGetter).call(this, a,k):(m(a,function(e,b){l=!1;c||J(this,b);this.symbolName&&-1!==d.inArray(b,N)&&(f||(this.symbolAttr(a),f=!0),l=!0);!this.rotation||"x"!==b&&"y"!==b||(this.doTransform=!0);l||(u=this[b+"Setter"]||this._defaultSetter,u.call(this,e,b,k),!this.styledMode&&this.shadows&&/^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(b)&&this.updateShadows(b,e,u))},this),this.afterSetters());b&&b.call(this);return A},afterSetters:function(){this.doTransform&&(this.updateTransform(),this.doTransform=!1)},updateShadows:function(a, e,b){for(var c=this.shadows,k=c.length;k--;)b.call(c[k],"height"===a?Math.max(e-(c[k].cutHeight||0),0):"d"===a?this.d:e,a,c[k])},addClass:function(a,e){var b=e?"":this.attr("class")||"";a=(a||"").split(/ /g).reduce(function(a,e){-1===b.indexOf(e)&&a.push(e);return a},b?[b]:[]).join(" ");a!==b&&this.attr("class",a);return this},hasClass:function(a){return-1!==(this.attr("class")||"").split(" ").indexOf(a)},removeClass:function(a){return this.attr("class",(this.attr("class")||"").replace(z(a)?new RegExp(" ?"+ a+" ?"):a,""))},symbolAttr:function(a){var e=this;"x y r start end width height innerR anchorX anchorY clockwise".split(" ").forEach(function(b){e[b]=q(a[b],e[b])});e.attr({d:e.renderer.symbols[e.symbolName](e.x,e.y,e.width,e.height,e)})},clip:function(a){return this.attr("clip-path",a?"url("+this.renderer.url+"#"+a.id+")":"none")},crisp:function(a,e){e=e||a.strokeWidth||0;var b=Math.round(e)%2/2;a.x=Math.floor(a.x||this.x||0)+b;a.y=Math.floor(a.y||this.y||0)+b;a.width=Math.floor((a.width||this.width|| 0)-2*b);a.height=Math.floor((a.height||this.height||0)-2*b);E(a.strokeWidth)&&(a.strokeWidth=e);return a},css:function(a){var e=this.styles,b={},c=this.element,k="",f=!e,A=["textOutline","textOverflow","width"];a&&a.color&&(a.fill=a.color);e&&m(a,function(a,c){a!==e[c]&&(b[c]=a,f=!0)});if(f){e&&(a=v(e,b));if(a)if(null===a.width||"auto"===a.width)delete this.textWidth;else if("text"===c.nodeName.toLowerCase()&&a.width)var u=this.textWidth=w(a.width);this.styles=a;u&&!L&&this.renderer.forExport&&delete a.width; if(c.namespaceURI===this.SVG_NS){var J=function(a,e){return"-"+e.toLowerCase()};m(a,function(a,e){-1===A.indexOf(e)&&(k+=e.replace(/([A-Z])/g,J)+":"+a+";")});k&&F(c,"style",k)}else l(c,a);this.added&&("text"===this.element.nodeName&&this.renderer.buildText(this),a&&a.textOutline&&this.applyTextOutline(a.textOutline))}return this},getStyle:function(a){return U.getComputedStyle(this.element||this,"").getPropertyValue(a)},strokeWidth:function(){if(!this.renderer.styledMode)return this["stroke-width"]|| 0;var a=this.getStyle("stroke-width"),e=0;if(a.indexOf("px")===a.length-2)e=w(a);else if(""!==a){var b=I.createElementNS(Q,"rect");F(b,{width:a,"stroke-width":0});this.element.parentNode.appendChild(b);e=b.getBBox().width;b.parentNode.removeChild(b)}return e},on:function(a,e){var b=this,c=b.element;r&&"click"===a?(c.ontouchstart=function(a){b.touchEventFired=Date.now();a.preventDefault();e.call(c,a)},c.onclick=function(a){(-1===U.navigator.userAgent.indexOf("Android")||1100<Date.now()-(b.touchEventFired|| 0))&&e.call(c,a)}):c["on"+a]=e;return this},setRadialReference:function(a){var e=this.renderer.gradients[this.element.gradient];this.element.radialReference=a;e&&e.radAttr&&e.animate(this.renderer.getRadialAttr(a,e.radAttr));return this},translate:function(a,e){return this.attr({translateX:a,translateY:e})},invert:function(a){this.inverted=a;this.updateTransform();return this},updateTransform:function(){var a=this.translateX||0,e=this.translateY||0,b=this.scaleX,c=this.scaleY,k=this.inverted,f=this.rotation, A=this.matrix,l=this.element;k&&(a+=this.width,e+=this.height);a=["translate("+a+","+e+")"];E(A)&&a.push("matrix("+A.join(",")+")");k?a.push("rotate(90) scale(-1,1)"):f&&a.push("rotate("+f+" "+q(this.rotationOriginX,l.getAttribute("x"),0)+" "+q(this.rotationOriginY,l.getAttribute("y")||0)+")");(E(b)||E(c))&&a.push("scale("+q(b,1)+" "+q(c,1)+")");a.length&&l.setAttribute("transform",a.join(" "))},toFront:function(){var a=this.element;a.parentNode.appendChild(a);return this},align:function(a,e,b){var c, k={};var f=this.renderer;var A=f.alignedObjects;var l,u;if(a){if(this.alignOptions=a,this.alignByTranslate=e,!b||z(b))this.alignTo=c=b||"renderer",x(A,this),A.push(this),b=null}else a=this.alignOptions,e=this.alignByTranslate,c=this.alignTo;b=q(b,f[c],f);c=a.align;f=a.verticalAlign;A=(b.x||0)+(a.x||0);var J=(b.y||0)+(a.y||0);"right"===c?l=1:"center"===c&&(l=2);l&&(A+=(b.width-(a.width||0))/l);k[e?"translateX":"x"]=Math.round(A);"bottom"===f?u=1:"middle"===f&&(u=2);u&&(J+=(b.height-(a.height||0))/ u);k[e?"translateY":"y"]=Math.round(J);this[this.placed?"animate":"attr"](k);this.placed=!0;this.alignAttr=k;return this},getBBox:function(a,e){var b,c=this.renderer,k=this.element,f=this.styles,A=this.textStr,l,u=c.cache,J=c.cacheKeys,h=k.namespaceURI===this.SVG_NS;e=q(e,this.rotation,0);var N=c.styledMode?k&&P.prototype.getStyle.call(k,"font-size"):f&&f.fontSize;if(E(A)){var n=A.toString();-1===n.indexOf("<")&&(n=n.replace(/[0-9]/g,"0"));n+=["",e,N,this.textWidth,f&&f.textOverflow].join()}n&&!a&& (b=u[n]);if(!b){if(h||c.forExport){try{(l=this.fakeTS&&function(a){[].forEach.call(k.querySelectorAll(".highcharts-text-outline"),function(e){e.style.display=a})})&&l("none"),b=k.getBBox?v({},k.getBBox()):{width:k.offsetWidth,height:k.offsetHeight},l&&l("")}catch(ea){""}if(!b||0>b.width)b={width:0,height:0}}else b=this.htmlGetBBox();c.isSVG&&(a=b.width,c=b.height,h&&(b.height=c={"11px,17":14,"13px,20":16}[f&&f.fontSize+","+Math.round(c)]||c),e&&(f=e*t,b.width=Math.abs(c*Math.sin(f))+Math.abs(a*Math.cos(f)), b.height=Math.abs(c*Math.cos(f))+Math.abs(a*Math.sin(f))));if(n&&0<b.height){for(;250<J.length;)delete u[J.shift()];u[n]||J.push(n);u[n]=b}}return b},show:function(a){return this.attr({visibility:a?"inherit":"visible"})},hide:function(a){a?this.attr({y:-9999}):this.attr({visibility:"hidden"});return this},fadeOut:function(a){var e=this;e.animate({opacity:0},{duration:a||150,complete:function(){e.attr({y:-9999})}})},add:function(a){var e=this.renderer,b=this.element;a&&(this.parentGroup=a);this.parentInverted= a&&a.inverted;"undefined"!==typeof this.textStr&&e.buildText(this);this.added=!0;if(!a||a.handleZ||this.zIndex)var c=this.zIndexSetter();c||(a?a.element:e.box).appendChild(b);if(this.onAdd)this.onAdd();return this},safeRemoveChild:function(a){var e=a.parentNode;e&&e.removeChild(a)},destroy:function(){var a=this,e=a.element||{},b=a.renderer,c=b.isSVG&&"SPAN"===e.nodeName&&a.parentGroup,k=e.ownerSVGElement,f=a.clipPath;e.onclick=e.onmouseout=e.onmouseover=e.onmousemove=e.point=null;J(a);f&&k&&([].forEach.call(k.querySelectorAll("[clip-path],[CLIP-PATH]"), function(a){-1<a.getAttribute("clip-path").indexOf(f.element.id)&&a.removeAttribute("clip-path")}),a.clipPath=f.destroy());if(a.stops){for(k=0;k<a.stops.length;k++)a.stops[k]=a.stops[k].destroy();a.stops=null}a.safeRemoveChild(e);for(b.styledMode||a.destroyShadows();c&&c.div&&0===c.div.childNodes.length;)e=c.parentGroup,a.safeRemoveChild(c.div),delete c.div,c=e;a.alignTo&&x(b.alignedObjects,a);m(a,function(e,b){a[b]&&a[b].parentGroup===a&&a[b].destroy&&a[b].destroy();delete a[b]})},shadow:function(a, e,b){var c=[],k,f=this.element;if(!a)this.destroyShadows();else if(!this.shadows){var A=q(a.width,3);var l=(a.opacity||.15)/A;var u=this.parentInverted?"(-1,-1)":"("+q(a.offsetX,1)+", "+q(a.offsetY,1)+")";for(k=1;k<=A;k++){var J=f.cloneNode(0);var h=2*A+1-2*k;F(J,{stroke:a.color||"#000000","stroke-opacity":l*k,"stroke-width":h,transform:"translate"+u,fill:"none"});J.setAttribute("class",(J.getAttribute("class")||"")+" highcharts-shadow");b&&(F(J,"height",Math.max(F(J,"height")-h,0)),J.cutHeight=h); e?e.element.appendChild(J):f.parentNode&&f.parentNode.insertBefore(J,f);c.push(J)}this.shadows=c}return this},destroyShadows:function(){(this.shadows||[]).forEach(function(a){this.safeRemoveChild(a)},this);this.shadows=void 0},xGetter:function(a){"circle"===this.element.nodeName&&("x"===a?a="cx":"y"===a&&(a="cy"));return this._defaultGetter(a)},_defaultGetter:function(a){a=q(this[a+"Value"],this[a],this.element?this.element.getAttribute(a):null,0);/^[\-0-9\.]+$/.test(a)&&(a=parseFloat(a));return a}, dSetter:function(a,e,b){a&&a.join&&(a=a.join(" "));/(NaN| {2}|^$)/.test(a)&&(a="M 0 0");this[e]!==a&&(b.setAttribute(e,a),this[e]=a)},dashstyleSetter:function(a){var e,b=this["stroke-width"];"inherit"===b&&(b=1);if(a=a&&a.toLowerCase()){a=a.replace("shortdashdotdot","3,1,1,1,1,1,").replace("shortdashdot","3,1,1,1").replace("shortdot","1,1,").replace("shortdash","3,1,").replace("longdash","8,3,").replace(/dot/g,"1,3,").replace("dash","4,3,").replace(/,$/,"").split(",");for(e=a.length;e--;)a[e]=w(a[e])* b;a=a.join(",").replace(/NaN/g,"none");this.element.setAttribute("stroke-dasharray",a)}},alignSetter:function(a){var e={left:"start",center:"middle",right:"end"};e[a]&&(this.alignValue=a,this.element.setAttribute("text-anchor",e[a]))},opacitySetter:function(a,e,b){this[e]=a;b.setAttribute(e,a)},titleSetter:function(a){var e=this.element.getElementsByTagName("title")[0];e||(e=I.createElementNS(this.SVG_NS,"title"),this.element.appendChild(e));e.firstChild&&e.removeChild(e.firstChild);e.appendChild(I.createTextNode(String(q(a, "")).replace(/<[^>]*>/g,"").replace(/&lt;/g,"<").replace(/&gt;/g,">")))},textSetter:function(a){a!==this.textStr&&(delete this.bBox,delete this.textPxLength,this.textStr=a,this.added&&this.renderer.buildText(this))},setTextPath:function(a,e){var b=this.element,c={textAnchor:"text-anchor"},k=!1,f=this.textPathWrapper,A=!f;e=H(!0,{enabled:!0,attributes:{dy:-5,startOffset:"50%",textAnchor:"middle"}},e);var l=e.attributes;if(a&&e&&e.enabled){f&&null===f.element.parentNode?(A=!0,f=f.destroy()):f&&this.removeTextOutline.call(f.parentGroup, [].slice.call(b.getElementsByTagName("tspan")));this.options&&this.options.padding&&(l.dx=-this.options.padding);f||(this.textPathWrapper=f=this.renderer.createElement("textPath"),k=!0);var u=f.element;(e=a.element.getAttribute("id"))||a.element.setAttribute("id",e=d.uniqueKey());if(A)for(a=b.getElementsByTagName("tspan");a.length;)a[0].setAttribute("y",0),B(l.dx)&&a[0].setAttribute("x",-l.dx),u.appendChild(a[0]);k&&f.add({element:this.text?this.text.element:b});u.setAttributeNS("http://www.w3.org/1999/xlink", "href",this.renderer.url+"#"+e);E(l.dy)&&(u.parentNode.setAttribute("dy",l.dy),delete l.dy);E(l.dx)&&(u.parentNode.setAttribute("dx",l.dx),delete l.dx);m(l,function(a,e){u.setAttribute(c[e]||e,a)});b.removeAttribute("transform");this.removeTextOutline.call(f,[].slice.call(b.getElementsByTagName("tspan")));this.text&&!this.renderer.styledMode&&this.attr({fill:"none","stroke-width":0});this.applyTextOutline=this.updateTransform=G}else f&&(delete this.updateTransform,delete this.applyTextOutline,this.destroyTextPath(b, a),this.updateTransform(),this.options.rotation&&this.applyTextOutline(this.options.style.textOutline));return this},destroyTextPath:function(a,e){var b=a.getElementsByTagName("text")[0];if(b){if(b.removeAttribute("dx"),b.removeAttribute("dy"),e.element.setAttribute("id",""),b.getElementsByTagName("textPath").length){for(a=this.textPathWrapper.element.childNodes;a.length;)b.appendChild(a[0]);b.removeChild(this.textPathWrapper.element)}}else if(a.getAttribute("dx")||a.getAttribute("dy"))a.removeAttribute("dx"), a.removeAttribute("dy");this.textPathWrapper=this.textPathWrapper.destroy()},fillSetter:function(a,e,b){"string"===typeof a?b.setAttribute(e,a):a&&this.complexColor(a,e,b)},visibilitySetter:function(a,e,b){"inherit"===a?b.removeAttribute(e):this[e]!==a&&b.setAttribute(e,a);this[e]=a},zIndexSetter:function(a,e){var b=this.renderer,c=this.parentGroup,k=(c||b).element||b.box,f=this.element,A=!1;b=k===b.box;var l=this.added;var u;E(a)?(f.setAttribute("data-z-index",a),a=+a,this[e]===a&&(l=!1)):E(this[e])&& f.removeAttribute("data-z-index");this[e]=a;if(l){(a=this.zIndex)&&c&&(c.handleZ=!0);e=k.childNodes;for(u=e.length-1;0<=u&&!A;u--){c=e[u];l=c.getAttribute("data-z-index");var J=!E(l);if(c!==f)if(0>a&&J&&!b&&!u)k.insertBefore(f,e[u]),A=!0;else if(w(l)<=a||J&&(!E(a)||0<=a))k.insertBefore(f,e[u+1]||null),A=!0}A||(k.insertBefore(f,e[b?3:0]||null),A=!0)}return A},_defaultSetter:function(a,e,b){b.setAttribute(e,a)}});P.prototype.yGetter=P.prototype.xGetter;P.prototype.translateXSetter=P.prototype.translateYSetter= P.prototype.rotationSetter=P.prototype.verticalAlignSetter=P.prototype.rotationOriginXSetter=P.prototype.rotationOriginYSetter=P.prototype.scaleXSetter=P.prototype.scaleYSetter=P.prototype.matrixSetter=function(a,e){this[e]=a;this.doTransform=!0};P.prototype["stroke-widthSetter"]=P.prototype.strokeSetter=function(a,e,b){this[e]=a;this.stroke&&this["stroke-width"]?(P.prototype.fillSetter.call(this,this.stroke,"stroke",b),b.setAttribute("stroke-width",this["stroke-width"]),this.hasStroke=!0):"stroke-width"=== e&&0===a&&this.hasStroke?(b.removeAttribute("stroke"),this.hasStroke=!1):this.renderer.styledMode&&this["stroke-width"]&&(b.setAttribute("stroke-width",this["stroke-width"]),this.hasStroke=!0)};g=d.SVGRenderer=function(){this.init.apply(this,arguments)};v(g.prototype,{Element:P,SVG_NS:Q,init:function(a,b,c,k,A,J,h){var n=this.createElement("svg").attr({version:"1.1","class":"highcharts-root"});h||n.css(this.getStyle(k));k=n.element;a.appendChild(k);F(a,"dir","ltr");-1===a.innerHTML.indexOf("xmlns")&& F(k,"xmlns",this.SVG_NS);this.isSVG=!0;this.box=k;this.boxWrapper=n;this.alignedObjects=[];this.url=(e||u)&&I.getElementsByTagName("base").length?U.location.href.split("#")[0].replace(/<[^>]*>/g,"").replace(/([\('\)])/g,"\\$1").replace(/ /g,"%20"):"";this.createElement("desc").add().element.appendChild(I.createTextNode("Created with Highcharts 8.0.0"));this.defs=this.createElement("defs").add();this.allowHTML=J;this.forExport=A;this.styledMode=h;this.gradients={};this.cache={};this.cacheKeys=[];this.imgCount= 0;this.setSize(b,c,!1);var t;e&&a.getBoundingClientRect&&(b=function(){l(a,{left:0,top:0});t=a.getBoundingClientRect();l(a,{left:Math.ceil(t.left)-t.left+"px",top:Math.ceil(t.top)-t.top+"px"})},b(),this.unSubPixelFix=f(U,"resize",b))},definition:function(a){function e(a,c){var k;h(a).forEach(function(a){var f=b.createElement(a.tagName),A={};m(a,function(a,e){"tagName"!==e&&"children"!==e&&"textContent"!==e&&(A[e]=a)});f.attr(A);f.add(c||b.defs);a.textContent&&f.element.appendChild(I.createTextNode(a.textContent)); e(a.children||[],f);k=f});return k}var b=this;return e(a)},getStyle:function(a){return this.style=v({fontFamily:'"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif',fontSize:"12px"},a)},setStyle:function(a){this.boxWrapper.css(this.getStyle(a))},isHidden:function(){return!this.boxWrapper.getBBox().width},destroy:function(){var a=this.defs;this.box=null;this.boxWrapper=this.boxWrapper.destroy();D(this.gradients||{});this.gradients=null;a&&(this.defs=a.destroy());this.unSubPixelFix&& this.unSubPixelFix();return this.alignedObjects=null},createElement:function(a){var e=new this.Element;e.init(this,a);return e},draw:G,getRadialAttr:function(a,e){return{cx:a[0]-a[2]/2+e.cx*a[2],cy:a[1]-a[2]/2+e.cy*a[2],r:e.r*a[2]}},truncate:function(a,e,b,c,k,f,A){var l=this,u=a.rotation,J,h=c?1:0,n=(b||c).length,t=n,L=[],H=function(a){e.firstChild&&e.removeChild(e.firstChild);a&&e.appendChild(I.createTextNode(a))},d=function(f,u){u=u||f;if("undefined"===typeof L[u])if(e.getSubStringLength)try{L[u]= k+e.getSubStringLength(0,c?u+1:u)}catch(ha){""}else l.getSpanWidth&&(H(A(b||c,f)),L[u]=k+l.getSpanWidth(a,e));return L[u]},r;a.rotation=0;var G=d(e.textContent.length);if(r=k+G>f){for(;h<=n;)t=Math.ceil((h+n)/2),c&&(J=A(c,t)),G=d(t,J&&J.length-1),h===n?h=n+1:G>f?n=t-1:h=t;0===n?H(""):b&&n===b.length-1||H(J||A(b||c,t))}c&&c.splice(0,t);a.actualWidth=G;a.rotation=u;return r},escapes:{"&":"&amp;","<":"&lt;",">":"&gt;","'":"&#39;",'"':"&quot;"},buildText:function(a){var e=a.element,b=this,c=b.forExport, k=q(a.textStr,"").toString(),f=-1!==k.indexOf("<"),A=e.childNodes,u,J=F(e,"x"),h=a.styles,n=a.textWidth,t=h&&h.lineHeight,H=h&&h.textOutline,d=h&&"ellipsis"===h.textOverflow,r=h&&"nowrap"===h.whiteSpace,G=h&&h.fontSize,g,O=A.length;h=n&&!a.added&&this.box;var V=function(a){var c;b.styledMode||(c=/(px|em)$/.test(a&&a.style.fontSize)?a.style.fontSize:G||b.style.fontSize||12);return t?w(t):b.fontMetrics(c,a.getAttribute("style")?a:e).h},p=function(a,e){m(b.escapes,function(b,c){e&&-1!==e.indexOf(b)|| (a=a.toString().replace(new RegExp(b,"g"),c))});return a},v=function(a,e){var b=a.indexOf("<");a=a.substring(b,a.indexOf(">")-b);b=a.indexOf(e+"=");if(-1!==b&&(b=b+e.length+1,e=a.charAt(b),'"'===e||"'"===e))return a=a.substring(b+1),a.substring(0,a.indexOf(e))},z=/<br.*?>/g;var U=[k,d,r,t,H,G,n].join();if(U!==a.textCache){for(a.textCache=U;O--;)e.removeChild(A[O]);f||H||d||n||-1!==k.indexOf(" ")&&(!r||z.test(k))?(h&&h.appendChild(e),f?(k=b.styledMode?k.replace(/<(b|strong)>/g,'<span class="highcharts-strong">').replace(/<(i|em)>/g, '<span class="highcharts-emphasized">'):k.replace(/<(b|strong)>/g,'<span style="font-weight:bold">').replace(/<(i|em)>/g,'<span style="font-style:italic">'),k=k.replace(/<a/g,"<span").replace(/<\/(b|strong|i|em|a)>/g,"</span>").split(z)):k=[k],k=k.filter(function(a){return""!==a}),k.forEach(function(k,f){var A=0,h=0;k=k.replace(/^\s+|\s+$/g,"").replace(/<span/g,"|||<span").replace(/<\/span>/g,"</span>|||");var t=k.split("|||");t.forEach(function(k){if(""!==k||1===t.length){var H={},N=I.createElementNS(b.SVG_NS, "tspan"),q,m;(q=v(k,"class"))&&F(N,"class",q);if(q=v(k,"style"))q=q.replace(/(;| |^)color([ :])/,"$1fill$2"),F(N,"style",q);(m=v(k,"href"))&&!c&&(F(N,"onclick",'location.href="'+m+'"'),F(N,"class","highcharts-anchor"),b.styledMode||l(N,{cursor:"pointer"}));k=p(k.replace(/<[a-zA-Z\/](.|\n)*?>/g,"")||" ");if(" "!==k){N.appendChild(I.createTextNode(k));A?H.dx=0:f&&null!==J&&(H.x=J);F(N,H);e.appendChild(N);!A&&g&&(!L&&c&&l(N,{display:"block"}),F(N,"dy",V(N)));if(n){var w=k.replace(/([^\^])-/g,"$1- ").split(" "); H=!r&&(1<t.length||f||1<w.length);m=0;var ba=V(N);if(d)u=b.truncate(a,N,k,void 0,0,Math.max(0,n-parseInt(G||12,10)),function(a,e){return a.substring(0,e)+"\u2026"});else if(H)for(;w.length;)w.length&&!r&&0<m&&(N=I.createElementNS(Q,"tspan"),F(N,{dy:ba,x:J}),q&&F(N,"style",q),N.appendChild(I.createTextNode(w.join(" ").replace(/- /g,"-"))),e.appendChild(N)),b.truncate(a,N,null,w,0===m?h:0,n,function(a,e){return w.slice(0,e).join(" ").replace(/- /g,"-")}),h=a.actualWidth,m++}A++}}});g=g||e.childNodes.length}), d&&u&&a.attr("title",p(a.textStr,["&lt;","&gt;"])),h&&h.removeChild(e),H&&a.applyTextOutline&&a.applyTextOutline(H)):e.appendChild(I.createTextNode(p(k)))}},getContrast:function(e){e=a(e).rgba;e[0]*=1;e[1]*=1.2;e[2]*=.5;return 459<e[0]+e[1]+e[2]?"#000000":"#FFFFFF"},button:function(a,e,b,c,A,l,u,J,h,n){var t=this.label(a,e,b,h,null,null,n,null,"button"),L=0,d=this.styledMode;t.attr(H({padding:8,r:2},A));if(!d){A=H({fill:"#f7f7f7",stroke:"#cccccc","stroke-width":1,style:{color:"#333333",cursor:"pointer", fontWeight:"normal"}},A);var r=A.style;delete A.style;l=H(A,{fill:"#e6e6e6"},l);var G=l.style;delete l.style;u=H(A,{fill:"#e6ebf5",style:{color:"#000000",fontWeight:"bold"}},u);var N=u.style;delete u.style;J=H(A,{style:{color:"#cccccc"}},J);var Q=J.style;delete J.style}f(t.element,k?"mouseover":"mouseenter",function(){3!==L&&t.setState(1)});f(t.element,k?"mouseout":"mouseleave",function(){3!==L&&t.setState(L)});t.setState=function(a){1!==a&&(t.state=L=a);t.removeClass(/highcharts-button-(normal|hover|pressed|disabled)/).addClass("highcharts-button-"+ ["normal","hover","pressed","disabled"][a||0]);d||t.attr([A,l,u,J][a||0]).css([r,G,N,Q][a||0])};d||t.attr(A).css(v({cursor:"default"},r));return t.on("click",function(a){3!==L&&c.call(t,a)})},crispLine:function(a,e){a[1]===a[4]&&(a[1]=a[4]=Math.round(a[1])-e%2/2);a[2]===a[5]&&(a[2]=a[5]=Math.round(a[2])+e%2/2);return a},path:function(a){var e=this.styledMode?{}:{fill:"none"};C(a)?e.d=a:p(a)&&v(e,a);return this.createElement("path").attr(e)},circle:function(a,e,b){a=p(a)?a:"undefined"===typeof a?{}: {x:a,y:e,r:b};e=this.createElement("circle");e.xSetter=e.ySetter=function(a,e,b){b.setAttribute("c"+e,a)};return e.attr(a)},arc:function(a,e,b,c,k,f){p(a)?(c=a,e=c.y,b=c.r,a=c.x):c={innerR:c,start:k,end:f};a=this.symbol("arc",a,e,b,b,c);a.r=b;return a},rect:function(a,e,b,c,k,f){k=p(a)?a.r:k;var A=this.createElement("rect");a=p(a)?a:"undefined"===typeof a?{}:{x:a,y:e,width:Math.max(b,0),height:Math.max(c,0)};this.styledMode||("undefined"!==typeof f&&(a.strokeWidth=f,a=A.crisp(a)),a.fill="none");k&& (a.r=k);A.rSetter=function(a,e,b){A.r=a;F(b,{rx:a,ry:a})};A.rGetter=function(){return A.r};return A.attr(a)},setSize:function(a,e,b){var c=this.alignedObjects,k=c.length;this.width=a;this.height=e;for(this.boxWrapper.animate({width:a,height:e},{step:function(){this.attr({viewBox:"0 0 "+this.attr("width")+" "+this.attr("height")})},duration:q(b,!0)?void 0:0});k--;)c[k].align()},g:function(a){var e=this.createElement("g");return a?e.attr({"class":"highcharts-"+a}):e},image:function(a,e,b,c,k,A){var l= {preserveAspectRatio:"none"},u=function(a,e){a.setAttributeNS?a.setAttributeNS("http://www.w3.org/1999/xlink","href",e):a.setAttribute("hc-svg-href",e)},J=function(e){u(h.element,a);A.call(h,e)};1<arguments.length&&v(l,{x:e,y:b,width:c,height:k});var h=this.createElement("image").attr(l);A?(u(h.element,"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="),l=new U.Image,f(l,"load",J),l.src=a,l.complete&&J({})):u(h.element,a);return h},symbol:function(a,e,c,k,f,A){var u=this, J=/^url\((.*?)\)$/,h=J.test(a),t=!h&&(this.symbols[a]?a:"circle"),L=t&&this.symbols[t],H=E(e)&&L&&L.call(this.symbols,Math.round(e),Math.round(c),k,f,A);if(L){var d=this.path(H);u.styledMode||d.attr("fill","none");v(d,{symbolName:t,x:e,y:c,width:k,height:f});A&&v(d,A)}else if(h){var r=a.match(J)[1];d=this.image(r);d.imgwidth=q(V[r]&&V[r].width,A&&A.width);d.imgheight=q(V[r]&&V[r].height,A&&A.height);var G=function(){d.attr({width:d.width,height:d.height})};["width","height"].forEach(function(a){d[a+ "Setter"]=function(a,e){var b={},c=this["img"+e],k="width"===e?"translateX":"translateY";this[e]=a;E(c)&&(A&&"within"===A.backgroundSize&&this.width&&this.height&&(c=Math.round(c*Math.min(this.width/this.imgwidth,this.height/this.imgheight))),this.element&&this.element.setAttribute(e,c),this.alignByTranslate||(b[k]=((this[e]||0)-c)/2,this.attr(b)))}});E(e)&&d.attr({x:e,y:c});d.isImg=!0;E(d.imgwidth)&&E(d.imgheight)?G():(d.attr({width:0,height:0}),n("img",{onload:function(){var a=b[u.chartIndex];0=== this.width&&(l(this,{position:"absolute",top:"-999em"}),I.body.appendChild(this));V[r]={width:this.width,height:this.height};d.imgwidth=this.width;d.imgheight=this.height;d.element&&G();this.parentNode&&this.parentNode.removeChild(this);u.imgCount--;if(!u.imgCount&&a&&a.onload)a.onload()},src:r}),this.imgCount++)}return d},symbols:{circle:function(a,e,b,c){return this.arc(a+b/2,e+c/2,b/2,c/2,{start:.5*Math.PI,end:2.5*Math.PI,open:!1})},square:function(a,e,b,c){return["M",a,e,"L",a+b,e,a+b,e+c,a,e+ c,"Z"]},triangle:function(a,e,b,c){return["M",a+b/2,e,"L",a+b,e+c,a,e+c,"Z"]},"triangle-down":function(a,e,b,c){return["M",a,e,"L",a+b,e,a+b/2,e+c,"Z"]},diamond:function(a,e,b,c){return["M",a+b/2,e,"L",a+b,e+c/2,a+b/2,e+c,a,e+c/2,"Z"]},arc:function(a,e,b,c,k){var f=k.start,A=k.r||b,u=k.r||c||b,l=k.end-.001;b=k.innerR;c=q(k.open,.001>Math.abs(k.end-k.start-2*Math.PI));var J=Math.cos(f),h=Math.sin(f),n=Math.cos(l);l=Math.sin(l);f=q(k.longArc,.001>k.end-f-Math.PI?0:1);A=["M",a+A*J,e+u*h,"A",A,u,0,f, q(k.clockwise,1),a+A*n,e+u*l];E(b)&&A.push(c?"M":"L",a+b*n,e+b*l,"A",b,b,0,f,E(k.clockwise)?1-k.clockwise:0,a+b*J,e+b*h);A.push(c?"":"Z");return A},callout:function(a,e,b,c,k){var f=Math.min(k&&k.r||0,b,c),A=f+6,l=k&&k.anchorX;k=k&&k.anchorY;var u=["M",a+f,e,"L",a+b-f,e,"C",a+b,e,a+b,e,a+b,e+f,"L",a+b,e+c-f,"C",a+b,e+c,a+b,e+c,a+b-f,e+c,"L",a+f,e+c,"C",a,e+c,a,e+c,a,e+c-f,"L",a,e+f,"C",a,e,a,e,a+f,e];l&&l>b?k>e+A&&k<e+c-A?u.splice(13,3,"L",a+b,k-6,a+b+6,k,a+b,k+6,a+b,e+c-f):u.splice(13,3,"L",a+b, c/2,l,k,a+b,c/2,a+b,e+c-f):l&&0>l?k>e+A&&k<e+c-A?u.splice(33,3,"L",a,k+6,a-6,k,a,k-6,a,e+f):u.splice(33,3,"L",a,c/2,l,k,a,c/2,a,e+f):k&&k>c&&l>a+A&&l<a+b-A?u.splice(23,3,"L",l+6,e+c,l,e+c+6,l-6,e+c,a+f,e+c):k&&0>k&&l>a+A&&l<a+b-A&&u.splice(3,3,"L",l-6,e,l,e-6,l+6,e,b-f,e);return u}},clipRect:function(a,e,b,c){var k=d.uniqueKey()+"-",f=this.createElement("clipPath").attr({id:k}).add(this.defs);a=this.rect(a,e,b,c,0).add(f);a.id=k;a.clipPath=f;a.count=0;return a},text:function(a,e,b,c){var k={};if(c&& (this.allowHTML||!this.forExport))return this.html(a,e,b);k.x=Math.round(e||0);b&&(k.y=Math.round(b));E(a)&&(k.text=a);a=this.createElement("text").attr(k);c||(a.xSetter=function(a,e,b){var c=b.getElementsByTagName("tspan"),k=b.getAttribute(e),f;for(f=0;f<c.length;f++){var A=c[f];A.getAttribute(e)===k&&A.setAttribute(e,a)}b.setAttribute(e,a)});return a},fontMetrics:function(a,e){a=!this.styledMode&&/px/.test(a)||!U.getComputedStyle?a||e&&e.style&&e.style.fontSize||this.style&&this.style.fontSize: e&&P.prototype.getStyle.call(e,"font-size");a=/px/.test(a)?w(a):12;e=24>a?a+3:Math.round(1.2*a);return{h:e,b:Math.round(.8*e),f:a}},rotCorr:function(a,e,b){var c=a;e&&b&&(c=Math.max(c*Math.cos(e*t),4));return{x:-a/3*Math.sin(e*t),y:c}},label:function(a,e,b,c,k,f,l,u,J){var h=this,n=h.styledMode,t=h.g("button"!==J&&"label"),L=t.text=h.text("",0,0,l).attr({zIndex:1}),d,r,G=0,Q=3,q=0,m,I,w,N,g,V={},p,ba,z=/^url\((.*?)\)$/.test(c),U=n||z,x=function(){return n?d.strokeWidth()%2/2:(p?parseInt(p,10):0)% 2/2};J&&t.addClass("highcharts-"+J);var O=function(){var a=L.element.style,e={};r=("undefined"===typeof m||"undefined"===typeof I||g)&&E(L.textStr)&&L.getBBox();t.width=(m||r.width||0)+2*Q+q;t.height=(I||r.height||0)+2*Q;ba=Q+Math.min(h.fontMetrics(a&&a.fontSize,L).b,r?r.height:Infinity);U&&(d||(t.box=d=h.symbols[c]||z?h.symbol(c):h.rect(),d.addClass(("button"===J?"":"highcharts-label-box")+(J?" highcharts-"+J+"-box":"")),d.add(t),a=x(),e.x=a,e.y=(u?-ba:0)+a),e.width=Math.round(t.width),e.height= Math.round(t.height),d.attr(v(e,V)),V={})};var ca=function(){var a=q+Q;var e=u?0:ba;E(m)&&r&&("center"===g||"right"===g)&&(a+={center:.5,right:1}[g]*(m-r.width));if(a!==L.x||e!==L.y)L.attr("x",a),L.hasBoxWidthChanged&&(r=L.getBBox(!0),O()),"undefined"!==typeof e&&L.attr("y",e);L.x=a;L.y=e};var C=function(a,e){d?d.attr(a,e):V[a]=e};t.onAdd=function(){L.add(t);t.attr({text:a||0===a?a:"",x:e,y:b});d&&E(k)&&t.attr({anchorX:k,anchorY:f})};t.widthSetter=function(a){m=B(a)?a:null};t.heightSetter=function(a){I= a};t["text-alignSetter"]=function(a){g=a};t.paddingSetter=function(a){E(a)&&a!==Q&&(Q=t.padding=a,ca())};t.paddingLeftSetter=function(a){E(a)&&a!==q&&(q=a,ca())};t.alignSetter=function(a){a={left:0,center:.5,right:1}[a];a!==G&&(G=a,r&&t.attr({x:w}))};t.textSetter=function(a){"undefined"!==typeof a&&L.attr({text:a});O();ca()};t["stroke-widthSetter"]=function(a,e){a&&(U=!0);p=this["stroke-width"]=a;C(e,a)};n?t.rSetter=function(a,e){C(e,a)}:t.strokeSetter=t.fillSetter=t.rSetter=function(a,e){"r"!==e&& ("fill"===e&&a&&(U=!0),t[e]=a);C(e,a)};t.anchorXSetter=function(a,e){k=t.anchorX=a;C(e,Math.round(a)-x()-w)};t.anchorYSetter=function(a,e){f=t.anchorY=a;C(e,a-N)};t.xSetter=function(a){t.x=a;G&&(a-=G*((m||r.width)+2*Q),t["forceAnimate:x"]=!0);w=Math.round(a);t.attr("translateX",w)};t.ySetter=function(a){N=t.y=Math.round(a);t.attr("translateY",N)};var T=t.css;l={css:function(a){if(a){var e={};a=H(a);t.textProps.forEach(function(b){"undefined"!==typeof a[b]&&(e[b]=a[b],delete a[b])});L.css(e);"width"in e&&O();"fontSize"in e&&(O(),ca())}return T.call(t,a)},getBBox:function(){return{width:r.width+2*Q,height:r.height+2*Q,x:r.x-Q,y:r.y-Q}},destroy:function(){A(t.element,"mouseenter");A(t.element,"mouseleave");L&&(L=L.destroy());d&&(d=d.destroy());P.prototype.destroy.call(t);t=h=O=ca=C=null}};n||(l.shadow=function(a){a&&(O(),d&&d.shadow(a));return t});return v(t,l)}});d.Renderer=g});K(y,"parts/Html.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var M=g.attr,F=g.defined,E=g.extend, D=g.pick,x=g.pInt,v=d.createElement,C=d.css,B=d.isFirefox,p=d.isMS,z=d.isWebKit,m=d.SVGElement;g=d.SVGRenderer;var q=d.win;E(m.prototype,{htmlCss:function(d){var h="SPAN"===this.element.tagName&&d&&"width"in d,f=D(h&&d.width,void 0);if(h){delete d.width;this.textWidth=f;var c=!0}d&&"ellipsis"===d.textOverflow&&(d.whiteSpace="nowrap",d.overflow="hidden");this.styles=E(this.styles,d);C(this.element,d);c&&this.htmlUpdateTransform();return this},htmlGetBBox:function(){var d=this.element;return{x:d.offsetLeft, y:d.offsetTop,width:d.offsetWidth,height:d.offsetHeight}},htmlUpdateTransform:function(){if(this.added){var d=this.renderer,h=this.element,f=this.translateX||0,c=this.translateY||0,b=this.x||0,a=this.y||0,l=this.textAlign||"left",n={left:0,center:.5,right:1}[l],t=this.styles,q=t&&t.whiteSpace;C(h,{marginLeft:f,marginTop:c});!d.styledMode&&this.shadows&&this.shadows.forEach(function(a){C(a,{marginLeft:f+1,marginTop:c+1})});this.inverted&&[].forEach.call(h.childNodes,function(a){d.invertChild(a,h)}); if("SPAN"===h.tagName){t=this.rotation;var r=this.textWidth&&x(this.textWidth),e=[t,l,h.innerHTML,this.textWidth,this.textAlign].join(),k;(k=r!==this.oldTextWidth)&&!(k=r>this.oldTextWidth)&&((k=this.textPxLength)||(C(h,{width:"",whiteSpace:q||"nowrap"}),k=h.offsetWidth),k=k>r);k&&(/[ \-]/.test(h.textContent||h.innerText)||"ellipsis"===h.style.textOverflow)?(C(h,{width:r+"px",display:"block",whiteSpace:q||"normal"}),this.oldTextWidth=r,this.hasBoxWidthChanged=!0):this.hasBoxWidthChanged=!1;e!==this.cTT&& (q=d.fontMetrics(h.style.fontSize,h).b,!F(t)||t===(this.oldRotation||0)&&l===this.oldAlign||this.setSpanRotation(t,n,q),this.getSpanCorrection(!F(t)&&this.textPxLength||h.offsetWidth,q,n,t,l));C(h,{left:b+(this.xCorr||0)+"px",top:a+(this.yCorr||0)+"px"});this.cTT=e;this.oldRotation=t;this.oldAlign=l}}else this.alignOnAdd=!0},setSpanRotation:function(d,h,f){var c={},b=this.renderer.getTransformKey();c[b]=c.transform="rotate("+d+"deg)";c[b+(B?"Origin":"-origin")]=c.transformOrigin=100*h+"% "+f+"px"; C(this.element,c)},getSpanCorrection:function(d,h,f){this.xCorr=-d*f;this.yCorr=-h}});E(g.prototype,{getTransformKey:function(){return p&&!/Edge/.test(q.navigator.userAgent)?"-ms-transform":z?"-webkit-transform":B?"MozTransform":q.opera?"-o-transform":""},html:function(d,h,f){var c=this.createElement("span"),b=c.element,a=c.renderer,l=a.isSVG,n=function(a,b){["opacity","visibility"].forEach(function(c){a[c+"Setter"]=function(e,k,f){var l=a.div?a.div.style:b;m.prototype[c+"Setter"].call(this,e,k,f); l&&(l[k]=e)}});a.addedSetters=!0};c.textSetter=function(a){a!==b.innerHTML&&(delete this.bBox,delete this.oldTextWidth);this.textStr=a;b.innerHTML=D(a,"");c.doTransform=!0};l&&n(c,c.element.style);c.xSetter=c.ySetter=c.alignSetter=c.rotationSetter=function(a,b){"align"===b&&(b="textAlign");c[b]=a;c.doTransform=!0};c.afterSetters=function(){this.doTransform&&(this.htmlUpdateTransform(),this.doTransform=!1)};c.attr({text:d,x:Math.round(h),y:Math.round(f)}).css({position:"absolute"});a.styledMode||c.css({fontFamily:this.style.fontFamily, fontSize:this.style.fontSize});b.style.whiteSpace="nowrap";c.css=c.htmlCss;l&&(c.add=function(f){var l=a.box.parentNode,h=[];if(this.parentGroup=f){var e=f.div;if(!e){for(;f;)h.push(f),f=f.parentGroup;h.reverse().forEach(function(a){function b(e,b){a[b]=e;"translateX"===b?f.left=e+"px":f.top=e+"px";a.doTransform=!0}var k=M(a.element,"class");e=a.div=a.div||v("div",k?{className:k}:void 0,{position:"absolute",left:(a.translateX||0)+"px",top:(a.translateY||0)+"px",display:a.display,opacity:a.opacity, pointerEvents:a.styles&&a.styles.pointerEvents},e||l);var f=e.style;E(a,{classSetter:function(a){return function(e){this.element.setAttribute("class",e);a.className=e}}(e),on:function(){h[0].div&&c.on.apply({element:h[0].div},arguments);return a},translateXSetter:b,translateYSetter:b});a.addedSetters||n(a)})}}else e=l;e.appendChild(b);c.added=!0;c.alignOnAdd&&c.htmlUpdateTransform();return c});return c}})});K(y,"parts/Time.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var M=g.defined, F=g.extend,E=g.isObject,D=g.objectEach,x=g.pad,v=g.pick,C=g.splat,B=d.merge,p=d.timeUnits,z=d.win;d.Time=function(d){this.update(d,!1)};d.Time.prototype={defaultOptions:{Date:void 0,getTimezoneOffset:void 0,timezone:void 0,timezoneOffset:0,useUTC:!0},update:function(d){var q=v(d&&d.useUTC,!0),m=this;this.options=d=B(!0,this.options||{},d);this.Date=d.Date||z.Date||Date;this.timezoneOffset=(this.useUTC=q)&&d.timezoneOffset;this.getTimezoneOffset=this.timezoneOffsetFunction();(this.variableTimezone= !(q&&!d.getTimezoneOffset&&!d.timezone))||this.timezoneOffset?(this.get=function(h,f){var c=f.getTime(),b=c-m.getTimezoneOffset(f);f.setTime(b);h=f["getUTC"+h]();f.setTime(c);return h},this.set=function(h,f,c){if("Milliseconds"===h||"Seconds"===h||"Minutes"===h&&0===f.getTimezoneOffset()%60)f["set"+h](c);else{var b=m.getTimezoneOffset(f);b=f.getTime()-b;f.setTime(b);f["setUTC"+h](c);h=m.getTimezoneOffset(f);b=f.getTime()+h;f.setTime(b)}}):q?(this.get=function(h,f){return f["getUTC"+h]()},this.set= function(h,f,c){return f["setUTC"+h](c)}):(this.get=function(h,f){return f["get"+h]()},this.set=function(h,f,c){return f["set"+h](c)})},makeTime:function(m,q,g,h,f,c){if(this.useUTC){var b=this.Date.UTC.apply(0,arguments);var a=this.getTimezoneOffset(b);b+=a;var l=this.getTimezoneOffset(b);a!==l?b+=l-a:a-36E5!==this.getTimezoneOffset(b-36E5)||d.isSafari||(b-=36E5)}else b=(new this.Date(m,q,v(g,1),v(h,0),v(f,0),v(c,0))).getTime();return b},timezoneOffsetFunction:function(){var m=this,q=this.options, g=z.moment;if(!this.useUTC)return function(h){return 6E4*(new Date(h)).getTimezoneOffset()};if(q.timezone){if(g)return function(h){return 6E4*-g.tz(h,q.timezone).utcOffset()};d.error(25)}return this.useUTC&&q.getTimezoneOffset?function(h){return 6E4*q.getTimezoneOffset(h)}:function(){return 6E4*(m.timezoneOffset||0)}},dateFormat:function(m,q,g){if(!M(q)||isNaN(q))return d.defaultOptions.lang.invalidDate||"";m=v(m,"%Y-%m-%d %H:%M:%S");var h=this,f=new this.Date(q),c=this.get("Hours",f),b=this.get("Day", f),a=this.get("Date",f),l=this.get("Month",f),n=this.get("FullYear",f),t=d.defaultOptions.lang,I=t.weekdays,r=t.shortWeekdays;f=F({a:r?r[b]:I[b].substr(0,3),A:I[b],d:x(a),e:x(a,2," "),w:b,b:t.shortMonths[l],B:t.months[l],m:x(l+1),o:l+1,y:n.toString().substr(2,2),Y:n,H:x(c),k:c,I:x(c%12||12),l:c%12||12,M:x(h.get("Minutes",f)),p:12>c?"AM":"PM",P:12>c?"am":"pm",S:x(f.getSeconds()),L:x(Math.floor(q%1E3),3)},d.dateFormats);D(f,function(a,b){for(;-1!==m.indexOf("%"+b);)m=m.replace("%"+b,"function"===typeof a? a.call(h,q):a)});return g?m.substr(0,1).toUpperCase()+m.substr(1):m},resolveDTLFormat:function(d){return E(d,!0)?d:(d=C(d),{main:d[0],from:d[1],to:d[2]})},getTimeTicks:function(d,q,g,h){var f=this,c=[],b={};var a=new f.Date(q);var l=d.unitRange,n=d.count||1,t;h=v(h,1);if(M(q)){f.set("Milliseconds",a,l>=p.second?0:n*Math.floor(f.get("Milliseconds",a)/n));l>=p.second&&f.set("Seconds",a,l>=p.minute?0:n*Math.floor(f.get("Seconds",a)/n));l>=p.minute&&f.set("Minutes",a,l>=p.hour?0:n*Math.floor(f.get("Minutes", a)/n));l>=p.hour&&f.set("Hours",a,l>=p.day?0:n*Math.floor(f.get("Hours",a)/n));l>=p.day&&f.set("Date",a,l>=p.month?1:Math.max(1,n*Math.floor(f.get("Date",a)/n)));if(l>=p.month){f.set("Month",a,l>=p.year?0:n*Math.floor(f.get("Month",a)/n));var m=f.get("FullYear",a)}l>=p.year&&f.set("FullYear",a,m-m%n);l===p.week&&(m=f.get("Day",a),f.set("Date",a,f.get("Date",a)-m+h+(m<h?-7:0)));m=f.get("FullYear",a);h=f.get("Month",a);var r=f.get("Date",a),e=f.get("Hours",a);q=a.getTime();f.variableTimezone&&(t=g- q>4*p.month||f.getTimezoneOffset(q)!==f.getTimezoneOffset(g));q=a.getTime();for(a=1;q<g;)c.push(q),q=l===p.year?f.makeTime(m+a*n,0):l===p.month?f.makeTime(m,h+a*n):!t||l!==p.day&&l!==p.week?t&&l===p.hour&&1<n?f.makeTime(m,h,r,e+a*n):q+l*n:f.makeTime(m,h,r+a*n*(l===p.day?1:7)),a++;c.push(q);l<=p.hour&&1E4>c.length&&c.forEach(function(a){0===a%18E5&&"000000000"===f.dateFormat("%H%M%S%L",a)&&(b[a]="day")})}c.info=F(d,{higherRanks:b,totalRange:l*n});return c}}});K(y,"parts/Options.js",[y["parts/Globals.js"]], function(d){var g=d.color,M=d.merge;d.defaultOptions={colors:"#7cb5ec #434348 #90ed7d #f7a35c #8085e9 #f15c80 #e4d354 #2b908f #f45b5b #91e8e1".split(" "),symbols:["circle","diamond","square","triangle","triangle-down"],lang:{loading:"Loading...",months:"January February March April May June July August September October November December".split(" "),shortMonths:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),weekdays:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), decimalPoint:".",numericSymbols:"kMGTPE".split(""),resetZoom:"Reset zoom",resetZoomTitle:"Reset zoom level 1:1",thousandsSep:" "},global:{},time:d.Time.prototype.defaultOptions,chart:{styledMode:!1,borderRadius:0,colorCount:10,defaultSeriesType:"line",ignoreHiddenSeries:!0,spacing:[10,10,15,10],resetZoomButton:{theme:{zIndex:6},position:{align:"right",x:-10,y:10}},width:null,height:null,borderColor:"#335cad",backgroundColor:"#ffffff",plotBorderColor:"#cccccc"},title:{text:"Chart title",align:"center", margin:15,widthAdjust:-44},subtitle:{text:"",align:"center",widthAdjust:-44},caption:{margin:15,text:"",align:"left",verticalAlign:"bottom"},plotOptions:{},labels:{style:{position:"absolute",color:"#333333"}},legend:{enabled:!0,align:"center",alignColumns:!0,layout:"horizontal",labelFormatter:function(){return this.name},borderColor:"#999999",borderRadius:0,navigation:{activeColor:"#003399",inactiveColor:"#cccccc"},itemStyle:{color:"#333333",cursor:"pointer",fontSize:"12px",fontWeight:"bold",textOverflow:"ellipsis"}, itemHoverStyle:{color:"#000000"},itemHiddenStyle:{color:"#cccccc"},shadow:!1,itemCheckboxStyle:{position:"absolute",width:"13px",height:"13px"},squareSymbol:!0,symbolPadding:5,verticalAlign:"bottom",x:0,y:0,title:{style:{fontWeight:"bold"}}},loading:{labelStyle:{fontWeight:"bold",position:"relative",top:"45%"},style:{position:"absolute",backgroundColor:"#ffffff",opacity:.5,textAlign:"center"}},tooltip:{enabled:!0,animation:d.svg,borderRadius:3,dateTimeLabelFormats:{millisecond:"%A, %b %e, %H:%M:%S.%L", second:"%A, %b %e, %H:%M:%S",minute:"%A, %b %e, %H:%M",hour:"%A, %b %e, %H:%M",day:"%A, %b %e, %Y",week:"Week from %A, %b %e, %Y",month:"%B %Y",year:"%Y"},footerFormat:"",padding:8,snap:d.isTouchDevice?25:10,headerFormat:'<span style="font-size: 10px">{point.key}</span><br/>',pointFormat:'<span style="color:{point.color}">\u25cf</span> {series.name}: <b>{point.y}</b><br/>',backgroundColor:g("#f7f7f7").setOpacity(.85).get(),borderWidth:1,shadow:!0,style:{color:"#333333",cursor:"default",fontSize:"12px", pointerEvents:"none",whiteSpace:"nowrap"}},credits:{enabled:!0,href:"https://www.highcharts.com?credits",position:{align:"right",x:-10,verticalAlign:"bottom",y:-5},style:{cursor:"pointer",color:"#999999",fontSize:"9px"},text:"Highcharts.com"}};d.setOptions=function(g){d.defaultOptions=M(!0,d.defaultOptions,g);(g.time||g.global)&&d.time.update(M(d.defaultOptions.global,d.defaultOptions.time,g.global,g.time));return d.defaultOptions};d.getOptions=function(){return d.defaultOptions};d.defaultPlotOptions= d.defaultOptions.plotOptions;d.time=new d.Time(M(d.defaultOptions.global,d.defaultOptions.time));d.dateFormat=function(g,E,D){return d.time.dateFormat(g,E,D)};""});K(y,"parts/Tick.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var M=g.clamp,F=g.correctFloat,E=g.defined,D=g.destroyObjectProperties,x=g.extend,v=g.isNumber,C=g.objectEach,B=g.pick,p=d.fireEvent,z=d.merge,m=d.deg2rad;d.Tick=function(d,m,h,f,c){this.axis=d;this.pos=m;this.type=h||"";this.isNewLabel=this.isNew=!0;this.parameters= c||{};this.tickmarkOffset=this.parameters.tickmarkOffset;this.options=this.parameters.options;h||f||this.addLabel()};d.Tick.prototype={addLabel:function(){var d=this,m=d.axis,h=m.options,f=m.chart,c=m.categories,b=m.names,a=d.pos,l=B(d.options&&d.options.labels,h.labels),n=m.tickPositions,t=a===n[0],g=a===n[n.length-1];b=this.parameters.category||(c?B(c[a],b[a],a):a);var r=d.label;c=(!l.step||1===l.step)&&1===m.tickInterval;n=n.info;var e,k;if(m.isDatetimeAxis&&n){var u=f.time.resolveDTLFormat(h.dateTimeLabelFormats[!h.grid&& n.higherRanks[a]||n.unitName]);var H=u.main}d.isFirst=t;d.isLast=g;d.formatCtx={axis:m,chart:f,isFirst:t,isLast:g,dateTimeLabelFormat:H,tickPositionInfo:n,value:m.isLog?F(m.lin2log(b)):b,pos:a};h=m.labelFormatter.call(d.formatCtx,this.formatCtx);if(k=u&&u.list)d.shortenLabel=function(){for(e=0;e<k.length;e++)if(r.attr({text:m.labelFormatter.call(x(d.formatCtx,{dateTimeLabelFormat:k[e]}))}),r.getBBox().width<m.getSlotWidth(d)-2*B(l.padding,5))return;r.attr({text:""})};c&&m._addedPlotLB&&m.isXAxis&& d.moveLabel(h,l);E(r)||d.movedLabel?r&&r.textStr!==h&&!c&&(!r.textWidth||l.style&&l.style.width||r.styles.width||r.css({width:null}),r.attr({text:h}),r.textPxLength=r.getBBox().width):(d.label=r=d.createLabel({x:0,y:0},h,l),d.rotation=0)},moveLabel:function(d,m){var h=this,f=h.label,c=!1,b=h.axis,a=b.reversed,l=b.chart.inverted;f&&f.textStr===d?(h.movedLabel=f,c=!0,delete h.label):C(b.ticks,function(a){c||a.isNew||a===h||!a.label||a.label.textStr!==d||(h.movedLabel=a.label,c=!0,a.labelPos=h.movedLabel.xy, delete a.label)});if(!c&&(h.labelPos||f)){var n=h.labelPos||f.xy;f=l?n.x:a?0:b.width+b.left;b=l?a?b.width+b.left:0:n.y;h.movedLabel=h.createLabel({x:f,y:b},d,m);h.movedLabel&&h.movedLabel.attr({opacity:0})}},createLabel:function(d,m,h){var f=this.axis,c=f.chart;if(d=E(m)&&h.enabled?c.renderer.text(m,d.x,d.y,h.useHTML).add(f.labelGroup):null)c.styledMode||d.css(z(h.style)),d.textPxLength=d.getBBox().width;return d},replaceMovedLabel:function(){var d=this.label,m=this.axis,h=m.reversed,f=this.axis.chart.inverted; if(d&&!this.isNew){var c=f?d.xy.x:h?m.left:m.width+m.left;h=f?h?m.width+m.top:m.top:d.xy.y;d.animate({x:c,y:h,opacity:0},void 0,d.destroy);delete this.label}m.isDirty=!0;this.label=this.movedLabel;delete this.movedLabel},getLabelSize:function(){return this.label?this.label.getBBox()[this.axis.horiz?"height":"width"]:0},handleOverflow:function(d){var g=this.axis,h=g.options.labels,f=d.x,c=g.chart.chartWidth,b=g.chart.spacing,a=B(g.labelLeft,Math.min(g.pos,b[3]));b=B(g.labelRight,Math.max(g.isRadial? 0:g.pos+g.len,c-b[1]));var l=this.label,n=this.rotation,t={left:0,center:.5,right:1}[g.labelAlign||l.attr("align")],q=l.getBBox().width,r=g.getSlotWidth(this),e=r,k=1,u,H={};if(n||"justify"!==B(h.overflow,"justify"))0>n&&f-t*q<a?u=Math.round(f/Math.cos(n*m)-a):0<n&&f+t*q>b&&(u=Math.round((c-f)/Math.cos(n*m)));else if(c=f+(1-t)*q,f-t*q<a?e=d.x+e*(1-t)-a:c>b&&(e=b-d.x+e*t,k=-1),e=Math.min(r,e),e<r&&"center"===g.labelAlign&&(d.x+=k*(r-e-t*(r-Math.min(q,e)))),q>e||g.autoRotation&&(l.styles||{}).width)u= e;u&&(this.shortenLabel?this.shortenLabel():(H.width=Math.floor(u),(h.style||{}).textOverflow||(H.textOverflow="ellipsis"),l.css(H)))},getPosition:function(d,m,h,f){var c=this.axis,b=c.chart,a=f&&b.oldChartHeight||b.chartHeight;d={x:d?F(c.translate(m+h,null,null,f)+c.transB):c.left+c.offset+(c.opposite?(f&&b.oldChartWidth||b.chartWidth)-c.right-c.left:0),y:d?a-c.bottom+c.offset-(c.opposite?c.height:0):F(a-c.translate(m+h,null,null,f)-c.transB)};d.y=M(d.y,-1E5,1E5);p(this,"afterGetPosition",{pos:d}); return d},getLabelPosition:function(d,g,h,f,c,b,a,l){var n=this.axis,t=n.transA,q=n.isLinked&&n.linkedParent?n.linkedParent.reversed:n.reversed,r=n.staggerLines,e=n.tickRotCorr||{x:0,y:0},k=c.y,u=f||n.reserveSpaceDefault?0:-n.labelOffset*("center"===n.labelAlign?.5:1),H={};E(k)||(k=0===n.side?h.rotation?-8:-h.getBBox().height:2===n.side?e.y+8:Math.cos(h.rotation*m)*(e.y-h.getBBox(!1,0).height/2));d=d+c.x+u+e.x-(b&&f?b*t*(q?-1:1):0);g=g+k-(b&&!f?b*t*(q?1:-1):0);r&&(h=a/(l||1)%r,n.opposite&&(h=r-h- 1),g+=n.labelOffset/r*h);H.x=d;H.y=Math.round(g);p(this,"afterGetLabelPosition",{pos:H,tickmarkOffset:b,index:a});return H},getMarkPath:function(d,m,h,f,c,b){return b.crispLine(["M",d,m,"L",d+(c?0:-h),m+(c?h:0)],f)},renderGridLine:function(d,m,h){var f=this.axis,c=f.options,b=this.gridLine,a={},l=this.pos,n=this.type,t=B(this.tickmarkOffset,f.tickmarkOffset),g=f.chart.renderer,r=n?n+"Grid":"grid",e=c[r+"LineWidth"],k=c[r+"LineColor"];c=c[r+"LineDashStyle"];b||(f.chart.styledMode||(a.stroke=k,a["stroke-width"]= e,c&&(a.dashstyle=c)),n||(a.zIndex=1),d&&(m=0),this.gridLine=b=g.path().attr(a).addClass("highcharts-"+(n?n+"-":"")+"grid-line").add(f.gridGroup));if(b&&(h=f.getPlotLinePath({value:l+t,lineWidth:b.strokeWidth()*h,force:"pass",old:d})))b[d||this.isNew?"attr":"animate"]({d:h,opacity:m})},renderMark:function(d,m,h){var f=this.axis,c=f.options,b=f.chart.renderer,a=this.type,l=a?a+"Tick":"tick",n=f.tickSize(l),t=this.mark,g=!t,r=d.x;d=d.y;var e=B(c[l+"Width"],!a&&f.isXAxis?1:0);c=c[l+"Color"];n&&(f.opposite&& (n[0]=-n[0]),g&&(this.mark=t=b.path().addClass("highcharts-"+(a?a+"-":"")+"tick").add(f.axisGroup),f.chart.styledMode||t.attr({stroke:c,"stroke-width":e})),t[g?"attr":"animate"]({d:this.getMarkPath(r,d,n[0],t.strokeWidth()*h,f.horiz,b),opacity:m}))},renderLabel:function(d,m,h,f){var c=this.axis,b=c.horiz,a=c.options,l=this.label,n=a.labels,t=n.step;c=B(this.tickmarkOffset,c.tickmarkOffset);var g=!0,r=d.x;d=d.y;l&&v(r)&&(l.xy=d=this.getLabelPosition(r,d,l,b,n,c,f,t),this.isFirst&&!this.isLast&&!B(a.showFirstLabel, 1)||this.isLast&&!this.isFirst&&!B(a.showLastLabel,1)?g=!1:!b||n.step||n.rotation||m||0===h||this.handleOverflow(d),t&&f%t&&(g=!1),g&&v(d.y)?(d.opacity=h,l[this.isNewLabel?"attr":"animate"](d),this.isNewLabel=!1):(l.attr("y",-9999),this.isNewLabel=!0))},render:function(m,g,h){var f=this.axis,c=f.horiz,b=this.pos,a=B(this.tickmarkOffset,f.tickmarkOffset);b=this.getPosition(c,b,a,g);a=b.x;var l=b.y;f=c&&a===f.pos+f.len||!c&&l===f.pos?-1:1;h=B(h,1);this.isActive=!0;this.renderGridLine(g,h,f);this.renderMark(b, h,f);this.renderLabel(b,g,h,m);this.isNew=!1;d.fireEvent(this,"afterRender")},destroy:function(){D(this,this.axis)}}});K(y,"parts/Axis.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var M=g.animObject,F=g.arrayMax,E=g.arrayMin,D=g.clamp,x=g.correctFloat,v=g.defined,C=g.destroyObjectProperties,B=g.extend,p=g.isArray,z=g.isNumber,m=g.isString,q=g.objectEach,w=g.pick,h=g.relativeLength,f=g.splat,c=g.syncTimeout,b=d.addEvent,a=d.color,l=d.defaultOptions,n=d.deg2rad,t=d.fireEvent,I= d.format,r=d.getMagnitude,e=d.merge,k=d.normalizeTickInterval,u=d.removeEvent,H=d.seriesTypes,G=d.Tick;g=function(){this.init.apply(this,arguments)};B(g.prototype,{defaultOptions:{dateTimeLabelFormats:{millisecond:{main:"%H:%M:%S.%L",range:!1},second:{main:"%H:%M:%S",range:!1},minute:{main:"%H:%M",range:!1},hour:{main:"%H:%M",range:!1},day:{main:"%e. %b"},week:{main:"%e. %b"},month:{main:"%b '%y"},year:{main:"%Y"}},endOnTick:!1,labels:{enabled:!0,indentation:10,x:0,style:{color:"#666666",cursor:"default", fontSize:"11px"}},maxPadding:.01,minorTickLength:2,minorTickPosition:"outside",minPadding:.01,showEmpty:!0,startOfWeek:1,startOnTick:!1,tickLength:10,tickPixelInterval:100,tickmarkPlacement:"between",tickPosition:"outside",title:{align:"middle",style:{color:"#666666"}},type:"linear",minorGridLineColor:"#f2f2f2",minorGridLineWidth:1,minorTickColor:"#999999",lineColor:"#ccd6eb",lineWidth:1,gridLineColor:"#e6e6e6",tickColor:"#ccd6eb"},defaultYAxisOptions:{endOnTick:!0,maxPadding:.05,minPadding:.05,tickPixelInterval:72, showLastLabel:!0,labels:{x:-8},startOnTick:!0,title:{rotation:270,text:"Values"},stackLabels:{allowOverlap:!1,enabled:!1,crop:!0,overflow:"justify",formatter:function(){var a=this.axis.chart.numberFormatter;return a(this.total,-1)},style:{color:"#000000",fontSize:"11px",fontWeight:"bold",textOutline:"1px contrast"}},gridLineWidth:1,lineWidth:0},defaultLeftAxisOptions:{labels:{x:-15},title:{rotation:270}},defaultRightAxisOptions:{labels:{x:15},title:{rotation:90}},defaultBottomAxisOptions:{labels:{autoRotation:[-45], x:0},margin:15,title:{rotation:0}},defaultTopAxisOptions:{labels:{autoRotation:[-45],x:0},margin:15,title:{rotation:0}},init:function(a,e){var c=e.isX,k=this;k.chart=a;k.horiz=a.inverted&&!k.isZAxis?!c:c;k.isXAxis=c;k.coll=k.coll||(c?"xAxis":"yAxis");t(this,"init",{userOptions:e});k.opposite=e.opposite;k.side=e.side||(k.horiz?k.opposite?0:2:k.opposite?1:3);k.setOptions(e);var A=this.options,l=A.type;k.labelFormatter=A.labels.formatter||k.defaultLabelFormatter;k.userOptions=e;k.minPixelPadding=0;k.reversed= A.reversed;k.visible=!1!==A.visible;k.zoomEnabled=!1!==A.zoomEnabled;k.hasNames="category"===l||!0===A.categories;k.categories=A.categories||k.hasNames;k.names||(k.names=[],k.names.keys={});k.plotLinesAndBandsGroups={};k.isLog="logarithmic"===l;k.isDatetimeAxis="datetime"===l;k.positiveValuesOnly=k.isLog&&!k.allowNegativeLog;k.isLinked=v(A.linkedTo);k.ticks={};k.labelEdge=[];k.minorTicks={};k.plotLinesAndBands=[];k.alternateBands={};k.len=0;k.minRange=k.userMinRange=A.minRange||A.maxZoom;k.range= A.range;k.offset=A.offset||0;k.stacks={};k.oldStacks={};k.stacksTouched=0;k.max=null;k.min=null;k.crosshair=w(A.crosshair,f(a.options.tooltip.crosshairs)[c?0:1],!1);e=k.options.events;-1===a.axes.indexOf(k)&&(c?a.axes.splice(a.xAxis.length,0,k):a.axes.push(k),a[k.coll].push(k));k.series=k.series||[];a.inverted&&!k.isZAxis&&c&&"undefined"===typeof k.reversed&&(k.reversed=!0);q(e,function(a,e){d.isFunction(a)&&b(k,e,a)});k.lin2log=A.linearToLogConverter||k.lin2log;k.isLog&&(k.val2lin=k.log2lin,k.lin2val= k.lin2log);t(this,"afterInit")},setOptions:function(a){this.options=e(this.defaultOptions,"yAxis"===this.coll&&this.defaultYAxisOptions,[this.defaultTopAxisOptions,this.defaultRightAxisOptions,this.defaultBottomAxisOptions,this.defaultLeftAxisOptions][this.side],e(l[this.coll],a));t(this,"afterSetOptions",{userOptions:a})},defaultLabelFormatter:function(){var a=this.axis,e=this.value,b=a.chart.time,c=a.categories,k=this.dateTimeLabelFormat,f=l.lang,u=f.numericSymbols;f=f.numericSymbolMagnitude||1E3; var d=u&&u.length,h=a.options.labels.format;a=a.isLog?Math.abs(e):a.tickInterval;var t=this.chart,n=t.numberFormatter;if(h)var r=I(h,this,t);else if(c)r=e;else if(k)r=b.dateFormat(k,e);else if(d&&1E3<=a)for(;d--&&"undefined"===typeof r;)b=Math.pow(f,d+1),a>=b&&0===10*e%b&&null!==u[d]&&0!==e&&(r=n(e/b,-1)+u[d]);"undefined"===typeof r&&(r=1E4<=Math.abs(e)?n(e,-1):n(e,-1,void 0,""));return r},getSeriesExtremes:function(){var a=this,e=a.chart,b;t(this,"getSeriesExtremes",null,function(){a.hasVisibleSeries= !1;a.dataMin=a.dataMax=a.threshold=null;a.softThreshold=!a.isXAxis;a.buildStacks&&a.buildStacks();a.series.forEach(function(c){if(c.visible||!e.options.chart.ignoreHiddenSeries){var k=c.options,f=k.threshold;a.hasVisibleSeries=!0;a.positiveValuesOnly&&0>=f&&(f=null);if(a.isXAxis){if(k=c.xData,k.length){b=c.getXExtremes(k);var A=b.min;var l=b.max;z(A)||A instanceof Date||(k=k.filter(z),b=c.getXExtremes(k),A=b.min,l=b.max);k.length&&(a.dataMin=Math.min(w(a.dataMin,A),A),a.dataMax=Math.max(w(a.dataMax, l),l))}}else if(c.getExtremes(),l=c.dataMax,A=c.dataMin,v(A)&&v(l)&&(a.dataMin=Math.min(w(a.dataMin,A),A),a.dataMax=Math.max(w(a.dataMax,l),l)),v(f)&&(a.threshold=f),!k.softThreshold||a.positiveValuesOnly)a.softThreshold=!1}})});t(this,"afterGetSeriesExtremes")},translate:function(a,e,b,c,k,f){var A=this.linkedParent||this,l=1,u=0,J=c?A.oldTransA:A.transA;c=c?A.oldMin:A.min;var d=A.minPixelPadding;k=(A.isOrdinal||A.isBroken||A.isLog&&k)&&A.lin2val;J||(J=A.transA);b&&(l*=-1,u=A.len);A.reversed&&(l*= -1,u-=l*(A.sector||A.len));e?(a=(a*l+u-d)/J+c,k&&(a=A.lin2val(a))):(k&&(a=A.val2lin(a)),a=z(c)?l*(a-c)*J+u+l*d+(z(f)?J*f:0):void 0);return a},toPixels:function(a,e){return this.translate(a,!1,!this.horiz,null,!0)+(e?0:this.pos)},toValue:function(a,e){return this.translate(a-(e?0:this.pos),!0,!this.horiz,null,!0)},getPlotLinePath:function(a){var e=this,b=e.chart,c=e.left,k=e.top,f=a.old,A=a.value,l=a.translatedValue,u=a.lineWidth,d=a.force,h,n,r,H,G=f&&b.oldChartHeight||b.chartHeight,m=f&&b.oldChartWidth|| b.chartWidth,g,q=e.transB,I=function(a,e,b){if("pass"!==d&&a<e||a>b)d?a=D(a,e,b):g=!0;return a};a={value:A,lineWidth:u,old:f,force:d,acrossPanes:a.acrossPanes,translatedValue:l};t(this,"getPlotLinePath",a,function(a){l=w(l,e.translate(A,null,null,f));l=D(l,-1E5,1E5);h=r=Math.round(l+q);n=H=Math.round(G-l-q);z(l)?e.horiz?(n=k,H=G-e.bottom,h=r=I(h,c,c+e.width)):(h=c,r=m-e.right,n=H=I(n,k,k+e.height)):(g=!0,d=!1);a.path=g&&!d?null:b.renderer.crispLine(["M",h,n,"L",r,H],u||1)});return a.path},getLinearTickPositions:function(a, e,b){var c=x(Math.floor(e/a)*a);b=x(Math.ceil(b/a)*a);var k=[],f;x(c+a)===c&&(f=20);if(this.single)return[e];for(e=c;e<=b;){k.push(e);e=x(e+a,f);if(e===l)break;var l=e}return k},getMinorTickInterval:function(){var a=this.options;return!0===a.minorTicks?w(a.minorTickInterval,"auto"):!1===a.minorTicks?null:a.minorTickInterval},getMinorTickPositions:function(){var a=this,e=a.options,b=a.tickPositions,c=a.minorTickInterval,k=[],f=a.pointRangePadding||0,l=a.min-f;f=a.max+f;var u=f-l;if(u&&u/c<a.len/3)if(a.isLog)this.paddedTicks.forEach(function(e, b,f){b&&k.push.apply(k,a.getLogTickPositions(c,f[b-1],f[b],!0))});else if(a.isDatetimeAxis&&"auto"===this.getMinorTickInterval())k=k.concat(a.getTimeTicks(a.normalizeTimeTickInterval(c),l,f,e.startOfWeek));else for(e=l+(b[0]-l)%c;e<=f&&e!==k[0];e+=c)k.push(e);0!==k.length&&a.trimTicks(k);return k},adjustForMinRange:function(){var a=this.options,e=this.min,b=this.max,c,k,f,l,u;this.isXAxis&&"undefined"===typeof this.minRange&&!this.isLog&&(v(a.min)||v(a.max)?this.minRange=null:(this.series.forEach(function(a){l= a.xData;for(k=u=a.xIncrement?1:l.length-1;0<k;k--)if(f=l[k]-l[k-1],"undefined"===typeof c||f<c)c=f}),this.minRange=Math.min(5*c,this.dataMax-this.dataMin)));if(b-e<this.minRange){var d=this.dataMax-this.dataMin>=this.minRange;var h=this.minRange;var t=(h-b+e)/2;t=[e-t,w(a.min,e-t)];d&&(t[2]=this.isLog?this.log2lin(this.dataMin):this.dataMin);e=F(t);b=[e+h,w(a.max,e+h)];d&&(b[2]=this.isLog?this.log2lin(this.dataMax):this.dataMax);b=E(b);b-e<h&&(t[0]=b-h,t[1]=w(a.min,b-h),e=F(t))}this.min=e;this.max= b},getClosest:function(){var a;this.categories?a=1:this.series.forEach(function(e){var b=e.closestPointRange,c=e.visible||!e.chart.options.chart.ignoreHiddenSeries;!e.noSharedTooltip&&v(b)&&c&&(a=v(a)?Math.min(a,b):b)});return a},nameToX:function(a){var e=p(this.categories),b=e?this.categories:this.names,c=a.options.x;a.series.requireSorting=!1;v(c)||(c=!1===this.options.uniqueNames?a.series.autoIncrement():e?b.indexOf(a.name):w(b.keys[a.name],-1));if(-1===c){if(!e)var k=b.length}else k=c;"undefined"!== typeof k&&(this.names[k]=a.name,this.names.keys[a.name]=k);return k},updateNames:function(){var a=this,e=this.names;0<e.length&&(Object.keys(e.keys).forEach(function(a){delete e.keys[a]}),e.length=0,this.minRange=this.userMinRange,(this.series||[]).forEach(function(e){e.xIncrement=null;if(!e.points||e.isDirtyData)a.max=Math.max(a.max,e.xData.length-1),e.processData(),e.generatePoints();e.data.forEach(function(b,c){if(b&&b.options&&"undefined"!==typeof b.name){var k=a.nameToX(b);"undefined"!==typeof k&& k!==b.x&&(b.x=k,e.xData[c]=k)}})}))},setAxisTranslation:function(a){var e=this,b=e.max-e.min,c=e.axisPointRange||0,k=0,f=0,l=e.linkedParent,u=!!e.categories,A=e.transA,d=e.isXAxis;if(d||u||c){var h=e.getClosest();l?(k=l.minPointOffset,f=l.pointRangePadding):e.series.forEach(function(a){var b=u?1:d?w(a.options.pointRange,h,0):e.axisPointRange||0,l=a.options.pointPlacement;c=Math.max(c,b);if(!e.single||u)a=H.xrange&&a instanceof H.xrange?!d:d,k=Math.max(k,a&&m(l)?0:b/2),f=Math.max(f,a&&"on"===l?0:b)}); l=e.ordinalSlope&&h?e.ordinalSlope/h:1;e.minPointOffset=k*=l;e.pointRangePadding=f*=l;e.pointRange=Math.min(c,e.single&&u?1:b);d&&(e.closestPointRange=h)}a&&(e.oldTransA=A);e.translationSlope=e.transA=A=e.staticScale||e.len/(b+f||1);e.transB=e.horiz?e.left:e.bottom;e.minPixelPadding=A*k;t(this,"afterSetAxisTranslation")},minFromRange:function(){return this.max-this.range},setTickInterval:function(a){var e=this,b=e.chart,c=e.options,f=e.isLog,l=e.isDatetimeAxis,u=e.isXAxis,A=e.isLinked,h=c.maxPadding, n=c.minPadding,H=c.tickInterval,G=c.tickPixelInterval,m=e.categories,g=z(e.threshold)?e.threshold:null,q=e.softThreshold;l||m||A||this.getTickAmount();var I=w(e.userMin,c.min);var p=w(e.userMax,c.max);if(A){e.linkedParent=b[e.coll][c.linkedTo];var C=e.linkedParent.getExtremes();e.min=w(C.min,C.dataMin);e.max=w(C.max,C.dataMax);c.type!==e.linkedParent.options.type&&d.error(11,1,b)}else{if(!q&&v(g))if(e.dataMin>=g)C=g,n=0;else if(e.dataMax<=g){var B=g;h=0}e.min=w(I,C,e.dataMin);e.max=w(p,B,e.dataMax)}f&& (e.positiveValuesOnly&&!a&&0>=Math.min(e.min,w(e.dataMin,e.min))&&d.error(10,1,b),e.min=x(e.log2lin(e.min),16),e.max=x(e.log2lin(e.max),16));e.range&&v(e.max)&&(e.userMin=e.min=I=Math.max(e.dataMin,e.minFromRange()),e.userMax=p=e.max,e.range=null);t(e,"foundExtremes");e.beforePadding&&e.beforePadding();e.adjustForMinRange();!(m||e.axisPointRange||e.usePercentage||A)&&v(e.min)&&v(e.max)&&(b=e.max-e.min)&&(!v(I)&&n&&(e.min-=b*n),!v(p)&&h&&(e.max+=b*h));z(e.userMin)||(z(c.softMin)&&c.softMin<e.min&& (e.min=I=c.softMin),z(c.floor)&&(e.min=Math.max(e.min,c.floor)));z(e.userMax)||(z(c.softMax)&&c.softMax>e.max&&(e.max=p=c.softMax),z(c.ceiling)&&(e.max=Math.min(e.max,c.ceiling)));q&&v(e.dataMin)&&(g=g||0,!v(I)&&e.min<g&&e.dataMin>=g?e.min=e.options.minRange?Math.min(g,e.max-e.minRange):g:!v(p)&&e.max>g&&e.dataMax<=g&&(e.max=e.options.minRange?Math.max(g,e.min+e.minRange):g));e.tickInterval=e.min===e.max||"undefined"===typeof e.min||"undefined"===typeof e.max?1:A&&!H&&G===e.linkedParent.options.tickPixelInterval? H=e.linkedParent.tickInterval:w(H,this.tickAmount?(e.max-e.min)/Math.max(this.tickAmount-1,1):void 0,m?1:(e.max-e.min)*G/Math.max(e.len,G));u&&!a&&e.series.forEach(function(a){a.processData(e.min!==e.oldMin||e.max!==e.oldMax)});e.setAxisTranslation(!0);e.beforeSetTickPositions&&e.beforeSetTickPositions();e.postProcessTickInterval&&(e.tickInterval=e.postProcessTickInterval(e.tickInterval));e.pointRange&&!H&&(e.tickInterval=Math.max(e.pointRange,e.tickInterval));a=w(c.minTickInterval,e.isDatetimeAxis&& e.closestPointRange);!H&&e.tickInterval<a&&(e.tickInterval=a);l||f||H||(e.tickInterval=k(e.tickInterval,null,r(e.tickInterval),w(c.allowDecimals,!(.5<e.tickInterval&&5>e.tickInterval&&1E3<e.max&&9999>e.max)),!!this.tickAmount));this.tickAmount||(e.tickInterval=e.unsquish());this.setTickPositions()},setTickPositions:function(){var a=this.options,e=a.tickPositions;var b=this.getMinorTickInterval();var c=a.tickPositioner,k=a.startOnTick,f=a.endOnTick;this.tickmarkOffset=this.categories&&"between"=== a.tickmarkPlacement&&1===this.tickInterval?.5:0;this.minorTickInterval="auto"===b&&this.tickInterval?this.tickInterval/5:b;this.single=this.min===this.max&&v(this.min)&&!this.tickAmount&&(parseInt(this.min,10)===this.min||!1!==a.allowDecimals);this.tickPositions=b=e&&e.slice();!b&&(!this.ordinalPositions&&(this.max-this.min)/this.tickInterval>Math.max(2*this.len,200)?(b=[this.min,this.max],d.error(19,!1,this.chart)):b=this.isDatetimeAxis?this.getTimeTicks(this.normalizeTimeTickInterval(this.tickInterval, a.units),this.min,this.max,a.startOfWeek,this.ordinalPositions,this.closestPointRange,!0):this.isLog?this.getLogTickPositions(this.tickInterval,this.min,this.max):this.getLinearTickPositions(this.tickInterval,this.min,this.max),b.length>this.len&&(b=[b[0],b.pop()],b[0]===b[1]&&(b.length=1)),this.tickPositions=b,c&&(c=c.apply(this,[this.min,this.max])))&&(this.tickPositions=b=c);this.paddedTicks=b.slice(0);this.trimTicks(b,k,f);this.isLinked||(this.single&&2>b.length&&!this.categories&&(this.min-= .5,this.max+=.5),e||c||this.adjustTickAmount());t(this,"afterSetTickPositions")},trimTicks:function(a,e,b){var c=a[0],k=a[a.length-1],f=this.minPointOffset||0;t(this,"trimTicks");if(!this.isLinked){if(e&&-Infinity!==c)this.min=c;else for(;this.min-f>a[0];)a.shift();if(b)this.max=k;else for(;this.max+f<a[a.length-1];)a.pop();0===a.length&&v(c)&&!this.options.tickPositions&&a.push((k+c)/2)}},alignToOthers:function(){var a={},e,b=this.options;!1===this.chart.options.chart.alignTicks||!1===b.alignTicks|| !1===b.startOnTick||!1===b.endOnTick||this.isLog||this.chart[this.coll].forEach(function(b){var c=b.options;c=[b.horiz?c.left:c.top,c.width,c.height,c.pane].join();b.series.length&&(a[c]?e=!0:a[c]=1)});return e},getTickAmount:function(){var a=this.options,e=a.tickAmount,b=a.tickPixelInterval;!v(a.tickInterval)&&this.len<b&&!this.isRadial&&!this.isLog&&a.startOnTick&&a.endOnTick&&(e=2);!e&&this.alignToOthers()&&(e=Math.ceil(this.len/b)+1);4>e&&(this.finalTickAmt=e,e=5);this.tickAmount=e},adjustTickAmount:function(){var a= this.options,e=this.tickInterval,b=this.tickPositions,c=this.tickAmount,k=this.finalTickAmt,f=b&&b.length,l=w(this.threshold,this.softThreshold?0:null),u;if(this.hasData()){if(f<c){for(u=this.min;b.length<c;)b.length%2||u===l?b.push(x(b[b.length-1]+e)):b.unshift(x(b[0]-e));this.transA*=(f-1)/(c-1);this.min=a.startOnTick?b[0]:Math.min(this.min,b[0]);this.max=a.endOnTick?b[b.length-1]:Math.max(this.max,b[b.length-1])}else f>c&&(this.tickInterval*=2,this.setTickPositions());if(v(k)){for(e=a=b.length;e--;)(3=== k&&1===e%2||2>=k&&0<e&&e<a-1)&&b.splice(e,1);this.finalTickAmt=void 0}}},setScale:function(){var a=this.series.some(function(a){return a.isDirtyData||a.isDirty||a.xAxis&&a.xAxis.isDirty}),e;this.oldMin=this.min;this.oldMax=this.max;this.oldAxisLength=this.len;this.setAxisSize();(e=this.len!==this.oldAxisLength)||a||this.isLinked||this.forceRedraw||this.userMin!==this.oldUserMin||this.userMax!==this.oldUserMax||this.alignToOthers()?(this.resetStacks&&this.resetStacks(),this.forceRedraw=!1,this.getSeriesExtremes(), this.setTickInterval(),this.oldUserMin=this.userMin,this.oldUserMax=this.userMax,this.isDirty||(this.isDirty=e||this.min!==this.oldMin||this.max!==this.oldMax)):this.cleanStacks&&this.cleanStacks();t(this,"afterSetScale")},setExtremes:function(a,e,b,c,k){var f=this,l=f.chart;b=w(b,!0);f.series.forEach(function(a){delete a.kdTree});k=B(k,{min:a,max:e});t(f,"setExtremes",k,function(){f.userMin=a;f.userMax=e;f.eventArgs=k;b&&l.redraw(c)})},zoom:function(a,e){var b=this.dataMin,c=this.dataMax,k=this.options, f=Math.min(b,w(k.min,b)),l=Math.max(c,w(k.max,c));a={newMin:a,newMax:e};t(this,"zoom",a,function(a){var e=a.newMin,k=a.newMax;if(e!==this.min||k!==this.max)this.allowZoomOutside||(v(b)&&(e<f&&(e=f),e>l&&(e=l)),v(c)&&(k<f&&(k=f),k>l&&(k=l))),this.displayBtn="undefined"!==typeof e||"undefined"!==typeof k,this.setExtremes(e,k,!1,void 0,{trigger:"zoom"});a.zoomed=!0});return a.zoomed},setAxisSize:function(){var a=this.chart,e=this.options,b=e.offsets||[0,0,0,0],c=this.horiz,k=this.width=Math.round(h(w(e.width, a.plotWidth-b[3]+b[1]),a.plotWidth)),f=this.height=Math.round(h(w(e.height,a.plotHeight-b[0]+b[2]),a.plotHeight)),l=this.top=Math.round(h(w(e.top,a.plotTop+b[0]),a.plotHeight,a.plotTop));e=this.left=Math.round(h(w(e.left,a.plotLeft+b[3]),a.plotWidth,a.plotLeft));this.bottom=a.chartHeight-f-l;this.right=a.chartWidth-k-e;this.len=Math.max(c?k:f,0);this.pos=c?e:l},getExtremes:function(){var a=this.isLog;return{min:a?x(this.lin2log(this.min)):this.min,max:a?x(this.lin2log(this.max)):this.max,dataMin:this.dataMin, dataMax:this.dataMax,userMin:this.userMin,userMax:this.userMax}},getThreshold:function(a){var e=this.isLog,b=e?this.lin2log(this.min):this.min;e=e?this.lin2log(this.max):this.max;null===a||-Infinity===a?a=b:Infinity===a?a=e:b>a?a=b:e<a&&(a=e);return this.translate(a,0,1,0,1)},autoLabelAlign:function(a){var e=(w(a,0)-90*this.side+720)%360;a={align:"center"};t(this,"autoLabelAlign",a,function(a){15<e&&165>e?a.align="right":195<e&&345>e&&(a.align="left")});return a.align},tickSize:function(a){var e= this.options,b=e[a+"Length"],c=w(e[a+"Width"],"tick"===a&&this.isXAxis&&!this.categories?1:0);if(c&&b){"inside"===e[a+"Position"]&&(b=-b);var k=[b,c]}a={tickSize:k};t(this,"afterTickSize",a);return a.tickSize},labelMetrics:function(){var a=this.tickPositions&&this.tickPositions[0]||0;return this.chart.renderer.fontMetrics(this.options.labels.style&&this.options.labels.style.fontSize,this.ticks[a]&&this.ticks[a].label)},unsquish:function(){var a=this.options.labels,e=this.horiz,b=this.tickInterval, c=b,k=this.len/(((this.categories?1:0)+this.max-this.min)/b),f,l=a.rotation,u=this.labelMetrics(),d,h=Number.MAX_VALUE,t,r=this.max-this.min,H=function(a){var e=a/(k||1);e=1<e?Math.ceil(e):1;e*b>r&&Infinity!==a&&Infinity!==k&&r&&(e=Math.ceil(r/b));return x(e*b)};e?(t=!a.staggerLines&&!a.step&&(v(l)?[l]:k<w(a.autoRotationLimit,80)&&a.autoRotation))&&t.forEach(function(a){if(a===l||a&&-90<=a&&90>=a){d=H(Math.abs(u.h/Math.sin(n*a)));var e=d+Math.abs(a/360);e<h&&(h=e,f=a,c=d)}}):a.step||(c=H(u.h));this.autoRotation= t;this.labelRotation=w(f,l);return c},getSlotWidth:function(a){var e=this.chart,b=this.horiz,c=this.options.labels,k=Math.max(this.tickPositions.length-(this.categories?0:1),1),f=e.margin[3];return a&&a.slotWidth||b&&2>(c.step||0)&&!c.rotation&&(this.staggerLines||1)*this.len/k||!b&&(c.style&&parseInt(c.style.width,10)||f&&f-e.spacing[3]||.33*e.chartWidth)},renderUnsquish:function(){var a=this.chart,e=a.renderer,b=this.tickPositions,c=this.ticks,k=this.options.labels,f=k&&k.style||{},l=this.horiz, u=this.getSlotWidth(),d=Math.max(1,Math.round(u-2*(k.padding||5))),h={},t=this.labelMetrics(),n=k.style&&k.style.textOverflow,r=0;m(k.rotation)||(h.rotation=k.rotation||0);b.forEach(function(a){a=c[a];a.movedLabel&&a.replaceMovedLabel();a&&a.label&&a.label.textPxLength>r&&(r=a.label.textPxLength)});this.maxLabelLength=r;if(this.autoRotation)r>d&&r>t.h?h.rotation=this.labelRotation:this.labelRotation=0;else if(u){var H=d;if(!n){var G="clip";for(d=b.length;!l&&d--;){var g=b[d];if(g=c[g].label)g.styles&& "ellipsis"===g.styles.textOverflow?g.css({textOverflow:"clip"}):g.textPxLength>u&&g.css({width:u+"px"}),g.getBBox().height>this.len/b.length-(t.h-t.f)&&(g.specificTextOverflow="ellipsis")}}}h.rotation&&(H=r>.5*a.chartHeight?.33*a.chartHeight:r,n||(G="ellipsis"));if(this.labelAlign=k.align||this.autoLabelAlign(this.labelRotation))h.align=this.labelAlign;b.forEach(function(a){var e=(a=c[a])&&a.label,b=f.width,k={};e&&(e.attr(h),a.shortenLabel?a.shortenLabel():H&&!b&&"nowrap"!==f.whiteSpace&&(H<e.textPxLength|| "SPAN"===e.element.tagName)?(k.width=H,n||(k.textOverflow=e.specificTextOverflow||G),e.css(k)):e.styles&&e.styles.width&&!k.width&&!b&&e.css({width:null}),delete e.specificTextOverflow,a.rotation=h.rotation)},this);this.tickRotCorr=e.rotCorr(t.b,this.labelRotation||0,0!==this.side)},hasData:function(){return this.series.some(function(a){return a.hasData()})||this.options.showEmpty&&v(this.min)&&v(this.max)},addTitle:function(a){var b=this.chart.renderer,c=this.horiz,k=this.opposite,f=this.options.title, l,u=this.chart.styledMode;this.axisTitle||((l=f.textAlign)||(l=(c?{low:"left",middle:"center",high:"right"}:{low:k?"right":"left",middle:"center",high:k?"left":"right"})[f.align]),this.axisTitle=b.text(f.text,0,0,f.useHTML).attr({zIndex:7,rotation:f.rotation||0,align:l}).addClass("highcharts-axis-title"),u||this.axisTitle.css(e(f.style)),this.axisTitle.add(this.axisGroup),this.axisTitle.isNew=!0);u||f.style.width||this.isRadial||this.axisTitle.css({width:this.len});this.axisTitle[a?"show":"hide"](a)}, generateTick:function(a){var e=this.ticks;e[a]?e[a].addLabel():e[a]=new G(this,a)},getOffset:function(){var a=this,e=a.chart,b=e.renderer,c=a.options,k=a.tickPositions,f=a.ticks,l=a.horiz,u=a.side,d=e.inverted&&!a.isZAxis?[1,0,3,2][u]:u,h,n=0,r=0,H=c.title,G=c.labels,g=0,m=e.axisOffset;e=e.clipOffset;var I=[-1,1,1,-1][u],p=c.className,z=a.axisParent;var x=a.hasData();a.showAxis=h=x||w(c.showEmpty,!0);a.staggerLines=a.horiz&&G.staggerLines;a.axisGroup||(a.gridGroup=b.g("grid").attr({zIndex:c.gridZIndex|| 1}).addClass("highcharts-"+this.coll.toLowerCase()+"-grid "+(p||"")).add(z),a.axisGroup=b.g("axis").attr({zIndex:c.zIndex||2}).addClass("highcharts-"+this.coll.toLowerCase()+" "+(p||"")).add(z),a.labelGroup=b.g("axis-labels").attr({zIndex:G.zIndex||7}).addClass("highcharts-"+a.coll.toLowerCase()+"-labels "+(p||"")).add(z));x||a.isLinked?(k.forEach(function(e,b){a.generateTick(e,b)}),a.renderUnsquish(),a.reserveSpaceDefault=0===u||2===u||{1:"left",3:"right"}[u]===a.labelAlign,w(G.reserveSpace,"center"=== a.labelAlign?!0:null,a.reserveSpaceDefault)&&k.forEach(function(a){g=Math.max(f[a].getLabelSize(),g)}),a.staggerLines&&(g*=a.staggerLines),a.labelOffset=g*(a.opposite?-1:1)):q(f,function(a,e){a.destroy();delete f[e]});if(H&&H.text&&!1!==H.enabled&&(a.addTitle(h),h&&!1!==H.reserveSpace)){a.titleOffset=n=a.axisTitle.getBBox()[l?"height":"width"];var C=H.offset;r=v(C)?0:w(H.margin,l?5:10)}a.renderLine();a.offset=I*w(c.offset,m[u]?m[u]+(c.margin||0):0);a.tickRotCorr=a.tickRotCorr||{x:0,y:0};b=0===u?-a.labelMetrics().h: 2===u?a.tickRotCorr.y:0;r=Math.abs(g)+r;g&&(r=r-b+I*(l?w(G.y,a.tickRotCorr.y+8*I):G.x));a.axisTitleMargin=w(C,r);a.getMaxLabelDimensions&&(a.maxLabelDimensions=a.getMaxLabelDimensions(f,k));l=this.tickSize("tick");m[u]=Math.max(m[u],a.axisTitleMargin+n+I*a.offset,r,k&&k.length&&l?l[0]+I*a.offset:0);c=c.offset?0:2*Math.floor(a.axisLine.strokeWidth()/2);e[d]=Math.max(e[d],c);t(this,"afterGetOffset")},getLinePath:function(a){var e=this.chart,b=this.opposite,c=this.offset,k=this.horiz,f=this.left+(b? this.width:0)+c;c=e.chartHeight-this.bottom-(b?this.height:0)+c;b&&(a*=-1);return e.renderer.crispLine(["M",k?this.left:f,k?c:this.top,"L",k?e.chartWidth-this.right:f,k?c:e.chartHeight-this.bottom],a)},renderLine:function(){this.axisLine||(this.axisLine=this.chart.renderer.path().addClass("highcharts-axis-line").add(this.axisGroup),this.chart.styledMode||this.axisLine.attr({stroke:this.options.lineColor,"stroke-width":this.options.lineWidth,zIndex:7}))},getTitlePosition:function(){var a=this.horiz, e=this.left,b=this.top,c=this.len,k=this.options.title,f=a?e:b,l=this.opposite,u=this.offset,d=k.x||0,h=k.y||0,n=this.axisTitle,r=this.chart.renderer.fontMetrics(k.style&&k.style.fontSize,n);n=Math.max(n.getBBox(null,0).height-r.h-1,0);c={low:f+(a?0:c),middle:f+c/2,high:f+(a?c:0)}[k.align];e=(a?b+this.height:e)+(a?1:-1)*(l?-1:1)*this.axisTitleMargin+[-n,n,r.f,-n][this.side];a={x:a?c+d:e+(l?this.width:0)+u+d,y:a?e+h-(l?this.height:0)+u:c+h};t(this,"afterGetTitlePosition",{titlePosition:a});return a}, renderMinorTick:function(a){var e=this.chart.hasRendered&&z(this.oldMin),b=this.minorTicks;b[a]||(b[a]=new G(this,a,"minor"));e&&b[a].isNew&&b[a].render(null,!0);b[a].render(null,!1,1)},renderTick:function(a,e){var b=this.isLinked,c=this.ticks,k=this.chart.hasRendered&&z(this.oldMin);if(!b||a>=this.min&&a<=this.max)c[a]||(c[a]=new G(this,a)),k&&c[a].isNew&&c[a].render(e,!0,-1),c[a].render(e)},render:function(){var a=this,e=a.chart,b=a.options,k=a.isLog,f=a.isLinked,l=a.tickPositions,u=a.axisTitle, h=a.ticks,n=a.minorTicks,r=a.alternateBands,H=b.stackLabels,g=b.alternateGridColor,m=a.tickmarkOffset,I=a.axisLine,p=a.showAxis,w=M(e.renderer.globalAnimation),v,x;a.labelEdge.length=0;a.overlap=!1;[h,n,r].forEach(function(a){q(a,function(a){a.isActive=!1})});if(a.hasData()||f)a.minorTickInterval&&!a.categories&&a.getMinorTickPositions().forEach(function(e){a.renderMinorTick(e)}),l.length&&(l.forEach(function(e,b){a.renderTick(e,b)}),m&&(0===a.min||a.single)&&(h[-1]||(h[-1]=new G(a,-1,null,!0)),h[-1].render(-1))), g&&l.forEach(function(b,c){x="undefined"!==typeof l[c+1]?l[c+1]+m:a.max-m;0===c%2&&b<a.max&&x<=a.max+(e.polar?-m:m)&&(r[b]||(r[b]=new d.PlotLineOrBand(a)),v=b+m,r[b].options={from:k?a.lin2log(v):v,to:k?a.lin2log(x):x,color:g},r[b].render(),r[b].isActive=!0)}),a._addedPlotLB||((b.plotLines||[]).concat(b.plotBands||[]).forEach(function(e){a.addPlotBandOrLine(e)}),a._addedPlotLB=!0);[h,n,r].forEach(function(a){var b,k=[],f=w.duration;q(a,function(a,e){a.isActive||(a.render(e,!1,0),a.isActive=!1,k.push(e))}); c(function(){for(b=k.length;b--;)a[k[b]]&&!a[k[b]].isActive&&(a[k[b]].destroy(),delete a[k[b]])},a!==r&&e.hasRendered&&f?f:0)});I&&(I[I.isPlaced?"animate":"attr"]({d:this.getLinePath(I.strokeWidth())}),I.isPlaced=!0,I[p?"show":"hide"](p));u&&p&&(b=a.getTitlePosition(),z(b.y)?(u[u.isNew?"attr":"animate"](b),u.isNew=!1):(u.attr("y",-9999),u.isNew=!0));H&&H.enabled&&a.renderStackTotals();a.isDirty=!1;t(this,"afterRender")},redraw:function(){this.visible&&(this.render(),this.plotLinesAndBands.forEach(function(a){a.render()})); this.series.forEach(function(a){a.isDirty=!0})},keepProps:"extKey hcEvents names series userMax userMin".split(" "),destroy:function(a){var e=this,b=e.stacks,c=e.plotLinesAndBands,k;t(this,"destroy",{keepEvents:a});a||u(e);q(b,function(a,e){C(a);b[e]=null});[e.ticks,e.minorTicks,e.alternateBands].forEach(function(a){C(a)});if(c)for(a=c.length;a--;)c[a].destroy();"stackTotalGroup axisLine axisTitle axisGroup gridGroup labelGroup cross scrollbar".split(" ").forEach(function(a){e[a]&&(e[a]=e[a].destroy())}); for(k in e.plotLinesAndBandsGroups)e.plotLinesAndBandsGroups[k]=e.plotLinesAndBandsGroups[k].destroy();q(e,function(a,b){-1===e.keepProps.indexOf(b)&&delete e[b]})},drawCrosshair:function(e,b){var c=this.crosshair,k=w(c.snap,!0),f,l=this.cross;t(this,"drawCrosshair",{e:e,point:b});e||(e=this.cross&&this.cross.e);if(this.crosshair&&!1!==(v(b)||!k)){k?v(b)&&(f=w("colorAxis"!==this.coll?b.crosshairPos:null,this.isXAxis?b.plotX:this.len-b.plotY)):f=e&&(this.horiz?e.chartX-this.pos:this.len-e.chartY+this.pos); if(v(f)){var u={value:b&&(this.isXAxis?b.x:w(b.stackY,b.y)),translatedValue:f};this.chart.polar&&B(u,{isCrosshair:!0,chartX:e&&e.chartX,chartY:e&&e.chartY,point:b});u=this.getPlotLinePath(u)||null}if(!v(u)){this.hideCrosshair();return}k=this.categories&&!this.isRadial;l||(this.cross=l=this.chart.renderer.path().addClass("highcharts-crosshair highcharts-crosshair-"+(k?"category ":"thin ")+c.className).attr({zIndex:w(c.zIndex,2)}).add(),this.chart.styledMode||(l.attr({stroke:c.color||(k?a("#ccd6eb").setOpacity(.25).get(): "#cccccc"),"stroke-width":w(c.width,1)}).css({"pointer-events":"none"}),c.dashStyle&&l.attr({dashstyle:c.dashStyle})));l.show().attr({d:u});k&&!c.width&&l.attr({"stroke-width":this.transA});this.cross.e=e}else this.hideCrosshair();t(this,"afterDrawCrosshair",{e:e,point:b})},hideCrosshair:function(){this.cross&&this.cross.hide();t(this,"afterHideCrosshair")}});return d.Axis=g});K(y,"parts/DateTimeAxis.js",[y["parts/Globals.js"]],function(d){var g=d.Axis,M=d.getMagnitude,F=d.normalizeTickInterval,E= d.timeUnits;g.prototype.getTimeTicks=function(){return this.chart.time.getTimeTicks.apply(this.chart.time,arguments)};g.prototype.normalizeTimeTickInterval=function(d,g){var v=g||[["millisecond",[1,2,5,10,20,25,50,100,200,500]],["second",[1,2,5,10,15,30]],["minute",[1,2,5,10,15,30]],["hour",[1,2,3,4,6,8,12]],["day",[1,2]],["week",[1,2]],["month",[1,2,3,4,6]],["year",null]];g=v[v.length-1];var x=E[g[0]],B=g[1],p;for(p=0;p<v.length&&!(g=v[p],x=E[g[0]],B=g[1],v[p+1]&&d<=(x*B[B.length-1]+E[v[p+1][0]])/ 2);p++);x===E.year&&d<5*x&&(B=[1,2,5]);d=F(d/x,B,"year"===g[0]?Math.max(M(d/x),1):1);return{unitRange:x,count:d,unitName:g[0]}}});K(y,"parts/LogarithmicAxis.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var M=g.pick;g=d.Axis;var F=d.getMagnitude,E=d.normalizeTickInterval;g.prototype.getLogTickPositions=function(d,g,v,C){var x=this.options,p=this.len,z=[];C||(this._minorAutoInterval=null);if(.5<=d)d=Math.round(d),z=this.getLinearTickPositions(d,g,v);else if(.08<=d){p=Math.floor(g); var m,q;for(x=.3<d?[1,2,4]:.15<d?[1,2,4,6,8]:[1,2,3,4,5,6,7,8,9];p<v+1&&!q;p++){var w=x.length;for(m=0;m<w&&!q;m++){var h=this.log2lin(this.lin2log(p)*x[m]);h>g&&(!C||f<=v)&&"undefined"!==typeof f&&z.push(f);f>v&&(q=!0);var f=h}}}else g=this.lin2log(g),v=this.lin2log(v),d=C?this.getMinorTickInterval():x.tickInterval,d=M("auto"===d?null:d,this._minorAutoInterval,x.tickPixelInterval/(C?5:1)*(v-g)/((C?p/this.tickPositions.length:p)||1)),d=E(d,null,F(d)),z=this.getLinearTickPositions(d,g,v).map(this.log2lin), C||(this._minorAutoInterval=d/5);C||(this.tickInterval=d);return z};g.prototype.log2lin=function(d){return Math.log(d)/Math.LN10};g.prototype.lin2log=function(d){return Math.pow(10,d)}});K(y,"parts/PlotLineOrBand.js",[y["parts/Globals.js"],y["parts/Axis.js"],y["parts/Utilities.js"]],function(d,g,M){var F=M.arrayMax,E=M.arrayMin,D=M.defined,x=M.destroyObjectProperties,v=M.erase,C=M.extend,B=M.objectEach,p=M.pick,z=d.merge;d.PlotLineOrBand=function(d,g){this.axis=d;g&&(this.options=g,this.id=g.id)}; d.PlotLineOrBand.prototype={render:function(){d.fireEvent(this,"render");var g=this,q=g.axis,w=q.horiz,h=g.options,f=h.label,c=g.label,b=h.to,a=h.from,l=h.value,n=D(a)&&D(b),t=D(l),I=g.svgElem,r=!I,e=[],k=h.color,u=p(h.zIndex,0),H=h.events;e={"class":"highcharts-plot-"+(n?"band ":"line ")+(h.className||"")};var G={},A=q.chart.renderer,J=n?"bands":"lines";q.isLog&&(a=q.log2lin(a),b=q.log2lin(b),l=q.log2lin(l));q.chart.styledMode||(t?(e.stroke=k||"#999999",e["stroke-width"]=p(h.width,1),h.dashStyle&& (e.dashstyle=h.dashStyle)):n&&(e.fill=k||"#e6ebf5",h.borderWidth&&(e.stroke=h.borderColor,e["stroke-width"]=h.borderWidth)));G.zIndex=u;J+="-"+u;(k=q.plotLinesAndBandsGroups[J])||(q.plotLinesAndBandsGroups[J]=k=A.g("plot-"+J).attr(G).add());r&&(g.svgElem=I=A.path().attr(e).add(k));if(t)e=q.getPlotLinePath({value:l,lineWidth:I.strokeWidth(),acrossPanes:h.acrossPanes});else if(n)e=q.getPlotBandPath(a,b,h);else return;(r||!I.d)&&e&&e.length?(I.attr({d:e}),H&&B(H,function(a,e){I.on(e,function(a){H[e].apply(g, [a])})})):I&&(e?(I.show(!0),I.animate({d:e})):I.d&&(I.hide(),c&&(g.label=c=c.destroy())));f&&(D(f.text)||D(f.formatter))&&e&&e.length&&0<q.width&&0<q.height&&!e.isFlat?(f=z({align:w&&n&&"center",x:w?!n&&4:10,verticalAlign:!w&&n&&"middle",y:w?n?16:10:n?6:-4,rotation:w&&!n&&90},f),this.renderLabel(f,e,n,u)):c&&c.hide();return g},renderLabel:function(d,g,p,h){var f=this.label,c=this.axis.chart.renderer;f||(f={align:d.textAlign||d.align,rotation:d.rotation,"class":"highcharts-plot-"+(p?"band":"line")+ "-label "+(d.className||"")},f.zIndex=h,h=this.getLabelText(d),this.label=f=c.text(h,0,0,d.useHTML).attr(f).add(),this.axis.chart.styledMode||f.css(d.style));c=g.xBounds||[g[1],g[4],p?g[6]:g[1]];g=g.yBounds||[g[2],g[5],p?g[7]:g[2]];p=E(c);h=E(g);f.align(d,!1,{x:p,y:h,width:F(c)-p,height:F(g)-h});f.show(!0)},getLabelText:function(d){return D(d.formatter)?d.formatter.call(this):d.text},destroy:function(){v(this.axis.plotLinesAndBands,this);delete this.axis;x(this)}};C(g.prototype,{getPlotBandPath:function(d, g){var m=this.getPlotLinePath({value:g,force:!0,acrossPanes:this.options.acrossPanes}),h=this.getPlotLinePath({value:d,force:!0,acrossPanes:this.options.acrossPanes}),f=[],c=this.horiz,b=1;d=d<this.min&&g<this.min||d>this.max&&g>this.max;if(h&&m){if(d){var a=h.toString()===m.toString();b=0}for(d=0;d<h.length;d+=6)c&&m[d+1]===h[d+1]?(m[d+1]+=b,m[d+4]+=b):c||m[d+2]!==h[d+2]||(m[d+2]+=b,m[d+5]+=b),f.push("M",h[d+1],h[d+2],"L",h[d+4],h[d+5],m[d+4],m[d+5],m[d+1],m[d+2],"z"),f.isFlat=a}return f},addPlotBand:function(d){return this.addPlotBandOrLine(d, "plotBands")},addPlotLine:function(d){return this.addPlotBandOrLine(d,"plotLines")},addPlotBandOrLine:function(g,q){var m=(new d.PlotLineOrBand(this,g)).render(),h=this.userOptions;if(m){if(q){var f=h[q]||[];f.push(g);h[q]=f}this.plotLinesAndBands.push(m)}return m},removePlotBandOrLine:function(d){for(var g=this.plotLinesAndBands,m=this.options,h=this.userOptions,f=g.length;f--;)g[f].id===d&&g[f].destroy();[m.plotLines||[],h.plotLines||[],m.plotBands||[],h.plotBands||[]].forEach(function(c){for(f= c.length;f--;)c[f].id===d&&v(c,c[f])})},removePlotBand:function(d){this.removePlotBandOrLine(d)},removePlotLine:function(d){this.removePlotBandOrLine(d)}})});K(y,"parts/Tooltip.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var M=g.clamp,F=g.defined,E=g.discardElement,D=g.extend,x=g.isNumber,v=g.isString,C=g.pick,B=g.splat,p=g.syncTimeout;"";var z=d.doc,m=d.format,q=d.merge,w=d.timeUnits;d.Tooltip=function(){this.init.apply(this,arguments)};d.Tooltip.prototype={init:function(d, f){this.chart=d;this.options=f;this.crosshairs=[];this.now={x:0,y:0};this.isHidden=!0;this.split=f.split&&!d.inverted&&!d.polar;this.shared=f.shared||this.split;this.outside=C(f.outside,!(!d.scrollablePixelsX&&!d.scrollablePixelsY))},cleanSplit:function(d){this.chart.series.forEach(function(f){var c=f&&f.tt;c&&(!c.isActive||d?f.tt=c.destroy():c.isActive=!1)})},applyFilter:function(){var d=this.chart;d.renderer.definition({tagName:"filter",id:"drop-shadow-"+d.index,opacity:.5,children:[{tagName:"feGaussianBlur", "in":"SourceAlpha",stdDeviation:1},{tagName:"feOffset",dx:1,dy:1},{tagName:"feComponentTransfer",children:[{tagName:"feFuncA",type:"linear",slope:.3}]},{tagName:"feMerge",children:[{tagName:"feMergeNode"},{tagName:"feMergeNode","in":"SourceGraphic"}]}]});d.renderer.definition({tagName:"style",textContent:".highcharts-tooltip-"+d.index+"{filter:url(#drop-shadow-"+d.index+")}"})},getLabel:function(){var h=this,f=this.chart.renderer,c=this.chart.styledMode,b=this.options,a="tooltip"+(F(b.className)? " "+b.className:""),l;if(!this.label){this.outside&&(this.container=l=d.doc.createElement("div"),l.className="highcharts-tooltip-container",d.css(l,{position:"absolute",top:"1px",pointerEvents:b.style&&b.style.pointerEvents,zIndex:3}),d.doc.body.appendChild(l),this.renderer=f=new d.Renderer(l,0,0,{},void 0,void 0,f.styledMode));this.split?this.label=f.g(a):(this.label=f.label("",0,0,b.shape||"callout",null,null,b.useHTML,null,a).attr({padding:b.padding,r:b.borderRadius}),c||this.label.attr({fill:b.backgroundColor, "stroke-width":b.borderWidth}).css(b.style).shadow(b.shadow));c&&(this.applyFilter(),this.label.addClass("highcharts-tooltip-"+this.chart.index));if(h.outside&&!h.split){var n={x:this.label.xSetter,y:this.label.ySetter};this.label.xSetter=function(a,b){n[b].call(this.label,h.distance);l.style.left=a+"px"};this.label.ySetter=function(a,b){n[b].call(this.label,h.distance);l.style.top=a+"px"}}this.label.attr({zIndex:8}).add()}return this.label},update:function(d){this.destroy();q(!0,this.chart.options.tooltip.userOptions, d);this.init(this.chart,q(!0,this.options,d))},destroy:function(){this.label&&(this.label=this.label.destroy());this.split&&this.tt&&(this.cleanSplit(this.chart,!0),this.tt=this.tt.destroy());this.renderer&&(this.renderer=this.renderer.destroy(),E(this.container));d.clearTimeout(this.hideTimer);d.clearTimeout(this.tooltipTimeout)},move:function(h,f,c,b){var a=this,l=a.now,n=!1!==a.options.animation&&!a.isHidden&&(1<Math.abs(h-l.x)||1<Math.abs(f-l.y)),t=a.followPointer||1<a.len;D(l,{x:n?(2*l.x+h)/ 3:h,y:n?(l.y+f)/2:f,anchorX:t?void 0:n?(2*l.anchorX+c)/3:c,anchorY:t?void 0:n?(l.anchorY+b)/2:b});a.getLabel().attr(l);n&&(d.clearTimeout(this.tooltipTimeout),this.tooltipTimeout=setTimeout(function(){a&&a.move(h,f,c,b)},32))},hide:function(h){var f=this;d.clearTimeout(this.hideTimer);h=C(h,this.options.hideDelay,500);this.isHidden||(this.hideTimer=p(function(){f.getLabel()[h?"fadeOut":"hide"]();f.isHidden=!0},h))},getAnchor:function(d,f){var c=this.chart,b=c.pointer,a=c.inverted,l=c.plotTop,h=c.plotLeft, t=0,g=0,r,e;d=B(d);this.followPointer&&f?("undefined"===typeof f.chartX&&(f=b.normalize(f)),d=[f.chartX-c.plotLeft,f.chartY-l]):d[0].tooltipPos?d=d[0].tooltipPos:(d.forEach(function(b){r=b.series.yAxis;e=b.series.xAxis;t+=b.plotX+(!a&&e?e.left-h:0);g+=(b.plotLow?(b.plotLow+b.plotHigh)/2:b.plotY)+(!a&&r?r.top-l:0)}),t/=d.length,g/=d.length,d=[a?c.plotWidth-g:t,this.shared&&!a&&1<d.length&&f?f.chartY-l:a?c.plotHeight-t:g]);return d.map(Math.round)},getPosition:function(d,f,c){var b=this.chart,a=this.distance, l={},h=b.inverted&&c.h||0,t,g=this.outside,r=g?z.documentElement.clientWidth-2*a:b.chartWidth,e=g?Math.max(z.body.scrollHeight,z.documentElement.scrollHeight,z.body.offsetHeight,z.documentElement.offsetHeight,z.documentElement.clientHeight):b.chartHeight,k=b.pointer.getChartPosition(),u=b.containerScaling,H=function(a){return u?a*u.scaleX:a},G=function(a){return u?a*u.scaleY:a},A=function(l){var u="x"===l;return[l,u?r:e,u?d:f].concat(g?[u?H(d):G(f),u?k.left-a+H(c.plotX+b.plotLeft):k.top-a+G(c.plotY+ b.plotTop),0,u?r:e]:[u?d:f,u?c.plotX+b.plotLeft:c.plotY+b.plotTop,u?b.plotLeft:b.plotTop,u?b.plotLeft+b.plotWidth:b.plotTop+b.plotHeight])},m=A("y"),L=A("x"),q=!this.followPointer&&C(c.ttBelow,!b.inverted===!!c.negative),p=function(e,b,c,k,f,u,d){var t="y"===e?G(a):H(a),n=(c-k)/2,r=k<f-a,A=f+a+k<b,g=f-t-c+n;f=f+t-n;if(q&&A)l[e]=f;else if(!q&&r)l[e]=g;else if(r)l[e]=Math.min(d-k,0>g-h?g:g-h);else if(A)l[e]=Math.max(u,f+h+c>b?f:f+h);else return!1},v=function(e,b,c,k,f){var u;f<a||f>b-a?u=!1:l[e]=f< c/2?1:f>b-k/2?b-k-2:f-c/2;return u},w=function(a){var e=m;m=L;L=e;t=a},x=function(){!1!==p.apply(0,m)?!1!==v.apply(0,L)||t||(w(!0),x()):t?l.x=l.y=0:(w(!0),x())};(b.inverted||1<this.len)&&w();x();return l},defaultFormatter:function(d){var f=this.points||B(this);var c=[d.tooltipFooterHeaderFormatter(f[0])];c=c.concat(d.bodyFormatter(f));c.push(d.tooltipFooterHeaderFormatter(f[0],!0));return c},refresh:function(h,f){var c=this.chart,b=this.options,a=h,l={},n=[],t=b.formatter||this.defaultFormatter;l= this.shared;var g=c.styledMode;if(b.enabled){d.clearTimeout(this.hideTimer);this.followPointer=B(a)[0].series.tooltipOptions.followPointer;var r=this.getAnchor(a,f);f=r[0];var e=r[1];!l||a.series&&a.series.noSharedTooltip?l=a.getLabelConfig():(c.pointer.applyInactiveState(a),a.forEach(function(a){a.setState("hover");n.push(a.getLabelConfig())}),l={x:a[0].category,y:a[0].y},l.points=n,a=a[0]);this.len=n.length;c=t.call(l,this);t=a.series;this.distance=C(t.tooltipOptions.distance,16);!1===c?this.hide(): (this.split?this.renderSplit(c,B(h)):(h=this.getLabel(),b.style.width&&!g||h.css({width:this.chart.spacingBox.width}),h.attr({text:c&&c.join?c.join(""):c}),h.removeClass(/highcharts-color-[\d]+/g).addClass("highcharts-color-"+C(a.colorIndex,t.colorIndex)),g||h.attr({stroke:b.borderColor||a.color||t.color||"#666666"}),this.updatePosition({plotX:f,plotY:e,negative:a.negative,ttBelow:a.ttBelow,h:r[2]||0})),this.isHidden&&this.label&&this.label.attr({opacity:1}).show(),this.isHidden=!1);d.fireEvent(this, "refresh")}},renderSplit:function(h,f){function c(a,e,b,c,k){void 0===k&&(k=!0);b?(e=B?0:y,a=M(a-c/2,N.left,N.right-c)):(e-=E,a=k?a-c-z:a+z,a=M(a,k?a:N.left,N.right));return{x:a,y:e}}var b=this,a=b.chart,l=b.chart,n=l.chartWidth,t=l.chartHeight,g=l.plotHeight,r=l.plotLeft,e=l.plotTop,k=l.plotWidth,u=l.pointer,H=l.renderer,G=l.scrollablePixelsX;G=void 0===G?0:G;var A=l.scrollablePixelsY,m=void 0===A?0:A;A=l.scrollingContainer;A=void 0===A?{scrollLeft:0,scrollTop:0}:A;var L=A.scrollLeft,q=A.scrollTop, p=l.styledMode,z=b.distance,w=b.options,x=b.options.positioner,N={left:G?r:0,right:G?r+k-G:n,top:m?e:0,bottom:m?e+g-m:t},ba=b.getLabel(),B=!(!a.xAxis[0]||!a.xAxis[0].opposite),E=e,F=0,y=g-m;v(h)&&(h=[!1,h]);h=h.slice(0,f.length+1).reduce(function(a,k,l){if(!1!==k&&""!==k){l=f[l-1]||{isHeader:!0,plotX:f[0].plotX,plotY:g,series:{}};var u=l.isHeader,d=u?b:l.series,h=d.tt,t=l.isHeader;var n=l.series;var A="highcharts-color-"+C(l.colorIndex,n.colorIndex,"none");h||(h={padding:w.padding,r:w.borderRadius}, p||(h.fill=w.backgroundColor,h["stroke-width"]=w.borderWidth),h=H.label(null,null,null,w[t?"headerShape":"shape"]||"callout",null,null,w.useHTML).addClass(t?"highcharts-tooltip-header ":"highcharts-tooltip-box "+A).attr(h).add(ba));h.isActive=!0;h.attr({text:k});p||h.css(w.style).shadow(w.shadow).attr({stroke:w.borderColor||l.color||n.color||"#333333"});k=d.tt=h;t=k.getBBox();d=t.width+k.strokeWidth();u&&(F=t.height,y+=F,B&&(E-=F));n=l.plotX;n=void 0===n?0:n;A=l.plotY;A=void 0===A?0:A;var G=l.series; l.isHeader?(n=r+n-L,A=e+(g-m)/2):(h=G.xAxis,G=G.yAxis,n=h.pos+M(n,-z,h.len+z)-L,A=G.pos+M(A,0,G.len)-q);n=M(n,N.left-z,N.right+z);A=M(A,N.top,N.bottom);t=t.height+1;h=x?x.call(b,d,t,l):c(n,A,u,d);a.push({align:x?0:void 0,anchorX:n,anchorY:A,boxWidth:d,point:l,rank:C(h.rank,u?1:0),size:t,target:h.y,tt:k,x:h.x})}return a},[]);!x&&h.some(function(a){return 0>a.x})&&(h=h.map(function(a){var e=c(a.anchorX,a.anchorY,a.point.isHeader,a.boxWidth,!1);return D(a,{target:e.y,x:e.x})}));b.cleanSplit();d.distribute(h, y,void 0);h.forEach(function(a){var e=a.pos;a.tt.attr({visibility:"undefined"===typeof e?"hidden":"inherit",x:a.x,y:e+E,anchorX:a.anchorX,anchorY:a.anchorY})});h=b.container;a=b.renderer;b.outside&&h&&a&&(l=ba.getBBox(),a.setSize(l.width+l.x,l.height+l.y,!1),u=u.getChartPosition(),h.style.left=u.left+"px",h.style.top=u.top+"px")},updatePosition:function(h){var f=this.chart,c=f.pointer,b=this.getLabel(),a=h.plotX+f.plotLeft,l=h.plotY+f.plotTop;c=c.getChartPosition();h=(this.options.positioner||this.getPosition).call(this, b.width,b.height,h);if(this.outside){var n=(this.options.borderWidth||0)+2*this.distance;this.renderer.setSize(b.width+n,b.height+n,!1);if(f=f.containerScaling)d.css(this.container,{transform:"scale("+f.scaleX+", "+f.scaleY+")"}),a*=f.scaleX,l*=f.scaleY;a+=c.left-h.x;l+=c.top-h.y}this.move(Math.round(h.x),Math.round(h.y||0),a,l)},getDateFormat:function(d,f,c,b){var a=this.chart.time,l=a.dateFormat("%m-%d %H:%M:%S.%L",f),h={millisecond:15,second:12,minute:9,hour:6,day:3},t="millisecond";for(g in w){if(d=== w.week&&+a.dateFormat("%w",f)===c&&"00:00:00.000"===l.substr(6)){var g="week";break}if(w[g]>d){g=t;break}if(h[g]&&l.substr(h[g])!=="01-01 00:00:00.000".substr(h[g]))break;"week"!==g&&(t=g)}if(g)var r=a.resolveDTLFormat(b[g]).main;return r},getXDateFormat:function(d,f,c){f=f.dateTimeLabelFormats;var b=c&&c.closestPointRange;return(b?this.getDateFormat(b,d.x,c.options.startOfWeek,f):f.day)||f.year},tooltipFooterHeaderFormatter:function(h,f){var c=f?"footer":"header",b=h.series,a=b.tooltipOptions,l= a.xDateFormat,n=b.xAxis,t=n&&"datetime"===n.options.type&&x(h.key),g=a[c+"Format"];f={isFooter:f,labelConfig:h};d.fireEvent(this,"headerFormatter",f,function(c){t&&!l&&(l=this.getXDateFormat(h,a,n));t&&l&&(h.point&&h.point.tooltipDateKeys||["key"]).forEach(function(a){g=g.replace("{point."+a+"}","{point."+a+":"+l+"}")});b.chart.styledMode&&(g=this.styledModeFormat(g));c.text=m(g,{point:h,series:b},this.chart)});return f.text},bodyFormatter:function(d){return d.map(function(f){var c=f.series.tooltipOptions; return(c[(f.point.formatPrefix||"point")+"Formatter"]||f.point.tooltipFormatter).call(f.point,c[(f.point.formatPrefix||"point")+"Format"]||"")})},styledModeFormat:function(d){return d.replace('style="font-size: 10px"','class="highcharts-header"').replace(/style="color:{(point|series)\.color}"/g,'class="highcharts-color-{$1.colorIndex}"')}}});K(y,"parts/Pointer.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.attr,F=g.defined,E=g.extend,D=g.isNumber,x=g.isObject,v=g.objectEach, C=g.offset,B=g.pick,p=g.splat,z=d.addEvent,m=d.charts,q=d.color,w=d.css,h=d.find,f=d.fireEvent,c=d.Tooltip;d.Pointer=function(b,a){this.init(b,a)};d.Pointer.prototype={init:function(b,a){this.options=a;this.chart=b;this.runChartClick=a.chart.events&&!!a.chart.events.click;this.pinchDown=[];this.lastValidTouch={};c&&(b.tooltip=new c(b,a.tooltip),this.followTouchMove=B(a.tooltip.followTouchMove,!0));this.setDOMEvents()},zoomOption:function(b){var a=this.chart,c=a.options.chart,f=c.zoomType||"";a=a.inverted; /touch/.test(b.type)&&(f=B(c.pinchType,f));this.zoomX=b=/x/.test(f);this.zoomY=f=/y/.test(f);this.zoomHor=b&&!a||f&&a;this.zoomVert=f&&!a||b&&a;this.hasZoom=b||f},getChartPosition:function(){var b=this.chart;b=b.scrollingContainer||b.container;return this.chartPosition||(this.chartPosition=C(b))},normalize:function(b,a){var c=b.touches?b.touches.length?b.touches.item(0):b.changedTouches[0]:b;a||(a=this.getChartPosition());var f=c.pageX-a.left;a=c.pageY-a.top;if(c=this.chart.containerScaling)f/=c.scaleX, a/=c.scaleY;return E(b,{chartX:Math.round(f),chartY:Math.round(a)})},getCoordinates:function(b){var a={xAxis:[],yAxis:[]};this.chart.axes.forEach(function(c){a[c.isXAxis?"xAxis":"yAxis"].push({axis:c,value:c.toValue(b[c.horiz?"chartX":"chartY"])})});return a},findNearestKDPoint:function(b,a,c){var f;b.forEach(function(b){var l=!(b.noSharedTooltip&&a)&&0>b.options.findNearestPointBy.indexOf("y");b=b.searchPoint(c,l);if((l=x(b,!0))&&!(l=!x(f,!0))){l=f.distX-b.distX;var d=f.dist-b.dist,e=(b.series.group&& b.series.group.zIndex)-(f.series.group&&f.series.group.zIndex);l=0<(0!==l&&a?l:0!==d?d:0!==e?e:f.series.index>b.series.index?-1:1)}l&&(f=b)});return f},getPointFromEvent:function(b){b=b.target;for(var a;b&&!a;)a=b.point,b=b.parentNode;return a},getChartCoordinatesFromPoint:function(b,a){var c=b.series,f=c.xAxis;c=c.yAxis;var d=B(b.clientX,b.plotX),h=b.shapeArgs;if(f&&c)return a?{chartX:f.len+f.pos-d,chartY:c.len+c.pos-b.plotY}:{chartX:d+f.pos,chartY:b.plotY+c.pos};if(h&&h.x&&h.y)return{chartX:h.x, chartY:h.y}},getHoverData:function(b,a,c,f,d,g){var l,e=[];f=!(!f||!b);var k=a&&!a.stickyTracking?[a]:c.filter(function(a){return a.visible&&!(!d&&a.directTouch)&&B(a.options.enableMouseTracking,!0)&&a.stickyTracking});a=(l=f||!g?b:this.findNearestKDPoint(k,d,g))&&l.series;l&&(d&&!a.noSharedTooltip?(k=c.filter(function(a){return a.visible&&!(!d&&a.directTouch)&&B(a.options.enableMouseTracking,!0)&&!a.noSharedTooltip}),k.forEach(function(a){var b=h(a.points,function(a){return a.x===l.x&&!a.isNull}); x(b)&&(a.chart.isBoosting&&(b=a.getPoint(b)),e.push(b))})):e.push(l));return{hoverPoint:l,hoverSeries:a,hoverPoints:e}},runPointActions:function(b,a){var c=this.chart,f=c.tooltip&&c.tooltip.options.enabled?c.tooltip:void 0,h=f?f.shared:!1,g=a||c.hoverPoint,r=g&&g.series||c.hoverSeries;r=this.getHoverData(g,r,c.series,(!b||"touchmove"!==b.type)&&(!!a||r&&r.directTouch&&this.isDirectTouch),h,b);g=r.hoverPoint;var e=r.hoverPoints;a=(r=r.hoverSeries)&&r.tooltipOptions.followPointer;h=h&&r&&!r.noSharedTooltip; if(g&&(g!==c.hoverPoint||f&&f.isHidden)){(c.hoverPoints||[]).forEach(function(a){-1===e.indexOf(a)&&a.setState()});if(c.hoverSeries!==r)r.onMouseOver();this.applyInactiveState(e);(e||[]).forEach(function(a){a.setState("hover")});c.hoverPoint&&c.hoverPoint.firePointEvent("mouseOut");if(!g.series)return;g.firePointEvent("mouseOver");c.hoverPoints=e;c.hoverPoint=g;f&&f.refresh(h?e:g,b)}else a&&f&&!f.isHidden&&(g=f.getAnchor([{}],b),f.updatePosition({plotX:g[0],plotY:g[1]}));this.unDocMouseMove||(this.unDocMouseMove= z(c.container.ownerDocument,"mousemove",function(a){var e=m[d.hoverChartIndex];if(e)e.pointer.onDocumentMouseMove(a)}));c.axes.forEach(function(a){var c=B(a.crosshair.snap,!0),k=c?d.find(e,function(e){return e.series[a.coll]===a}):void 0;k||!c?a.drawCrosshair(b,k):a.hideCrosshair()})},applyInactiveState:function(b){var a=[],c;(b||[]).forEach(function(b){c=b.series;a.push(c);c.linkedParent&&a.push(c.linkedParent);c.linkedSeries&&(a=a.concat(c.linkedSeries));c.navigatorSeries&&a.push(c.navigatorSeries)}); this.chart.series.forEach(function(b){-1===a.indexOf(b)?b.setState("inactive",!0):b.options.inactiveOtherPoints&&b.setAllPointsToState("inactive")})},reset:function(b,a){var c=this.chart,f=c.hoverSeries,d=c.hoverPoint,h=c.hoverPoints,r=c.tooltip,e=r&&r.shared?h:d;b&&e&&p(e).forEach(function(a){a.series.isCartesian&&"undefined"===typeof a.plotX&&(b=!1)});if(b)r&&e&&p(e).length&&(r.refresh(e),r.shared&&h?h.forEach(function(a){a.setState(a.state,!0);a.series.isCartesian&&(a.series.xAxis.crosshair&&a.series.xAxis.drawCrosshair(null, a),a.series.yAxis.crosshair&&a.series.yAxis.drawCrosshair(null,a))}):d&&(d.setState(d.state,!0),c.axes.forEach(function(a){a.crosshair&&d.series[a.coll]===a&&a.drawCrosshair(null,d)})));else{if(d)d.onMouseOut();h&&h.forEach(function(a){a.setState()});if(f)f.onMouseOut();r&&r.hide(a);this.unDocMouseMove&&(this.unDocMouseMove=this.unDocMouseMove());c.axes.forEach(function(a){a.hideCrosshair()});this.hoverX=c.hoverPoints=c.hoverPoint=null}},scaleGroups:function(b,a){var c=this.chart,f;c.series.forEach(function(d){f= b||d.getPlotBox();d.xAxis&&d.xAxis.zoomEnabled&&d.group&&(d.group.attr(f),d.markerGroup&&(d.markerGroup.attr(f),d.markerGroup.clip(a?c.clipRect:null)),d.dataLabelsGroup&&d.dataLabelsGroup.attr(f))});c.clipRect.attr(a||c.clipBox)},dragStart:function(b){var a=this.chart;a.mouseIsDown=b.type;a.cancelClick=!1;a.mouseDownX=this.mouseDownX=b.chartX;a.mouseDownY=this.mouseDownY=b.chartY},drag:function(b){var a=this.chart,c=a.options.chart,f=b.chartX,d=b.chartY,h=this.zoomHor,r=this.zoomVert,e=a.plotLeft, k=a.plotTop,u=a.plotWidth,g=a.plotHeight,G=this.selectionMarker,A=this.mouseDownX,m=this.mouseDownY,L=x(c.panning)?c.panning&&c.panning.enabled:c.panning,p=c.panKey&&b[c.panKey+"Key"];if(!G||!G.touch)if(f<e?f=e:f>e+u&&(f=e+u),d<k?d=k:d>k+g&&(d=k+g),this.hasDragged=Math.sqrt(Math.pow(A-f,2)+Math.pow(m-d,2)),10<this.hasDragged){var v=a.isInsidePlot(A-e,m-k);a.hasCartesianSeries&&(this.zoomX||this.zoomY)&&v&&!p&&!G&&(this.selectionMarker=G=a.renderer.rect(e,k,h?1:u,r?1:g,0).attr({"class":"highcharts-selection-marker", zIndex:7}).add(),a.styledMode||G.attr({fill:c.selectionMarkerFill||q("#335cad").setOpacity(.25).get()}));G&&h&&(f-=A,G.attr({width:Math.abs(f),x:(0<f?0:f)+A}));G&&r&&(f=d-m,G.attr({height:Math.abs(f),y:(0<f?0:f)+m}));v&&!G&&L&&a.pan(b,c.panning)}},drop:function(b){var a=this,c=this.chart,d=this.hasPinched;if(this.selectionMarker){var h={originalEvent:b,xAxis:[],yAxis:[]},g=this.selectionMarker,r=g.attr?g.attr("x"):g.x,e=g.attr?g.attr("y"):g.y,k=g.attr?g.attr("width"):g.width,u=g.attr?g.attr("height"): g.height,H;if(this.hasDragged||d)c.axes.forEach(function(c){if(c.zoomEnabled&&F(c.min)&&(d||a[{xAxis:"zoomX",yAxis:"zoomY"}[c.coll]])){var f=c.horiz,l="touchend"===b.type?c.minPixelPadding:0,t=c.toValue((f?r:e)+l);f=c.toValue((f?r+k:e+u)-l);h[c.coll].push({axis:c,min:Math.min(t,f),max:Math.max(t,f)});H=!0}}),H&&f(c,"selection",h,function(a){c.zoom(E(a,d?{animation:!1}:null))});D(c.index)&&(this.selectionMarker=this.selectionMarker.destroy());d&&this.scaleGroups()}c&&D(c.index)&&(w(c.container,{cursor:c._cursor}), c.cancelClick=10<this.hasDragged,c.mouseIsDown=this.hasDragged=this.hasPinched=!1,this.pinchDown=[])},onContainerMouseDown:function(b){b=this.normalize(b);2!==b.button&&(this.zoomOption(b),b.preventDefault&&b.preventDefault(),this.dragStart(b))},onDocumentMouseUp:function(b){m[d.hoverChartIndex]&&m[d.hoverChartIndex].pointer.drop(b)},onDocumentMouseMove:function(b){var a=this.chart,c=this.chartPosition;b=this.normalize(b,c);!c||this.inClass(b.target,"highcharts-tracker")||a.isInsidePlot(b.chartX- a.plotLeft,b.chartY-a.plotTop)||this.reset()},onContainerMouseLeave:function(b){var a=m[d.hoverChartIndex];a&&(b.relatedTarget||b.toElement)&&(a.pointer.reset(),a.pointer.chartPosition=void 0)},onContainerMouseMove:function(b){var a=this.chart;F(d.hoverChartIndex)&&m[d.hoverChartIndex]&&m[d.hoverChartIndex].mouseIsDown||(d.hoverChartIndex=a.index);b=this.normalize(b);b.preventDefault||(b.returnValue=!1);"mousedown"===a.mouseIsDown&&this.drag(b);!this.inClass(b.target,"highcharts-tracker")&&!a.isInsidePlot(b.chartX- a.plotLeft,b.chartY-a.plotTop)||a.openMenu||this.runPointActions(b)},inClass:function(b,a){for(var c;b;){if(c=y(b,"class")){if(-1!==c.indexOf(a))return!0;if(-1!==c.indexOf("highcharts-container"))return!1}b=b.parentNode}},onTrackerMouseOut:function(b){var a=this.chart.hoverSeries;b=b.relatedTarget||b.toElement;this.isDirectTouch=!1;if(!(!a||!b||a.stickyTracking||this.inClass(b,"highcharts-tooltip")||this.inClass(b,"highcharts-series-"+a.index)&&this.inClass(b,"highcharts-tracker")))a.onMouseOut()}, onContainerClick:function(b){var a=this.chart,c=a.hoverPoint,d=a.plotLeft,h=a.plotTop;b=this.normalize(b);a.cancelClick||(c&&this.inClass(b.target,"highcharts-tracker")?(f(c.series,"click",E(b,{point:c})),a.hoverPoint&&c.firePointEvent("click",b)):(E(b,this.getCoordinates(b)),a.isInsidePlot(b.chartX-d,b.chartY-h)&&f(a,"click",b)))},setDOMEvents:function(){var b=this,a=b.chart.container,c=a.ownerDocument;a.onmousedown=function(a){b.onContainerMouseDown(a)};a.onmousemove=function(a){b.onContainerMouseMove(a)}; a.onclick=function(a){b.onContainerClick(a)};this.unbindContainerMouseLeave=z(a,"mouseleave",b.onContainerMouseLeave);d.unbindDocumentMouseUp||(d.unbindDocumentMouseUp=z(c,"mouseup",b.onDocumentMouseUp));d.hasTouch&&(z(a,"touchstart",function(a){b.onContainerTouchStart(a)}),z(a,"touchmove",function(a){b.onContainerTouchMove(a)}),d.unbindDocumentTouchEnd||(d.unbindDocumentTouchEnd=z(c,"touchend",b.onDocumentTouchEnd)))},destroy:function(){var b=this;b.unDocMouseMove&&b.unDocMouseMove();this.unbindContainerMouseLeave(); d.chartCount||(d.unbindDocumentMouseUp&&(d.unbindDocumentMouseUp=d.unbindDocumentMouseUp()),d.unbindDocumentTouchEnd&&(d.unbindDocumentTouchEnd=d.unbindDocumentTouchEnd()));clearInterval(b.tooltipTimeout);v(b,function(a,c){b[c]=null})}}});K(y,"parts/TouchPointer.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.extend,F=g.pick,E=d.charts,D=d.noop;y(d.Pointer.prototype,{pinchTranslate:function(d,g,C,B,p,z){this.zoomHor&&this.pinchTranslateDirection(!0,d,g,C,B,p,z);this.zoomVert&& this.pinchTranslateDirection(!1,d,g,C,B,p,z)},pinchTranslateDirection:function(d,g,C,B,p,z,m,q){var v=this.chart,h=d?"x":"y",f=d?"X":"Y",c="chart"+f,b=d?"width":"height",a=v["plot"+(d?"Left":"Top")],l,n,t=q||1,I=v.inverted,r=v.bounds[d?"h":"v"],e=1===g.length,k=g[0][c],u=C[0][c],H=!e&&g[1][c],G=!e&&C[1][c];C=function(){!e&&20<Math.abs(k-H)&&(t=q||Math.abs(u-G)/Math.abs(k-H));n=(a-u)/t+k;l=v["plot"+(d?"Width":"Height")]/t};C();g=n;if(g<r.min){g=r.min;var A=!0}else g+l>r.max&&(g=r.max-l,A=!0);A?(u-= .8*(u-m[h][0]),e||(G-=.8*(G-m[h][1])),C()):m[h]=[u,G];I||(z[h]=n-a,z[b]=l);z=I?1/t:t;p[b]=l;p[h]=g;B[I?d?"scaleY":"scaleX":"scale"+f]=t;B["translate"+f]=z*a+(u-z*k)},pinch:function(d){var g=this,x=g.chart,B=g.pinchDown,p=d.touches,z=p.length,m=g.lastValidTouch,q=g.hasZoom,w=g.selectionMarker,h={},f=1===z&&(g.inClass(d.target,"highcharts-tracker")&&x.runTrackerClick||g.runChartClick),c={};1<z&&(g.initiated=!0);q&&g.initiated&&!f&&d.preventDefault();[].map.call(p,function(b){return g.normalize(b)}); "touchstart"===d.type?([].forEach.call(p,function(b,a){B[a]={chartX:b.chartX,chartY:b.chartY}}),m.x=[B[0].chartX,B[1]&&B[1].chartX],m.y=[B[0].chartY,B[1]&&B[1].chartY],x.axes.forEach(function(b){if(b.zoomEnabled){var a=x.bounds[b.horiz?"h":"v"],c=b.minPixelPadding,f=b.toPixels(Math.min(F(b.options.min,b.dataMin),b.dataMin)),d=b.toPixels(Math.max(F(b.options.max,b.dataMax),b.dataMax)),h=Math.max(f,d);a.min=Math.min(b.pos,Math.min(f,d)-c);a.max=Math.max(b.pos+b.len,h+c)}}),g.res=!0):g.followTouchMove&& 1===z?this.runPointActions(g.normalize(d)):B.length&&(w||(g.selectionMarker=w=y({destroy:D,touch:!0},x.plotBox)),g.pinchTranslate(B,p,h,w,c,m),g.hasPinched=q,g.scaleGroups(h,c),g.res&&(g.res=!1,this.reset(!1,0)))},touch:function(g,v){var x=this.chart,B;if(x.index!==d.hoverChartIndex)this.onContainerMouseLeave({relatedTarget:!0});d.hoverChartIndex=x.index;if(1===g.touches.length)if(g=this.normalize(g),(B=x.isInsidePlot(g.chartX-x.plotLeft,g.chartY-x.plotTop))&&!x.openMenu){v&&this.runPointActions(g); if("touchmove"===g.type){v=this.pinchDown;var p=v[0]?4<=Math.sqrt(Math.pow(v[0].chartX-g.chartX,2)+Math.pow(v[0].chartY-g.chartY,2)):!1}F(p,!0)&&this.pinch(g)}else v&&this.reset();else 2===g.touches.length&&this.pinch(g)},onContainerTouchStart:function(d){this.zoomOption(d);this.touch(d,!0)},onContainerTouchMove:function(d){this.touch(d)},onDocumentTouchEnd:function(g){E[d.hoverChartIndex]&&E[d.hoverChartIndex].pointer.drop(g)}})});K(y,"parts/MSPointer.js",[y["parts/Globals.js"],y["parts/Utilities.js"]], function(d,g){var y=g.extend,F=g.objectEach;g=g.wrap;var E=d.addEvent,D=d.charts,x=d.css,v=d.doc,C=d.noop,B=d.Pointer,p=d.removeEvent,z=d.win;if(!d.hasTouch&&(z.PointerEvent||z.MSPointerEvent)){var m={},q=!!z.PointerEvent,w=function(){var f=[];f.item=function(c){return this[c]};F(m,function(c){f.push({pageX:c.pageX,pageY:c.pageY,target:c.target})});return f},h=function(f,c,b,a){"touch"!==f.pointerType&&f.pointerType!==f.MSPOINTER_TYPE_TOUCH||!D[d.hoverChartIndex]||(a(f),a=D[d.hoverChartIndex].pointer, a[c]({type:b,target:f.currentTarget,preventDefault:C,touches:w()}))};y(B.prototype,{onContainerPointerDown:function(f){h(f,"onContainerTouchStart","touchstart",function(c){m[c.pointerId]={pageX:c.pageX,pageY:c.pageY,target:c.currentTarget}})},onContainerPointerMove:function(f){h(f,"onContainerTouchMove","touchmove",function(c){m[c.pointerId]={pageX:c.pageX,pageY:c.pageY};m[c.pointerId].target||(m[c.pointerId].target=c.currentTarget)})},onDocumentPointerUp:function(f){h(f,"onDocumentTouchEnd","touchend", function(c){delete m[c.pointerId]})},batchMSEvents:function(f){f(this.chart.container,q?"pointerdown":"MSPointerDown",this.onContainerPointerDown);f(this.chart.container,q?"pointermove":"MSPointerMove",this.onContainerPointerMove);f(v,q?"pointerup":"MSPointerUp",this.onDocumentPointerUp)}});g(B.prototype,"init",function(f,c,b){f.call(this,c,b);this.hasZoom&&x(c.container,{"-ms-touch-action":"none","touch-action":"none"})});g(B.prototype,"setDOMEvents",function(f){f.apply(this);(this.hasZoom||this.followTouchMove)&& this.batchMSEvents(E)});g(B.prototype,"destroy",function(f){this.batchMSEvents(p);f.call(this)})}});K(y,"parts/Legend.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.defined,F=g.discardElement,E=g.isNumber,D=g.pick,x=g.relativeLength,v=g.setAnimation,C=g.syncTimeout;g=g.wrap;var B=d.addEvent,p=d.css,z=d.fireEvent,m=d.isFirefox,q=d.marginNames,w=d.merge,h=d.stableSort,f=d.win;d.Legend=function(c,b){this.init(c,b)};d.Legend.prototype={init:function(c,b){this.chart=c;this.setOptions(b); b.enabled&&(this.render(),B(this.chart,"endResize",function(){this.legend.positionCheckboxes()}),this.proximate?this.unchartrender=B(this.chart,"render",function(){this.legend.proximatePositions();this.legend.positionItems()}):this.unchartrender&&this.unchartrender())},setOptions:function(c){var b=D(c.padding,8);this.options=c;this.chart.styledMode||(this.itemStyle=c.itemStyle,this.itemHiddenStyle=w(this.itemStyle,c.itemHiddenStyle));this.itemMarginTop=c.itemMarginTop||0;this.itemMarginBottom=c.itemMarginBottom|| 0;this.padding=b;this.initialItemY=b-5;this.symbolWidth=D(c.symbolWidth,16);this.pages=[];this.proximate="proximate"===c.layout&&!this.chart.inverted},update:function(c,b){var a=this.chart;this.setOptions(w(!0,this.options,c));this.destroy();a.isDirtyLegend=a.isDirtyBox=!0;D(b,!0)&&a.redraw();z(this,"afterUpdate")},colorizeItem:function(c,b){c.legendGroup[b?"removeClass":"addClass"]("highcharts-legend-item-hidden");if(!this.chart.styledMode){var a=this.options,f=c.legendItem,d=c.legendLine,h=c.legendSymbol, g=this.itemHiddenStyle.color;a=b?a.itemStyle.color:g;var r=b?c.color||g:g,e=c.options&&c.options.marker,k={fill:r};f&&f.css({fill:a,color:a});d&&d.attr({stroke:r});h&&(e&&h.isMarker&&(k=c.pointAttribs(),b||(k.stroke=k.fill=g)),h.attr(k))}z(this,"afterColorizeItem",{item:c,visible:b})},positionItems:function(){this.allItems.forEach(this.positionItem,this);this.chart.isResizing||this.positionCheckboxes()},positionItem:function(c){var b=this.options,a=b.symbolPadding;b=!b.rtl;var f=c._legendItemPos, d=f[0];f=f[1];var h=c.checkbox;if((c=c.legendGroup)&&c.element)c[y(c.translateY)?"animate":"attr"]({translateX:b?d:this.legendWidth-d-2*a-4,translateY:f});h&&(h.x=d,h.y=f)},destroyItem:function(c){var b=c.checkbox;["legendItem","legendLine","legendSymbol","legendGroup"].forEach(function(a){c[a]&&(c[a]=c[a].destroy())});b&&F(c.checkbox)},destroy:function(){function c(b){this[b]&&(this[b]=this[b].destroy())}this.getAllItems().forEach(function(b){["legendItem","legendGroup"].forEach(c,b)});"clipRect up down pager nav box title group".split(" ").forEach(c, this);this.display=null},positionCheckboxes:function(){var c=this.group&&this.group.alignAttr,b=this.clipHeight||this.legendHeight,a=this.titleHeight;if(c){var f=c.translateY;this.allItems.forEach(function(d){var l=d.checkbox;if(l){var h=f+a+l.y+(this.scrollOffset||0)+3;p(l,{left:c.translateX+d.checkboxOffset+l.x-20+"px",top:h+"px",display:this.proximate||h>f-6&&h<f+b-6?"":"none"})}},this)}},renderTitle:function(){var c=this.options,b=this.padding,a=c.title,f=0;a.text&&(this.title||(this.title=this.chart.renderer.label(a.text, b-3,b-4,null,null,null,c.useHTML,null,"legend-title").attr({zIndex:1}),this.chart.styledMode||this.title.css(a.style),this.title.add(this.group)),a.width||this.title.css({width:this.maxLegendWidth+"px"}),c=this.title.getBBox(),f=c.height,this.offsetWidth=c.width,this.contentGroup.attr({translateY:f}));this.titleHeight=f},setText:function(c){var b=this.options;c.legendItem.attr({text:b.labelFormat?d.format(b.labelFormat,c,this.chart):b.labelFormatter.call(c)})},renderItem:function(c){var b=this.chart, a=b.renderer,f=this.options,d=this.symbolWidth,h=f.symbolPadding,g=this.itemStyle,r=this.itemHiddenStyle,e="horizontal"===f.layout?D(f.itemDistance,20):0,k=!f.rtl,u=c.legendItem,H=!c.series,G=!H&&c.series.drawLegendSymbol?c.series:c,A=G.options;A=this.createCheckboxForItem&&A&&A.showCheckbox;e=d+h+e+(A?20:0);var m=f.useHTML,L=c.options.className;u||(c.legendGroup=a.g("legend-item").addClass("highcharts-"+G.type+"-series highcharts-color-"+c.colorIndex+(L?" "+L:"")+(H?" highcharts-series-"+c.index: "")).attr({zIndex:1}).add(this.scrollGroup),c.legendItem=u=a.text("",k?d+h:-h,this.baseline||0,m),b.styledMode||u.css(w(c.visible?g:r)),u.attr({align:k?"left":"right",zIndex:2}).add(c.legendGroup),this.baseline||(this.fontMetrics=a.fontMetrics(b.styledMode?12:g.fontSize,u),this.baseline=this.fontMetrics.f+3+this.itemMarginTop,u.attr("y",this.baseline)),this.symbolHeight=f.symbolHeight||this.fontMetrics.f,G.drawLegendSymbol(this,c),this.setItemEvents&&this.setItemEvents(c,u,m));A&&!c.checkbox&&this.createCheckboxForItem(c); this.colorizeItem(c,c.visible);!b.styledMode&&g.width||u.css({width:(f.itemWidth||this.widthOption||b.spacingBox.width)-e});this.setText(c);b=u.getBBox();c.itemWidth=c.checkboxOffset=f.itemWidth||c.legendItemWidth||b.width+e;this.maxItemWidth=Math.max(this.maxItemWidth,c.itemWidth);this.totalItemWidth+=c.itemWidth;this.itemHeight=c.itemHeight=Math.round(c.legendItemHeight||b.height||this.symbolHeight)},layoutItem:function(c){var b=this.options,a=this.padding,f="horizontal"===b.layout,d=c.itemHeight, h=this.itemMarginBottom,g=this.itemMarginTop,r=f?D(b.itemDistance,20):0,e=this.maxLegendWidth;b=b.alignColumns&&this.totalItemWidth>e?this.maxItemWidth:c.itemWidth;f&&this.itemX-a+b>e&&(this.itemX=a,this.lastLineHeight&&(this.itemY+=g+this.lastLineHeight+h),this.lastLineHeight=0);this.lastItemY=g+this.itemY+h;this.lastLineHeight=Math.max(d,this.lastLineHeight);c._legendItemPos=[this.itemX,this.itemY];f?this.itemX+=b:(this.itemY+=g+d+h,this.lastLineHeight=d);this.offsetWidth=this.widthOption||Math.max((f? this.itemX-a-(c.checkbox?0:r):b)+a,this.offsetWidth)},getAllItems:function(){var c=[];this.chart.series.forEach(function(b){var a=b&&b.options;b&&D(a.showInLegend,y(a.linkedTo)?!1:void 0,!0)&&(c=c.concat(b.legendItems||("point"===a.legendType?b.data:b)))});z(this,"afterGetAllItems",{allItems:c});return c},getAlignment:function(){var c=this.options;return this.proximate?c.align.charAt(0)+"tv":c.floating?"":c.align.charAt(0)+c.verticalAlign.charAt(0)+c.layout.charAt(0)},adjustMargins:function(c,b){var a= this.chart,f=this.options,d=this.getAlignment();d&&[/(lth|ct|rth)/,/(rtv|rm|rbv)/,/(rbh|cb|lbh)/,/(lbv|lm|ltv)/].forEach(function(l,h){l.test(d)&&!y(c[h])&&(a[q[h]]=Math.max(a[q[h]],a.legend[(h+1)%2?"legendHeight":"legendWidth"]+[1,-1,-1,1][h]*f[h%2?"x":"y"]+D(f.margin,12)+b[h]+(a.titleOffset[h]||0)))})},proximatePositions:function(){var c=this.chart,b=[],a="left"===this.options.align;this.allItems.forEach(function(f){var l=a;if(f.yAxis&&f.points){f.xAxis.options.reversed&&(l=!l);var h=d.find(l?f.points: f.points.slice(0).reverse(),function(a){return E(a.plotY)});l=this.itemMarginTop+f.legendItem.getBBox().height+this.itemMarginBottom;var g=f.yAxis.top-c.plotTop;f.visible?(h=h?h.plotY:f.yAxis.height,h+=g-.3*l):h=g+f.yAxis.height;b.push({target:h,size:l,item:f})}},this);d.distribute(b,c.plotHeight);b.forEach(function(a){a.item._legendItemPos[1]=c.plotTop-c.spacing[0]+a.pos})},render:function(){var c=this.chart,b=c.renderer,a=this.group,f,d=this.box,g=this.options,m=this.padding;this.itemX=m;this.itemY= this.initialItemY;this.lastItemY=this.offsetWidth=0;this.widthOption=x(g.width,c.spacingBox.width-m);var r=c.spacingBox.width-2*m-g.x;-1<["rm","lm"].indexOf(this.getAlignment().substring(0,2))&&(r/=2);this.maxLegendWidth=this.widthOption||r;a||(this.group=a=b.g("legend").attr({zIndex:7}).add(),this.contentGroup=b.g().attr({zIndex:1}).add(a),this.scrollGroup=b.g().add(this.contentGroup));this.renderTitle();r=this.getAllItems();h(r,function(a,e){return(a.options&&a.options.legendIndex||0)-(e.options&& e.options.legendIndex||0)});g.reversed&&r.reverse();this.allItems=r;this.display=f=!!r.length;this.itemHeight=this.totalItemWidth=this.maxItemWidth=this.lastLineHeight=0;r.forEach(this.renderItem,this);r.forEach(this.layoutItem,this);r=(this.widthOption||this.offsetWidth)+m;var e=this.lastItemY+this.lastLineHeight+this.titleHeight;e=this.handleOverflow(e);e+=m;d||(this.box=d=b.rect().addClass("highcharts-legend-box").attr({r:g.borderRadius}).add(a),d.isNew=!0);c.styledMode||d.attr({stroke:g.borderColor, "stroke-width":g.borderWidth||0,fill:g.backgroundColor||"none"}).shadow(g.shadow);0<r&&0<e&&(d[d.isNew?"attr":"animate"](d.crisp.call({},{x:0,y:0,width:r,height:e},d.strokeWidth())),d.isNew=!1);d[f?"show":"hide"]();c.styledMode&&"none"===a.getStyle("display")&&(r=e=0);this.legendWidth=r;this.legendHeight=e;f&&(b=c.spacingBox,d=b.y,/(lth|ct|rth)/.test(this.getAlignment())&&0<c.titleOffset[0]?d+=c.titleOffset[0]:/(lbh|cb|rbh)/.test(this.getAlignment())&&0<c.titleOffset[2]&&(d-=c.titleOffset[2]),d!== b.y&&(b=w(b,{y:d})),a.align(w(g,{width:r,height:e,verticalAlign:this.proximate?"top":g.verticalAlign}),!0,b));this.proximate||this.positionItems();z(this,"afterRender")},handleOverflow:function(c){var b=this,a=this.chart,f=a.renderer,d=this.options,h=d.y,g=this.padding;h=a.spacingBox.height+("top"===d.verticalAlign?-h:h)-g;var r=d.maxHeight,e,k=this.clipRect,u=d.navigation,H=D(u.animation,!0),G=u.arrowSize||12,A=this.nav,m=this.pages,L,q=this.allItems,p=function(a){"number"===typeof a?k.attr({height:a}): k&&(b.clipRect=k.destroy(),b.contentGroup.clip());b.contentGroup.div&&(b.contentGroup.div.style.clip=a?"rect("+g+"px,9999px,"+(g+a)+"px,0)":"auto")},z=function(e){b[e]=f.circle(0,0,1.3*G).translate(G/2,G/2).add(A);a.styledMode||b[e].attr("fill","rgba(0,0,0,0.0001)");return b[e]};"horizontal"!==d.layout||"middle"===d.verticalAlign||d.floating||(h/=2);r&&(h=Math.min(h,r));m.length=0;c>h&&!1!==u.enabled?(this.clipHeight=e=Math.max(h-20-this.titleHeight-g,0),this.currentPage=D(this.currentPage,1),this.fullHeight= c,q.forEach(function(a,b){var c=a._legendItemPos[1],k=Math.round(a.legendItem.getBBox().height),f=m.length;if(!f||c-m[f-1]>e&&(L||c)!==m[f-1])m.push(L||c),f++;a.pageIx=f-1;L&&(q[b-1].pageIx=f-1);b===q.length-1&&c+k-m[f-1]>e&&c!==L&&(m.push(c),a.pageIx=f);c!==L&&(L=c)}),k||(k=b.clipRect=f.clipRect(0,g,9999,0),b.contentGroup.clip(k)),p(e),A||(this.nav=A=f.g().attr({zIndex:1}).add(this.group),this.up=f.symbol("triangle",0,0,G,G).add(A),z("upTracker").on("click",function(){b.scroll(-1,H)}),this.pager= f.text("",15,10).addClass("highcharts-legend-navigation"),a.styledMode||this.pager.css(u.style),this.pager.add(A),this.down=f.symbol("triangle-down",0,0,G,G).add(A),z("downTracker").on("click",function(){b.scroll(1,H)})),b.scroll(0),c=h):A&&(p(),this.nav=A.destroy(),this.scrollGroup.attr({translateY:1}),this.clipHeight=0);return c},scroll:function(c,b){var a=this,f=this.chart,h=this.pages,g=h.length,m=this.currentPage+c;c=this.clipHeight;var r=this.options.navigation,e=this.pager,k=this.padding;m> g&&(m=g);0<m&&("undefined"!==typeof b&&v(b,f),this.nav.attr({translateX:k,translateY:c+this.padding+7+this.titleHeight,visibility:"visible"}),[this.up,this.upTracker].forEach(function(a){a.attr({"class":1===m?"highcharts-legend-nav-inactive":"highcharts-legend-nav-active"})}),e.attr({text:m+"/"+g}),[this.down,this.downTracker].forEach(function(a){a.attr({x:18+this.pager.getBBox().width,"class":m===g?"highcharts-legend-nav-inactive":"highcharts-legend-nav-active"})},this),f.styledMode||(this.up.attr({fill:1=== m?r.inactiveColor:r.activeColor}),this.upTracker.css({cursor:1===m?"default":"pointer"}),this.down.attr({fill:m===g?r.inactiveColor:r.activeColor}),this.downTracker.css({cursor:m===g?"default":"pointer"})),this.scrollOffset=-h[m-1]+this.initialItemY,this.scrollGroup.animate({translateY:this.scrollOffset}),this.currentPage=m,this.positionCheckboxes(),b=d.animObject(D(b,f.renderer.globalAnimation,!0)),C(function(){z(a,"afterScroll",{currentPage:m})},b.duration||0))}};d.LegendSymbolMixin={drawRectangle:function(c, b){var a=c.symbolHeight,f=c.options.squareSymbol;b.legendSymbol=this.chart.renderer.rect(f?(c.symbolWidth-a)/2:0,c.baseline-a+1,f?a:c.symbolWidth,a,D(c.options.symbolRadius,a/2)).addClass("highcharts-point").attr({zIndex:3}).add(b.legendGroup)},drawLineMarker:function(c){var b=this.options,a=b.marker,f=c.symbolWidth,d=c.symbolHeight,h=d/2,g=this.chart.renderer,r=this.legendGroup;c=c.baseline-Math.round(.3*c.fontMetrics.b);var e={};this.chart.styledMode||(e={"stroke-width":b.lineWidth||0},b.dashStyle&& (e.dashstyle=b.dashStyle));this.legendLine=g.path(["M",0,c,"L",f,c]).addClass("highcharts-graph").attr(e).add(r);a&&!1!==a.enabled&&f&&(b=Math.min(D(a.radius,h),h),0===this.symbol.indexOf("url")&&(a=w(a,{width:d,height:d}),b=0),this.legendSymbol=a=g.symbol(this.symbol,f/2-b,c-b,2*b,2*b,a).addClass("highcharts-point").add(r),a.isMarker=!0)}};(/Trident\/7\.0/.test(f.navigator&&f.navigator.userAgent)||m)&&g(d.Legend.prototype,"positionItem",function(c,b){var a=this,f=function(){b._legendItemPos&&c.call(a, b)};f();a.bubbleLegend||setTimeout(f)})});K(y,"parts/Chart.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.animObject,F=g.attr,E=g.defined,D=g.discardElement,x=g.erase,v=g.extend,C=g.isArray,B=g.isNumber,p=g.isObject,z=g.isString,m=g.numberFormat,q=g.objectEach,w=g.pick,h=g.pInt,f=g.relativeLength,c=g.setAnimation,b=g.splat,a=g.syncTimeout,l=d.addEvent,n=d.animate,t=d.doc,I=d.Axis,r=d.createElement,e=d.defaultOptions,k=d.charts,u=d.css,H=d.find,G=d.fireEvent,A=d.Legend,J= d.marginNames,L=d.merge,Q=d.Pointer,V=d.removeEvent,U=d.seriesTypes,P=d.win,O=d.Chart=function(){this.getArgs.apply(this,arguments)};d.chart=function(a,e,b){return new O(a,e,b)};v(O.prototype,{callbacks:[],getArgs:function(){var a=[].slice.call(arguments);if(z(a[0])||a[0].nodeName)this.renderTo=a.shift();this.init(a[0],a[1])},init:function(a,b){var c,f=a.series,u=a.plotOptions||{};G(this,"init",{args:arguments},function(){a.series=null;c=L(e,a);q(c.plotOptions,function(a,e){p(a)&&(a.tooltip=u[e]&& L(u[e].tooltip)||void 0)});c.tooltip.userOptions=a.chart&&a.chart.forExport&&a.tooltip.userOptions||a.tooltip;c.series=a.series=f;this.userOptions=a;var h=c.chart,g=h.events;this.margin=[];this.spacing=[];this.bounds={h:{},v:{}};this.labelCollectors=[];this.callback=b;this.isResizing=0;this.options=c;this.axes=[];this.series=[];this.time=a.time&&Object.keys(a.time).length?new d.Time(a.time):d.time;this.numberFormatter=h.numberFormatter||m;this.styledMode=h.styledMode;this.hasCartesianSeries=h.showAxes; var r=this;r.index=k.length;k.push(r);d.chartCount++;g&&q(g,function(a,e){d.isFunction(a)&&l(r,e,a)});r.xAxis=[];r.yAxis=[];r.pointCount=r.colorCounter=r.symbolCounter=0;G(r,"afterInit");r.firstRender()})},initSeries:function(a){var e=this.options.chart;e=a.type||e.type||e.defaultSeriesType;var b=U[e];b||d.error(17,!0,this,{missingModuleFor:e});e=new b;e.init(this,a);return e},setSeriesData:function(){this.getSeriesOrderByLinks().forEach(function(a){a.points||a.data||!a.enabledDataSorting||a.setData(a.options.data, !1)})},getSeriesOrderByLinks:function(){return this.series.concat().sort(function(a,e){return a.linkedSeries.length||e.linkedSeries.length?e.linkedSeries.length-a.linkedSeries.length:0})},orderSeries:function(a){var e=this.series;for(a=a||0;a<e.length;a++)e[a]&&(e[a].index=a,e[a].name=e[a].getName())},isInsidePlot:function(a,e,b){var c=b?e:a;a=b?a:e;return 0<=c&&c<=this.plotWidth&&0<=a&&a<=this.plotHeight},redraw:function(a){G(this,"beforeRedraw");var e=this.axes,b=this.series,k=this.pointer,f=this.legend, d=this.userOptions.legend,u=this.isDirtyLegend,l=this.hasCartesianSeries,h=this.isDirtyBox,g=this.renderer,r=g.isHidden(),A=[];this.setResponsive&&this.setResponsive(!1);c(a,this);r&&this.temporaryDisplay();this.layOutTitles();for(a=b.length;a--;){var H=b[a];if(H.options.stacking){var t=!0;if(H.isDirty){var n=!0;break}}}if(n)for(a=b.length;a--;)H=b[a],H.options.stacking&&(H.isDirty=!0);b.forEach(function(a){a.isDirty&&("point"===a.options.legendType?(a.updateTotals&&a.updateTotals(),u=!0):d&&(d.labelFormatter|| d.labelFormat)&&(u=!0));a.isDirtyData&&G(a,"updatedData")});u&&f&&f.options.enabled&&(f.render(),this.isDirtyLegend=!1);t&&this.getStacks();l&&e.forEach(function(a){a.updateNames();a.setScale()});this.getMargins();l&&(e.forEach(function(a){a.isDirty&&(h=!0)}),e.forEach(function(a){var e=a.min+","+a.max;a.extKey!==e&&(a.extKey=e,A.push(function(){G(a,"afterSetExtremes",v(a.eventArgs,a.getExtremes()));delete a.eventArgs}));(h||t)&&a.redraw()}));h&&this.drawChartBox();G(this,"predraw");b.forEach(function(a){(h|| a.isDirty)&&a.visible&&a.redraw();a.isDirtyData=!1});k&&k.reset(!0);g.draw();G(this,"redraw");G(this,"render");r&&this.temporaryDisplay(!0);A.forEach(function(a){a.call()})},get:function(a){function e(e){return e.id===a||e.options&&e.options.id===a}var b=this.series,c;var k=H(this.axes,e)||H(this.series,e);for(c=0;!k&&c<b.length;c++)k=H(b[c].points||[],e);return k},getAxes:function(){var a=this,e=this.options,c=e.xAxis=b(e.xAxis||{});e=e.yAxis=b(e.yAxis||{});G(this,"getAxes");c.forEach(function(a, e){a.index=e;a.isX=!0});e.forEach(function(a,e){a.index=e});c.concat(e).forEach(function(e){new I(a,e)});G(this,"afterGetAxes")},getSelectedPoints:function(){var a=[];this.series.forEach(function(e){a=a.concat((e[e.hasGroupedData?"points":"data"]||[]).filter(function(a){return w(a.selectedStaging,a.selected)}))});return a},getSelectedSeries:function(){return this.series.filter(function(a){return a.selected})},setTitle:function(a,e,b){this.applyDescription("title",a);this.applyDescription("subtitle", e);this.applyDescription("caption",void 0);this.layOutTitles(b)},applyDescription:function(a,e){var b=this,c="title"===a?{color:"#333333",fontSize:this.options.isStock?"16px":"18px"}:{color:"#666666"};c=this.options[a]=L(!this.styledMode&&{style:c},this.options[a],e);var k=this[a];k&&e&&(this[a]=k=k.destroy());c&&!k&&(k=this.renderer.text(c.text,0,0,c.useHTML).attr({align:c.align,"class":"highcharts-"+a,zIndex:c.zIndex||4}).add(),k.update=function(e){b[{title:"setTitle",subtitle:"setSubtitle",caption:"setCaption"}[a]](e)}, this.styledMode||k.css(c.style),this[a]=k)},layOutTitles:function(a){var e=[0,0,0],b=this.renderer,c=this.spacingBox;["title","subtitle","caption"].forEach(function(a){var k=this[a],f=this.options[a],d=f.verticalAlign||"top";a="title"===a?-3:"top"===d?e[0]+2:0;if(k){if(!this.styledMode)var u=f.style.fontSize;u=b.fontMetrics(u,k).b;k.css({width:(f.width||c.width+(f.widthAdjust||0))+"px"});var l=Math.round(k.getBBox(f.useHTML).height);k.align(v({y:"bottom"===d?u:a+u,height:l},f),!1,"spacingBox");f.floating|| ("top"===d?e[0]=Math.ceil(e[0]+l):"bottom"===d&&(e[2]=Math.ceil(e[2]+l)))}},this);e[0]&&"top"===(this.options.title.verticalAlign||"top")&&(e[0]+=this.options.title.margin);e[2]&&"bottom"===this.options.caption.verticalAlign&&(e[2]+=this.options.caption.margin);var k=!this.titleOffset||this.titleOffset.join(",")!==e.join(",");this.titleOffset=e;G(this,"afterLayOutTitles");!this.isDirtyBox&&k&&(this.isDirtyBox=this.isDirtyLegend=k,this.hasRendered&&w(a,!0)&&this.isDirtyBox&&this.redraw())},getChartSize:function(){var a= this.options.chart,e=a.width;a=a.height;var b=this.renderTo;E(e)||(this.containerWidth=d.getStyle(b,"width"));E(a)||(this.containerHeight=d.getStyle(b,"height"));this.chartWidth=Math.max(0,e||this.containerWidth||600);this.chartHeight=Math.max(0,f(a,this.chartWidth)||(1<this.containerHeight?this.containerHeight:400))},temporaryDisplay:function(a){var e=this.renderTo;if(a)for(;e&&e.style;)e.hcOrigStyle&&(d.css(e,e.hcOrigStyle),delete e.hcOrigStyle),e.hcOrigDetached&&(t.body.removeChild(e),e.hcOrigDetached= !1),e=e.parentNode;else for(;e&&e.style;){t.body.contains(e)||e.parentNode||(e.hcOrigDetached=!0,t.body.appendChild(e));if("none"===d.getStyle(e,"display",!1)||e.hcOricDetached)e.hcOrigStyle={display:e.style.display,height:e.style.height,overflow:e.style.overflow},a={display:"block",overflow:"hidden"},e!==this.renderTo&&(a.height=0),d.css(e,a),e.offsetWidth||e.style.setProperty("display","block","important");e=e.parentNode;if(e===t.body)break}},setClassName:function(a){this.container.className="highcharts-container "+ (a||"")},getContainer:function(){var a=this.options,e=a.chart;var b=this.renderTo;var c=d.uniqueKey(),f,l;b||(this.renderTo=b=e.renderTo);z(b)&&(this.renderTo=b=t.getElementById(b));b||d.error(13,!0,this);var g=h(F(b,"data-highcharts-chart"));B(g)&&k[g]&&k[g].hasRendered&&k[g].destroy();F(b,"data-highcharts-chart",this.index);b.innerHTML="";e.skipClone||b.offsetWidth||this.temporaryDisplay();this.getChartSize();g=this.chartWidth;var A=this.chartHeight;u(b,{overflow:"hidden"});this.styledMode||(f= v({position:"relative",overflow:"hidden",width:g+"px",height:A+"px",textAlign:"left",lineHeight:"normal",zIndex:0,"-webkit-tap-highlight-color":"rgba(0,0,0,0)"},e.style));this.container=b=r("div",{id:c},f,b);this._cursor=b.style.cursor;this.renderer=new (d[e.renderer]||d.Renderer)(b,g,A,null,e.forExport,a.exporting&&a.exporting.allowHTML,this.styledMode);this.setClassName(e.className);if(this.styledMode)for(l in a.defs)this.renderer.definition(a.defs[l]);else this.renderer.setStyle(e.style);this.renderer.chartIndex= this.index;G(this,"afterGetContainer")},getMargins:function(a){var e=this.spacing,b=this.margin,c=this.titleOffset;this.resetMargins();c[0]&&!E(b[0])&&(this.plotTop=Math.max(this.plotTop,c[0]+e[0]));c[2]&&!E(b[2])&&(this.marginBottom=Math.max(this.marginBottom,c[2]+e[2]));this.legend&&this.legend.display&&this.legend.adjustMargins(b,e);G(this,"getMargins");a||this.getAxisMargins()},getAxisMargins:function(){var a=this,e=a.axisOffset=[0,0,0,0],b=a.colorAxis,c=a.margin,k=function(a){a.forEach(function(a){a.visible&& a.getOffset()})};a.hasCartesianSeries?k(a.axes):b&&b.length&&k(b);J.forEach(function(b,k){E(c[k])||(a[b]+=e[k])});a.setChartSize()},reflow:function(e){var b=this,c=b.options.chart,k=b.renderTo,f=E(c.width)&&E(c.height),u=c.width||d.getStyle(k,"width");c=c.height||d.getStyle(k,"height");k=e?e.target:P;if(!f&&!b.isPrinting&&u&&c&&(k===P||k===t)){if(u!==b.containerWidth||c!==b.containerHeight)d.clearTimeout(b.reflowTimeout),b.reflowTimeout=a(function(){b.container&&b.setSize(void 0,void 0,!1)},e?100: 0);b.containerWidth=u;b.containerHeight=c}},setReflow:function(a){var e=this;!1===a||this.unbindReflow?!1===a&&this.unbindReflow&&(this.unbindReflow=this.unbindReflow()):(this.unbindReflow=l(P,"resize",function(a){e.options&&e.reflow(a)}),l(this,"destroy",this.unbindReflow))},setSize:function(e,b,k){var f=this,d=f.renderer;f.isResizing+=1;c(k,f);f.oldChartHeight=f.chartHeight;f.oldChartWidth=f.chartWidth;"undefined"!==typeof e&&(f.options.chart.width=e);"undefined"!==typeof b&&(f.options.chart.height= b);f.getChartSize();if(!f.styledMode){var l=d.globalAnimation;(l?n:u)(f.container,{width:f.chartWidth+"px",height:f.chartHeight+"px"},l)}f.setChartSize(!0);d.setSize(f.chartWidth,f.chartHeight,k);f.axes.forEach(function(a){a.isDirty=!0;a.setScale()});f.isDirtyLegend=!0;f.isDirtyBox=!0;f.layOutTitles();f.getMargins();f.redraw(k);f.oldChartHeight=null;G(f,"resize");a(function(){f&&G(f,"endResize",null,function(){--f.isResizing})},y(l).duration||0)},setChartSize:function(a){var e=this.inverted,b=this.renderer, c=this.chartWidth,k=this.chartHeight,f=this.options.chart,d=this.spacing,u=this.clipOffset,l,h,g,r;this.plotLeft=l=Math.round(this.plotLeft);this.plotTop=h=Math.round(this.plotTop);this.plotWidth=g=Math.max(0,Math.round(c-l-this.marginRight));this.plotHeight=r=Math.max(0,Math.round(k-h-this.marginBottom));this.plotSizeX=e?r:g;this.plotSizeY=e?g:r;this.plotBorderWidth=f.plotBorderWidth||0;this.spacingBox=b.spacingBox={x:d[3],y:d[0],width:c-d[3]-d[1],height:k-d[0]-d[2]};this.plotBox=b.plotBox={x:l, y:h,width:g,height:r};c=2*Math.floor(this.plotBorderWidth/2);e=Math.ceil(Math.max(c,u[3])/2);b=Math.ceil(Math.max(c,u[0])/2);this.clipBox={x:e,y:b,width:Math.floor(this.plotSizeX-Math.max(c,u[1])/2-e),height:Math.max(0,Math.floor(this.plotSizeY-Math.max(c,u[2])/2-b))};a||this.axes.forEach(function(a){a.setAxisSize();a.setAxisTranslation()});G(this,"afterSetChartSize",{skipAxes:a})},resetMargins:function(){G(this,"resetMargins");var a=this,e=a.options.chart;["margin","spacing"].forEach(function(b){var c= e[b],k=p(c)?c:[c,c,c,c];["Top","Right","Bottom","Left"].forEach(function(c,f){a[b][f]=w(e[b+c],k[f])})});J.forEach(function(e,b){a[e]=w(a.margin[b],a.spacing[b])});a.axisOffset=[0,0,0,0];a.clipOffset=[0,0,0,0]},drawChartBox:function(){var a=this.options.chart,e=this.renderer,b=this.chartWidth,c=this.chartHeight,k=this.chartBackground,f=this.plotBackground,d=this.plotBorder,u=this.styledMode,l=this.plotBGImage,h=a.backgroundColor,g=a.plotBackgroundColor,r=a.plotBackgroundImage,A,H=this.plotLeft,t= this.plotTop,n=this.plotWidth,m=this.plotHeight,L=this.plotBox,J=this.clipRect,q=this.clipBox,p="animate";k||(this.chartBackground=k=e.rect().addClass("highcharts-background").add(),p="attr");if(u)var z=A=k.strokeWidth();else{z=a.borderWidth||0;A=z+(a.shadow?8:0);h={fill:h||"none"};if(z||k["stroke-width"])h.stroke=a.borderColor,h["stroke-width"]=z;k.attr(h).shadow(a.shadow)}k[p]({x:A/2,y:A/2,width:b-A-z%2,height:c-A-z%2,r:a.borderRadius});p="animate";f||(p="attr",this.plotBackground=f=e.rect().addClass("highcharts-plot-background").add()); f[p](L);u||(f.attr({fill:g||"none"}).shadow(a.plotShadow),r&&(l?(r!==l.attr("href")&&l.attr("href",r),l.animate(L)):this.plotBGImage=e.image(r,H,t,n,m).add()));J?J.animate({width:q.width,height:q.height}):this.clipRect=e.clipRect(q);p="animate";d||(p="attr",this.plotBorder=d=e.rect().addClass("highcharts-plot-border").attr({zIndex:1}).add());u||d.attr({stroke:a.plotBorderColor,"stroke-width":a.plotBorderWidth||0,fill:"none"});d[p](d.crisp({x:H,y:t,width:n,height:m},-d.strokeWidth()));this.isDirtyBox= !1;G(this,"afterDrawChartBox")},propFromSeries:function(){var a=this,e=a.options.chart,b,c=a.options.series,k,f;["inverted","angular","polar"].forEach(function(d){b=U[e.type||e.defaultSeriesType];f=e[d]||b&&b.prototype[d];for(k=c&&c.length;!f&&k--;)(b=U[c[k].type])&&b.prototype[d]&&(f=!0);a[d]=f})},linkSeries:function(){var a=this,e=a.series;e.forEach(function(a){a.linkedSeries.length=0});e.forEach(function(e){var b=e.options.linkedTo;z(b)&&(b=":previous"===b?a.series[e.index-1]:a.get(b))&&b.linkedParent!== e&&(b.linkedSeries.push(e),e.linkedParent=b,b.enabledDataSorting&&e.setDataSortingOptions(),e.visible=w(e.options.visible,b.options.visible,e.visible))});G(this,"afterLinkSeries")},renderSeries:function(){this.series.forEach(function(a){a.translate();a.render()})},renderLabels:function(){var a=this,e=a.options.labels;e.items&&e.items.forEach(function(b){var c=v(e.style,b.style),k=h(c.left)+a.plotLeft,f=h(c.top)+a.plotTop+12;delete c.left;delete c.top;a.renderer.text(b.html,k,f).attr({zIndex:2}).css(c).add()})}, render:function(){var a=this.axes,e=this.colorAxis,b=this.renderer,c=this.options,k=0,f=function(a){a.forEach(function(a){a.visible&&a.render()})};this.setTitle();this.legend=new A(this,c.legend);this.getStacks&&this.getStacks();this.getMargins(!0);this.setChartSize();c=this.plotWidth;a.some(function(a){if(a.horiz&&a.visible&&a.options.labels.enabled&&a.series.length)return k=21,!0});var d=this.plotHeight=Math.max(this.plotHeight-k,0);a.forEach(function(a){a.setScale()});this.getAxisMargins();var u= 1.1<c/this.plotWidth;var l=1.05<d/this.plotHeight;if(u||l)a.forEach(function(a){(a.horiz&&u||!a.horiz&&l)&&a.setTickInterval(!0)}),this.getMargins();this.drawChartBox();this.hasCartesianSeries?f(a):e&&e.length&&f(e);this.seriesGroup||(this.seriesGroup=b.g("series-group").attr({zIndex:3}).add());this.renderSeries();this.renderLabels();this.addCredits();this.setResponsive&&this.setResponsive();this.updateContainerScaling();this.hasRendered=!0},addCredits:function(a){var e=this;a=L(!0,this.options.credits, a);a.enabled&&!this.credits&&(this.credits=this.renderer.text(a.text+(this.mapCredits||""),0,0).addClass("highcharts-credits").on("click",function(){a.href&&(P.location.href=a.href)}).attr({align:a.position.align,zIndex:8}),e.styledMode||this.credits.css(a.style),this.credits.add().align(a.position),this.credits.update=function(a){e.credits=e.credits.destroy();e.addCredits(a)})},updateContainerScaling:function(){var a=this.container;if(a.offsetWidth&&a.offsetHeight&&a.getBoundingClientRect){var e= a.getBoundingClientRect(),b=e.width/a.offsetWidth;a=e.height/a.offsetHeight;1!==b||1!==a?this.containerScaling={scaleX:b,scaleY:a}:delete this.containerScaling}},destroy:function(){var a=this,e=a.axes,b=a.series,c=a.container,f,u=c&&c.parentNode;G(a,"destroy");a.renderer.forExport?x(k,a):k[a.index]=void 0;d.chartCount--;a.renderTo.removeAttribute("data-highcharts-chart");V(a);for(f=e.length;f--;)e[f]=e[f].destroy();this.scroller&&this.scroller.destroy&&this.scroller.destroy();for(f=b.length;f--;)b[f]= b[f].destroy();"title subtitle chartBackground plotBackground plotBGImage plotBorder seriesGroup clipRect credits pointer rangeSelector legend resetZoomButton tooltip renderer".split(" ").forEach(function(e){var b=a[e];b&&b.destroy&&(a[e]=b.destroy())});c&&(c.innerHTML="",V(c),u&&D(c));q(a,function(e,b){delete a[b]})},firstRender:function(){var a=this,e=a.options;if(!a.isReadyToRender||a.isReadyToRender()){a.getContainer();a.resetMargins();a.setChartSize();a.propFromSeries();a.getAxes();(C(e.series)? e.series:[]).forEach(function(e){a.initSeries(e)});a.linkSeries();a.setSeriesData();G(a,"beforeRender");Q&&(a.pointer=new Q(a,e));a.render();if(!a.renderer.imgCount&&a.onload)a.onload();a.temporaryDisplay(!0)}},onload:function(){this.callbacks.concat([this.callback]).forEach(function(a){a&&"undefined"!==typeof this.index&&a.apply(this,[this])},this);G(this,"load");G(this,"render");E(this.index)&&this.setReflow(this.options.chart.reflow);this.onload=null}})});K(y,"parts/ScrollablePlotArea.js",[y["parts/Globals.js"], y["parts/Utilities.js"]],function(d,g){var y=g.pick,F=d.addEvent;g=d.Chart;"";F(g,"afterSetChartSize",function(g){var D=this.options.chart.scrollablePlotArea,x=D&&D.minWidth;D=D&&D.minHeight;if(!this.renderer.forExport){if(x){if(this.scrollablePixelsX=x=Math.max(0,x-this.chartWidth)){this.plotWidth+=x;this.inverted?(this.clipBox.height+=x,this.plotBox.height+=x):(this.clipBox.width+=x,this.plotBox.width+=x);var v={1:{name:"right",value:x}}}}else D&&(this.scrollablePixelsY=x=Math.max(0,D-this.chartHeight))&& (this.plotHeight+=x,this.inverted?(this.clipBox.width+=x,this.plotBox.width+=x):(this.clipBox.height+=x,this.plotBox.height+=x),v={2:{name:"bottom",value:x}});v&&!g.skipAxes&&this.axes.forEach(function(g){v[g.side]?g.getPlotLinePath=function(){var x=v[g.side].name,p=this[x];this[x]=p-v[g.side].value;var z=d.Axis.prototype.getPlotLinePath.apply(this,arguments);this[x]=p;return z}:(g.setAxisSize(),g.setAxisTranslation())})}});F(g,"render",function(){this.scrollablePixelsX||this.scrollablePixelsY?(this.setUpScrolling&& this.setUpScrolling(),this.applyFixed()):this.fixedDiv&&this.applyFixed()});g.prototype.setUpScrolling=function(){var g={WebkitOverflowScrolling:"touch",overflowX:"hidden",overflowY:"hidden"};this.scrollablePixelsX&&(g.overflowX="auto");this.scrollablePixelsY&&(g.overflowY="auto");this.scrollingContainer=d.createElement("div",{className:"highcharts-scrolling"},g,this.renderTo);this.innerContainer=d.createElement("div",{className:"highcharts-inner-container"},null,this.scrollingContainer);this.innerContainer.appendChild(this.container); this.setUpScrolling=null};g.prototype.moveFixedElements=function(){var d=this.container,g=this.fixedRenderer,x=".highcharts-contextbutton .highcharts-credits .highcharts-legend .highcharts-legend-checkbox .highcharts-navigator-series .highcharts-navigator-xaxis .highcharts-navigator-yaxis .highcharts-navigator .highcharts-reset-zoom .highcharts-scrollbar .highcharts-subtitle .highcharts-title".split(" "),v;this.scrollablePixelsX&&!this.inverted?v=".highcharts-yaxis":this.scrollablePixelsX&&this.inverted? v=".highcharts-xaxis":this.scrollablePixelsY&&!this.inverted?v=".highcharts-xaxis":this.scrollablePixelsY&&this.inverted&&(v=".highcharts-yaxis");x.push(v,v+"-labels");x.forEach(function(v){[].forEach.call(d.querySelectorAll(v),function(d){(d.namespaceURI===g.SVG_NS?g.box:g.box.parentNode).appendChild(d);d.style.pointerEvents="auto"})})};g.prototype.applyFixed=function(){var g,D=!this.fixedDiv,x=this.options.chart.scrollablePlotArea;D?(this.fixedDiv=d.createElement("div",{className:"highcharts-fixed"}, {position:"absolute",overflow:"hidden",pointerEvents:"none",zIndex:2},null,!0),this.renderTo.insertBefore(this.fixedDiv,this.renderTo.firstChild),this.renderTo.style.overflow="visible",this.fixedRenderer=g=new d.Renderer(this.fixedDiv,this.chartWidth,this.chartHeight),this.scrollableMask=g.path().attr({fill:this.options.chart.backgroundColor||"#fff","fill-opacity":y(x.opacity,.85),zIndex:-1}).addClass("highcharts-scrollable-mask").add(),this.moveFixedElements(),F(this,"afterShowResetZoom",this.moveFixedElements), F(this,"afterLayOutTitles",this.moveFixedElements)):this.fixedRenderer.setSize(this.chartWidth,this.chartHeight);g=this.chartWidth+(this.scrollablePixelsX||0);var v=this.chartHeight+(this.scrollablePixelsY||0);d.stop(this.container);this.container.style.width=g+"px";this.container.style.height=v+"px";this.renderer.boxWrapper.attr({width:g,height:v,viewBox:[0,0,g,v].join(" ")});this.chartBackground.attr({width:g,height:v});this.scrollablePixelsY&&(this.scrollingContainer.style.height=this.chartHeight+ "px");D&&(x.scrollPositionX&&(this.scrollingContainer.scrollLeft=this.scrollablePixelsX*x.scrollPositionX),x.scrollPositionY&&(this.scrollingContainer.scrollTop=this.scrollablePixelsY*x.scrollPositionY));v=this.axisOffset;D=this.plotTop-v[0]-1;x=this.plotLeft-v[3]-1;g=this.plotTop+this.plotHeight+v[2]+1;v=this.plotLeft+this.plotWidth+v[1]+1;var C=this.plotLeft+this.plotWidth-(this.scrollablePixelsX||0),B=this.plotTop+this.plotHeight-(this.scrollablePixelsY||0);D=this.scrollablePixelsX?["M",0,D,"L", this.plotLeft-1,D,"L",this.plotLeft-1,g,"L",0,g,"Z","M",C,D,"L",this.chartWidth,D,"L",this.chartWidth,g,"L",C,g,"Z"]:this.scrollablePixelsY?["M",x,0,"L",x,this.plotTop-1,"L",v,this.plotTop-1,"L",v,0,"Z","M",x,B,"L",x,this.chartHeight,"L",v,this.chartHeight,"L",v,B,"Z"]:["M",0,0];"adjustHeight"!==this.redrawTrigger&&this.scrollableMask.attr({d:D})}});K(y,"parts/Point.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.animObject,F=g.defined,E=g.erase,D=g.extend,x=g.isArray,v= g.isNumber,C=g.isObject,B=g.syncTimeout,p=g.pick,z,m=d.fireEvent,q=d.format,w=d.uniqueKey,h=d.removeEvent;d.Point=z=function(){};d.Point.prototype={init:function(f,c,b){this.series=f;this.applyOptions(c,b);this.id=F(this.id)?this.id:w();this.resolveColor();f.chart.pointCount++;m(this,"afterInit");return this},resolveColor:function(){var f=this.series;var c=f.chart.options.chart.colorCount;var b=f.chart.styledMode;b||this.options.color||(this.color=f.color);f.options.colorByPoint?(b||(c=f.options.colors|| f.chart.options.colors,this.color=this.color||c[f.colorCounter],c=c.length),b=f.colorCounter,f.colorCounter++,f.colorCounter===c&&(f.colorCounter=0)):b=f.colorIndex;this.colorIndex=p(this.colorIndex,b)},applyOptions:function(f,c){var b=this.series,a=b.options.pointValKey||b.pointValKey;f=z.prototype.optionsToObject.call(this,f);D(this,f);this.options=this.options?D(this.options,f):f;f.group&&delete this.group;f.dataLabels&&delete this.dataLabels;a&&(this.y=this[a]);this.formatPrefix=(this.isNull= p(this.isValid&&!this.isValid(),null===this.x||!v(this.y)))?"null":"point";this.selected&&(this.state="select");"name"in this&&"undefined"===typeof c&&b.xAxis&&b.xAxis.hasNames&&(this.x=b.xAxis.nameToX(this));"undefined"===typeof this.x&&b&&(this.x="undefined"===typeof c?b.autoIncrement(this):c);return this},setNestedProperty:function(f,c,b){b.split(".").reduce(function(a,b,f,d){a[b]=d.length-1===f?c:C(a[b],!0)?a[b]:{};return a[b]},f);return f},optionsToObject:function(f){var c={},b=this.series,a= b.options.keys,l=a||b.pointArrayMap||["y"],h=l.length,g=0,m=0;if(v(f)||null===f)c[l[0]]=f;else if(x(f))for(!a&&f.length>h&&(b=typeof f[0],"string"===b?c.name=f[0]:"number"===b&&(c.x=f[0]),g++);m<h;)a&&"undefined"===typeof f[g]||(0<l[m].indexOf(".")?d.Point.prototype.setNestedProperty(c,f[g],l[m]):c[l[m]]=f[g]),g++,m++;else"object"===typeof f&&(c=f,f.dataLabels&&(b._hasPointLabels=!0),f.marker&&(b._hasPointMarkers=!0));return c},getClassName:function(){return"highcharts-point"+(this.selected?" highcharts-point-select": "")+(this.negative?" highcharts-negative":"")+(this.isNull?" highcharts-null-point":"")+("undefined"!==typeof this.colorIndex?" highcharts-color-"+this.colorIndex:"")+(this.options.className?" "+this.options.className:"")+(this.zone&&this.zone.className?" "+this.zone.className.replace("highcharts-negative",""):"")},getZone:function(){var f=this.series,c=f.zones;f=f.zoneAxis||"y";var b=0,a;for(a=c[b];this[f]>=a.value;)a=c[++b];this.nonZonedColor||(this.nonZonedColor=this.color);this.color=a&&a.color&& !this.options.color?a.color:this.nonZonedColor;return a},hasNewShapeType:function(){return(this.graphic&&(this.graphic.symbolName||this.graphic.element.nodeName))!==this.shapeType},destroy:function(){function f(){d&&(c.setState(),E(d,c),d.length||(a.hoverPoints=null));if(c===a.hoverPoint)c.onMouseOut();if(c.graphic||c.dataLabel||c.dataLabels)h(c),c.destroyElements();for(t in c)c[t]=null}var c=this,b=c.series,a=b.chart;b=b.options.dataSorting;var d=a.hoverPoints,g=y(c.series.chart.renderer.globalAnimation), t;b&&b.enabled?(this.animateBeforeDestroy(),B(f,g.duration)):f();a.pointCount--;c.legendItem&&a.legend.destroyItem(c)},animateBeforeDestroy:function(){var f=this,c={x:f.startXPos,opacity:0},b,a=f.getGraphicalProps();a.singular.forEach(function(a){b="dataLabel"===a;f[a]=f[a].animate(b?{x:f[a].startXPos,y:f[a].startYPos,opacity:0}:c)});a.plural.forEach(function(a){f[a].forEach(function(a){a.element&&a.animate(D({x:f.startXPos},a.startYPos?{x:a.startXPos,y:a.startYPos}:{}))})})},destroyElements:function(f){var c= this;f=c.getGraphicalProps(f);f.singular.forEach(function(b){c[b]=c[b].destroy()});f.plural.forEach(function(b){c[b].forEach(function(a){a.element&&a.destroy()});delete c[b]})},getGraphicalProps:function(f){var c=this,b=[],a,d={singular:[],plural:[]};f=f||{graphic:1,dataLabel:1};f.graphic&&b.push("graphic","shadowGroup");f.dataLabel&&b.push("dataLabel","dataLabelUpper","connector");for(a=b.length;a--;){var h=b[a];c[h]&&d.singular.push(h)}["dataLabel","connector"].forEach(function(a){var b=a+"s";f[a]&& c[b]&&d.plural.push(b)});return d},getLabelConfig:function(){return{x:this.category,y:this.y,color:this.color,colorIndex:this.colorIndex,key:this.name||this.category,series:this.series,point:this,percentage:this.percentage,total:this.total||this.stackTotal}},tooltipFormatter:function(f){var c=this.series,b=c.tooltipOptions,a=p(b.valueDecimals,""),d=b.valuePrefix||"",h=b.valueSuffix||"";c.chart.styledMode&&(f=c.chart.tooltip.styledModeFormat(f));(c.pointArrayMap||["y"]).forEach(function(b){b="{point."+ b;if(d||h)f=f.replace(RegExp(b+"}","g"),d+b+"}"+h);f=f.replace(RegExp(b+"}","g"),b+":,."+a+"f}")});return q(f,{point:this,series:this.series},c.chart)},firePointEvent:function(f,c,b){var a=this,d=this.series.options;(d.point.events[f]||a.options&&a.options.events&&a.options.events[f])&&this.importEvents();"click"===f&&d.allowPointSelect&&(b=function(b){a.select&&a.select(null,b.ctrlKey||b.metaKey||b.shiftKey)});m(this,f,c,b)},visible:!0}});K(y,"parts/Series.js",[y["parts/Globals.js"],y["parts/Utilities.js"]], function(d,g){var y=g.animObject,F=g.arrayMax,E=g.arrayMin,D=g.clamp,x=g.correctFloat,v=g.defined,C=g.erase,B=g.extend,p=g.isArray,z=g.isNumber,m=g.isString,q=g.objectEach,w=g.pick,h=g.splat,f=g.syncTimeout,c=d.addEvent,b=d.defaultOptions,a=d.defaultPlotOptions,l=d.fireEvent,n=d.merge,t=d.removeEvent,I=d.SVGElement,r=d.win;d.Series=d.seriesType("line",null,{lineWidth:2,allowPointSelect:!1,showCheckbox:!1,animation:{duration:1E3},events:{},marker:{enabledThreshold:2,lineColor:"#ffffff",lineWidth:0, radius:4,states:{normal:{animation:!0},hover:{animation:{duration:50},enabled:!0,radiusPlus:2,lineWidthPlus:1},select:{fillColor:"#cccccc",lineColor:"#000000",lineWidth:2}}},point:{events:{}},dataLabels:{align:"center",formatter:function(){var a=this.series.chart.numberFormatter;return null===this.y?"":a(this.y,-1)},padding:5,style:{fontSize:"11px",fontWeight:"bold",color:"contrast",textOutline:"1px contrast"},verticalAlign:"bottom",x:0,y:0},cropThreshold:300,opacity:1,pointRange:0,softThreshold:!0, states:{normal:{animation:!0},hover:{animation:{duration:50},lineWidthPlus:1,marker:{},halo:{size:10,opacity:.25}},select:{animation:{duration:0}},inactive:{animation:{duration:50},opacity:.2}},stickyTracking:!0,turboThreshold:1E3,findNearestPointBy:"x"},{axisTypes:["xAxis","yAxis"],coll:"series",colorCounter:0,cropShoulder:1,directTouch:!1,eventsToUnbind:[],isCartesian:!0,parallelArrays:["x","y"],pointClass:d.Point,requireSorting:!0,sorted:!0,init:function(a,b){l(this,"init",{options:b});var e=this, k=a.series,f;this.eventOptions=this.eventOptions||{};e.chart=a;e.options=b=e.setOptions(b);e.linkedSeries=[];e.bindAxes();B(e,{name:b.name,state:"",visible:!1!==b.visible,selected:!0===b.selected});var h=b.events;q(h,function(a,b){d.isFunction(a)&&e.eventOptions[b]!==a&&(d.isFunction(e.eventOptions[b])&&t(e,b,e.eventOptions[b]),e.eventOptions[b]=a,c(e,b,a))});if(h&&h.click||b.point&&b.point.events&&b.point.events.click||b.allowPointSelect)a.runTrackerClick=!0;e.getColor();e.getSymbol();e.parallelArrays.forEach(function(a){e[a+ "Data"]||(e[a+"Data"]=[])});e.isCartesian&&(a.hasCartesianSeries=!0);k.length&&(f=k[k.length-1]);e._i=w(f&&f._i,-1)+1;a.orderSeries(this.insert(k));b.dataSorting&&b.dataSorting.enabled?e.setDataSortingOptions():e.points||e.data||e.setData(b.data,!1);l(this,"afterInit")},insert:function(a){var e=this.options.index,b;if(z(e)){for(b=a.length;b--;)if(e>=w(a[b].options.index,a[b]._i)){a.splice(b+1,0,this);break}-1===b&&a.unshift(this);b+=1}else a.push(this);return w(b,a.length-1)},bindAxes:function(){var a= this,b=a.options,c=a.chart,f;l(this,"bindAxes",null,function(){(a.axisTypes||[]).forEach(function(e){c[e].forEach(function(c){f=c.options;if(b[e]===f.index||"undefined"!==typeof b[e]&&b[e]===f.id||"undefined"===typeof b[e]&&0===f.index)a.insert(c.series),a[e]=c,c.isDirty=!0});a[e]||a.optionalAxis===e||d.error(18,!0,c)})})},updateParallelArrays:function(a,b){var e=a.series,c=arguments,k=z(b)?function(c){var k="y"===c&&e.toYData?e.toYData(a):a[c];e[c+"Data"][b]=k}:function(a){Array.prototype[b].apply(e[a+ "Data"],Array.prototype.slice.call(c,2))};e.parallelArrays.forEach(k)},hasData:function(){return this.visible&&"undefined"!==typeof this.dataMax&&"undefined"!==typeof this.dataMin||this.visible&&this.yData&&0<this.yData.length},autoIncrement:function(){var a=this.options,b=this.xIncrement,c,f=a.pointIntervalUnit,d=this.chart.time;b=w(b,a.pointStart,0);this.pointInterval=c=w(this.pointInterval,a.pointInterval,1);f&&(a=new d.Date(b),"day"===f?d.set("Date",a,d.get("Date",a)+c):"month"===f?d.set("Month", a,d.get("Month",a)+c):"year"===f&&d.set("FullYear",a,d.get("FullYear",a)+c),c=a.getTime()-b);this.xIncrement=b+c;return b},setDataSortingOptions:function(){var a=this.options;B(this,{requireSorting:!1,sorted:!1,enabledDataSorting:!0,allowDG:!1});v(a.pointRange)||(a.pointRange=1)},setOptions:function(a){var e=this.chart,c=e.options,f=c.plotOptions,d=e.userOptions||{};a=n(a);e=e.styledMode;var h={plotOptions:f,userOptions:a};l(this,"setOptions",h);var g=h.plotOptions[this.type],r=d.plotOptions||{}; this.userOptions=h.userOptions;d=n(g,f.series,d.plotOptions&&d.plotOptions[this.type],a);this.tooltipOptions=n(b.tooltip,b.plotOptions.series&&b.plotOptions.series.tooltip,b.plotOptions[this.type].tooltip,c.tooltip.userOptions,f.series&&f.series.tooltip,f[this.type].tooltip,a.tooltip);this.stickyTracking=w(a.stickyTracking,r[this.type]&&r[this.type].stickyTracking,r.series&&r.series.stickyTracking,this.tooltipOptions.shared&&!this.noSharedTooltip?!0:d.stickyTracking);null===g.marker&&delete d.marker; this.zoneAxis=d.zoneAxis;c=this.zones=(d.zones||[]).slice();!d.negativeColor&&!d.negativeFillColor||d.zones||(f={value:d[this.zoneAxis+"Threshold"]||d.threshold||0,className:"highcharts-negative"},e||(f.color=d.negativeColor,f.fillColor=d.negativeFillColor),c.push(f));c.length&&v(c[c.length-1].value)&&c.push(e?{}:{color:this.color,fillColor:this.fillColor});l(this,"afterSetOptions",{options:d});return d},getName:function(){return w(this.options.name,"Series "+(this.index+1))},getCyclic:function(a, b,c){var e=this.chart,f=this.userOptions,k=a+"Index",d=a+"Counter",u=c?c.length:w(e.options.chart[a+"Count"],e[a+"Count"]);if(!b){var h=w(f[k],f["_"+k]);v(h)||(e.series.length||(e[d]=0),f["_"+k]=h=e[d]%u,e[d]+=1);c&&(b=c[h])}"undefined"!==typeof h&&(this[k]=h);this[a]=b},getColor:function(){this.chart.styledMode?this.getCyclic("color"):this.options.colorByPoint?this.options.color=null:this.getCyclic("color",this.options.color||a[this.type].color,this.chart.options.colors)},getSymbol:function(){this.getCyclic("symbol", this.options.marker.symbol,this.chart.options.symbols)},findPointIndex:function(a,b){var e=a.id,c=a.x,f=this.points,k,h=this.options.dataSorting;if(e)var l=this.chart.get(e);else if(this.linkedParent||this.enabledDataSorting){var g=h&&h.matchByName?"name":"index";l=d.find(f,function(e){return!e.touched&&e[g]===a[g]});if(!l)return}if(l){var r=l&&l.index;"undefined"!==typeof r&&(k=!0)}"undefined"===typeof r&&z(c)&&(r=this.xData.indexOf(c,b));-1!==r&&"undefined"!==typeof r&&this.cropped&&(r=r>=this.cropStart? r-this.cropStart:r);!k&&f[r]&&f[r].touched&&(r=void 0);return r},drawLegendSymbol:d.LegendSymbolMixin.drawLineMarker,updateData:function(a,b){var e=this.options,c=e.dataSorting,f=this.points,k=[],d,h,l,g=this.requireSorting,r=a.length===f.length,t=!0;this.xIncrement=null;a.forEach(function(a,b){var h=v(a)&&this.pointClass.prototype.optionsToObject.call({series:this},a)||{};var u=h.x;if(h.id||z(u)){if(u=this.findPointIndex(h,l),-1===u||"undefined"===typeof u?k.push(a):f[u]&&a!==e.data[u]?(f[u].update(a, !1,null,!1),f[u].touched=!0,g&&(l=u+1)):f[u]&&(f[u].touched=!0),!r||b!==u||c&&c.enabled||this.hasDerivedData)d=!0}else k.push(a)},this);if(d)for(a=f.length;a--;)(h=f[a])&&!h.touched&&h.remove&&h.remove(!1,b);else!r||c&&c.enabled?t=!1:(a.forEach(function(a,e){f[e].update&&a!==f[e].y&&f[e].update(a,!1,null,!1)}),k.length=0);f.forEach(function(a){a&&(a.touched=!1)});if(!t)return!1;k.forEach(function(a){this.addPoint(a,!1,null,null,!1)},this);null===this.xIncrement&&this.xData&&this.xData.length&&(this.xIncrement= F(this.xData),this.autoIncrement());return!0},setData:function(a,b,c,f){var e=this,k=e.points,h=k&&k.length||0,l,u=e.options,g=e.chart,r=u.dataSorting,t=null,H=e.xAxis;t=u.turboThreshold;var n=this.xData,q=this.yData,v=(l=e.pointArrayMap)&&l.length,I=u.keys,x=0,C=1,B;a=a||[];l=a.length;b=w(b,!0);r&&r.enabled&&(a=this.sortData(a));!1!==f&&l&&h&&!e.cropped&&!e.hasGroupedData&&e.visible&&!e.isSeriesBoosting&&(B=this.updateData(a,c));if(!B){e.xIncrement=null;e.colorCounter=0;this.parallelArrays.forEach(function(a){e[a+ "Data"].length=0});if(t&&l>t)if(t=e.getFirstValidPoint(a),z(t))for(c=0;c<l;c++)n[c]=this.autoIncrement(),q[c]=a[c];else if(p(t))if(v)for(c=0;c<l;c++)f=a[c],n[c]=f[0],q[c]=f.slice(1,v+1);else for(I&&(x=I.indexOf("x"),C=I.indexOf("y"),x=0<=x?x:0,C=0<=C?C:1),c=0;c<l;c++)f=a[c],n[c]=f[x],q[c]=f[C];else d.error(12,!1,g);else for(c=0;c<l;c++)"undefined"!==typeof a[c]&&(f={series:e},e.pointClass.prototype.applyOptions.apply(f,[a[c]]),e.updateParallelArrays(f,c));q&&m(q[0])&&d.error(14,!0,g);e.data=[];e.options.data= e.userOptions.data=a;for(c=h;c--;)k[c]&&k[c].destroy&&k[c].destroy();H&&(H.minRange=H.userMinRange);e.isDirty=g.isDirtyBox=!0;e.isDirtyData=!!k;c=!1}"point"===u.legendType&&(this.processData(),this.generatePoints());b&&g.redraw(c)},sortData:function(a){var e=this,b=e.options.dataSorting.sortKey||"y",c=function(a,e){return v(e)&&a.pointClass.prototype.optionsToObject.call({series:a},e)||{}};a.forEach(function(b,f){a[f]=c(e,b);a[f].index=f},this);a.concat().sort(function(a,e){return z(e[b])?e[b]-a[b]: -1}).forEach(function(a,e){a.x=e},this);e.linkedSeries&&e.linkedSeries.forEach(function(e){var b=e.options,f=b.data;b.dataSorting&&b.dataSorting.enabled||!f||(f.forEach(function(b,k){f[k]=c(e,b);a[k]&&(f[k].x=a[k].x,f[k].index=k)}),e.setData(f,!1))});return a},processData:function(a){var e=this.xData,b=this.yData,c=e.length;var f=0;var h=this.xAxis,l=this.options;var g=l.cropThreshold;var r=this.getExtremesFromAll||l.getExtremesFromAll,t=this.isCartesian;l=h&&h.val2lin;var n=h&&h.isLog,m=this.requireSorting; if(t&&!this.isDirty&&!h.isDirty&&!this.yAxis.isDirty&&!a)return!1;if(h){a=h.getExtremes();var q=a.min;var p=a.max}if(t&&this.sorted&&!r&&(!g||c>g||this.forceCrop))if(e[c-1]<q||e[0]>p)e=[],b=[];else if(this.yData&&(e[0]<q||e[c-1]>p)){f=this.cropData(this.xData,this.yData,q,p);e=f.xData;b=f.yData;f=f.start;var z=!0}for(g=e.length||1;--g;)if(c=n?l(e[g])-l(e[g-1]):e[g]-e[g-1],0<c&&("undefined"===typeof w||c<w))var w=c;else 0>c&&m&&(d.error(15,!1,this.chart),m=!1);this.cropped=z;this.cropStart=f;this.processedXData= e;this.processedYData=b;this.closestPointRange=this.basePointRange=w},cropData:function(a,b,c,f,d){var e=a.length,k=0,h=e,l;d=w(d,this.cropShoulder);for(l=0;l<e;l++)if(a[l]>=c){k=Math.max(0,l-d);break}for(c=l;c<e;c++)if(a[c]>f){h=c+d;break}return{xData:a.slice(k,h),yData:b.slice(k,h),start:k,end:h}},generatePoints:function(){var a=this.options,b=a.data,c=this.data,f,d=this.processedXData,g=this.processedYData,r=this.pointClass,t=d.length,n=this.cropStart||0,m=this.hasGroupedData;a=a.keys;var q=[], p;c||m||(c=[],c.length=b.length,c=this.data=c);a&&m&&(this.options.keys=!1);for(p=0;p<t;p++){var z=n+p;if(m){var w=(new r).init(this,[d[p]].concat(h(g[p])));w.dataGroup=this.groupMap[p];w.dataGroup.options&&(w.options=w.dataGroup.options,B(w,w.dataGroup.options),delete w.dataLabels)}else(w=c[z])||"undefined"===typeof b[z]||(c[z]=w=(new r).init(this,b[z],d[p]));w&&(w.index=z,q[p]=w)}this.options.keys=a;if(c&&(t!==(f=c.length)||m))for(p=0;p<f;p++)p!==n||m||(p+=t),c[p]&&(c[p].destroyElements(),c[p].plotX= void 0);this.data=c;this.points=q;l(this,"afterGeneratePoints")},getXExtremes:function(a){return{min:E(a),max:F(a)}},getExtremes:function(a){var e=this.xAxis,b=this.yAxis,c=this.processedXData||this.xData,f=[],d=0,h=0;var g=0;var r=this.requireSorting?this.cropShoulder:0,t=b?b.positiveValuesOnly:!1,n;a=a||this.stackedYData||this.processedYData||[];b=a.length;e&&(g=e.getExtremes(),h=g.min,g=g.max);for(n=0;n<b;n++){var m=c[n];var q=a[n];var w=(z(q)||p(q))&&(q.length||0<q||!t);m=this.getExtremesFromAll|| this.options.getExtremesFromAll||this.cropped||!e||(c[n+r]||m)>=h&&(c[n-r]||m)<=g;if(w&&m)if(w=q.length)for(;w--;)z(q[w])&&(f[d++]=q[w]);else f[d++]=q}this.dataMin=E(f);this.dataMax=F(f);l(this,"afterGetExtremes")},getFirstValidPoint:function(a){for(var e=null,b=a.length,c=0;null===e&&c<b;)e=a[c],c++;return e},translate:function(){this.processedXData||this.processData();this.generatePoints();var a=this.options,b=a.stacking,c=this.xAxis,f=c.categories,d=this.enabledDataSorting,h=this.yAxis,g=this.points, r=g.length,t=!!this.modifyValue,n,m=this.pointPlacementToXValue(),q=z(m),I=a.threshold,C=a.startFromThreshold?I:0,B,E=this.zoneAxis||"y",F=Number.MAX_VALUE;for(n=0;n<r;n++){var y=g[n],M=y.x;var R=y.y;var X=y.low,K=b&&h.stacks[(this.negStacks&&R<(C?0:I)?"-":"")+this.stackKey];h.positiveValuesOnly&&null!==R&&0>=R&&(y.isNull=!0);y.plotX=B=x(D(c.translate(M,0,0,0,1,m,"flags"===this.type),-1E5,1E5));if(b&&this.visible&&K&&K[M]){var aa=this.getStackIndicator(aa,M,this.index);if(!y.isNull){var W=K[M];var Y= W.points[aa.key]}}p(Y)&&(X=Y[0],R=Y[1],X===C&&aa.key===K[M].base&&(X=w(z(I)&&I,h.min)),h.positiveValuesOnly&&0>=X&&(X=null),y.total=y.stackTotal=W.total,y.percentage=W.total&&y.y/W.total*100,y.stackY=R,this.irregularWidths||W.setOffset(this.pointXOffset||0,this.barW||0));y.yBottom=v(X)?D(h.translate(X,0,1,0,1),-1E5,1E5):null;t&&(R=this.modifyValue(R,y));y.plotY=R="number"===typeof R&&Infinity!==R?D(h.translate(R,0,1,0,1),-1E5,1E5):void 0;y.isInside="undefined"!==typeof R&&0<=R&&R<=h.len&&0<=B&&B<= c.len;y.clientX=q?x(c.translate(M,0,0,0,1,m)):B;y.negative=y[E]<(a[E+"Threshold"]||I||0);y.category=f&&"undefined"!==typeof f[y.x]?f[y.x]:y.x;if(!y.isNull&&!1!==y.visible){"undefined"!==typeof S&&(F=Math.min(F,Math.abs(B-S)));var S=B}y.zone=this.zones.length&&y.getZone();!y.graphic&&this.group&&d&&(y.isNew=!0)}this.closestPointRangePx=F;l(this,"afterTranslate")},getValidPoints:function(a,b,c){var e=this.chart;return(a||this.points||[]).filter(function(a){return b&&!e.isInsidePlot(a.plotX,a.plotY, e.inverted)?!1:!1!==a.visible&&(c||!a.isNull)})},getClipBox:function(a,b){var e=this.options,c=this.chart,f=c.inverted,k=this.xAxis,d=k&&this.yAxis;a&&!1===e.clip&&d?a=f?{y:-c.chartWidth+d.len+d.pos,height:c.chartWidth,width:c.chartHeight,x:-c.chartHeight+k.len+k.pos}:{y:-d.pos,height:c.chartHeight,width:c.chartWidth,x:-k.pos}:(a=this.clipBox||c.clipBox,b&&(a.width=c.plotSizeX,a.x=0));return b?{width:a.width,x:a.x}:a},setClip:function(a){var e=this.chart,b=this.options,c=e.renderer,f=e.inverted,d= this.clipBox,h=this.getClipBox(a),l=this.sharedClipKey||["_sharedClip",a&&a.duration,a&&a.easing,h.height,b.xAxis,b.yAxis].join(),g=e[l],r=e[l+"m"];g||(a&&(h.width=0,f&&(h.x=e.plotSizeX+(!1!==b.clip?0:e.plotTop)),e[l+"m"]=r=c.clipRect(f?e.plotSizeX+99:-99,f?-e.plotLeft:-e.plotTop,99,f?e.chartWidth:e.chartHeight)),e[l]=g=c.clipRect(h),g.count={length:0});a&&!g.count[this.index]&&(g.count[this.index]=!0,g.count.length+=1);if(!1!==b.clip||a)this.group.clip(a||d?g:e.clipRect),this.markerGroup.clip(r), this.sharedClipKey=l;a||(g.count[this.index]&&(delete g.count[this.index],--g.count.length),0===g.count.length&&l&&e[l]&&(d||(e[l]=e[l].destroy()),e[l+"m"]&&(e[l+"m"]=e[l+"m"].destroy())))},animate:function(a){var e=this.chart,b=y(this.options.animation);if(a)this.setClip(b);else{var c=this.sharedClipKey;a=e[c];var f=this.getClipBox(b,!0);a&&a.animate(f,b);e[c+"m"]&&e[c+"m"].animate({width:f.width+99,x:f.x-(e.inverted?0:99)},b);this.animate=null}},afterAnimate:function(){this.setClip();l(this,"afterAnimate"); this.finishedAnimating=!0},drawPoints:function(){var a=this.points,b=this.chart,c,f,d=this.options.marker,h=this[this.specialGroup]||this.markerGroup,l=this.xAxis,g=w(d.enabled,!l||l.isRadial?!0:null,this.closestPointRangePx>=d.enabledThreshold*d.radius);if(!1!==d.enabled||this._hasPointMarkers)for(c=0;c<a.length;c++){var r=a[c];var t=(f=r.graphic)?"animate":"attr";var n=r.marker||{};var m=!!r.marker;if((g&&"undefined"===typeof n.enabled||n.enabled)&&!r.isNull&&!1!==r.visible){var q=w(n.symbol,this.symbol); var p=this.markerAttribs(r,r.selected&&"select");this.enabledDataSorting&&(r.startXPos=l.reversed?-p.width:l.width);var z=!1!==r.isInside;f?f[z?"show":"hide"](z).animate(p):z&&(0<p.width||r.hasImage)&&(r.graphic=f=b.renderer.symbol(q,p.x,p.y,p.width,p.height,m?n:d).add(h),this.enabledDataSorting&&b.hasRendered&&(f.attr({x:r.startXPos}),t="animate"));f&&"animate"===t&&f[z?"show":"hide"](z).animate(p);if(f&&!b.styledMode)f[t](this.pointAttribs(r,r.selected&&"select"));f&&f.addClass(r.getClassName(), !0)}else f&&(r.graphic=f.destroy())}},markerAttribs:function(a,b){var e=this.options.marker,c=a.marker||{},f=c.symbol||e.symbol,k=w(c.radius,e.radius);b&&(e=e.states[b],b=c.states&&c.states[b],k=w(b&&b.radius,e&&e.radius,k+(e&&e.radiusPlus||0)));a.hasImage=f&&0===f.indexOf("url");a.hasImage&&(k=0);a={x:Math.floor(a.plotX)-k,y:a.plotY-k};k&&(a.width=a.height=2*k);return a},pointAttribs:function(a,b){var e=this.options.marker,c=a&&a.options,f=c&&c.marker||{},k=this.color,d=c&&c.color,h=a&&a.color;c= w(f.lineWidth,e.lineWidth);var l=a&&a.zone&&a.zone.color;a=1;k=d||l||h||k;d=f.fillColor||e.fillColor||k;k=f.lineColor||e.lineColor||k;b=b||"normal";e=e.states[b];b=f.states&&f.states[b]||{};c=w(b.lineWidth,e.lineWidth,c+w(b.lineWidthPlus,e.lineWidthPlus,0));d=b.fillColor||e.fillColor||d;k=b.lineColor||e.lineColor||k;a=w(b.opacity,e.opacity,a);return{stroke:k,"stroke-width":c,fill:d,opacity:a}},destroy:function(a){var e=this,b=e.chart,c=/AppleWebKit\/533/.test(r.navigator.userAgent),f,h,g=e.data|| [],t,n;l(e,"destroy");this.removeEvents(a);(e.axisTypes||[]).forEach(function(a){(n=e[a])&&n.series&&(C(n.series,e),n.isDirty=n.forceRedraw=!0)});e.legendItem&&e.chart.legend.destroyItem(e);for(h=g.length;h--;)(t=g[h])&&t.destroy&&t.destroy();e.points=null;d.clearTimeout(e.animationTimeout);q(e,function(a,e){a instanceof I&&!a.survive&&(f=c&&"group"===e?"hide":"destroy",a[f]())});b.hoverSeries===e&&(b.hoverSeries=null);C(b.series,e);b.orderSeries();q(e,function(b,c){a&&"hcEvents"===c||delete e[c]})}, getGraphPath:function(a,b,c){var e=this,f=e.options,k=f.step,d,h=[],l=[],g;a=a||e.points;(d=a.reversed)&&a.reverse();(k={right:1,center:2}[k]||k&&3)&&d&&(k=4-k);a=this.getValidPoints(a,!1,!(f.connectNulls&&!b&&!c));a.forEach(function(d,u){var r=d.plotX,t=d.plotY,n=a[u-1];(d.leftCliff||n&&n.rightCliff)&&!c&&(g=!0);d.isNull&&!v(b)&&0<u?g=!f.connectNulls:d.isNull&&!b?g=!0:(0===u||g?u=["M",d.plotX,d.plotY]:e.getPointSpline?u=e.getPointSpline(a,d,u):k?(u=1===k?["L",n.plotX,t]:2===k?["L",(n.plotX+r)/2, n.plotY,"L",(n.plotX+r)/2,t]:["L",r,n.plotY],u.push("L",r,t)):u=["L",r,t],l.push(d.x),k&&(l.push(d.x),2===k&&l.push(d.x)),h.push.apply(h,u),g=!1)});h.xMap=l;return e.graphPath=h},drawGraph:function(){var a=this,b=this.options,c=(this.gappedPath||this.getGraphPath).call(this),f=this.chart.styledMode,d=[["graph","highcharts-graph"]];f||d[0].push(b.lineColor||this.color||"#cccccc",b.dashStyle);d=a.getZonesGraphs(d);d.forEach(function(e,k){var d=e[0],h=a[d],l=h?"animate":"attr";h?(h.endX=a.preventGraphAnimation? null:c.xMap,h.animate({d:c})):c.length&&(a[d]=h=a.chart.renderer.path(c).addClass(e[1]).attr({zIndex:1}).add(a.group));h&&!f&&(d={stroke:e[2],"stroke-width":b.lineWidth,fill:a.fillGraph&&a.color||"none"},e[3]?d.dashstyle=e[3]:"square"!==b.linecap&&(d["stroke-linecap"]=d["stroke-linejoin"]="round"),h[l](d).shadow(2>k&&b.shadow));h&&(h.startX=c.xMap,h.isArea=c.isArea)})},getZonesGraphs:function(a){this.zones.forEach(function(e,b){b=["zone-graph-"+b,"highcharts-graph highcharts-zone-graph-"+b+" "+(e.className|| "")];this.chart.styledMode||b.push(e.color||this.color,e.dashStyle||this.options.dashStyle);a.push(b)},this);return a},applyZones:function(){var a=this,b=this.chart,c=b.renderer,f=this.zones,d,h,l=this.clips||[],g,r=this.graph,t=this.area,n=Math.max(b.chartWidth,b.chartHeight),m=this[(this.zoneAxis||"y")+"Axis"],q=b.inverted,p,z,v,I=!1;if(f.length&&(r||t)&&m&&"undefined"!==typeof m.min){var x=m.reversed;var C=m.horiz;r&&!this.showLine&&r.hide();t&&t.hide();var B=m.getExtremes();f.forEach(function(e, f){d=x?C?b.plotWidth:0:C?0:m.toPixels(B.min)||0;d=D(w(h,d),0,n);h=D(Math.round(m.toPixels(w(e.value,B.max),!0)||0),0,n);I&&(d=h=m.toPixels(B.max));p=Math.abs(d-h);z=Math.min(d,h);v=Math.max(d,h);m.isXAxis?(g={x:q?v:z,y:0,width:p,height:n},C||(g.x=b.plotHeight-g.x)):(g={x:0,y:q?v:z,width:n,height:p},C&&(g.y=b.plotWidth-g.y));q&&c.isVML&&(g=m.isXAxis?{x:0,y:x?z:v,height:g.width,width:b.chartWidth}:{x:g.y-b.plotLeft-b.spacingBox.x,y:0,width:g.height,height:b.chartHeight});l[f]?l[f].animate(g):l[f]=c.clipRect(g); r&&a["zone-graph-"+f].clip(l[f]);t&&a["zone-area-"+f].clip(l[f]);I=e.value>B.max;a.resetZones&&0===h&&(h=void 0)});this.clips=l}else a.visible&&(r&&r.show(!0),t&&t.show(!0))},invertGroups:function(a){function e(){["group","markerGroup"].forEach(function(e){b[e]&&(f.renderer.isVML&&b[e].attr({width:b.yAxis.len,height:b.xAxis.len}),b[e].width=b.yAxis.len,b[e].height=b.xAxis.len,b[e].invert(b.isRadialSeries?!1:a))})}var b=this,f=b.chart;b.xAxis&&(b.eventsToUnbind.push(c(f,"resize",e)),e(),b.invertGroups= e)},plotGroup:function(a,b,c,f,d){var e=this[a],k=!e;k&&(this[a]=e=this.chart.renderer.g().attr({zIndex:f||.1}).add(d));e.addClass("highcharts-"+b+" highcharts-series-"+this.index+" highcharts-"+this.type+"-series "+(v(this.colorIndex)?"highcharts-color-"+this.colorIndex+" ":"")+(this.options.className||"")+(e.hasClass("highcharts-tracker")?" highcharts-tracker":""),!0);e.attr({visibility:c})[k?"attr":"animate"](this.getPlotBox());return e},getPlotBox:function(){var a=this.chart,b=this.xAxis,c=this.yAxis; a.inverted&&(b=c,c=this.xAxis);return{translateX:b?b.left:a.plotLeft,translateY:c?c.top:a.plotTop,scaleX:1,scaleY:1}},removeEvents:function(a){a?this.eventsToUnbind.length&&(this.eventsToUnbind.forEach(function(a){a()}),this.eventsToUnbind.length=0):t(this)},render:function(){var a=this,b=a.chart,c=a.options,d=!!a.animate&&b.renderer.isSVG&&y(c.animation).duration,h=a.visible?"inherit":"hidden",g=c.zIndex,r=a.hasRendered,t=b.seriesGroup,n=b.inverted;l(this,"render");var m=a.plotGroup("group","series", h,g,t);a.markerGroup=a.plotGroup("markerGroup","markers",h,g,t);d&&a.animate(!0);m.inverted=a.isCartesian||a.invertable?n:!1;a.drawGraph&&(a.drawGraph(),a.applyZones());a.visible&&a.drawPoints();a.drawDataLabels&&a.drawDataLabels();a.redrawPoints&&a.redrawPoints();a.drawTracker&&!1!==a.options.enableMouseTracking&&a.drawTracker();a.invertGroups(n);!1===c.clip||a.sharedClipKey||r||m.clip(b.clipRect);d&&a.animate();r||(a.animationTimeout=f(function(){a.afterAnimate()},d||0));a.isDirty=!1;a.hasRendered= !0;l(a,"afterRender")},redraw:function(){var a=this.chart,b=this.isDirty||this.isDirtyData,c=this.group,f=this.xAxis,d=this.yAxis;c&&(a.inverted&&c.attr({width:a.plotWidth,height:a.plotHeight}),c.animate({translateX:w(f&&f.left,a.plotLeft),translateY:w(d&&d.top,a.plotTop)}));this.translate();this.render();b&&delete this.kdTree},kdAxisArray:["clientX","plotY"],searchPoint:function(a,b){var e=this.xAxis,c=this.yAxis,f=this.chart.inverted;return this.searchKDTree({clientX:f?e.len-a.chartY+e.pos:a.chartX- e.pos,plotY:f?c.len-a.chartX+c.pos:a.chartY-c.pos},b,a)},buildKDTree:function(a){function e(a,c,f){var k;if(k=a&&a.length){var d=b.kdAxisArray[c%f];a.sort(function(a,e){return a[d]-e[d]});k=Math.floor(k/2);return{point:a[k],left:e(a.slice(0,k),c+1,f),right:e(a.slice(k+1),c+1,f)}}}this.buildingKdTree=!0;var b=this,c=-1<b.options.findNearestPointBy.indexOf("y")?2:1;delete b.kdTree;f(function(){b.kdTree=e(b.getValidPoints(null,!b.directTouch),c,c);b.buildingKdTree=!1},b.options.kdNow||a&&"touchstart"=== a.type?0:1)},searchKDTree:function(a,b,c){function e(a,b,c,l){var g=b.point,r=f.kdAxisArray[c%l],u=g;var t=v(a[k])&&v(g[k])?Math.pow(a[k]-g[k],2):null;var n=v(a[d])&&v(g[d])?Math.pow(a[d]-g[d],2):null;n=(t||0)+(n||0);g.dist=v(n)?Math.sqrt(n):Number.MAX_VALUE;g.distX=v(t)?Math.sqrt(t):Number.MAX_VALUE;r=a[r]-g[r];n=0>r?"left":"right";t=0>r?"right":"left";b[n]&&(n=e(a,b[n],c+1,l),u=n[h]<u[h]?n:g);b[t]&&Math.sqrt(r*r)<u[h]&&(a=e(a,b[t],c+1,l),u=a[h]<u[h]?a:u);return u}var f=this,k=this.kdAxisArray[0], d=this.kdAxisArray[1],h=b?"distX":"dist";b=-1<f.options.findNearestPointBy.indexOf("y")?2:1;this.kdTree||this.buildingKdTree||this.buildKDTree(c);if(this.kdTree)return e(a,this.kdTree,b,b)},pointPlacementToXValue:function(){var a=this.xAxis,b=this.options.pointPlacement;"between"===b&&(b=a.reversed?-.5:.5);z(b)&&(b*=w(this.options.pointRange||a.pointRange));return b}});""});K(y,"parts/Stacking.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.correctFloat,F=g.defined,E=g.destroyObjectProperties, D=g.objectEach,x=g.pick;g=d.Axis;var v=d.Chart,C=d.format,B=d.Series;d.StackItem=function(d,g,m,q,w){var h=d.chart.inverted;this.axis=d;this.isNegative=m;this.options=g=g||{};this.x=q;this.total=null;this.points={};this.stack=w;this.rightCliff=this.leftCliff=0;this.alignOptions={align:g.align||(h?m?"left":"right":"center"),verticalAlign:g.verticalAlign||(h?"middle":m?"bottom":"top"),y:g.y,x:g.x};this.textAlign=g.textAlign||(h?m?"right":"left":"center")};d.StackItem.prototype={destroy:function(){E(this, this.axis)},render:function(d){var g=this.axis.chart,m=this.options,q=m.format;q=q?C(q,this,g):m.formatter.call(this);this.label?this.label.attr({text:q,visibility:"hidden"}):(this.label=g.renderer.label(q,null,null,m.shape,null,null,m.useHTML,!1,"stack-labels"),q={text:q,align:this.textAlign,rotation:m.rotation,padding:x(m.padding,0),visibility:"hidden"},this.label.attr(q),g.styledMode||this.label.css(m.style),this.label.added||this.label.add(d));this.label.labelrank=g.plotHeight},setOffset:function(d, g,m,q,w){var h=this.axis,f=h.chart;q=h.translate(h.usePercentage?100:q?q:this.total,0,0,0,1);m=h.translate(m?m:0);m=F(q)&&Math.abs(q-m);d=x(w,f.xAxis[0].translate(this.x))+d;h=F(q)&&this.getStackBox(f,this,d,q,g,m,h);g=this.label;d=this.isNegative;w="justify"===x(this.options.overflow,"justify");if(g&&h){m=g.getBBox();var c=f.inverted?d?m.width:0:m.width/2,b=f.inverted?m.height/2:d?-4:m.height+4;this.alignOptions.x=x(this.options.x,0);g.align(this.alignOptions,null,h);q=g.alignAttr;g.show();q.y-= b;w&&(q.x-=c,B.prototype.justifyDataLabel.call(this.axis,g,this.alignOptions,q,m,h),q.x+=c);q.x=g.alignAttr.x;g.attr({x:q.x,y:q.y});x(!w&&this.options.crop,!0)&&((f=f.isInsidePlot(g.x+(f.inverted?0:-m.width/2),g.y)&&f.isInsidePlot(g.x+(f.inverted?d?-m.width:m.width:m.width/2),g.y+m.height))||g.hide())}},getStackBox:function(d,g,m,q,w,h,f){var c=g.axis.reversed,b=d.inverted;d=f.height+f.pos-(b?d.plotLeft:d.plotTop);g=g.isNegative&&!c||!g.isNegative&&c;return{x:b?g?q:q-h:m,y:b?d-m-w:g?d-q-h:d-q,width:b? h:w,height:b?w:h}}};v.prototype.getStacks=function(){var d=this,g=d.inverted;d.yAxis.forEach(function(d){d.stacks&&d.hasVisibleSeries&&(d.oldStacks=d.stacks)});d.series.forEach(function(m){var q=m.xAxis&&m.xAxis.options||{};!m.options.stacking||!0!==m.visible&&!1!==d.options.chart.ignoreHiddenSeries||(m.stackKey=[m.type,x(m.options.stack,""),g?q.top:q.left,g?q.height:q.width].join())})};g.prototype.buildStacks=function(){var g=this.series,v=x(this.options.reversedStacks,!0),m=g.length,q;if(!this.isXAxis){this.usePercentage= !1;for(q=m;q--;){var w=g[v?q:m-q-1];w.setStackedPoints()}for(q=0;q<m;q++)g[q].modifyStacks();d.fireEvent(this,"afterBuildStacks")}};g.prototype.renderStackTotals=function(){var d=this.chart,g=d.renderer,m=this.stacks,q=this.stackTotalGroup;q||(this.stackTotalGroup=q=g.g("stack-labels").attr({visibility:"visible",zIndex:6}).add());q.translate(d.plotLeft,d.plotTop);D(m,function(d){D(d,function(d){d.render(q)})})};g.prototype.resetStacks=function(){var d=this,g=d.stacks;d.isXAxis||D(g,function(g){D(g, function(m,p){m.touched<d.stacksTouched?(m.destroy(),delete g[p]):(m.total=null,m.cumulative=null)})})};g.prototype.cleanStacks=function(){if(!this.isXAxis){if(this.oldStacks)var d=this.stacks=this.oldStacks;D(d,function(d){D(d,function(d){d.cumulative=d.total})})}};B.prototype.setStackedPoints=function(){if(this.options.stacking&&(!0===this.visible||!1===this.chart.options.chart.ignoreHiddenSeries)){var g=this.processedXData,v=this.processedYData,m=[],q=v.length,w=this.options,h=w.threshold,f=x(w.startFromThreshold&& h,0),c=w.stack;w=w.stacking;var b=this.stackKey,a="-"+b,l=this.negStacks,n=this.yAxis,t=n.stacks,I=n.oldStacks,r,e;n.stacksTouched+=1;for(e=0;e<q;e++){var k=g[e];var u=v[e];var H=this.getStackIndicator(H,k,this.index);var G=H.key;var A=(r=l&&u<(f?0:h))?a:b;t[A]||(t[A]={});t[A][k]||(I[A]&&I[A][k]?(t[A][k]=I[A][k],t[A][k].total=null):t[A][k]=new d.StackItem(n,n.options.stackLabels,r,k,c));A=t[A][k];null!==u?(A.points[G]=A.points[this.index]=[x(A.cumulative,f)],F(A.cumulative)||(A.base=G),A.touched= n.stacksTouched,0<H.index&&!1===this.singleStacks&&(A.points[G][0]=A.points[this.index+","+k+",0"][0])):A.points[G]=A.points[this.index]=null;"percent"===w?(r=r?b:a,l&&t[r]&&t[r][k]?(r=t[r][k],A.total=r.total=Math.max(r.total,A.total)+Math.abs(u)||0):A.total=y(A.total+(Math.abs(u)||0))):A.total=y(A.total+(u||0));A.cumulative=x(A.cumulative,f)+(u||0);null!==u&&(A.points[G].push(A.cumulative),m[e]=A.cumulative)}"percent"===w&&(n.usePercentage=!0);this.stackedYData=m;n.oldStacks={}}};B.prototype.modifyStacks= function(){var d=this,g=d.stackKey,m=d.yAxis.stacks,q=d.processedXData,w,h=d.options.stacking;d[h+"Stacker"]&&[g,"-"+g].forEach(function(f){for(var c=q.length,b,a;c--;)if(b=q[c],w=d.getStackIndicator(w,b,d.index,f),a=(b=m[f]&&m[f][b])&&b.points[w.key])d[h+"Stacker"](a,b,c)})};B.prototype.percentStacker=function(d,g,m){g=g.total?100/g.total:0;d[0]=y(d[0]*g);d[1]=y(d[1]*g);this.stackedYData[m]=d[1]};B.prototype.getStackIndicator=function(d,g,m,q){!F(d)||d.x!==g||q&&d.key!==q?d={x:g,index:0,key:q}:d.index++; d.key=[m,g,d.index].join();return d}});K(y,"parts/Dynamics.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.defined,F=g.erase,E=g.extend,D=g.isArray,x=g.isNumber,v=g.isObject,C=g.isString,B=g.objectEach,p=g.pick,z=g.relativeLength,m=g.setAnimation,q=g.splat,w=d.addEvent,h=d.animate,f=d.Axis;g=d.Chart;var c=d.createElement,b=d.css,a=d.fireEvent,l=d.merge,n=d.Point,t=d.Series,I=d.seriesTypes;d.cleanRecursively=function(a,e){var b={};B(a,function(c,f){if(v(a[f],!0)&&!a.nodeType&& e[f])c=d.cleanRecursively(a[f],e[f]),Object.keys(c).length&&(b[f]=c);else if(v(a[f])||a[f]!==e[f])b[f]=a[f]});return b};E(g.prototype,{addSeries:function(b,e,c){var f,d=this;b&&(e=p(e,!0),a(d,"addSeries",{options:b},function(){f=d.initSeries(b);d.isDirtyLegend=!0;d.linkSeries();f.enabledDataSorting&&f.setData(b.data,!1);a(d,"afterAddSeries",{series:f});e&&d.redraw(c)}));return f},addAxis:function(a,e,b,c){return this.createAxis(e?"xAxis":"yAxis",{axis:a,redraw:b,animation:c})},addColorAxis:function(a, e,b){return this.createAxis("colorAxis",{axis:a,redraw:e,animation:b})},createAxis:function(a,e){var b=this.options,c="colorAxis"===a,h=e.redraw,g=e.animation;e=l(e.axis,{index:this[a].length,isX:"xAxis"===a});var r=c?new d.ColorAxis(this,e):new f(this,e);b[a]=q(b[a]||{});b[a].push(e);c&&(this.isDirtyLegend=!0,this.axes.forEach(function(a){a.series=[]}),this.series.forEach(function(a){a.bindAxes();a.isDirtyData=!0}));p(h,!0)&&this.redraw(g);return r},showLoading:function(a){var e=this,f=e.options, d=e.loadingDiv,g=f.loading,l=function(){d&&b(d,{left:e.plotLeft+"px",top:e.plotTop+"px",width:e.plotWidth+"px",height:e.plotHeight+"px"})};d||(e.loadingDiv=d=c("div",{className:"highcharts-loading highcharts-loading-hidden"},null,e.container),e.loadingSpan=c("span",{className:"highcharts-loading-inner"},null,d),w(e,"redraw",l));d.className="highcharts-loading";e.loadingSpan.innerHTML=p(a,f.lang.loading,"");e.styledMode||(b(d,E(g.style,{zIndex:10})),b(e.loadingSpan,g.labelStyle),e.loadingShown||(b(d, {opacity:0,display:""}),h(d,{opacity:g.style.opacity||.5},{duration:g.showDuration||0})));e.loadingShown=!0;l()},hideLoading:function(){var a=this.options,e=this.loadingDiv;e&&(e.className="highcharts-loading highcharts-loading-hidden",this.styledMode||h(e,{opacity:0},{duration:a.loading.hideDuration||100,complete:function(){b(e,{display:"none"})}}));this.loadingShown=!1},propsRequireDirtyBox:"backgroundColor borderColor borderWidth borderRadius plotBackgroundColor plotBackgroundImage plotBorderColor plotBorderWidth plotShadow shadow".split(" "), propsRequireReflow:"margin marginTop marginRight marginBottom marginLeft spacing spacingTop spacingRight spacingBottom spacingLeft".split(" "),propsRequireUpdateSeries:"chart.inverted chart.polar chart.ignoreHiddenSeries chart.type colors plotOptions time tooltip".split(" "),collectionsWithUpdate:["xAxis","yAxis","zAxis","series"],update:function(b,e,c,f){var k=this,h={credits:"addCredits",title:"setTitle",subtitle:"setSubtitle",caption:"setCaption"},g,u,r,t=b.isResponsiveOptions,n=[];a(k,"update", {options:b});t||k.setResponsive(!1,!0);b=d.cleanRecursively(b,k.options);l(!0,k.userOptions,b);if(g=b.chart){l(!0,k.options.chart,g);"className"in g&&k.setClassName(g.className);"reflow"in g&&k.setReflow(g.reflow);if("inverted"in g||"polar"in g||"type"in g){k.propFromSeries();var m=!0}"alignTicks"in g&&(m=!0);B(g,function(a,e){-1!==k.propsRequireUpdateSeries.indexOf("chart."+e)&&(u=!0);-1!==k.propsRequireDirtyBox.indexOf(e)&&(k.isDirtyBox=!0);t||-1===k.propsRequireReflow.indexOf(e)||(r=!0)});!k.styledMode&& "style"in g&&k.renderer.setStyle(g.style)}!k.styledMode&&b.colors&&(this.options.colors=b.colors);b.plotOptions&&l(!0,this.options.plotOptions,b.plotOptions);b.time&&this.time===d.time&&(this.time=new d.Time(b.time));B(b,function(a,e){if(k[e]&&"function"===typeof k[e].update)k[e].update(a,!1);else if("function"===typeof k[h[e]])k[h[e]](a);"chart"!==e&&-1!==k.propsRequireUpdateSeries.indexOf(e)&&(u=!0)});this.collectionsWithUpdate.forEach(function(a){if(b[a]){if("series"===a){var e=[];k[a].forEach(function(a, b){a.options.isInternal||e.push(p(a.options.index,b))})}q(b[a]).forEach(function(b,f){(f=y(b.id)&&k.get(b.id)||k[a][e?e[f]:f])&&f.coll===a&&(f.update(b,!1),c&&(f.touched=!0));!f&&c&&k.collectionsWithInit[a]&&(k.collectionsWithInit[a][0].apply(k,[b].concat(k.collectionsWithInit[a][1]||[]).concat([!1])).touched=!0)});c&&k[a].forEach(function(a){a.touched||a.options.isInternal?delete a.touched:n.push(a)})}});n.forEach(function(a){a.remove&&a.remove(!1)});m&&k.axes.forEach(function(a){a.update({},!1)}); u&&k.getSeriesOrderByLinks().forEach(function(a){a.chart&&a.update({},!1)},this);b.loading&&l(!0,k.options.loading,b.loading);m=g&&g.width;g=g&&g.height;C(g)&&(g=z(g,m||k.chartWidth));r||x(m)&&m!==k.chartWidth||x(g)&&g!==k.chartHeight?k.setSize(m,g,f):p(e,!0)&&k.redraw(f);a(k,"afterUpdate",{options:b,redraw:e,animation:f})},setSubtitle:function(a,e){this.applyDescription("subtitle",a);this.layOutTitles(e)},setCaption:function(a,e){this.applyDescription("caption",a);this.layOutTitles(e)}});g.prototype.collectionsWithInit= {xAxis:[g.prototype.addAxis,[!0]],yAxis:[g.prototype.addAxis,[!1]],series:[g.prototype.addSeries]};E(n.prototype,{update:function(a,e,b,c){function f(){d.applyOptions(a);null===d.y&&g&&(d.graphic=g.destroy());v(a,!0)&&(g&&g.element&&a&&a.marker&&"undefined"!==typeof a.marker.symbol&&(d.graphic=g.destroy()),a&&a.dataLabels&&d.dataLabel&&(d.dataLabel=d.dataLabel.destroy()),d.connector&&(d.connector=d.connector.destroy()));h=d.index;k.updateParallelArrays(d,h);u.data[h]=v(u.data[h],!0)||v(a,!0)?d.options: p(a,u.data[h]);k.isDirty=k.isDirtyData=!0;!k.fixedBox&&k.hasCartesianSeries&&(l.isDirtyBox=!0);"point"===u.legendType&&(l.isDirtyLegend=!0);e&&l.redraw(b)}var d=this,k=d.series,g=d.graphic,h,l=k.chart,u=k.options;e=p(e,!0);!1===c?f():d.firePointEvent("update",{options:a},f)},remove:function(a,e){this.series.removePoint(this.series.data.indexOf(this),a,e)}});E(t.prototype,{addPoint:function(b,e,c,f,d){var k=this.options,g=this.data,h=this.chart,l=this.xAxis;l=l&&l.hasNames&&l.names;var u=k.data,r= this.xData,t;e=p(e,!0);var n={series:this};this.pointClass.prototype.applyOptions.apply(n,[b]);var m=n.x;var q=r.length;if(this.requireSorting&&m<r[q-1])for(t=!0;q&&r[q-1]>m;)q--;this.updateParallelArrays(n,"splice",q,0,0);this.updateParallelArrays(n,q);l&&n.name&&(l[m]=n.name);u.splice(q,0,b);t&&(this.data.splice(q,0,null),this.processData());"point"===k.legendType&&this.generatePoints();c&&(g[0]&&g[0].remove?g[0].remove(!1):(g.shift(),this.updateParallelArrays(n,"shift"),u.shift()));!1!==d&&a(this, "addPoint",{point:n});this.isDirtyData=this.isDirty=!0;e&&h.redraw(f)},removePoint:function(a,e,b){var c=this,f=c.data,d=f[a],k=c.points,g=c.chart,h=function(){k&&k.length===f.length&&k.splice(a,1);f.splice(a,1);c.options.data.splice(a,1);c.updateParallelArrays(d||{series:c},"splice",a,1);d&&d.destroy();c.isDirty=!0;c.isDirtyData=!0;e&&g.redraw()};m(b,g);e=p(e,!0);d?d.firePointEvent("remove",null,h):h()},remove:function(b,e,c,f){function d(){k.destroy(f);k.remove=null;g.isDirtyLegend=g.isDirtyBox= !0;g.linkSeries();p(b,!0)&&g.redraw(e)}var k=this,g=k.chart;!1!==c?a(k,"remove",null,d):d()},update:function(b,e){b=d.cleanRecursively(b,this.userOptions);a(this,"update",{options:b});var c=this,f=c.chart,g=c.userOptions,h=c.initialType||c.type,r=b.type||g.type||f.options.chart.type,t=!(this.hasDerivedData||b.dataGrouping||r&&r!==this.type||"undefined"!==typeof b.pointStart||b.pointInterval||b.pointIntervalUnit||b.keys),n=I[h].prototype,m,q=["group","markerGroup","dataLabelsGroup","transformGroup"], w=["eventOptions","navigatorSeries","baseSeries"],v=c.finishedAnimating&&{animation:!1},z={};t&&(w.push("data","isDirtyData","points","processedXData","processedYData","xIncrement","_hasPointMarkers","_hasPointLabels","mapMap","mapData","minY","maxY","minX","maxX"),!1!==b.visible&&w.push("area","graph"),c.parallelArrays.forEach(function(a){w.push(a+"Data")}),b.data&&(b.dataSorting&&E(c.options.dataSorting,b.dataSorting),this.setData(b.data,!1)));b=l(g,v,{index:"undefined"===typeof g.index?c.index: g.index,pointStart:p(g.pointStart,c.xData[0])},!t&&{data:c.options.data},b);t&&b.data&&(b.data=c.options.data);w=q.concat(w);w.forEach(function(a){w[a]=c[a];delete c[a]});c.remove(!1,null,!1,!0);for(m in n)c[m]=void 0;I[r||h]?E(c,I[r||h].prototype):d.error(17,!0,f,{missingModuleFor:r||h});w.forEach(function(a){c[a]=w[a]});c.init(f,b);if(t&&this.points){var x=c.options;!1===x.visible?(z.graphic=1,z.dataLabel=1):c._hasPointLabels||(r=x.marker,n=x.dataLabels,r&&(!1===r.enabled||"symbol"in r)&&(z.graphic= 1),n&&!1===n.enabled&&(z.dataLabel=1));this.points.forEach(function(a){a&&a.series&&(a.resolveColor(),Object.keys(z).length&&a.destroyElements(z),!1===x.showInLegend&&a.legendItem&&f.legend.destroyItem(a))},this)}b.zIndex!==g.zIndex&&q.forEach(function(a){c[a]&&c[a].attr({zIndex:b.zIndex})});c.initialType=h;f.linkSeries();a(this,"afterUpdate");p(e,!0)&&f.redraw(t?void 0:!1)},setName:function(a){this.name=this.options.name=this.userOptions.name=a;this.chart.isDirtyLegend=!0}});E(f.prototype,{update:function(a, e){var b=this.chart,c=a&&a.events||{};a=l(this.userOptions,a);b.options[this.coll].indexOf&&(b.options[this.coll][b.options[this.coll].indexOf(this.userOptions)]=a);B(b.options[this.coll].events,function(a,e){"undefined"===typeof c[e]&&(c[e]=void 0)});this.destroy(!0);this.init(b,E(a,{events:c}));b.isDirtyBox=!0;p(e,!0)&&b.redraw()},remove:function(a){for(var e=this.chart,b=this.coll,c=this.series,f=c.length;f--;)c[f]&&c[f].remove(!1);F(e.axes,this);F(e[b],this);D(e.options[b])?e.options[b].splice(this.options.index, 1):delete e.options[b];e[b].forEach(function(a,e){a.options.index=a.userOptions.index=e});this.destroy();e.isDirtyBox=!0;p(a,!0)&&e.redraw()},setTitle:function(a,e){this.update({title:a},e)},setCategories:function(a,e){this.update({categories:a},e)}})});K(y,"parts/AreaSeries.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.objectEach,F=g.pick,E=d.color,D=d.Series;g=d.seriesType;g("area","line",{softThreshold:!1,threshold:0},{singleStacks:!1,getStackPoints:function(d){var g= [],x=[],B=this.xAxis,p=this.yAxis,z=p.stacks[this.stackKey],m={},q=this.index,w=p.series,h=w.length,f=F(p.options.reversedStacks,!0)?1:-1,c;d=d||this.points;if(this.options.stacking){for(c=0;c<d.length;c++)d[c].leftNull=d[c].rightNull=void 0,m[d[c].x]=d[c];y(z,function(a,b){null!==a.total&&x.push(b)});x.sort(function(a,b){return a-b});var b=w.map(function(a){return a.visible});x.forEach(function(a,d){var l=0,t,w;if(m[a]&&!m[a].isNull)g.push(m[a]),[-1,1].forEach(function(g){var e=1===g?"rightNull": "leftNull",k=0,l=z[x[d+g]];if(l)for(c=q;0<=c&&c<h;)t=l.points[c],t||(c===q?m[a][e]=!0:b[c]&&(w=z[a].points[c])&&(k-=w[1]-w[0])),c+=f;m[a][1===g?"rightCliff":"leftCliff"]=k});else{for(c=q;0<=c&&c<h;){if(t=z[a].points[c]){l=t[1];break}c+=f}l=p.translate(l,0,1,0,1);g.push({isNull:!0,plotX:B.translate(a,0,0,0,1),x:a,plotY:l,yBottom:l})}})}return g},getGraphPath:function(d){var g=D.prototype.getGraphPath,x=this.options,B=x.stacking,p=this.yAxis,z,m=[],q=[],w=this.index,h=p.stacks[this.stackKey],f=x.threshold, c=Math.round(p.getThreshold(x.threshold));x=F(x.connectNulls,"percent"===B);var b=function(a,b,g){var e=d[a];a=B&&h[e.x].points[w];var k=e[g+"Null"]||0;g=e[g+"Cliff"]||0;e=!0;if(g||k){var u=(k?a[0]:a[1])+g;var t=a[0]+g;e=!!k}else!B&&d[b]&&d[b].isNull&&(u=t=f);"undefined"!==typeof u&&(q.push({plotX:l,plotY:null===u?c:p.getThreshold(u),isNull:e,isCliff:!0}),m.push({plotX:l,plotY:null===t?c:p.getThreshold(t),doCurve:!1}))};d=d||this.points;B&&(d=this.getStackPoints(d));for(z=0;z<d.length;z++){B||(d[z].leftCliff= d[z].rightCliff=d[z].leftNull=d[z].rightNull=void 0);var a=d[z].isNull;var l=F(d[z].rectPlotX,d[z].plotX);var n=F(d[z].yBottom,c);if(!a||x)x||b(z,z-1,"left"),a&&!B&&x||(q.push(d[z]),m.push({x:z,plotX:l,plotY:n})),x||b(z,z+1,"right")}z=g.call(this,q,!0,!0);m.reversed=!0;a=g.call(this,m,!0,!0);a.length&&(a[0]="L");a=z.concat(a);g=g.call(this,q,!1,x);a.xMap=z.xMap;this.areaPath=a;return g},drawGraph:function(){this.areaPath=[];D.prototype.drawGraph.apply(this);var d=this,g=this.areaPath,C=this.options, B=[["area","highcharts-area",this.color,C.fillColor]];this.zones.forEach(function(g,v){B.push(["zone-area-"+v,"highcharts-area highcharts-zone-area-"+v+" "+g.className,g.color||d.color,g.fillColor||C.fillColor])});B.forEach(function(p){var v=p[0],m=d[v],q=m?"animate":"attr",w={};m?(m.endX=d.preventGraphAnimation?null:g.xMap,m.animate({d:g})):(w.zIndex=0,m=d[v]=d.chart.renderer.path(g).addClass(p[1]).add(d.group),m.isArea=!0);d.chart.styledMode||(w.fill=F(p[3],E(p[2]).setOpacity(F(C.fillOpacity,.75)).get())); m[q](w);m.startX=g.xMap;m.shiftUnit=C.step?2:1})},drawLegendSymbol:d.LegendSymbolMixin.drawRectangle});""});K(y,"parts/SplineSeries.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.pick;d=d.seriesType;d("spline","line",{},{getPointSpline:function(d,g,D){var x=g.plotX,v=g.plotY,C=d[D-1];D=d[D+1];if(C&&!C.isNull&&!1!==C.doCurve&&!g.isCliff&&D&&!D.isNull&&!1!==D.doCurve&&!g.isCliff){d=C.plotY;var B=D.plotX;D=D.plotY;var p=0;var z=(1.5*x+C.plotX)/2.5;var m=(1.5*v+d)/2.5;B=(1.5* x+B)/2.5;var q=(1.5*v+D)/2.5;B!==z&&(p=(q-m)*(B-x)/(B-z)+v-q);m+=p;q+=p;m>d&&m>v?(m=Math.max(d,v),q=2*v-m):m<d&&m<v&&(m=Math.min(d,v),q=2*v-m);q>D&&q>v?(q=Math.max(D,v),m=2*v-q):q<D&&q<v&&(q=Math.min(D,v),m=2*v-q);g.rightContX=B;g.rightContY=q}g=["C",y(C.rightContX,C.plotX),y(C.rightContY,C.plotY),y(z,x),y(m,v),x,v];C.rightContX=C.rightContY=null;return g}});""});K(y,"parts/AreaSplineSeries.js",[y["parts/Globals.js"]],function(d){var g=d.seriesTypes.area.prototype,y=d.seriesType;y("areaspline","spline", d.defaultPlotOptions.area,{getStackPoints:g.getStackPoints,getGraphPath:g.getGraphPath,drawGraph:g.drawGraph,drawLegendSymbol:d.LegendSymbolMixin.drawRectangle});""});K(y,"parts/ColumnSeries.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.animObject,F=g.clamp,E=g.defined,D=g.extend,x=g.isNumber,v=g.pick,C=d.color,B=d.merge,p=d.Series;g=d.seriesType;var z=d.svg;g("column","line",{borderRadius:0,crisp:!0,groupPadding:.2,marker:null,pointPadding:.1,minPointLength:0,cropThreshold:50, pointRange:null,states:{hover:{halo:!1,brightness:.1},select:{color:"#cccccc",borderColor:"#000000"}},dataLabels:{align:null,verticalAlign:null,y:null},softThreshold:!1,startFromThreshold:!0,stickyTracking:!1,tooltip:{distance:6},threshold:0,borderColor:"#ffffff"},{cropShoulder:0,directTouch:!0,trackerGroups:["group","dataLabelsGroup"],negStacks:!0,init:function(){p.prototype.init.apply(this,arguments);var d=this,g=d.chart;g.hasRendered&&g.series.forEach(function(g){g.type===d.type&&(g.isDirty=!0)})}, getColumnMetrics:function(){var d=this,g=d.options,w=d.xAxis,h=d.yAxis,f=w.options.reversedStacks;f=w.reversed&&!f||!w.reversed&&f;var c,b={},a=0;!1===g.grouping?a=1:d.chart.series.forEach(function(f){var g=f.yAxis,e=f.options;if(f.type===d.type&&(f.visible||!d.chart.options.chart.ignoreHiddenSeries)&&h.len===g.len&&h.pos===g.pos){if(e.stacking){c=f.stackKey;"undefined"===typeof b[c]&&(b[c]=a++);var k=b[c]}else!1!==e.grouping&&(k=a++);f.columnIndex=k}});var l=Math.min(Math.abs(w.transA)*(w.ordinalSlope|| g.pointRange||w.closestPointRange||w.tickInterval||1),w.len),n=l*g.groupPadding,t=(l-2*n)/(a||1);g=Math.min(g.maxPointWidth||w.len,v(g.pointWidth,t*(1-2*g.pointPadding)));d.columnMetrics={width:g,offset:(t-g)/2+(n+((d.columnIndex||0)+(f?1:0))*t-l/2)*(f?-1:1)};return d.columnMetrics},crispCol:function(d,g,w,h){var f=this.chart,c=this.borderWidth,b=-(c%2?.5:0);c=c%2?.5:1;f.inverted&&f.renderer.isVML&&(c+=1);this.options.crisp&&(w=Math.round(d+w)+b,d=Math.round(d)+b,w-=d);h=Math.round(g+h)+c;b=.5>=Math.abs(g)&& .5<h;g=Math.round(g)+c;h-=g;b&&h&&(--g,h+=1);return{x:d,y:g,width:w,height:h}},translate:function(){var d=this,g=d.chart,w=d.options,h=d.dense=2>d.closestPointRange*d.xAxis.transA;h=d.borderWidth=v(w.borderWidth,h?0:1);var f=d.yAxis,c=w.threshold,b=d.translatedThreshold=f.getThreshold(c),a=v(w.minPointLength,5),l=d.getColumnMetrics(),n=l.width,t=d.barW=Math.max(n,1+2*h),z=d.pointXOffset=l.offset,r=d.dataMin,e=d.dataMax;g.inverted&&(b-=.5);w.pointPadding&&(t=Math.ceil(t));p.prototype.translate.apply(d); d.points.forEach(function(k){var h=v(k.yBottom,b),l=999+Math.abs(h),m=n;l=F(k.plotY,-l,f.len+l);var A=k.plotX+z,q=t,w=Math.min(l,h),p=Math.max(l,h)-w;if(a&&Math.abs(p)<a){p=a;var I=!f.reversed&&!k.negative||f.reversed&&k.negative;k.y===c&&d.dataMax<=c&&f.min<c&&r!==e&&(I=!I);w=Math.abs(w-b)>a?h-a:b-(I?a:0)}E(k.options.pointWidth)&&(m=q=Math.ceil(k.options.pointWidth),A-=Math.round((m-n)/2));k.barX=A;k.pointWidth=m;k.tooltipPos=g.inverted?[f.len+f.pos-g.plotLeft-l,d.xAxis.len-A-q/2,p]:[A+q/2,l+f.pos- g.plotTop,p];k.shapeType=d.pointClass.prototype.shapeType||"rect";k.shapeArgs=d.crispCol.apply(d,k.isNull?[A,b,q,0]:[A,w,q,p])})},getSymbol:d.noop,drawLegendSymbol:d.LegendSymbolMixin.drawRectangle,drawGraph:function(){this.group[this.dense?"addClass":"removeClass"]("highcharts-dense-data")},pointAttribs:function(d,g){var m=this.options,h=this.pointAttrToOptions||{};var f=h.stroke||"borderColor";var c=h["stroke-width"]||"borderWidth",b=d&&d.color||this.color,a=d&&d[f]||m[f]||this.color||b,l=d&&d[c]|| m[c]||this[c]||0;h=d&&d.options.dashStyle||m.dashStyle;var n=v(d&&d.opacity,m.opacity,1);if(d&&this.zones.length){var t=d.getZone();b=d.options.color||t&&(t.color||d.nonZonedColor)||this.color;t&&(a=t.borderColor||a,h=t.dashStyle||h,l=t.borderWidth||l)}g&&d&&(d=B(m.states[g],d.options.states&&d.options.states[g]||{}),g=d.brightness,b=d.color||"undefined"!==typeof g&&C(b).brighten(d.brightness).get()||b,a=d[f]||a,l=d[c]||l,h=d.dashStyle||h,n=v(d.opacity,n));f={fill:b,stroke:a,"stroke-width":l,opacity:n}; h&&(f.dashstyle=h);return f},drawPoints:function(){var d=this,g=this.chart,p=d.options,h=g.renderer,f=p.animationLimit||250,c;d.points.forEach(function(b){var a=b.graphic,l=!!a,n=a&&g.pointCount<f?"animate":"attr";if(x(b.plotY)&&null!==b.y){c=b.shapeArgs;a&&b.hasNewShapeType()&&(a=a.destroy());d.enabledDataSorting&&(b.startXPos=d.xAxis.reversed?-(c?c.width:0):d.xAxis.width);a||(b.graphic=a=h[b.shapeType](c).add(b.group||d.group))&&d.enabledDataSorting&&g.hasRendered&&g.pointCount<f&&(a.attr({x:b.startXPos}), l=!0,n="animate");if(a&&l)a[n](B(c));if(p.borderRadius)a[n]({r:p.borderRadius});g.styledMode||a[n](d.pointAttribs(b,b.selected&&"select")).shadow(!1!==b.allowShadow&&p.shadow,null,p.stacking&&!p.borderRadius);a.addClass(b.getClassName(),!0)}else a&&(b.graphic=a.destroy())})},animate:function(d){var g=this,m=this.yAxis,h=g.options,f=this.chart.inverted,c={},b=f?"translateX":"translateY";if(z)if(d)c.scaleY=.001,d=F(m.toPixels(h.threshold),m.pos,m.pos+m.len),f?c.translateX=d-m.len:c.translateY=d,g.clipBox&& g.setClip(),g.group.attr(c);else{var a=g.group.attr(b);g.group.animate({scaleY:1},D(y(g.options.animation),{step:function(f,d){c[b]=a+d.pos*(m.pos-a);g.group.attr(c)}}));g.animate=null}},remove:function(){var d=this,g=d.chart;g.hasRendered&&g.series.forEach(function(g){g.type===d.type&&(g.isDirty=!0)});p.prototype.remove.apply(d,arguments)}});""});K(y,"parts/BarSeries.js",[y["parts/Globals.js"]],function(d){d=d.seriesType;d("bar","column",null,{inverted:!0});""});K(y,"parts/ScatterSeries.js",[y["parts/Globals.js"]], function(d){var g=d.Series,y=d.seriesType;y("scatter","line",{lineWidth:0,findNearestPointBy:"xy",jitter:{x:0,y:0},marker:{enabled:!0},tooltip:{headerFormat:'<span style="color:{point.color}">\u25cf</span> <span style="font-size: 10px"> {series.name}</span><br/>',pointFormat:"x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>"}},{sorted:!1,requireSorting:!1,noSharedTooltip:!0,trackerGroups:["group","markerGroup","dataLabelsGroup"],takeOrdinalPosition:!1,drawGraph:function(){this.options.lineWidth&& g.prototype.drawGraph.call(this)},applyJitter:function(){var d=this,g=this.options.jitter,y=this.points.length;g&&this.points.forEach(function(x,v){["x","y"].forEach(function(C,B){var p="plot"+C.toUpperCase();if(g[C]&&!x.isNull){var z=d[C+"Axis"];var m=g[C]*z.transA;if(z&&!z.isLog){var q=Math.max(0,x[p]-m);z=Math.min(z.len,x[p]+m);B=1E4*Math.sin(v+B*y);x[p]=q+(z-q)*(B-Math.floor(B));"x"===C&&(x.clientX=x.plotX)}}})})}});d.addEvent(g,"afterTranslate",function(){this.applyJitter&&this.applyJitter()}); ""});K(y,"mixins/centered-series.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.isNumber,F=g.pick,E=g.relativeLength,D=d.deg2rad;d.CenteredSeriesMixin={getCenter:function(){var d=this.options,g=this.chart,C=2*(d.slicedOffset||0),B=g.plotWidth-2*C;g=g.plotHeight-2*C;var p=d.center;p=[F(p[0],"50%"),F(p[1],"50%"),d.size||"100%",d.innerSize||0];var z=Math.min(B,g),m;for(m=0;4>m;++m){var q=p[m];d=2>m||2===m&&/%$/.test(q);p[m]=E(q,[B,g,z,p[2]][m])+(d?C:0)}p[3]>p[2]&&(p[3]=p[2]); return p},getStartAndEndRadians:function(d,g){d=y(d)?d:0;g=y(g)&&g>d&&360>g-d?g:d+360;return{start:D*(d+-90),end:D*(g+-90)}}}});K(y,"parts/PieSeries.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.clamp,F=g.defined,E=g.isNumber,D=g.pick,x=g.relativeLength,v=g.setAnimation,C=d.addEvent;g=d.CenteredSeriesMixin;var B=g.getStartAndEndRadians,p=d.merge,z=d.noop,m=d.Point,q=d.Series,w=d.seriesType,h=d.fireEvent;w("pie","line",{center:[null,null],clip:!1,colorByPoint:!0,dataLabels:{allowOverlap:!0, connectorPadding:5,connectorShape:"fixedOffset",crookDistance:"70%",distance:30,enabled:!0,formatter:function(){return this.point.isNull?void 0:this.point.name},softConnector:!0,x:0},fillColor:void 0,ignoreHiddenPoint:!0,inactiveOtherPoints:!0,legendType:"point",marker:null,size:null,showInLegend:!1,slicedOffset:10,stickyTracking:!1,tooltip:{followPointer:!0},borderColor:"#ffffff",borderWidth:1,lineWidth:void 0,states:{hover:{brightness:.1}}},{isCartesian:!1,requireSorting:!1,directTouch:!0,noSharedTooltip:!0, trackerGroups:["group","dataLabelsGroup"],axisTypes:[],pointAttribs:d.seriesTypes.column.prototype.pointAttribs,animate:function(f){var c=this,b=c.points,a=c.startAngleRad;f||(b.forEach(function(b){var f=b.graphic,d=b.shapeArgs;f&&d&&(f.attr({r:D(b.startR,c.center&&c.center[3]/2),start:a,end:a}),f.animate({r:d.r,start:d.start,end:d.end},c.options.animation))}),c.animate=null)},hasData:function(){return!!this.processedXData.length},updateTotals:function(){var f,c=0,b=this.points,a=b.length,d=this.options.ignoreHiddenPoint; for(f=0;f<a;f++){var g=b[f];c+=d&&!g.visible?0:g.isNull?0:g.y}this.total=c;for(f=0;f<a;f++)g=b[f],g.percentage=0<c&&(g.visible||!d)?g.y/c*100:0,g.total=c},generatePoints:function(){q.prototype.generatePoints.call(this);this.updateTotals()},getX:function(f,c,b){var a=this.center,d=this.radii?this.radii[b.index]:a[2]/2;f=Math.asin(y((f-a[1])/(d+b.labelDistance),-1,1));return a[0]+(c?-1:1)*Math.cos(f)*(d+b.labelDistance)+(0<b.labelDistance?(c?-1:1)*this.options.dataLabels.padding:0)},translate:function(f){this.generatePoints(); var c=0,b=this.options,a=b.slicedOffset,d=a+(b.borderWidth||0),g=B(b.startAngle,b.endAngle),t=this.startAngleRad=g.start;g=(this.endAngleRad=g.end)-t;var m=this.points,r=b.dataLabels.distance;b=b.ignoreHiddenPoint;var e,k=m.length;f||(this.center=f=this.getCenter());for(e=0;e<k;e++){var u=m[e];var q=t+c*g;if(!b||u.visible)c+=u.percentage/100;var p=t+c*g;u.shapeType="arc";u.shapeArgs={x:f[0],y:f[1],r:f[2]/2,innerR:f[3]/2,start:Math.round(1E3*q)/1E3,end:Math.round(1E3*p)/1E3};u.labelDistance=D(u.options.dataLabels&& u.options.dataLabels.distance,r);u.labelDistance=x(u.labelDistance,u.shapeArgs.r);this.maxLabelDistance=Math.max(this.maxLabelDistance||0,u.labelDistance);p=(p+q)/2;p>1.5*Math.PI?p-=2*Math.PI:p<-Math.PI/2&&(p+=2*Math.PI);u.slicedTranslation={translateX:Math.round(Math.cos(p)*a),translateY:Math.round(Math.sin(p)*a)};var A=Math.cos(p)*f[2]/2;var w=Math.sin(p)*f[2]/2;u.tooltipPos=[f[0]+.7*A,f[1]+.7*w];u.half=p<-Math.PI/2||p>Math.PI/2?1:0;u.angle=p;q=Math.min(d,u.labelDistance/5);u.labelPosition={natural:{x:f[0]+ A+Math.cos(p)*u.labelDistance,y:f[1]+w+Math.sin(p)*u.labelDistance},"final":{},alignment:0>u.labelDistance?"center":u.half?"right":"left",connectorPosition:{breakAt:{x:f[0]+A+Math.cos(p)*q,y:f[1]+w+Math.sin(p)*q},touchingSliceAt:{x:f[0]+A,y:f[1]+w}}}}h(this,"afterTranslate")},drawEmpty:function(){var f=this.options;if(0===this.total){var c=this.center[0];var b=this.center[1];this.graph||(this.graph=this.chart.renderer.circle(c,b,0).addClass("highcharts-graph").add(this.group));this.graph.animate({"stroke-width":f.borderWidth, cx:c,cy:b,r:this.center[2]/2,fill:f.fillColor||"none",stroke:f.color||"#cccccc"})}else this.graph&&(this.graph=this.graph.destroy())},redrawPoints:function(){var f=this,c=f.chart,b=c.renderer,a,d,g,h,m=f.options.shadow;this.drawEmpty();!m||f.shadowGroup||c.styledMode||(f.shadowGroup=b.g("shadow").attr({zIndex:-1}).add(f.group));f.points.forEach(function(l){var e={};d=l.graphic;if(!l.isNull&&d){h=l.shapeArgs;a=l.getTranslate();if(!c.styledMode){var k=l.shadowGroup;m&&!k&&(k=l.shadowGroup=b.g("shadow").add(f.shadowGroup)); k&&k.attr(a);g=f.pointAttribs(l,l.selected&&"select")}l.delayedRendering?(d.setRadialReference(f.center).attr(h).attr(a),c.styledMode||d.attr(g).attr({"stroke-linejoin":"round"}).shadow(m,k),l.delayedRendering=!1):(d.setRadialReference(f.center),c.styledMode||p(!0,e,g),p(!0,e,h,a),d.animate(e));d.attr({visibility:l.visible?"inherit":"hidden"});d.addClass(l.getClassName())}else d&&(l.graphic=d.destroy())})},drawPoints:function(){var f=this.chart.renderer;this.points.forEach(function(c){c.graphic|| (c.graphic=f[c.shapeType](c.shapeArgs).add(c.series.group),c.delayedRendering=!0)})},searchPoint:z,sortByAngle:function(f,c){f.sort(function(b,a){return"undefined"!==typeof b.angle&&(a.angle-b.angle)*c})},drawLegendSymbol:d.LegendSymbolMixin.drawRectangle,getCenter:g.getCenter,getSymbol:z,drawGraph:null},{init:function(){m.prototype.init.apply(this,arguments);var f=this;f.name=D(f.name,"Slice");var c=function(b){f.slice("select"===b.type)};C(f,"select",c);C(f,"unselect",c);return f},isValid:function(){return E(this.y)&& 0<=this.y},setVisible:function(f,c){var b=this,a=b.series,d=a.chart,g=a.options.ignoreHiddenPoint;c=D(c,g);f!==b.visible&&(b.visible=b.options.visible=f="undefined"===typeof f?!b.visible:f,a.options.data[a.data.indexOf(b)]=b.options,["graphic","dataLabel","connector","shadowGroup"].forEach(function(a){if(b[a])b[a][f?"show":"hide"](!0)}),b.legendItem&&d.legend.colorizeItem(b,f),f||"hover"!==b.state||b.setState(""),g&&(a.isDirty=!0),c&&d.redraw())},slice:function(f,c,b){var a=this.series;v(b,a.chart); D(c,!0);this.sliced=this.options.sliced=F(f)?f:!this.sliced;a.options.data[a.data.indexOf(this)]=this.options;this.graphic.animate(this.getTranslate());this.shadowGroup&&this.shadowGroup.animate(this.getTranslate())},getTranslate:function(){return this.sliced?this.slicedTranslation:{translateX:0,translateY:0}},haloPath:function(f){var c=this.shapeArgs;return this.sliced||!this.visible?[]:this.series.chart.renderer.symbols.arc(c.x,c.y,c.r+f,c.r+f,{innerR:c.r-1,start:c.start,end:c.end})},connectorShapes:{fixedOffset:function(f, c,b){var a=c.breakAt;c=c.touchingSliceAt;return["M",f.x,f.y].concat(b.softConnector?["C",f.x+("left"===f.alignment?-5:5),f.y,2*a.x-c.x,2*a.y-c.y,a.x,a.y]:["L",a.x,a.y]).concat(["L",c.x,c.y])},straight:function(f,c){c=c.touchingSliceAt;return["M",f.x,f.y,"L",c.x,c.y]},crookedLine:function(f,c,b){c=c.touchingSliceAt;var a=this.series,d=a.center[0],g=a.chart.plotWidth,h=a.chart.plotLeft;a=f.alignment;var m=this.shapeArgs.r;b=x(b.crookDistance,1);b="left"===a?d+m+(g+h-d-m)*(1-b):h+(d-m)*b;d=["L",b,f.y]; if("left"===a?b>f.x||b<c.x:b<f.x||b>c.x)d=[];return["M",f.x,f.y].concat(d).concat(["L",c.x,c.y])}},getConnectorPath:function(){var f=this.labelPosition,c=this.series.options.dataLabels,b=c.connectorShape,a=this.connectorShapes;a[b]&&(b=a[b]);return b.call(this,{x:f.final.x,y:f.final.y,alignment:f.alignment},f.connectorPosition,c)}});""});K(y,"parts/DataLabels.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.animObject,F=g.arrayMax,E=g.clamp,D=g.defined,x=g.extend,v=g.isArray, C=g.objectEach,B=g.pick,p=g.relativeLength,z=g.splat,m=d.format,q=d.merge;g=d.noop;var w=d.Series,h=d.seriesTypes,f=d.stableSort;d.distribute=function(c,b,a){function g(a,e){return a.target-e.target}var h,t=!0,m=c,r=[];var e=0;var k=m.reducedLen||b;for(h=c.length;h--;)e+=c[h].size;if(e>k){f(c,function(a,e){return(e.rank||0)-(a.rank||0)});for(e=h=0;e<=k;)e+=c[h].size,h++;r=c.splice(h-1,c.length)}f(c,g);for(c=c.map(function(a){return{size:a.size,targets:[a.target],align:B(a.align,.5)}});t;){for(h=c.length;h--;)t= c[h],e=(Math.min.apply(0,t.targets)+Math.max.apply(0,t.targets))/2,t.pos=E(e-t.size*t.align,0,b-t.size);h=c.length;for(t=!1;h--;)0<h&&c[h-1].pos+c[h-1].size>c[h].pos&&(c[h-1].size+=c[h].size,c[h-1].targets=c[h-1].targets.concat(c[h].targets),c[h-1].align=.5,c[h-1].pos+c[h-1].size>b&&(c[h-1].pos=b-c[h-1].size),c.splice(h,1),t=!0)}m.push.apply(m,r);h=0;c.some(function(e){var c=0;if(e.targets.some(function(){m[h].pos=e.pos+c;if(Math.abs(m[h].pos-m[h].target)>a)return m.slice(0,h+1).forEach(function(a){delete a.pos}), m.reducedLen=(m.reducedLen||b)-.1*b,m.reducedLen>.1*b&&d.distribute(m,b,a),!0;c+=m[h].size;h++}))return!0});f(m,g)};w.prototype.drawDataLabels=function(){function c(a,e){var b=e.filter;return b?(e=b.operator,a=a[b.property],b=b.value,">"===e&&a>b||"<"===e&&a<b||">="===e&&a>=b||"<="===e&&a<=b||"=="===e&&a==b||"==="===e&&a===b?!0:!1):!0}function b(a,e){var b=[],c;if(v(a)&&!v(e))b=a.map(function(a){return q(a,e)});else if(v(e)&&!v(a))b=e.map(function(e){return q(a,e)});else if(v(a)||v(e))for(c=Math.max(a.length, e.length);c--;)b[c]=q(a[c],e[c]);else b=q(a,e);return b}var a=this,f=a.chart,g=a.options,h=g.dataLabels,p=a.points,r,e=a.hasRendered||0,k=y(g.animation).duration,u=Math.min(k,200),H=!f.renderer.forExport&&B(h.defer,0<u),w=f.renderer;h=b(b(f.options.plotOptions&&f.options.plotOptions.series&&f.options.plotOptions.series.dataLabels,f.options.plotOptions&&f.options.plotOptions[a.type]&&f.options.plotOptions[a.type].dataLabels),h);d.fireEvent(this,"drawDataLabels");if(v(h)||h.enabled||a._hasPointLabels){var A= a.plotGroup("dataLabelsGroup","data-labels",H&&!e?"hidden":"inherit",h.zIndex||6);H&&(A.attr({opacity:+e}),e||setTimeout(function(){var e=a.dataLabelsGroup;e&&(a.visible&&A.show(!0),e[g.animation?"animate":"attr"]({opacity:1},{duration:u}))},k-u));p.forEach(function(e){r=z(b(h,e.dlOptions||e.options&&e.options.dataLabels));r.forEach(function(b,d){var k=b.enabled&&(!e.isNull||e.dataLabelOnNull)&&c(e,b),h=e.dataLabels?e.dataLabels[d]:e.dataLabel,l=e.connectors?e.connectors[d]:e.connector,u=B(b.distance, e.labelDistance),t=!h;if(k){var r=e.getLabelConfig();var n=B(b[e.formatPrefix+"Format"],b.format);r=D(n)?m(n,r,f):(b[e.formatPrefix+"Formatter"]||b.formatter).call(r,b);n=b.style;var q=b.rotation;f.styledMode||(n.color=B(b.color,n.color,a.color,"#000000"),"contrast"===n.color?(e.contrastColor=w.getContrast(e.color||a.color),n.color=!D(u)&&b.inside||0>u||g.stacking?e.contrastColor:"#000000"):delete e.contrastColor,g.cursor&&(n.cursor=g.cursor));var p={r:b.borderRadius||0,rotation:q,padding:b.padding, zIndex:1};f.styledMode||(p.fill=b.backgroundColor,p.stroke=b.borderColor,p["stroke-width"]=b.borderWidth);C(p,function(a,e){"undefined"===typeof a&&delete p[e]})}!h||k&&D(r)?k&&D(r)&&(h?p.text=r:(e.dataLabels=e.dataLabels||[],h=e.dataLabels[d]=q?w.text(r,0,-9999).addClass("highcharts-data-label"):w.label(r,0,-9999,b.shape,null,null,b.useHTML,null,"data-label"),d||(e.dataLabel=h),h.addClass(" highcharts-data-label-color-"+e.colorIndex+" "+(b.className||"")+(b.useHTML?" highcharts-tracker":""))),h.options= b,h.attr(p),f.styledMode||h.css(n).shadow(b.shadow),h.added||h.add(A),b.textPath&&!b.useHTML&&(h.setTextPath(e.getDataLabelPath&&e.getDataLabelPath(h)||e.graphic,b.textPath),e.dataLabelPath&&!b.textPath.enabled&&(e.dataLabelPath=e.dataLabelPath.destroy())),a.alignDataLabel(e,h,b,null,t)):(e.dataLabel=e.dataLabel&&e.dataLabel.destroy(),e.dataLabels&&(1===e.dataLabels.length?delete e.dataLabels:delete e.dataLabels[d]),d||delete e.dataLabel,l&&(e.connector=e.connector.destroy(),e.connectors&&(1===e.connectors.length? delete e.connectors:delete e.connectors[d])))})})}d.fireEvent(this,"afterDrawDataLabels")};w.prototype.alignDataLabel=function(c,b,a,f,d){var g=this,h=this.chart,l=this.isCartesian&&h.inverted,e=this.enabledDataSorting,k=B(c.dlBox&&c.dlBox.centerX,c.plotX,-9999),u=B(c.plotY,-9999),n=b.getBBox(),m=a.rotation,A=a.align,q=h.isInsidePlot(k,Math.round(u),l),p="justify"===B(a.overflow,e?"none":"justify"),w=this.visible&&(c.series.forceDL||e&&!p||q||f&&h.isInsidePlot(k,l?f.x+1:f.y+f.height-1,l));var v=function(a){e&& g.xAxis&&!p&&g.setDataLabelStartPos(c,b,d,q,a)};if(w){var z=h.renderer.fontMetrics(h.styledMode?void 0:a.style.fontSize,b).b;f=x({x:l?this.yAxis.len-u:k,y:Math.round(l?this.xAxis.len-k:u),width:0,height:0},f);x(a,{width:n.width,height:n.height});m?(p=!1,k=h.renderer.rotCorr(z,m),k={x:f.x+a.x+f.width/2+k.x,y:f.y+a.y+{top:0,middle:.5,bottom:1}[a.verticalAlign]*f.height},v(k),b[d?"attr":"animate"](k).attr({align:A}),v=(m+720)%360,v=180<v&&360>v,"left"===A?k.y-=v?n.height:0:"center"===A?(k.x-=n.width/ 2,k.y-=n.height/2):"right"===A&&(k.x-=n.width,k.y-=v?0:n.height),b.placed=!0,b.alignAttr=k):(v(f),b.align(a,null,f),k=b.alignAttr);p&&0<=f.height?this.justifyDataLabel(b,a,k,n,f,d):B(a.crop,!0)&&(w=h.isInsidePlot(k.x,k.y)&&h.isInsidePlot(k.x+n.width,k.y+n.height));if(a.shape&&!m)b[d?"attr":"animate"]({anchorX:l?h.plotWidth-c.plotY:c.plotX,anchorY:l?h.plotHeight-c.plotX:c.plotY})}d&&e&&(b.placed=!1);w||e&&!p||(b.hide(!0),b.placed=!1)};w.prototype.setDataLabelStartPos=function(c,b,a,f,d){var g=this.chart, h=g.inverted,l=this.xAxis,e=l.reversed,k=h?b.height/2:b.width/2;c=(c=c.pointWidth)?c/2:0;l=h?d.x:e?-k-c:l.width-k+c;d=h?e?this.yAxis.height-k+c:-k-c:d.y;b.startXPos=l;b.startYPos=d;f?"hidden"===b.visibility&&(b.show(),b.attr({opacity:0}).animate({opacity:1})):b.attr({opacity:1}).animate({opacity:0},void 0,b.hide);g.hasRendered&&(a&&b.attr({x:b.startXPos,y:b.startYPos}),b.placed=!0)};w.prototype.justifyDataLabel=function(c,b,a,f,d,g){var h=this.chart,l=b.align,e=b.verticalAlign,k=c.box?0:c.padding|| 0;var u=a.x+k;if(0>u){"right"===l?(b.align="left",b.inside=!0):b.x=-u;var t=!0}u=a.x+f.width-k;u>h.plotWidth&&("left"===l?(b.align="right",b.inside=!0):b.x=h.plotWidth-u,t=!0);u=a.y+k;0>u&&("bottom"===e?(b.verticalAlign="top",b.inside=!0):b.y=-u,t=!0);u=a.y+f.height-k;u>h.plotHeight&&("top"===e?(b.verticalAlign="bottom",b.inside=!0):b.y=h.plotHeight-u,t=!0);t&&(c.placed=!g,c.align(b,null,d));return t};h.pie&&(h.pie.prototype.dataLabelPositioners={radialDistributionY:function(c){return c.top+c.distributeBox.pos}, radialDistributionX:function(c,b,a,f){return c.getX(a<b.top+2||a>b.bottom-2?f:a,b.half,b)},justify:function(c,b,a){return a[0]+(c.half?-1:1)*(b+c.labelDistance)},alignToPlotEdges:function(c,b,a,f){c=c.getBBox().width;return b?c+f:a-c-f},alignToConnectors:function(c,b,a,f){var d=0,g;c.forEach(function(a){g=a.dataLabel.getBBox().width;g>d&&(d=g)});return b?d+f:a-d-f}},h.pie.prototype.drawDataLabels=function(){var c=this,b=c.data,a,f=c.chart,g=c.options.dataLabels,h=g.connectorPadding,m,r=f.plotWidth, e=f.plotHeight,k=f.plotLeft,u=Math.round(f.chartWidth/3),p,v=c.center,A=v[2]/2,z=v[1],x,C,y,E,P=[[],[]],O,N,M,K,T=[0,0,0,0],Z=c.dataLabelPositioners,da;c.visible&&(g.enabled||c._hasPointLabels)&&(b.forEach(function(a){a.dataLabel&&a.visible&&a.dataLabel.shortened&&(a.dataLabel.attr({width:"auto"}).css({width:"auto",textOverflow:"clip"}),a.dataLabel.shortened=!1)}),w.prototype.drawDataLabels.apply(c),b.forEach(function(a){a.dataLabel&&(a.visible?(P[a.half].push(a),a.dataLabel._pos=null,!D(g.style.width)&& !D(a.options.dataLabels&&a.options.dataLabels.style&&a.options.dataLabels.style.width)&&a.dataLabel.getBBox().width>u&&(a.dataLabel.css({width:.7*u}),a.dataLabel.shortened=!0)):(a.dataLabel=a.dataLabel.destroy(),a.dataLabels&&1===a.dataLabels.length&&delete a.dataLabels))}),P.forEach(function(b,l){var u=b.length,t=[],n;if(u){c.sortByAngle(b,l-.5);if(0<c.maxLabelDistance){var m=Math.max(0,z-A-c.maxLabelDistance);var q=Math.min(z+A+c.maxLabelDistance,f.plotHeight);b.forEach(function(a){0<a.labelDistance&& a.dataLabel&&(a.top=Math.max(0,z-A-a.labelDistance),a.bottom=Math.min(z+A+a.labelDistance,f.plotHeight),n=a.dataLabel.getBBox().height||21,a.distributeBox={target:a.labelPosition.natural.y-a.top+n/2,size:n,rank:a.y},t.push(a.distributeBox))});m=q+n-m;d.distribute(t,m,m/5)}for(K=0;K<u;K++){a=b[K];y=a.labelPosition;x=a.dataLabel;M=!1===a.visible?"hidden":"inherit";N=m=y.natural.y;t&&D(a.distributeBox)&&("undefined"===typeof a.distributeBox.pos?M="hidden":(E=a.distributeBox.size,N=Z.radialDistributionY(a))); delete a.positionIndex;if(g.justify)O=Z.justify(a,A,v);else switch(g.alignTo){case "connectors":O=Z.alignToConnectors(b,l,r,k);break;case "plotEdges":O=Z.alignToPlotEdges(x,l,r,k);break;default:O=Z.radialDistributionX(c,a,N,m)}x._attr={visibility:M,align:y.alignment};x._pos={x:O+g.x+({left:h,right:-h}[y.alignment]||0),y:N+g.y-10};y.final.x=O;y.final.y=N;B(g.crop,!0)&&(C=x.getBBox().width,m=null,O-C<h&&1===l?(m=Math.round(C-O+h),T[3]=Math.max(m,T[3])):O+C>r-h&&0===l&&(m=Math.round(O+C-r+h),T[1]=Math.max(m, T[1])),0>N-E/2?T[0]=Math.max(Math.round(-N+E/2),T[0]):N+E/2>e&&(T[2]=Math.max(Math.round(N+E/2-e),T[2])),x.sideOverflow=m)}}}),0===F(T)||this.verifyDataLabelOverflow(T))&&(this.placeDataLabels(),this.points.forEach(function(a){da=q(g,a.options.dataLabels);if(m=B(da.connectorWidth,1)){var e;p=a.connector;if((x=a.dataLabel)&&x._pos&&a.visible&&0<a.labelDistance){M=x._attr.visibility;if(e=!p)a.connector=p=f.renderer.path().addClass("highcharts-data-label-connector highcharts-color-"+a.colorIndex+(a.className? " "+a.className:"")).add(c.dataLabelsGroup),f.styledMode||p.attr({"stroke-width":m,stroke:da.connectorColor||a.color||"#666666"});p[e?"attr":"animate"]({d:a.getConnectorPath()});p.attr("visibility",M)}else p&&(a.connector=p.destroy())}}))},h.pie.prototype.placeDataLabels=function(){this.points.forEach(function(c){var b=c.dataLabel,a;b&&c.visible&&((a=b._pos)?(b.sideOverflow&&(b._attr.width=Math.max(b.getBBox().width-b.sideOverflow,0),b.css({width:b._attr.width+"px",textOverflow:(this.options.dataLabels.style|| {}).textOverflow||"ellipsis"}),b.shortened=!0),b.attr(b._attr),b[b.moved?"animate":"attr"](a),b.moved=!0):b&&b.attr({y:-9999}));delete c.distributeBox},this)},h.pie.prototype.alignDataLabel=g,h.pie.prototype.verifyDataLabelOverflow=function(c){var b=this.center,a=this.options,f=a.center,d=a.minSize||80,g=null!==a.size;if(!g){if(null!==f[0])var h=Math.max(b[2]-Math.max(c[1],c[3]),d);else h=Math.max(b[2]-c[1]-c[3],d),b[0]+=(c[3]-c[1])/2;null!==f[1]?h=E(h,d,b[2]-Math.max(c[0],c[2])):(h=E(h,d,b[2]-c[0]- c[2]),b[1]+=(c[0]-c[2])/2);h<b[2]?(b[2]=h,b[3]=Math.min(p(a.innerSize||0,h),h),this.translate(b),this.drawDataLabels&&this.drawDataLabels()):g=!0}return g});h.column&&(h.column.prototype.alignDataLabel=function(c,b,a,f,d){var g=this.chart.inverted,h=c.series,l=c.dlBox||c.shapeArgs,e=B(c.below,c.plotY>B(this.translatedThreshold,h.yAxis.len)),k=B(a.inside,!!this.options.stacking);l&&(f=q(l),0>f.y&&(f.height+=f.y,f.y=0),l=f.y+f.height-h.yAxis.len,0<l&&(f.height-=l),g&&(f={x:h.yAxis.len-f.y-f.height, y:h.xAxis.len-f.x-f.width,width:f.height,height:f.width}),k||(g?(f.x+=e?0:f.width,f.width=0):(f.y+=e?f.height:0,f.height=0)));a.align=B(a.align,!g||k?"center":e?"right":"left");a.verticalAlign=B(a.verticalAlign,g||k?"middle":e?"top":"bottom");w.prototype.alignDataLabel.call(this,c,b,a,f,d);f&&(0>=f.height&&f.y===this.chart.plotHeight||0>=f.width&&0===f.x)&&(b.hide(!0),b.placed=!1);a.inside&&c.contrastColor&&b.css({color:c.contrastColor})})});K(y,"modules/overlapping-datalabels.src.js",[y["parts/Globals.js"], y["parts/Utilities.js"]],function(d,g){var y=g.isArray,F=g.objectEach,E=g.pick;g=d.Chart;var D=d.addEvent,x=d.fireEvent;D(g,"render",function(){var d=[];(this.labelCollectors||[]).forEach(function(g){d=d.concat(g())});(this.yAxis||[]).forEach(function(g){g.options.stackLabels&&!g.options.stackLabels.allowOverlap&&F(g.stacks,function(g){F(g,function(g){d.push(g.label)})})});(this.series||[]).forEach(function(g){var v=g.options.dataLabels;g.visible&&(!1!==v.enabled||g._hasPointLabels)&&g.points.forEach(function(g){g.visible&& (y(g.dataLabels)?g.dataLabels:g.dataLabel?[g.dataLabel]:[]).forEach(function(p){var m=p.options;p.labelrank=E(m.labelrank,g.labelrank,g.shapeArgs&&g.shapeArgs.height);m.allowOverlap||d.push(p)})})});this.hideOverlappingLabels(d)});g.prototype.hideOverlappingLabels=function(d){var g=this,v=d.length,p=g.renderer,z,m,q,w=!1;var h=function(b){var a=b.box?0:b.padding||0;var c=0;if(b&&(!b.alignAttr||b.placed)){var f=b.alignAttr||{x:b.attr("x"),y:b.attr("y")};var d=b.parentGroup;b.width||(c=b.getBBox(), b.width=c.width,b.height=c.height,c=p.fontMetrics(null,b.element).h);return{x:f.x+(d.translateX||0)+a,y:f.y+(d.translateY||0)+a-c,width:b.width-2*a,height:b.height-2*a}}};for(m=0;m<v;m++)if(z=d[m])z.oldOpacity=z.opacity,z.newOpacity=1,z.absoluteBox=h(z);d.sort(function(b,a){return(a.labelrank||0)-(b.labelrank||0)});for(m=0;m<v;m++){var f=(h=d[m])&&h.absoluteBox;for(z=m+1;z<v;++z){var c=(q=d[z])&&q.absoluteBox;!f||!c||h===q||0===h.newOpacity||0===q.newOpacity||c.x>f.x+f.width||c.x+c.width<f.x||c.y> f.y+f.height||c.y+c.height<f.y||((h.labelrank<q.labelrank?h:q).newOpacity=0)}}d.forEach(function(b){var a;if(b){var c=b.newOpacity;b.oldOpacity!==c&&(b.alignAttr&&b.placed?(c?b.show(!0):a=function(){b.hide(!0);b.placed=!1},w=!0,b.alignAttr.opacity=c,b[b.isOld?"animate":"attr"](b.alignAttr,null,a),x(g,"afterHideOverlappingLabel")):b.attr({opacity:c}));b.isOld=!0}});w&&x(g,"afterHideAllOverlappingLabels")}});K(y,"parts/Interaction.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y= g.defined,F=g.extend,E=g.isArray,D=g.isObject,x=g.objectEach,v=g.pick,C=d.addEvent;g=d.Chart;var B=d.createElement,p=d.css,z=d.defaultOptions,m=d.defaultPlotOptions,q=d.fireEvent,w=d.hasTouch,h=d.Legend,f=d.merge,c=d.Point,b=d.Series,a=d.seriesTypes,l=d.svg;var n=d.TrackerMixin={drawTrackerPoint:function(){var a=this,b=a.chart,c=b.pointer,e=function(a){var e=c.getPointFromEvent(a);"undefined"!==typeof e&&(c.isDirectTouch=!0,e.onMouseOver(a))},f;a.points.forEach(function(a){f=E(a.dataLabels)?a.dataLabels: a.dataLabel?[a.dataLabel]:[];a.graphic&&(a.graphic.element.point=a);f.forEach(function(e){e.div?e.div.point=a:e.element.point=a})});a._hasTracking||(a.trackerGroups.forEach(function(f){if(a[f]){a[f].addClass("highcharts-tracker").on("mouseover",e).on("mouseout",function(a){c.onTrackerMouseOut(a)});if(w)a[f].on("touchstart",e);!b.styledMode&&a.options.cursor&&a[f].css(p).css({cursor:a.options.cursor})}}),a._hasTracking=!0);q(this,"afterDrawTracker")},drawTrackerGraph:function(){var a=this,b=a.options, c=b.trackByArea,e=[].concat(c?a.areaPath:a.graphPath),f=e.length,d=a.chart,g=d.pointer,h=d.renderer,m=d.options.tooltip.snap,n=a.tracker,p,v=function(){if(d.hoverSeries!==a)a.onMouseOver()},z="rgba(192,192,192,"+(l?.0001:.002)+")";if(f&&!c)for(p=f+1;p--;)"M"===e[p]&&e.splice(p+1,0,e[p+1]-m,e[p+2],"L"),(p&&"M"===e[p]||p===f)&&e.splice(p,0,"L",e[p-2]+m,e[p-1]);n?n.attr({d:e}):a.graph&&(a.tracker=h.path(e).attr({visibility:a.visible?"visible":"hidden",zIndex:2}).addClass(c?"highcharts-tracker-area": "highcharts-tracker-line").add(a.group),d.styledMode||a.tracker.attr({"stroke-linejoin":"round",stroke:z,fill:c?z:"none","stroke-width":a.graph.strokeWidth()+(c?0:2*m)}),[a.tracker,a.markerGroup].forEach(function(a){a.addClass("highcharts-tracker").on("mouseover",v).on("mouseout",function(a){g.onTrackerMouseOut(a)});b.cursor&&!d.styledMode&&a.css({cursor:b.cursor});if(w)a.on("touchstart",v)}));q(this,"afterDrawTracker")}};a.column&&(a.column.prototype.drawTracker=n.drawTrackerPoint);a.pie&&(a.pie.prototype.drawTracker= n.drawTrackerPoint);a.scatter&&(a.scatter.prototype.drawTracker=n.drawTrackerPoint);F(h.prototype,{setItemEvents:function(a,b,d){var e=this,k=e.chart.renderer.boxWrapper,g=a instanceof c,h="highcharts-legend-"+(g?"point":"series")+"-active",l=e.chart.styledMode;(d?b:a.legendGroup).on("mouseover",function(){a.visible&&e.allItems.forEach(function(e){a!==e&&e.setState("inactive",!g)});a.setState("hover");a.visible&&k.addClass(h);l||b.css(e.options.itemHoverStyle)}).on("mouseout",function(){e.chart.styledMode|| b.css(f(a.visible?e.itemStyle:e.itemHiddenStyle));e.allItems.forEach(function(e){a!==e&&e.setState("",!g)});k.removeClass(h);a.setState()}).on("click",function(b){var c=function(){a.setVisible&&a.setVisible();e.allItems.forEach(function(e){a!==e&&e.setState(a.visible?"inactive":"",!g)})};k.removeClass(h);b={browserEvent:b};a.firePointEvent?a.firePointEvent("legendItemClick",b,c):q(a,"legendItemClick",b,c)})},createCheckboxForItem:function(a){a.checkbox=B("input",{type:"checkbox",className:"highcharts-legend-checkbox", checked:a.selected,defaultChecked:a.selected},this.options.itemCheckboxStyle,this.chart.container);C(a.checkbox,"click",function(b){q(a.series||a,"checkboxClick",{checked:b.target.checked,item:a},function(){a.select()})})}});F(g.prototype,{showResetZoom:function(){function a(){b.zoomOut()}var b=this,c=z.lang,e=b.options.chart.resetZoomButton,f=e.theme,d=f.states,g="chart"===e.relativeTo||"spaceBox"===e.relativeTo?null:"plotBox";q(this,"beforeShowResetZoom",null,function(){b.resetZoomButton=b.renderer.button(c.resetZoom, null,null,a,f,d&&d.hover).attr({align:e.position.align,title:c.resetZoomTitle}).addClass("highcharts-reset-zoom").add().align(e.position,!1,g)});q(this,"afterShowResetZoom")},zoomOut:function(){q(this,"selection",{resetSelection:!0},this.zoom)},zoom:function(a){var b=this,c,e=b.pointer,f=!1,d=b.inverted?e.mouseDownX:e.mouseDownY;!a||a.resetSelection?(b.axes.forEach(function(a){c=a.zoom()}),e.initiated=!1):a.xAxis.concat(a.yAxis).forEach(function(a){var k=a.axis,g=b.inverted?k.left:k.top,h=b.inverted? g+k.width:g+k.height,l=k.isXAxis,u=!1;if(!l&&d>=g&&d<=h||l||!y(d))u=!0;e[l?"zoomX":"zoomY"]&&u&&(c=k.zoom(a.min,a.max),k.displayBtn&&(f=!0))});var g=b.resetZoomButton;f&&!g?b.showResetZoom():!f&&D(g)&&(b.resetZoomButton=g.destroy());c&&b.redraw(v(b.options.chart.animation,a&&a.animation,100>b.pointCount))},pan:function(a,b){var c=this,e=c.hoverPoints,f=c.options.chart,d;b="object"===typeof b?b:{enabled:b,type:"x"};f&&f.panning&&(f.panning=b);var g=b.type;q(this,"pan",{originalEvent:a},function(){e&& e.forEach(function(a){a.setState()});var b=[1];"xy"===g?b=[1,0]:"y"===g&&(b=[0]);b.forEach(function(e){var b=c[e?"xAxis":"yAxis"][0],f=b.options,g=b.horiz,k=a[g?"chartX":"chartY"];g=g?"mouseDownX":"mouseDownY";var h=c[g],l=(b.pointRange||0)/2,u=b.reversed&&!c.inverted||!b.reversed&&c.inverted?-1:1,r=b.getExtremes(),m=b.toValue(h-k,!0)+l*u;u=b.toValue(h+b.len-k,!0)-l*u;var t=u<m;h=t?u:m;m=t?m:u;u=Math.min(r.dataMin,l?r.min:b.toValue(b.toPixels(r.min)-b.minPixelPadding));l=Math.max(r.dataMax,l?r.max: b.toValue(b.toPixels(r.max)+b.minPixelPadding));if(!f.ordinal){e&&(f=u-h,0<f&&(m+=f,h=u),f=m-l,0<f&&(m=l,h-=f));if(b.series.length&&h!==r.min&&m!==r.max&&e||b.panningState&&h>=b.panningState.startMin&&m<=b.panningState.startMax)b.setExtremes(h,m,!1,!1,{trigger:"pan"}),d=!0;c[g]=k}});d&&c.redraw(!1);p(c.container,{cursor:"move"})})}});F(c.prototype,{select:function(a,b){var c=this,e=c.series,f=e.chart;this.selectedStaging=a=v(a,!c.selected);c.firePointEvent(a?"select":"unselect",{accumulate:b},function(){c.selected= c.options.selected=a;e.options.data[e.data.indexOf(c)]=c.options;c.setState(a&&"select");b||f.getSelectedPoints().forEach(function(a){var e=a.series;a.selected&&a!==c&&(a.selected=a.options.selected=!1,e.options.data[e.data.indexOf(a)]=a.options,a.setState(f.hoverPoints&&e.options.inactiveOtherPoints?"inactive":""),a.firePointEvent("unselect"))})});delete this.selectedStaging},onMouseOver:function(a){var b=this.series.chart,c=b.pointer;a=a?c.normalize(a):c.getChartCoordinatesFromPoint(this,b.inverted); c.runPointActions(a,this)},onMouseOut:function(){var a=this.series.chart;this.firePointEvent("mouseOut");this.series.options.inactiveOtherPoints||(a.hoverPoints||[]).forEach(function(a){a.setState()});a.hoverPoints=a.hoverPoint=null},importEvents:function(){if(!this.hasImportedEvents){var a=this,b=f(a.series.options.point,a.options).events;a.events=b;x(b,function(b,e){d.isFunction(b)&&C(a,e,b)});this.hasImportedEvents=!0}},setState:function(a,b){var c=this.series,e=this.state,f=c.options.states[a|| "normal"]||{},d=m[c.type].marker&&c.options.marker,g=d&&!1===d.enabled,h=d&&d.states&&d.states[a||"normal"]||{},l=!1===h.enabled,n=c.stateMarkerGraphic,t=this.marker||{},p=c.chart,w=c.halo,z,x=d&&c.markerAttribs;a=a||"";if(!(a===this.state&&!b||this.selected&&"select"!==a||!1===f.enabled||a&&(l||g&&!1===h.enabled)||a&&t.states&&t.states[a]&&!1===t.states[a].enabled)){this.state=a;x&&(z=c.markerAttribs(this,a));if(this.graphic){e&&this.graphic.removeClass("highcharts-point-"+e);a&&this.graphic.addClass("highcharts-point-"+ a);if(!p.styledMode){var B=c.pointAttribs(this,a);var y=v(p.options.chart.animation,f.animation);c.options.inactiveOtherPoints&&((this.dataLabels||[]).forEach(function(a){a&&a.animate({opacity:B.opacity},y)}),this.connector&&this.connector.animate({opacity:B.opacity},y));this.graphic.animate(B,y)}z&&this.graphic.animate(z,v(p.options.chart.animation,h.animation,d.animation));n&&n.hide()}else{if(a&&h){e=t.symbol||c.symbol;n&&n.currentSymbol!==e&&(n=n.destroy());if(z)if(n)n[b?"animate":"attr"]({x:z.x, y:z.y});else e&&(c.stateMarkerGraphic=n=p.renderer.symbol(e,z.x,z.y,z.width,z.height).add(c.markerGroup),n.currentSymbol=e);!p.styledMode&&n&&n.attr(c.pointAttribs(this,a))}n&&(n[a&&this.isInside?"show":"hide"](),n.element.point=this)}a=f.halo;f=(n=this.graphic||n)&&n.visibility||"inherit";a&&a.size&&n&&"hidden"!==f&&!this.isCluster?(w||(c.halo=w=p.renderer.path().add(n.parentGroup)),w.show()[b?"animate":"attr"]({d:this.haloPath(a.size)}),w.attr({"class":"highcharts-halo highcharts-color-"+v(this.colorIndex, c.colorIndex)+(this.className?" "+this.className:""),visibility:f,zIndex:-1}),w.point=this,p.styledMode||w.attr(F({fill:this.color||c.color,"fill-opacity":a.opacity},a.attributes))):w&&w.point&&w.point.haloPath&&w.animate({d:w.point.haloPath(0)},null,w.hide);q(this,"afterSetState")}},haloPath:function(a){return this.series.chart.renderer.symbols.circle(Math.floor(this.plotX)-a,this.plotY-a,2*a,2*a)}});F(b.prototype,{onMouseOver:function(){var a=this.chart,b=a.hoverSeries;if(b&&b!==this)b.onMouseOut(); this.options.events.mouseOver&&q(this,"mouseOver");this.setState("hover");a.hoverSeries=this},onMouseOut:function(){var a=this.options,b=this.chart,c=b.tooltip,e=b.hoverPoint;b.hoverSeries=null;if(e)e.onMouseOut();this&&a.events.mouseOut&&q(this,"mouseOut");!c||this.stickyTracking||c.shared&&!this.noSharedTooltip||c.hide();b.series.forEach(function(a){a.setState("",!0)})},setState:function(a,b){var c=this,e=c.options,f=c.graph,d=e.inactiveOtherPoints,g=e.states,h=e.lineWidth,l=e.opacity,m=v(g[a|| "normal"]&&g[a||"normal"].animation,c.chart.options.chart.animation);e=0;a=a||"";if(c.state!==a&&([c.group,c.markerGroup,c.dataLabelsGroup].forEach(function(e){e&&(c.state&&e.removeClass("highcharts-series-"+c.state),a&&e.addClass("highcharts-series-"+a))}),c.state=a,!c.chart.styledMode)){if(g[a]&&!1===g[a].enabled)return;a&&(h=g[a].lineWidth||h+(g[a].lineWidthPlus||0),l=v(g[a].opacity,l));if(f&&!f.dashstyle)for(g={"stroke-width":h},f.animate(g,m);c["zone-graph-"+e];)c["zone-graph-"+e].attr(g),e+= 1;d||[c.group,c.markerGroup,c.dataLabelsGroup,c.labelBySeries].forEach(function(a){a&&a.animate({opacity:l},m)})}b&&d&&c.points&&c.setAllPointsToState(a)},setAllPointsToState:function(a){this.points.forEach(function(b){b.setState&&b.setState(a)})},setVisible:function(a,b){var c=this,e=c.chart,f=c.legendItem,d=e.options.chart.ignoreHiddenSeries,g=c.visible;var h=(c.visible=a=c.options.visible=c.userOptions.visible="undefined"===typeof a?!g:a)?"show":"hide";["group","dataLabelsGroup","markerGroup", "tracker","tt"].forEach(function(a){if(c[a])c[a][h]()});if(e.hoverSeries===c||(e.hoverPoint&&e.hoverPoint.series)===c)c.onMouseOut();f&&e.legend.colorizeItem(c,a);c.isDirty=!0;c.options.stacking&&e.series.forEach(function(a){a.options.stacking&&a.visible&&(a.isDirty=!0)});c.linkedSeries.forEach(function(e){e.setVisible(a,!1)});d&&(e.isDirtyBox=!0);q(c,h);!1!==b&&e.redraw()},show:function(){this.setVisible(!0)},hide:function(){this.setVisible(!1)},select:function(a){this.selected=a=this.options.selected= "undefined"===typeof a?!this.selected:a;this.checkbox&&(this.checkbox.checked=a);q(this,a?"select":"unselect")},drawTracker:n.drawTrackerGraph})});K(y,"parts/Responsive.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.isArray,F=g.isObject,E=g.objectEach,D=g.pick,x=g.splat;g=d.Chart;g.prototype.setResponsive=function(g,x){var v=this.options.responsive,p=[],z=this.currentResponsive;!x&&v&&v.rules&&v.rules.forEach(function(g){"undefined"===typeof g._id&&(g._id=d.uniqueKey()); this.matchResponsiveRule(g,p)},this);x=d.merge.apply(0,p.map(function(g){return d.find(v.rules,function(d){return d._id===g}).chartOptions}));x.isResponsiveOptions=!0;p=p.toString()||void 0;p!==(z&&z.ruleIds)&&(z&&this.update(z.undoOptions,g,!0),p?(z=this.currentOptions(x),z.isResponsiveOptions=!0,this.currentResponsive={ruleIds:p,mergedOptions:x,undoOptions:z},this.update(x,g,!0)):this.currentResponsive=void 0)};g.prototype.matchResponsiveRule=function(d,g){var v=d.condition;(v.callback||function(){return this.chartWidth<= D(v.maxWidth,Number.MAX_VALUE)&&this.chartHeight<=D(v.maxHeight,Number.MAX_VALUE)&&this.chartWidth>=D(v.minWidth,0)&&this.chartHeight>=D(v.minHeight,0)}).call(this)&&g.push(d._id)};g.prototype.currentOptions=function(d){function g(d,m,p,w){var h;E(d,function(f,c){if(!w&&-1<v.collectionsWithUpdate.indexOf(c))for(f=x(f),p[c]=[],h=0;h<f.length;h++)m[c][h]&&(p[c][h]={},g(f[h],m[c][h],p[c][h],w+1));else F(f)?(p[c]=y(f)?[]:{},g(f,m[c]||{},p[c],w+1)):p[c]="undefined"===typeof m[c]?null:m[c]})}var v=this, p={};g(d,this.options,p,0);return p}});K(y,"masters/highcharts.src.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.extend;y(d,{animObject:g.animObject,arrayMax:g.arrayMax,arrayMin:g.arrayMin,attr:g.attr,correctFloat:g.correctFloat,defined:g.defined,destroyObjectProperties:g.destroyObjectProperties,discardElement:g.discardElement,erase:g.erase,extend:g.extend,extendClass:g.extendClass,isArray:g.isArray,isClass:g.isClass,isDOMElement:g.isDOMElement,isNumber:g.isNumber,isObject:g.isObject, isString:g.isString,numberFormat:g.numberFormat,objectEach:g.objectEach,offset:g.offset,pad:g.pad,pick:g.pick,pInt:g.pInt,relativeLength:g.relativeLength,setAnimation:g.setAnimation,splat:g.splat,syncTimeout:g.syncTimeout,wrap:g.wrap});return d});K(y,"parts/Scrollbar.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){function y(d,f,c){this.init(d,f,c)}var F=g.correctFloat,E=g.defined,D=g.destroyObjectProperties,x=g.pick,v=d.addEvent;g=d.Axis;var C=d.defaultOptions,B=d.fireEvent,p=d.hasTouch, z=d.merge,m=d.removeEvent,q,w={height:d.isTouchDevice?20:14,barBorderRadius:0,buttonBorderRadius:0,liveRedraw:void 0,margin:10,minWidth:6,step:.2,zIndex:3,barBackgroundColor:"#cccccc",barBorderWidth:1,barBorderColor:"#cccccc",buttonArrowColor:"#333333",buttonBackgroundColor:"#e6e6e6",buttonBorderColor:"#cccccc",buttonBorderWidth:1,rifleColor:"#333333",trackBackgroundColor:"#f2f2f2",trackBorderColor:"#f2f2f2",trackBorderWidth:1};C.scrollbar=z(!0,w,C.scrollbar);d.swapXY=q=function(d,f){var c=d.length; if(f)for(f=0;f<c;f+=3){var b=d[f+1];d[f+1]=d[f+2];d[f+2]=b}return d};y.prototype={init:function(d,f,c){this.scrollbarButtons=[];this.renderer=d;this.userOptions=f;this.options=z(w,f);this.chart=c;this.size=x(this.options.size,this.options.height);f.enabled&&(this.render(),this.initEvents(),this.addEvents())},render:function(){var d=this.renderer,f=this.options,c=this.size,b=this.chart.styledMode,a;this.group=a=d.g("scrollbar").attr({zIndex:f.zIndex,translateY:-99999}).add();this.track=d.rect().addClass("highcharts-scrollbar-track").attr({x:0, r:f.trackBorderRadius||0,height:c,width:c}).add(a);b||this.track.attr({fill:f.trackBackgroundColor,stroke:f.trackBorderColor,"stroke-width":f.trackBorderWidth});this.trackBorderWidth=this.track.strokeWidth();this.track.attr({y:-this.trackBorderWidth%2/2});this.scrollbarGroup=d.g().add(a);this.scrollbar=d.rect().addClass("highcharts-scrollbar-thumb").attr({height:c,width:c,r:f.barBorderRadius||0}).add(this.scrollbarGroup);this.scrollbarRifles=d.path(q(["M",-3,c/4,"L",-3,2*c/3,"M",0,c/4,"L",0,2*c/3, "M",3,c/4,"L",3,2*c/3],f.vertical)).addClass("highcharts-scrollbar-rifles").add(this.scrollbarGroup);b||(this.scrollbar.attr({fill:f.barBackgroundColor,stroke:f.barBorderColor,"stroke-width":f.barBorderWidth}),this.scrollbarRifles.attr({stroke:f.rifleColor,"stroke-width":1}));this.scrollbarStrokeWidth=this.scrollbar.strokeWidth();this.scrollbarGroup.translate(-this.scrollbarStrokeWidth%2/2,-this.scrollbarStrokeWidth%2/2);this.drawScrollbarButton(0);this.drawScrollbarButton(1)},position:function(d, f,c,b){var a=this.options.vertical,g=0,h=this.rendered?"animate":"attr";this.x=d;this.y=f+this.trackBorderWidth;this.width=c;this.xOffset=this.height=b;this.yOffset=g;a?(this.width=this.yOffset=c=g=this.size,this.xOffset=f=0,this.barWidth=b-2*c,this.x=d+=this.options.margin):(this.height=this.xOffset=b=f=this.size,this.barWidth=c-2*b,this.y+=this.options.margin);this.group[h]({translateX:d,translateY:this.y});this.track[h]({width:c,height:b});this.scrollbarButtons[1][h]({translateX:a?0:c-f,translateY:a? b-g:0})},drawScrollbarButton:function(d){var f=this.renderer,c=this.scrollbarButtons,b=this.options,a=this.size;var g=f.g().add(this.group);c.push(g);g=f.rect().addClass("highcharts-scrollbar-button").add(g);this.chart.styledMode||g.attr({stroke:b.buttonBorderColor,"stroke-width":b.buttonBorderWidth,fill:b.buttonBackgroundColor});g.attr(g.crisp({x:-.5,y:-.5,width:a+1,height:a+1,r:b.buttonBorderRadius},g.strokeWidth()));g=f.path(q(["M",a/2+(d?-1:1),a/2-3,"L",a/2+(d?-1:1),a/2+3,"L",a/2+(d?2:-2),a/2], b.vertical)).addClass("highcharts-scrollbar-arrow").add(c[d]);this.chart.styledMode||g.attr({fill:b.buttonArrowColor})},setRange:function(d,f){var c=this.options,b=c.vertical,a=c.minWidth,g=this.barWidth,h,m=!this.rendered||this.hasDragged||this.chart.navigator&&this.chart.navigator.hasDragged?"attr":"animate";if(E(g)){d=Math.max(d,0);var p=Math.ceil(g*d);this.calculatedWidth=h=F(g*Math.min(f,1)-p);h<a&&(p=(g-a+h)*d,h=a);a=Math.floor(p+this.xOffset+this.yOffset);g=h/2-.5;this.from=d;this.to=f;b?(this.scrollbarGroup[m]({translateY:a}), this.scrollbar[m]({height:h}),this.scrollbarRifles[m]({translateY:g}),this.scrollbarTop=a,this.scrollbarLeft=0):(this.scrollbarGroup[m]({translateX:a}),this.scrollbar[m]({width:h}),this.scrollbarRifles[m]({translateX:g}),this.scrollbarLeft=a,this.scrollbarTop=0);12>=h?this.scrollbarRifles.hide():this.scrollbarRifles.show(!0);!1===c.showFull&&(0>=d&&1<=f?this.group.hide():this.group.show());this.rendered=!0}},initEvents:function(){var d=this;d.mouseMoveHandler=function(f){var c=d.chart.pointer.normalize(f), b=d.options.vertical?"chartY":"chartX",a=d.initPositions;!d.grabbedCenter||f.touches&&0===f.touches[0][b]||(c=d.cursorToScrollbarPosition(c)[b],b=d[b],b=c-b,d.hasDragged=!0,d.updatePosition(a[0]+b,a[1]+b),d.hasDragged&&B(d,"changed",{from:d.from,to:d.to,trigger:"scrollbar",DOMType:f.type,DOMEvent:f}))};d.mouseUpHandler=function(f){d.hasDragged&&B(d,"changed",{from:d.from,to:d.to,trigger:"scrollbar",DOMType:f.type,DOMEvent:f});d.grabbedCenter=d.hasDragged=d.chartX=d.chartY=null};d.mouseDownHandler= function(f){f=d.chart.pointer.normalize(f);f=d.cursorToScrollbarPosition(f);d.chartX=f.chartX;d.chartY=f.chartY;d.initPositions=[d.from,d.to];d.grabbedCenter=!0};d.buttonToMinClick=function(f){var c=F(d.to-d.from)*d.options.step;d.updatePosition(F(d.from-c),F(d.to-c));B(d,"changed",{from:d.from,to:d.to,trigger:"scrollbar",DOMEvent:f})};d.buttonToMaxClick=function(f){var c=(d.to-d.from)*d.options.step;d.updatePosition(d.from+c,d.to+c);B(d,"changed",{from:d.from,to:d.to,trigger:"scrollbar",DOMEvent:f})}; d.trackClick=function(f){var c=d.chart.pointer.normalize(f),b=d.to-d.from,a=d.y+d.scrollbarTop,g=d.x+d.scrollbarLeft;d.options.vertical&&c.chartY>a||!d.options.vertical&&c.chartX>g?d.updatePosition(d.from+b,d.to+b):d.updatePosition(d.from-b,d.to-b);B(d,"changed",{from:d.from,to:d.to,trigger:"scrollbar",DOMEvent:f})}},cursorToScrollbarPosition:function(d){var f=this.options;f=f.minWidth>this.calculatedWidth?f.minWidth:0;return{chartX:(d.chartX-this.x-this.xOffset)/(this.barWidth-f),chartY:(d.chartY- this.y-this.yOffset)/(this.barWidth-f)}},updatePosition:function(d,f){1<f&&(d=F(1-F(f-d)),f=1);0>d&&(f=F(f-d),d=0);this.from=d;this.to=f},update:function(d){this.destroy();this.init(this.chart.renderer,z(!0,this.options,d),this.chart)},addEvents:function(){var d=this.options.inverted?[1,0]:[0,1],f=this.scrollbarButtons,c=this.scrollbarGroup.element,b=this.mouseDownHandler,a=this.mouseMoveHandler,g=this.mouseUpHandler;d=[[f[d[0]].element,"click",this.buttonToMinClick],[f[d[1]].element,"click",this.buttonToMaxClick], [this.track.element,"click",this.trackClick],[c,"mousedown",b],[c.ownerDocument,"mousemove",a],[c.ownerDocument,"mouseup",g]];p&&d.push([c,"touchstart",b],[c.ownerDocument,"touchmove",a],[c.ownerDocument,"touchend",g]);d.forEach(function(a){v.apply(null,a)});this._events=d},removeEvents:function(){this._events.forEach(function(d){m.apply(null,d)});this._events.length=0},destroy:function(){var d=this.chart.scroller;this.removeEvents();["track","scrollbarRifles","scrollbar","scrollbarGroup","group"].forEach(function(d){this[d]&& this[d].destroy&&(this[d]=this[d].destroy())},this);d&&this===d.scrollbar&&(d.scrollbar=null,D(d.scrollbarButtons))}};d.Scrollbar||(v(g,"afterInit",function(){var g=this;g.options&&g.options.scrollbar&&g.options.scrollbar.enabled&&(g.options.scrollbar.vertical=!g.horiz,g.options.startOnTick=g.options.endOnTick=!1,g.scrollbar=new y(g.chart.renderer,g.options.scrollbar,g.chart),v(g.scrollbar,"changed",function(f){var c=Math.min(x(g.options.min,g.min),g.min,g.dataMin),b=Math.max(x(g.options.max,g.max), g.max,g.dataMax)-c;if(g.horiz&&!g.reversed||!g.horiz&&g.reversed){var a=c+b*this.to;c+=b*this.from}else a=c+b*(1-this.from),c+=b*(1-this.to);x(this.options.liveRedraw,d.svg&&!d.isTouchDevice&&!this.chart.isBoosting)||"mouseup"===f.DOMType||!E(f.DOMType)?g.setExtremes(c,a,!0,"mousemove"!==f.DOMType,f):this.setRange(this.from,this.to)}))}),v(g,"afterRender",function(){var d=Math.min(x(this.options.min,this.min),this.min,x(this.dataMin,this.min)),f=Math.max(x(this.options.max,this.max),this.max,x(this.dataMax, this.max)),c=this.scrollbar,b=this.axisTitleMargin+(this.titleOffset||0),a=this.chart.scrollbarsOffsets,g=this.options.margin||0;c&&(this.horiz?(this.opposite||(a[1]+=b),c.position(this.left,this.top+this.height+2+a[1]-(this.opposite?g:0),this.width,this.height),this.opposite||(a[1]+=g),b=1):(this.opposite&&(a[0]+=b),c.position(this.left+this.width+2+a[0]-(this.opposite?0:g),this.top,this.width,this.height),this.opposite&&(a[0]+=g),b=0),a[b]+=c.size+c.options.margin,isNaN(d)||isNaN(f)||!E(this.min)|| !E(this.max)||this.min===this.max?c.setRange(0,1):(a=(this.min-d)/(f-d),d=(this.max-d)/(f-d),this.horiz&&!this.reversed||!this.horiz&&this.reversed?c.setRange(a,d):c.setRange(1-d,1-a)))}),v(g,"afterGetOffset",function(){var d=this.horiz?2:1,f=this.scrollbar;f&&(this.chart.scrollbarsOffsets=[0,0],this.chart.axisOffset[d]+=f.size+f.options.margin)}),d.Scrollbar=y)});K(y,"parts/Navigator.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){function y(a){this.init(a)}var F=g.clamp,E=g.correctFloat, D=g.defined,x=g.destroyObjectProperties,v=g.erase,C=g.extend,B=g.isArray,p=g.isNumber,z=g.pick,m=g.splat,q=d.addEvent,w=d.Axis;g=d.Chart;var h=d.color,f=d.defaultOptions,c=d.hasTouch,b=d.isTouchDevice,a=d.merge,l=d.removeEvent,n=d.Scrollbar,t=d.Series,I=function(a){for(var e=[],b=1;b<arguments.length;b++)e[b-1]=arguments[b];e=[].filter.call(e,p);if(e.length)return Math[a].apply(0,e)};var r="undefined"===typeof d.seriesTypes.areaspline?"line":"areaspline";C(f,{navigator:{height:40,margin:25,maskInside:!0, handles:{width:7,height:15,symbols:["navigator-handle","navigator-handle"],enabled:!0,lineWidth:1,backgroundColor:"#f2f2f2",borderColor:"#999999"},maskFill:h("#6685c2").setOpacity(.3).get(),outlineColor:"#cccccc",outlineWidth:1,series:{type:r,fillOpacity:.05,lineWidth:1,compare:null,dataGrouping:{approximation:"average",enabled:!0,groupPixelWidth:2,smoothed:!0,units:[["millisecond",[1,2,5,10,20,25,50,100,200,500]],["second",[1,2,5,10,15,30]],["minute",[1,2,5,10,15,30]],["hour",[1,2,3,4,6,8,12]],["day", [1,2,3,4]],["week",[1,2,3]],["month",[1,3,6]],["year",null]]},dataLabels:{enabled:!1,zIndex:2},id:"highcharts-navigator-series",className:"highcharts-navigator-series",lineColor:null,marker:{enabled:!1},threshold:null},xAxis:{overscroll:0,className:"highcharts-navigator-xaxis",tickLength:0,lineWidth:0,gridLineColor:"#e6e6e6",gridLineWidth:1,tickPixelInterval:200,labels:{align:"left",style:{color:"#999999"},x:3,y:-4},crosshair:!1},yAxis:{className:"highcharts-navigator-yaxis",gridLineWidth:0,startOnTick:!1, endOnTick:!1,minPadding:.1,maxPadding:.1,labels:{enabled:!1},crosshair:!1,title:{text:null},tickLength:0,tickWidth:0}}});d.Renderer.prototype.symbols["navigator-handle"]=function(a,b,c,d,f){a=f.width/2;b=Math.round(a/3)+.5;f=f.height;return["M",-a-1,.5,"L",a,.5,"L",a,f+.5,"L",-a-1,f+.5,"L",-a-1,.5,"M",-b,4,"L",-b,f-3,"M",b-1,4,"L",b-1,f-3]};w.prototype.toFixedRange=function(a,b,c,d){var e=this.chart&&this.chart.fixedRange,f=(this.pointRange||0)/2;a=z(c,this.translate(a,!0,!this.horiz));b=z(d,this.translate(b, !0,!this.horiz));var g=e&&(b-a)/e;D(c)||(a=E(a+f));D(d)||(b=E(b-f));.7<g&&1.3>g&&(d?a=b-e:b=a+e);p(a)&&p(b)||(a=b=void 0);return{min:a,max:b}};y.prototype={drawHandle:function(a,b,c,d){var e=this.navigatorOptions.handles.height;this.handles[b][d](c?{translateX:Math.round(this.left+this.height/2),translateY:Math.round(this.top+parseInt(a,10)+.5-e)}:{translateX:Math.round(this.left+parseInt(a,10)),translateY:Math.round(this.top+this.height/2-e/2-1)})},drawOutline:function(a,b,c,d){var e=this.navigatorOptions.maskInside, f=this.outline.strokeWidth(),g=f/2;f=f%2/2;var k=this.outlineHeight,h=this.scrollbarHeight,l=this.size,u=this.left-h,m=this.top;c?(u-=g,c=m+b+f,b=m+a+f,a=["M",u+k,m-h-f,"L",u+k,c,"L",u,c,"L",u,b,"L",u+k,b,"L",u+k,m+l+h].concat(e?["M",u+k,c-g,"L",u+k,b+g]:[])):(a+=u+h-f,b+=u+h-f,m+=g,a=["M",u,m,"L",a,m,"L",a,m+k,"L",b,m+k,"L",b,m,"L",u+l+2*h,m].concat(e?["M",a-g,m,"L",b+g,m]:[]));this.outline[d]({d:a})},drawMasks:function(a,b,c,d){var e=this.left,f=this.top,g=this.height;if(c){var k=[e,e,e];var h= [f,f+a,f+b];var l=[g,g,g];var u=[a,b-a,this.size-b]}else k=[e,e+a,e+b],h=[f,f,f],l=[a,b-a,this.size-b],u=[g,g,g];this.shades.forEach(function(a,b){a[d]({x:k[b],y:h[b],width:l[b],height:u[b]})})},renderElements:function(){var a=this,b=a.navigatorOptions,c=b.maskInside,d=a.chart,f=d.renderer,g,h={cursor:d.inverted?"ns-resize":"ew-resize"};a.navigatorGroup=g=f.g("navigator").attr({zIndex:8,visibility:"hidden"}).add();[!c,c,!c].forEach(function(e,c){a.shades[c]=f.rect().addClass("highcharts-navigator-mask"+ (1===c?"-inside":"-outside")).add(g);d.styledMode||a.shades[c].attr({fill:e?b.maskFill:"rgba(0,0,0,0)"}).css(1===c&&h)});a.outline=f.path().addClass("highcharts-navigator-outline").add(g);d.styledMode||a.outline.attr({"stroke-width":b.outlineWidth,stroke:b.outlineColor});b.handles.enabled&&[0,1].forEach(function(e){b.handles.inverted=d.inverted;a.handles[e]=f.symbol(b.handles.symbols[e],-b.handles.width/2-1,0,b.handles.width,b.handles.height,b.handles);a.handles[e].attr({zIndex:7-e}).addClass("highcharts-navigator-handle highcharts-navigator-handle-"+ ["left","right"][e]).add(g);if(!d.styledMode){var c=b.handles;a.handles[e].attr({fill:c.backgroundColor,stroke:c.borderColor,"stroke-width":c.lineWidth}).css(h)}})},update:function(b){(this.series||[]).forEach(function(a){a.baseSeries&&delete a.baseSeries.navigatorSeries});this.destroy();a(!0,this.chart.options.navigator,this.options,b);this.init(this.chart)},render:function(a,b,c,d){var e=this.chart,f=this.scrollbarHeight,g,k=this.xAxis,h=k.pointRange||0;var l=k.fake?e.xAxis[0]:k;var u=this.navigatorEnabled, m,n=this.rendered;var r=e.inverted;var t=e.xAxis[0].minRange,q=e.xAxis[0].options.maxRange;if(!this.hasDragged||D(c)){a=E(a-h/2);b=E(b+h/2);if(!p(a)||!p(b))if(n)c=0,d=z(k.width,l.width);else return;this.left=z(k.left,e.plotLeft+f+(r?e.plotWidth:0));this.size=m=g=z(k.len,(r?e.plotHeight:e.plotWidth)-2*f);e=r?f:g+2*f;c=z(c,k.toPixels(a,!0));d=z(d,k.toPixels(b,!0));p(c)&&Infinity!==Math.abs(c)||(c=0,d=e);a=k.toValue(c,!0);b=k.toValue(d,!0);var w=Math.abs(E(b-a));w<t?this.grabbedLeft?c=k.toPixels(b-t- h,!0):this.grabbedRight&&(d=k.toPixels(a+t+h,!0)):D(q)&&E(w-h)>q&&(this.grabbedLeft?c=k.toPixels(b-q-h,!0):this.grabbedRight&&(d=k.toPixels(a+q+h,!0)));this.zoomedMax=F(Math.max(c,d),0,m);this.zoomedMin=F(this.fixedWidth?this.zoomedMax-this.fixedWidth:Math.min(c,d),0,m);this.range=this.zoomedMax-this.zoomedMin;m=Math.round(this.zoomedMax);c=Math.round(this.zoomedMin);u&&(this.navigatorGroup.attr({visibility:"visible"}),n=n&&!this.hasDragged?"animate":"attr",this.drawMasks(c,m,r,n),this.drawOutline(c, m,r,n),this.navigatorOptions.handles.enabled&&(this.drawHandle(c,0,r,n),this.drawHandle(m,1,r,n)));this.scrollbar&&(r?(r=this.top-f,l=this.left-f+(u||!l.opposite?0:(l.titleOffset||0)+l.axisTitleMargin),f=g+2*f):(r=this.top+(u?this.height:-f),l=this.left-f),this.scrollbar.position(l,r,e,f),this.scrollbar.setRange(this.zoomedMin/(g||1),this.zoomedMax/(g||1)));this.rendered=!0}},addMouseEvents:function(){var a=this,b=a.chart,d=b.container,f=[],g,h;a.mouseMoveHandler=g=function(b){a.onMouseMove(b)};a.mouseUpHandler= h=function(b){a.onMouseUp(b)};f=a.getPartsEvents("mousedown");f.push(q(b.renderTo,"mousemove",g),q(d.ownerDocument,"mouseup",h));c&&(f.push(q(b.renderTo,"touchmove",g),q(d.ownerDocument,"touchend",h)),f.concat(a.getPartsEvents("touchstart")));a.eventsToUnbind=f;a.series&&a.series[0]&&f.push(q(a.series[0].xAxis,"foundExtremes",function(){b.navigator.modifyNavigatorAxisExtremes()}))},getPartsEvents:function(a){var b=this,e=[];["shades","handles"].forEach(function(c){b[c].forEach(function(d,f){e.push(q(d.element, a,function(a){b[c+"Mousedown"](a,f)}))})});return e},shadesMousedown:function(a,b){a=this.chart.pointer.normalize(a);var e=this.chart,c=this.xAxis,d=this.zoomedMin,f=this.left,g=this.size,k=this.range,h=a.chartX;e.inverted&&(h=a.chartY,f=this.top);if(1===b)this.grabbedCenter=h,this.fixedWidth=k,this.dragOffset=h-d;else{a=h-f-k/2;if(0===b)a=Math.max(0,a);else if(2===b&&a+k>=g)if(a=g-k,this.reversedExtremes){a-=k;var l=this.getUnionExtremes().dataMin}else var m=this.getUnionExtremes().dataMax;a!==d&& (this.fixedWidth=k,b=c.toFixedRange(a,a+k,l,m),D(b.min)&&e.xAxis[0].setExtremes(Math.min(b.min,b.max),Math.max(b.min,b.max),!0,null,{trigger:"navigator"}))}},handlesMousedown:function(a,b){this.chart.pointer.normalize(a);a=this.chart;var e=a.xAxis[0],c=this.reversedExtremes;0===b?(this.grabbedLeft=!0,this.otherHandlePos=this.zoomedMax,this.fixedExtreme=c?e.min:e.max):(this.grabbedRight=!0,this.otherHandlePos=this.zoomedMin,this.fixedExtreme=c?e.max:e.min);a.fixedRange=null},onMouseMove:function(a){var e= this,c=e.chart,f=e.left,g=e.navigatorSize,h=e.range,l=e.dragOffset,m=c.inverted;a.touches&&0===a.touches[0].pageX||(a=c.pointer.normalize(a),c=a.chartX,m&&(f=e.top,c=a.chartY),e.grabbedLeft?(e.hasDragged=!0,e.render(0,0,c-f,e.otherHandlePos)):e.grabbedRight?(e.hasDragged=!0,e.render(0,0,e.otherHandlePos,c-f)):e.grabbedCenter&&(e.hasDragged=!0,c<l?c=l:c>g+l-h&&(c=g+l-h),e.render(0,0,c-l,c-l+h)),e.hasDragged&&e.scrollbar&&z(e.scrollbar.options.liveRedraw,d.svg&&!b&&!this.chart.isBoosting)&&(a.DOMType= a.type,setTimeout(function(){e.onMouseUp(a)},0)))},onMouseUp:function(a){var b=this.chart,e=this.xAxis,c=this.scrollbar,d=a.DOMEvent||a;if(this.hasDragged&&(!c||!c.hasDragged)||"scrollbar"===a.trigger){c=this.getUnionExtremes();if(this.zoomedMin===this.otherHandlePos)var f=this.fixedExtreme;else if(this.zoomedMax===this.otherHandlePos)var g=this.fixedExtreme;this.zoomedMax===this.size&&(g=this.reversedExtremes?c.dataMin:c.dataMax);0===this.zoomedMin&&(f=this.reversedExtremes?c.dataMax:c.dataMin); e=e.toFixedRange(this.zoomedMin,this.zoomedMax,f,g);D(e.min)&&b.xAxis[0].setExtremes(Math.min(e.min,e.max),Math.max(e.min,e.max),!0,this.hasDragged?!1:null,{trigger:"navigator",triggerOp:"navigator-drag",DOMEvent:d})}"mousemove"!==a.DOMType&&"touchmove"!==a.DOMType&&(this.grabbedLeft=this.grabbedRight=this.grabbedCenter=this.fixedWidth=this.fixedExtreme=this.otherHandlePos=this.hasDragged=this.dragOffset=null)},removeEvents:function(){this.eventsToUnbind&&(this.eventsToUnbind.forEach(function(a){a()}), this.eventsToUnbind=void 0);this.removeBaseSeriesEvents()},removeBaseSeriesEvents:function(){var a=this.baseSeries||[];this.navigatorEnabled&&a[0]&&(!1!==this.navigatorOptions.adaptToUpdatedData&&a.forEach(function(a){l(a,"updatedData",this.updatedDataHandler)},this),a[0].xAxis&&l(a[0].xAxis,"foundExtremes",this.modifyBaseAxisExtremes))},init:function(b){var e=b.options,c=e.navigator,d=c.enabled,f=e.scrollbar,g=f.enabled;e=d?c.height:0;var h=g?f.height:0;this.handles=[];this.shades=[];this.chart= b;this.setBaseSeries();this.height=e;this.scrollbarHeight=h;this.scrollbarEnabled=g;this.navigatorEnabled=d;this.navigatorOptions=c;this.scrollbarOptions=f;this.outlineHeight=e+h;this.opposite=z(c.opposite,!(d||!b.inverted));var l=this;d=l.baseSeries;f=b.xAxis.length;g=b.yAxis.length;var m=d&&d[0]&&d[0].xAxis||b.xAxis[0]||{options:{}};b.isDirtyBox=!0;l.navigatorEnabled?(l.xAxis=new w(b,a({breaks:m.options.breaks,ordinal:m.options.ordinal},c.xAxis,{id:"navigator-x-axis",yAxis:"navigator-y-axis",isX:!0, type:"datetime",index:f,isInternal:!0,offset:0,keepOrdinalPadding:!0,startOnTick:!1,endOnTick:!1,minPadding:0,maxPadding:0,zoomEnabled:!1},b.inverted?{offsets:[h,0,-h,0],width:e}:{offsets:[0,-h,0,h],height:e})),l.yAxis=new w(b,a(c.yAxis,{id:"navigator-y-axis",alignTicks:!1,offset:0,index:g,isInternal:!0,zoomEnabled:!1},b.inverted?{width:e}:{height:e})),d||c.series.data?l.updateNavigatorSeries(!1):0===b.series.length&&(l.unbindRedraw=q(b,"beforeRedraw",function(){0<b.series.length&&!l.series&&(l.setBaseSeries(), l.unbindRedraw())})),l.reversedExtremes=b.inverted&&!l.xAxis.reversed||!b.inverted&&l.xAxis.reversed,l.renderElements(),l.addMouseEvents()):l.xAxis={translate:function(a,e){var c=b.xAxis[0],d=c.getExtremes(),f=c.len-2*h,g=I("min",c.options.min,d.dataMin);c=I("max",c.options.max,d.dataMax)-g;return e?a*c/f+g:f*(a-g)/c},toPixels:function(a){return this.translate(a)},toValue:function(a){return this.translate(a,!0)},toFixedRange:w.prototype.toFixedRange,fake:!0};b.options.scrollbar.enabled&&(b.scrollbar= l.scrollbar=new n(b.renderer,a(b.options.scrollbar,{margin:l.navigatorEnabled?0:10,vertical:b.inverted}),b),q(l.scrollbar,"changed",function(a){var e=l.size,c=e*this.to;e*=this.from;l.hasDragged=l.scrollbar.hasDragged;l.render(0,0,e,c);(b.options.scrollbar.liveRedraw||"mousemove"!==a.DOMType&&"touchmove"!==a.DOMType)&&setTimeout(function(){l.onMouseUp(a)})}));l.addBaseSeriesEvents();l.addChartEvents()},getUnionExtremes:function(a){var b=this.chart.xAxis[0],e=this.xAxis,c=e.options,d=b.options,f;a&& null===b.dataMin||(f={dataMin:z(c&&c.min,I("min",d.min,b.dataMin,e.dataMin,e.min)),dataMax:z(c&&c.max,I("max",d.max,b.dataMax,e.dataMax,e.max))});return f},setBaseSeries:function(a,b){var e=this.chart,c=this.baseSeries=[];a=a||e.options&&e.options.navigator.baseSeries||(e.series.length?d.find(e.series,function(a){return!a.options.isInternal}).index:0);(e.series||[]).forEach(function(b,e){b.options.isInternal||!b.options.showInNavigator&&(e!==a&&b.options.id!==a||!1===b.options.showInNavigator)||c.push(b)}); this.xAxis&&!this.xAxis.fake&&this.updateNavigatorSeries(!0,b)},updateNavigatorSeries:function(b,c){var e=this,d=e.chart,g=e.baseSeries,k,h,n=e.navigatorOptions.series,r,t={enableMouseTracking:!1,index:null,linkedTo:null,group:"nav",padXAxis:!1,xAxis:"navigator-x-axis",yAxis:"navigator-y-axis",showInLegend:!1,stacking:!1,isInternal:!0,states:{inactive:{opacity:1}}},p=e.series=(e.series||[]).filter(function(a){var b=a.baseSeries;return 0>g.indexOf(b)?(b&&(l(b,"updatedData",e.updatedDataHandler),delete b.navigatorSeries), a.chart&&a.destroy(),!1):!0});g&&g.length&&g.forEach(function(b){var l=b.navigatorSeries,m=C({color:b.color,visible:b.visible},B(n)?f.navigator.series:n);l&&!1===e.navigatorOptions.adaptToUpdatedData||(t.name="Navigator "+g.length,k=b.options||{},r=k.navigatorOptions||{},h=a(k,t,m,r),h.pointRange=z(m.pointRange,r.pointRange,f.plotOptions[h.type||"line"].pointRange),m=r.data||m.data,e.hasNavigatorData=e.hasNavigatorData||!!m,h.data=m||k.data&&k.data.slice(0),l&&l.options?l.update(h,c):(b.navigatorSeries= d.initSeries(h),b.navigatorSeries.baseSeries=b,p.push(b.navigatorSeries)))});if(n.data&&(!g||!g.length)||B(n))e.hasNavigatorData=!1,n=m(n),n.forEach(function(b,c){t.name="Navigator "+(p.length+1);h=a(f.navigator.series,{color:d.series[c]&&!d.series[c].options.isInternal&&d.series[c].color||d.options.colors[c]||d.options.colors[0]},t,b);h.data=b.data;h.data&&(e.hasNavigatorData=!0,p.push(d.initSeries(h)))});b&&this.addBaseSeriesEvents()},addBaseSeriesEvents:function(){var a=this,b=a.baseSeries||[]; b[0]&&b[0].xAxis&&q(b[0].xAxis,"foundExtremes",this.modifyBaseAxisExtremes);b.forEach(function(b){q(b,"show",function(){this.navigatorSeries&&this.navigatorSeries.setVisible(!0,!1)});q(b,"hide",function(){this.navigatorSeries&&this.navigatorSeries.setVisible(!1,!1)});!1!==this.navigatorOptions.adaptToUpdatedData&&b.xAxis&&q(b,"updatedData",this.updatedDataHandler);q(b,"remove",function(){this.navigatorSeries&&(v(a.series,this.navigatorSeries),D(this.navigatorSeries.options)&&this.navigatorSeries.remove(!1), delete this.navigatorSeries)})},this)},getBaseSeriesMin:function(a){return this.baseSeries.reduce(function(a,b){return Math.min(a,b.xData?b.xData[0]:a)},a)},modifyNavigatorAxisExtremes:function(){var a=this.xAxis,b;"undefined"!==typeof a.getExtremes&&(!(b=this.getUnionExtremes(!0))||b.dataMin===a.min&&b.dataMax===a.max||(a.min=b.dataMin,a.max=b.dataMax))},modifyBaseAxisExtremes:function(){var a=this.chart.navigator,b=this.getExtremes(),c=b.dataMin,d=b.dataMax;b=b.max-b.min;var f=a.stickToMin,g=a.stickToMax, h=z(this.options.overscroll,0),l=a.series&&a.series[0],m=!!this.setExtremes;if(!this.eventArgs||"rangeSelectorButton"!==this.eventArgs.trigger){if(f){var n=c;var r=n+b}g&&(r=d+h,f||(n=Math.max(r-b,a.getBaseSeriesMin(l&&l.xData?l.xData[0]:-Number.MAX_VALUE))));m&&(f||g)&&p(n)&&(this.min=this.userMin=n,this.max=this.userMax=r)}a.stickToMin=a.stickToMax=null},updatedDataHandler:function(){var a=this.chart.navigator,b=this.navigatorSeries,c=a.getBaseSeriesMin(this.xData[0]);a.stickToMax=a.reversedExtremes? 0===Math.round(a.zoomedMin):Math.round(a.zoomedMax)>=Math.round(a.size);a.stickToMin=p(this.xAxis.min)&&this.xAxis.min<=c&&(!this.chart.fixedRange||!a.stickToMax);b&&!a.hasNavigatorData&&(b.options.pointStart=this.xData[0],b.setData(this.options.data,!1,null,!1))},addChartEvents:function(){this.eventsToUnbind||(this.eventsToUnbind=[]);this.eventsToUnbind.push(q(this.chart,"redraw",function(){var a=this.navigator,b=a&&(a.baseSeries&&a.baseSeries[0]&&a.baseSeries[0].xAxis||a.scrollbar&&this.xAxis[0]); b&&a.render(b.min,b.max)}),q(this.chart,"getMargins",function(){var a=this.navigator,b=a.opposite?"plotTop":"marginBottom";this.inverted&&(b=a.opposite?"marginRight":"plotLeft");this[b]=(this[b]||0)+(a.navigatorEnabled||!this.inverted?a.outlineHeight:0)+a.navigatorOptions.margin}))},destroy:function(){this.removeEvents();this.xAxis&&(v(this.chart.xAxis,this.xAxis),v(this.chart.axes,this.xAxis));this.yAxis&&(v(this.chart.yAxis,this.yAxis),v(this.chart.axes,this.yAxis));(this.series||[]).forEach(function(a){a.destroy&& a.destroy()});"series xAxis yAxis shades outline scrollbarTrack scrollbarRifles scrollbarGroup scrollbar navigatorGroup rendered".split(" ").forEach(function(a){this[a]&&this[a].destroy&&this[a].destroy();this[a]=null},this);[this.handles].forEach(function(a){x(a)},this)}};d.Navigator||(d.Navigator=y,q(w,"zoom",function(a){var e=this.chart.options,c=e.chart.zoomType,d=e.chart.pinchType,f=e.navigator;e=e.rangeSelector;this.isXAxis&&(f&&f.enabled||e&&e.enabled)&&("y"===c?a.zoomed=!1:(!b&&"xy"===c|| b&&"xy"===d)&&this.options.range&&(c=this.previousZoom,D(a.newMin)?this.previousZoom=[this.min,this.max]:c&&(a.newMin=c[0],a.newMax=c[1],delete this.previousZoom)));"undefined"!==typeof a.zoomed&&a.preventDefault()}),q(g,"beforeShowResetZoom",function(){var a=this.options,c=a.navigator,d=a.rangeSelector;if((c&&c.enabled||d&&d.enabled)&&(!b&&"x"===a.chart.zoomType||b&&"x"===a.chart.pinchType))return!1}),q(g,"beforeRender",function(){var a=this.options;if(a.navigator.enabled||a.scrollbar.enabled)this.scroller= this.navigator=new y(this)}),q(g,"afterSetChartSize",function(){var a=this.legend,b=this.navigator;if(b){var c=a&&a.options;var d=b.xAxis;var f=b.yAxis;var g=b.scrollbarHeight;this.inverted?(b.left=b.opposite?this.chartWidth-g-b.height:this.spacing[3]+g,b.top=this.plotTop+g):(b.left=this.plotLeft+g,b.top=b.navigatorOptions.top||this.chartHeight-b.height-g-this.spacing[2]-(this.rangeSelector&&this.extraBottomMargin?this.rangeSelector.getHeight():0)-(c&&"bottom"===c.verticalAlign&&c.enabled&&!c.floating? a.legendHeight+z(c.margin,10):0)-(this.titleOffset?this.titleOffset[2]:0));d&&f&&(this.inverted?d.options.left=f.options.left=b.left:d.options.top=f.options.top=b.top,d.setAxisSize(),f.setAxisSize())}}),q(g,"update",function(b){var e=b.options.navigator||{},c=b.options.scrollbar||{};this.navigator||this.scroller||!e.enabled&&!c.enabled||(a(!0,this.options.navigator,e),a(!0,this.options.scrollbar,c),delete b.options.navigator,delete b.options.scrollbar)}),q(g,"afterUpdate",function(a){this.navigator|| this.scroller||!this.options.navigator.enabled&&!this.options.scrollbar.enabled||(this.scroller=this.navigator=new y(this),z(a.redraw,!0)&&this.redraw(a.animation))}),q(g,"afterAddSeries",function(){this.navigator&&this.navigator.setBaseSeries(null,!1)}),q(t,"afterUpdate",function(){this.chart.navigator&&!this.options.isInternal&&this.chart.navigator.setBaseSeries(null,!1)}),g.prototype.callbacks.push(function(a){var b=a.navigator;b&&a.xAxis[0]&&(a=a.xAxis[0].getExtremes(),b.render(a.min,a.max))}))}); K(y,"parts/OrdinalAxis.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.defined,F=g.extend,E=g.pick;g=d.addEvent;var D=d.Axis,x=d.Chart,v=d.css,C=d.noop,B=d.timeUnits;g(d.Series,"updatedData",function(){var d=this.xAxis;d&&d.options.ordinal&&delete d.ordinalIndex});D.prototype.getTimeTicks=function(d,g,m,q,w,h,f){var c=0,b,a,l={},n=[],t=-Number.MAX_VALUE,p=this.options.tickPixelInterval,r=this.chart.time,e=[];if(!this.options.ordinal&&!this.options.breaks||!w||3>w.length|| "undefined"===typeof g)return r.getTimeTicks.apply(r,arguments);var k=w.length;for(b=0;b<k;b++){var u=b&&w[b-1]>m;w[b]<g&&(c=b);if(b===k-1||w[b+1]-w[b]>5*h||u){if(w[b]>t){for(a=r.getTimeTicks(d,w[c],w[b],q);a.length&&a[0]<=t;)a.shift();a.length&&(t=a[a.length-1]);e.push(n.length);n=n.concat(a)}c=b+1}if(u)break}a=a.info;if(f&&a.unitRange<=B.hour){b=n.length-1;for(c=1;c<b;c++)if(r.dateFormat("%d",n[c])!==r.dateFormat("%d",n[c-1])){l[n[c]]="day";var v=!0}v&&(l[n[0]]="day");a.higherRanks=l}a.segmentStarts= e;n.info=a;if(f&&y(p)){c=e=n.length;v=[];var z;for(r=[];c--;)b=this.translate(n[c]),z&&(r[c]=z-b),v[c]=z=b;r.sort();r=r[Math.floor(r.length/2)];r<.6*p&&(r=null);c=n[e-1]>m?e-1:e;for(z=void 0;c--;)b=v[c],e=Math.abs(z-b),z&&e<.8*p&&(null===r||e<.8*r)?(l[n[c]]&&!l[n[c+1]]?(e=c+1,z=b):e=c,n.splice(e,1)):z=b}return n};F(D.prototype,{beforeSetTickPositions:function(){var d=[],g,m=!1,q=this.getExtremes(),w=q.min,h=q.max,f,c=this.isXAxis&&!!this.options.breaks;q=this.options.ordinal;var b=Number.MAX_VALUE, a=this.chart.options.chart.ignoreHiddenSeries,l;if(q||c){this.series.forEach(function(f,h){g=[];if(!(a&&!1===f.visible||!1===f.takeOrdinalPosition&&!c)&&(d=d.concat(f.processedXData),n=d.length,d.sort(function(a,b){return a-b}),b=Math.min(b,E(f.closestPointRange,b)),n)){for(h=0;h<n-1;)d[h]!==d[h+1]&&g.push(d[h+1]),h++;g[0]!==d[0]&&g.unshift(d[0]);d=g}f.isSeriesBoosting&&(l=!0)});l&&(d.length=0);var n=d.length;if(2<n){var t=d[1]-d[0];for(f=n-1;f--&&!m;)d[f+1]-d[f]!==t&&(m=!0);!this.options.keepOrdinalPadding&& (d[0]-w>t||h-d[d.length-1]>t)&&(m=!0)}else this.options.overscroll&&(2===n?b=d[1]-d[0]:1===n?(b=this.options.overscroll,d=[d[0],d[0]+b]):b=this.overscrollPointsRange);m?(this.options.overscroll&&(this.overscrollPointsRange=b,d=d.concat(this.getOverscrollPositions())),this.ordinalPositions=d,t=this.ordinal2lin(Math.max(w,d[0]),!0),f=Math.max(this.ordinal2lin(Math.min(h,d[d.length-1]),!0),1),this.ordinalSlope=h=(h-w)/(f-t),this.ordinalOffset=w-t*h):(this.overscrollPointsRange=E(this.closestPointRange, this.overscrollPointsRange),this.ordinalPositions=this.ordinalSlope=this.ordinalOffset=void 0)}this.isOrdinal=q&&m;this.groupIntervalFactor=null},val2lin:function(d,g){var m=this.ordinalPositions;if(m){var q=m.length,p;for(p=q;p--;)if(m[p]===d){var h=p;break}for(p=q-1;p--;)if(d>m[p]||0===p){d=(d-m[p])/(m[p+1]-m[p]);h=p+d;break}g=g?h:this.ordinalSlope*(h||0)+this.ordinalOffset}else g=d;return g},lin2val:function(d,g){var m=this.ordinalPositions;if(m){var q=this.ordinalSlope,p=this.ordinalOffset,h= m.length-1;if(g)if(0>d)d=m[0];else if(d>h)d=m[h];else{h=Math.floor(d);var f=d-h}else for(;h--;)if(g=q*h+p,d>=g){q=q*(h+1)+p;f=(d-g)/(q-g);break}return"undefined"!==typeof f&&"undefined"!==typeof m[h]?m[h]+(f?f*(m[h+1]-m[h]):0):d}return d},getExtendedPositions:function(){var d=this,g=d.chart,m=d.series[0].currentDataGrouping,q=d.ordinalIndex,w=m?m.count+m.unitName:"raw",h=d.options.overscroll,f=d.getExtremes(),c;q||(q=d.ordinalIndex={});if(!q[w]){var b={series:[],chart:g,getExtremes:function(){return{min:f.dataMin, max:f.dataMax+h}},options:{ordinal:!0},val2lin:D.prototype.val2lin,ordinal2lin:D.prototype.ordinal2lin};d.series.forEach(function(a){c={xAxis:b,xData:a.xData.slice(),chart:g,destroyGroupedData:C};c.xData=c.xData.concat(d.getOverscrollPositions());c.options={dataGrouping:m?{enabled:!0,forced:!0,approximation:"open",units:[[m.unitName,[m.count]]]}:{enabled:!1}};a.processData.apply(c);b.series.push(c)});d.beforeSetTickPositions.apply(b);q[w]=b.ordinalPositions}return q[w]},getOverscrollPositions:function(){var d= this.options.overscroll,g=this.overscrollPointsRange,m=[],q=this.dataMax;if(y(g))for(m.push(q);q<=this.dataMax+d;)q+=g,m.push(q);return m},getGroupIntervalFactor:function(d,g,m){m=m.processedXData;var q=m.length,p=[];var h=this.groupIntervalFactor;if(!h){for(h=0;h<q-1;h++)p[h]=m[h+1]-m[h];p.sort(function(d,c){return d-c});p=p[Math.floor(q/2)];d=Math.max(d,m[0]);g=Math.min(g,m[q-1]);this.groupIntervalFactor=h=q*p/(g-d)}return h},postProcessTickInterval:function(d){var g=this.ordinalSlope;return g? this.options.breaks?this.closestPointRange||d:d/(g/this.closestPointRange):d}});D.prototype.ordinal2lin=D.prototype.val2lin;g(x,"pan",function(d){var g=this.xAxis[0],m=g.options.overscroll,q=d.originalEvent.chartX,p=this.options.chart&&this.options.chart.panning,h=!1;if(p&&"y"!==p.type&&g.options.ordinal&&g.series.length){var f=this.mouseDownX,c=g.getExtremes(),b=c.dataMax,a=c.min,l=c.max,n=this.hoverPoints,t=g.closestPointRange||g.overscrollPointsRange;f=(f-q)/(g.translationSlope*(g.ordinalSlope|| t));var x={ordinalPositions:g.getExtendedPositions()};t=g.lin2val;var r=g.val2lin;if(!x.ordinalPositions)h=!0;else if(1<Math.abs(f)){n&&n.forEach(function(a){a.setState()});if(0>f){n=x;var e=g.ordinalPositions?g:x}else n=g.ordinalPositions?g:x,e=x;x=e.ordinalPositions;b>x[x.length-1]&&x.push(b);this.fixedRange=l-a;f=g.toFixedRange(null,null,t.apply(n,[r.apply(n,[a,!0])+f,!0]),t.apply(e,[r.apply(e,[l,!0])+f,!0]));f.min>=Math.min(c.dataMin,a)&&f.max<=Math.max(b,l)+m&&g.setExtremes(f.min,f.max,!0,!1, {trigger:"pan"});this.mouseDownX=q;v(this.container,{cursor:"move"})}}else h=!0;h||p&&/y/.test(p.type)?m&&(g.max=g.dataMax+m):d.preventDefault()});g(D,"foundExtremes",function(){this.isXAxis&&y(this.options.overscroll)&&this.max===this.dataMax&&(!this.chart.mouseIsDown||this.isInternal)&&(!this.eventArgs||this.eventArgs&&"navigator"!==this.eventArgs.trigger)&&(this.max+=this.options.overscroll,!this.isInternal&&y(this.userMin)&&(this.min+=this.options.overscroll))});g(D,"afterSetScale",function(){this.horiz&& !this.isDirty&&(this.isDirty=this.isOrdinal&&this.chart.navigator&&!this.chart.navigator.adaptToUpdatedData)})});K(y,"modules/broken-axis.src.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.extend,F=g.isArray,E=g.pick;g=d.addEvent;var D=d.find,x=d.fireEvent,v=d.Axis,C=d.Series,B=function(d,g){return D(g,function(g){return g.from<d&&d<g.to})};y(v.prototype,{isInBreak:function(d,g){var m=d.repeat||Infinity,q=d.from,p=d.to-d.from;g=g>=q?(g-q)%m:m-(q-g)%m;return d.inclusive? g<=p:g<p&&0!==g},isInAnyBreak:function(d,g){var m=this.options.breaks,q=m&&m.length,p;if(q){for(;q--;)if(this.isInBreak(m[q],d)){var h=!0;p||(p=E(m[q].showPoints,!this.isXAxis))}var f=h&&g?h&&!p:h}return f}});g(v,"afterInit",function(){"function"===typeof this.setBreaks&&this.setBreaks(this.options.breaks,!1)});g(v,"afterSetTickPositions",function(){if(this.isBroken){var d=this.tickPositions,g=this.tickPositions.info,m=[],q;for(q=0;q<d.length;q++)this.isInAnyBreak(d[q])||m.push(d[q]);this.tickPositions= m;this.tickPositions.info=g}});g(v,"afterSetOptions",function(){this.isBroken&&(this.options.ordinal=!1)});v.prototype.setBreaks=function(d,g){function m(d){var c=d,b;for(b=0;b<p.breakArray.length;b++){var a=p.breakArray[b];if(a.to<=d)c-=a.len;else if(a.from>=d)break;else if(p.isInBreak(a,d)){c-=d-a.from;break}}return c}function q(d){var c;for(c=0;c<p.breakArray.length;c++){var b=p.breakArray[c];if(b.from>=d)break;else b.to<d?d+=b.len:p.isInBreak(b,d)&&(d+=b.len)}return d}var p=this,h=F(d)&&!!d.length; p.isDirty=p.isBroken!==h;p.isBroken=h;p.options.breaks=p.userOptions.breaks=d;p.forceRedraw=!0;p.series.forEach(function(d){d.isDirty=!0});h||p.val2lin!==m||(delete p.val2lin,delete p.lin2val);h&&(p.userOptions.ordinal=!1,p.val2lin=m,p.lin2val=q,p.setExtremes=function(d,c,b,a,g){if(this.isBroken){for(var f,h=this.options.breaks;f=B(d,h);)d=f.to;for(;f=B(c,h);)c=f.from;c<d&&(c=d)}v.prototype.setExtremes.call(this,d,c,b,a,g)},p.setAxisTranslation=function(d){v.prototype.setAxisTranslation.call(this, d);this.unitLength=null;if(this.isBroken){d=p.options.breaks;var c=[],b=[],a=0,f,g=p.userMin||p.min,h=p.userMax||p.max,m=E(p.pointRangePadding,0),r;d.forEach(function(a){f=a.repeat||Infinity;p.isInBreak(a,g)&&(g+=a.to%f-g%f);p.isInBreak(a,h)&&(h-=h%f-a.from%f)});d.forEach(function(a){k=a.from;for(f=a.repeat||Infinity;k-f>g;)k-=f;for(;k<g;)k+=f;for(r=k;r<h;r+=f)c.push({value:r,move:"in"}),c.push({value:r+(a.to-a.from),move:"out",size:a.breakSize})});c.sort(function(a,b){return a.value===b.value?("in"=== a.move?0:1)-("in"===b.move?0:1):a.value-b.value});var e=0;var k=g;c.forEach(function(c){e+="in"===c.move?1:-1;1===e&&"in"===c.move&&(k=c.value);0===e&&(b.push({from:k,to:c.value,len:c.value-k-(c.size||0)}),a+=c.value-k-(c.size||0))});p.breakArray=b;p.unitLength=h-g-a+m;x(p,"afterBreaks");p.staticScale?p.transA=p.staticScale:p.unitLength&&(p.transA*=(h-p.min+m)/p.unitLength);m&&(p.minPixelPadding=p.transA*p.minPointOffset);p.min=g;p.max=h}});E(g,!0)&&this.chart.redraw()};g(C,"afterGeneratePoints", function(){var d=this.options.connectNulls,g=this.points,m=this.xAxis,q=this.yAxis;if(this.isDirty)for(var v=g.length;v--;){var h=g[v],f=!(null===h.y&&!1===d)&&(m&&m.isInAnyBreak(h.x,!0)||q&&q.isInAnyBreak(h.y,!0));h.visible=f?!1:!1!==h.options.visible}});g(C,"afterRender",function(){this.drawBreaks(this.xAxis,["x"]);this.drawBreaks(this.yAxis,E(this.pointArrayMap,["y"]))});d.Series.prototype.drawBreaks=function(d,g){var m=this,p=m.points,v,h,f,c;d&&g.forEach(function(b){v=d.breakArray||[];h=d.isXAxis? d.min:E(m.options.threshold,d.min);p.forEach(function(a){c=E(a["stack"+b.toUpperCase()],a[b]);v.forEach(function(b){f=!1;if(h<b.from&&c>b.to||h>b.from&&c<b.from)f="pointBreak";else if(h<b.from&&c>b.from&&c<b.to||h>b.from&&c>b.to&&c<b.from)f="pointInBreak";f&&x(d,f,{point:a,brk:b})})})})};d.Series.prototype.gappedPath=function(){var g=this.currentDataGrouping,v=g&&g.gapSize;g=this.options.gapSize;var m=this.points.slice(),q=m.length-1,w=this.yAxis,h;if(g&&0<q)for("value"!==this.options.gapUnit&&(g*= this.basePointRange),v&&v>g&&v>=this.basePointRange&&(g=v),h=void 0;q--;)h&&!1!==h.visible||(h=m[q+1]),v=m[q],!1!==h.visible&&!1!==v.visible&&(h.x-v.x>g&&(h=(v.x+h.x)/2,m.splice(q+1,0,{isNull:!0,x:h}),this.options.stacking&&(h=w.stacks[this.stackKey][h]=new d.StackItem(w,w.options.stackLabels,!1,h,this.stack),h.total=0)),h=v);return this.getGraphPath(m)}});K(y,"masters/modules/broken-axis.src.js",[],function(){});K(y,"parts/DataGrouping.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d, g){var y=g.arrayMax,F=g.arrayMin,E=g.correctFloat,D=g.defined,x=g.extend,v=g.isNumber,C=g.pick;g=d.addEvent;var B=d.Axis,p=d.defaultPlotOptions,z=d.format,m=d.merge,q=d.Point,w=d.Series,h=d.Tooltip,f=d.approximations={sum:function(a){var b=a.length;if(!b&&a.hasNulls)var e=null;else if(b)for(e=0;b--;)e+=a[b];return e},average:function(a){var b=a.length;a=f.sum(a);v(a)&&b&&(a=E(a/b));return a},averages:function(){var a=[];[].forEach.call(arguments,function(b){a.push(f.average(b))});return"undefined"=== typeof a[0]?void 0:a},open:function(a){return a.length?a[0]:a.hasNulls?null:void 0},high:function(a){return a.length?y(a):a.hasNulls?null:void 0},low:function(a){return a.length?F(a):a.hasNulls?null:void 0},close:function(a){return a.length?a[a.length-1]:a.hasNulls?null:void 0},ohlc:function(a,b,c,d){a=f.open(a);b=f.high(b);c=f.low(c);d=f.close(d);if(v(a)||v(b)||v(c)||v(d))return[a,b,c,d]},range:function(a,b){a=f.low(a);b=f.high(b);if(v(a)||v(b))return[a,b];if(null===a&&null===b)return null}},c=function(a, b,c,d){var e=this,g=e.data,h=e.options&&e.options.data,k=[],l=[],n=[],r=a.length,u=!!b,t=[],p=e.pointArrayMap,q=p&&p.length,w=["x"].concat(p||["y"]),x=0,z=0,y;d="function"===typeof d?d:f[d]?f[d]:f[e.getDGApproximation&&e.getDGApproximation()||"average"];q?p.forEach(function(){t.push([])}):t.push([]);var H=q||1;for(y=0;y<=r&&!(a[y]>=c[0]);y++);for(y;y<=r;y++){for(;"undefined"!==typeof c[x+1]&&a[y]>=c[x+1]||y===r;){var B=c[x];e.dataGroupInfo={start:e.cropStart+z,length:t[0].length};var C=d.apply(e, t);e.pointClass&&!D(e.dataGroupInfo.options)&&(e.dataGroupInfo.options=m(e.pointClass.prototype.optionsToObject.call({series:e},e.options.data[e.cropStart+z])),w.forEach(function(a){delete e.dataGroupInfo.options[a]}));"undefined"!==typeof C&&(k.push(B),l.push(C),n.push(e.dataGroupInfo));z=y;for(B=0;B<H;B++)t[B].length=0,t[B].hasNulls=!1;x+=1;if(y===r)break}if(y===r)break;if(p)for(B=e.cropStart+y,C=g&&g[B]||e.pointClass.prototype.applyOptions.apply({series:e},[h[B]]),B=0;B<q;B++){var E=C[p[B]];v(E)? t[B].push(E):null===E&&(t[B].hasNulls=!0)}else B=u?b[y]:null,v(B)?t[0].push(B):null===B&&(t[0].hasNulls=!0)}return{groupedXData:k,groupedYData:l,groupMap:n}},b={approximations:f,groupData:c},a=w.prototype,l=a.processData,n=a.generatePoints,t={groupPixelWidth:2,dateTimeLabelFormats:{millisecond:["%A, %b %e, %H:%M:%S.%L","%A, %b %e, %H:%M:%S.%L","-%H:%M:%S.%L"],second:["%A, %b %e, %H:%M:%S","%A, %b %e, %H:%M:%S","-%H:%M:%S"],minute:["%A, %b %e, %H:%M","%A, %b %e, %H:%M","-%H:%M"],hour:["%A, %b %e, %H:%M", "%A, %b %e, %H:%M","-%H:%M"],day:["%A, %b %e, %Y","%A, %b %e","-%A, %b %e, %Y"],week:["Week from %A, %b %e, %Y","%A, %b %e","-%A, %b %e, %Y"],month:["%B %Y","%B","-%B %Y"],year:["%Y","%Y","-%Y"]}},I={line:{},spline:{},area:{},areaspline:{},arearange:{},column:{groupPixelWidth:10},columnrange:{groupPixelWidth:10},candlestick:{groupPixelWidth:10},ohlc:{groupPixelWidth:5}},r=d.defaultDataGroupingUnits=[["millisecond",[1,2,5,10,20,25,50,100,200,500]],["second",[1,2,5,10,15,30]],["minute",[1,2,5,10,15, 30]],["hour",[1,2,3,4,6,8,12]],["day",[1]],["week",[1]],["month",[1,3,6]],["year",null]];a.getDGApproximation=function(){return d.seriesTypes.arearange&&this instanceof d.seriesTypes.arearange?"range":d.seriesTypes.ohlc&&this instanceof d.seriesTypes.ohlc?"ohlc":d.seriesTypes.column&&this instanceof d.seriesTypes.column?"sum":"average"};a.groupData=c;a.processData=function(){var b=this.chart,c=this.options.dataGrouping,d=!1!==this.allowDG&&c&&C(c.enabled,b.options.isStock),f=this.visible||!b.options.chart.ignoreHiddenSeries, g,h=this.currentDataGrouping,m=!1;this.forceCrop=d;this.groupPixelWidth=null;this.hasProcessed=!0;d&&!this.requireSorting&&(this.requireSorting=m=!0);d=!1===l.apply(this,arguments)||!d;m&&(this.requireSorting=!1);if(!d){this.destroyGroupedData();d=c.groupAll?this.xData:this.processedXData;var n=c.groupAll?this.yData:this.processedYData,t=b.plotSizeX;b=this.xAxis;var p=b.options.ordinal,q=this.groupPixelWidth=b.getGroupPixelWidth&&b.getGroupPixelWidth();if(q){this.isDirty=g=!0;this.points=null;m=b.getExtremes(); var v=m.min;m=m.max;p=p&&b.getGroupIntervalFactor(v,m,this)||1;q=q*(m-v)/t*p;t=b.getTimeTicks(b.normalizeTimeTickInterval(q,c.units||r),Math.min(v,d[0]),Math.max(m,d[d.length-1]),b.options.startOfWeek,d,this.closestPointRange);n=a.groupData.apply(this,[d,n,t,c.approximation]);d=n.groupedXData;p=n.groupedYData;var w=0;if(c.smoothed&&d.length){var x=d.length-1;for(d[x]=Math.min(d[x],m);x--&&0<x;)d[x]+=q/2;d[0]=Math.max(d[0],v)}for(x=1;x<t.length;x++)t.info.segmentStarts&&-1!==t.info.segmentStarts.indexOf(x)|| (w=Math.max(t[x]-t[x-1],w));v=t.info;v.gapSize=w;this.closestPointRange=t.info.totalRange;this.groupMap=n.groupMap;if(D(d[0])&&d[0]<b.min&&f){if(!D(b.options.min)&&b.min<=b.dataMin||b.min===b.dataMin)b.min=Math.min(d[0],b.min);b.dataMin=Math.min(d[0],b.dataMin)}c.groupAll&&(c=this.cropData(d,p,b.min,b.max,1),d=c.xData,p=c.yData);this.processedXData=d;this.processedYData=p}else this.groupMap=null;this.hasGroupedData=g;this.currentDataGrouping=v;this.preventGraphAnimation=(h&&h.totalRange)!==(v&&v.totalRange)}}; a.destroyGroupedData=function(){this.groupedData&&(this.groupedData.forEach(function(a,b){a&&(this.groupedData[b]=a.destroy?a.destroy():null)},this),this.groupedData.length=0)};a.generatePoints=function(){n.apply(this);this.destroyGroupedData();this.groupedData=this.hasGroupedData?this.points:null};g(q,"update",function(){if(this.dataGroup)return d.error(24,!1,this.series.chart),!1});g(h,"headerFormatter",function(a){var b=this.chart,c=b.time,e=a.labelConfig,d=e.series,f=d.tooltipOptions,g=d.options.dataGrouping, h=f.xDateFormat,l=d.xAxis,m=f[(a.isFooter?"footer":"header")+"Format"];if(l&&"datetime"===l.options.type&&g&&v(e.key)){var n=d.currentDataGrouping;g=g.dateTimeLabelFormats||t.dateTimeLabelFormats;if(n)if(f=g[n.unitName],1===n.count)h=f[0];else{h=f[1];var r=f[2]}else!h&&g&&(h=this.getXDateFormat(e,f,l));h=c.dateFormat(h,e.key);r&&(h+=c.dateFormat(r,e.key+n.totalRange-1));d.chart.styledMode&&(m=this.styledModeFormat(m));a.text=z(m,{point:x(e.point,{key:h}),series:d},b);a.preventDefault()}});g(w,"destroy", a.destroyGroupedData);g(w,"afterSetOptions",function(a){a=a.options;var b=this.type,c=this.chart.options.plotOptions,e=p[b].dataGrouping,d=this.useCommonDataGrouping&&t;if(I[b]||d)e||(e=m(t,I[b])),a.dataGrouping=m(d,e,c.series&&c.series.dataGrouping,c[b].dataGrouping,this.userOptions.dataGrouping)});g(B,"afterSetScale",function(){this.series.forEach(function(a){a.hasProcessed=!1})});B.prototype.getGroupPixelWidth=function(){var a=this.series,b=a.length,c,d=0,f=!1,g;for(c=b;c--;)(g=a[c].options.dataGrouping)&& (d=Math.max(d,C(g.groupPixelWidth,t.groupPixelWidth)));for(c=b;c--;)(g=a[c].options.dataGrouping)&&a[c].hasProcessed&&(b=(a[c].processedXData||a[c].data).length,a[c].groupPixelWidth||b>this.chart.plotSizeX/d||b&&g.forced)&&(f=!0);return f?d:0};B.prototype.setDataGrouping=function(a,b){var c;b=C(b,!0);a||(a={forced:!1,units:null});if(this instanceof B)for(c=this.series.length;c--;)this.series[c].update({dataGrouping:a},!1);else this.chart.options.series.forEach(function(b){b.dataGrouping=a},!1);this.ordinalSlope= null;b&&this.chart.redraw()};d.dataGrouping=b;"";return b});K(y,"parts/OHLCSeries.js",[y["parts/Globals.js"]],function(d){var g=d.Point,y=d.seriesType,F=d.seriesTypes;y("ohlc","column",{lineWidth:1,tooltip:{pointFormat:'<span style="color:{point.color}">\u25cf</span> <b> {series.name}</b><br/>Open: {point.open}<br/>High: {point.high}<br/>Low: {point.low}<br/>Close: {point.close}<br/>'},threshold:null,states:{hover:{lineWidth:3}},stickyTracking:!0},{directTouch:!1,pointArrayMap:["open","high","low", "close"],toYData:function(d){return[d.open,d.high,d.low,d.close]},pointValKey:"close",pointAttrToOptions:{stroke:"color","stroke-width":"lineWidth"},init:function(){F.column.prototype.init.apply(this,arguments);this.options.stacking=!1},pointAttribs:function(d,g){g=F.column.prototype.pointAttribs.call(this,d,g);var x=this.options;delete g.fill;!d.options.color&&x.upColor&&d.open<d.close&&(g.stroke=x.upColor);return g},translate:function(){var d=this,g=d.yAxis,x=!!d.modifyValue,v=["plotOpen","plotHigh", "plotLow","plotClose","yBottom"];F.column.prototype.translate.apply(d);d.points.forEach(function(y){[y.open,y.high,y.low,y.close,y.low].forEach(function(B,p){null!==B&&(x&&(B=d.modifyValue(B)),y[v[p]]=g.toPixels(B,!0))});y.tooltipPos[1]=y.plotHigh+g.pos-d.chart.plotTop})},drawPoints:function(){var d=this,g=d.chart;d.points.forEach(function(x){var v=x.graphic,y=!v;if("undefined"!==typeof x.plotY){v||(x.graphic=v=g.renderer.path().add(d.group));g.styledMode||v.attr(d.pointAttribs(x,x.selected&&"select")); var B=v.strokeWidth()%2/2;var p=Math.round(x.plotX)-B;var z=Math.round(x.shapeArgs.width/2);var m=["M",p,Math.round(x.yBottom),"L",p,Math.round(x.plotHigh)];if(null!==x.open){var q=Math.round(x.plotOpen)+B;m.push("M",p,q,"L",p-z,q)}null!==x.close&&(q=Math.round(x.plotClose)+B,m.push("M",p,q,"L",p+z,q));v[y?"attr":"animate"]({d:m}).addClass(x.getClassName(),!0)}})},animate:null},{getClassName:function(){return g.prototype.getClassName.call(this)+(this.open<this.close?" highcharts-point-up":" highcharts-point-down")}}); ""});K(y,"parts/CandlestickSeries.js",[y["parts/Globals.js"]],function(d){var g=d.defaultPlotOptions,y=d.merge,F=d.seriesType,E=d.seriesTypes;F("candlestick","ohlc",y(g.column,{states:{hover:{lineWidth:2}},tooltip:g.ohlc.tooltip,threshold:null,lineColor:"#000000",lineWidth:1,upColor:"#ffffff",stickyTracking:!0}),{pointAttribs:function(d,g){var v=E.column.prototype.pointAttribs.call(this,d,g),x=this.options,y=d.open<d.close,p=x.lineColor||this.color;v["stroke-width"]=x.lineWidth;v.fill=d.options.color|| (y?x.upColor||this.color:this.color);v.stroke=d.options.lineColor||(y?x.upLineColor||p:p);g&&(d=x.states[g],v.fill=d.color||v.fill,v.stroke=d.lineColor||v.stroke,v["stroke-width"]=d.lineWidth||v["stroke-width"]);return v},drawPoints:function(){var d=this,g=d.chart,v=d.yAxis.reversed;d.points.forEach(function(x){var y=x.graphic,p=!y;if("undefined"!==typeof x.plotY){y||(x.graphic=y=g.renderer.path().add(d.group));d.chart.styledMode||y.attr(d.pointAttribs(x,x.selected&&"select")).shadow(d.options.shadow); var z=y.strokeWidth()%2/2;var m=Math.round(x.plotX)-z;var q=x.plotOpen;var w=x.plotClose;var h=Math.min(q,w);q=Math.max(q,w);var f=Math.round(x.shapeArgs.width/2);w=v?q!==x.yBottom:Math.round(h)!==Math.round(x.plotHigh);var c=v?Math.round(h)!==Math.round(x.plotHigh):q!==x.yBottom;h=Math.round(h)+z;q=Math.round(q)+z;z=[];z.push("M",m-f,q,"L",m-f,h,"L",m+f,h,"L",m+f,q,"Z","M",m,h,"L",m,w?Math.round(v?x.yBottom:x.plotHigh):h,"M",m,q,"L",m,c?Math.round(v?x.plotHigh:x.yBottom):q);y[p?"attr":"animate"]({d:z}).addClass(x.getClassName(), !0)}})}});""});K(y,"mixins/on-series.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.defined,F=d.seriesTypes,E=d.stableSort;return{getPlotBox:function(){return d.Series.prototype.getPlotBox.call(this.options.onSeries&&this.chart.get(this.options.onSeries)||this)},translate:function(){F.column.prototype.translate.apply(this);var d=this,g=d.options,v=d.chart,C=d.points,B=C.length-1,p,z=g.onSeries;z=z&&v.get(z);g=g.onKey||"y";var m=z&&z.options.step,q=z&&z.points,w=q&&q.length, h=v.inverted,f=d.xAxis,c=d.yAxis,b=0,a;if(z&&z.visible&&w){b=(z.pointXOffset||0)+(z.barW||0)/2;v=z.currentDataGrouping;var l=q[w-1].x+(v?v.totalRange:0);E(C,function(a,b){return a.x-b.x});for(g="plot"+g[0].toUpperCase()+g.substr(1);w--&&C[B];){var n=q[w];v=C[B];v.y=n.y;if(n.x<=v.x&&"undefined"!==typeof n[g]){if(v.x<=l&&(v.plotY=n[g],n.x<v.x&&!m&&(a=q[w+1])&&"undefined"!==typeof a[g])){var t=(v.x-n.x)/(a.x-n.x);v.plotY+=t*(a[g]-n[g]);v.y+=t*(a.y-n.y)}B--;w++;if(0>B)break}}}C.forEach(function(a,g){a.plotX+= b;if("undefined"===typeof a.plotY||h)0<=a.plotX&&a.plotX<=f.len?h?(a.plotY=f.translate(a.x,0,1,0,1),a.plotX=y(a.y)?c.translate(a.y,0,0,0,1):0):a.plotY=(f.opposite?0:d.yAxis.len)+f.offset:a.shapeArgs={};if((p=C[g-1])&&p.plotX===a.plotX){"undefined"===typeof p.stackIndex&&(p.stackIndex=0);var e=p.stackIndex+1}a.stackIndex=e});this.onSeries=z}}});K(y,"parts/FlagsSeries.js",[y["parts/Globals.js"],y["parts/Utilities.js"],y["mixins/on-series.js"]],function(d,g,y){function F(d){h[d+"pin"]=function(c,b,a, f,g){var l=g&&g.anchorX;g=g&&g.anchorY;"circle"===d&&f>a&&(c-=Math.round((f-a)/2),a=f);var m=h[d](c,b,a,f);l&&g&&(m.push("M","circle"===d?c+a/2:m[1]+m[4]/2,b>g?b:b+f,"L",l,g),m=m.concat(h.circle(l-1,g-1,2,2)));return m}}var E=g.defined,D=g.isNumber,x=g.objectEach,v=g.wrap,C=d.addEvent,B=d.merge;g=d.noop;var p=d.Renderer,z=d.Series,m=d.seriesType,q=d.TrackerMixin,w=d.VMLRenderer,h=d.SVGRenderer.prototype.symbols;m("flags","column",{pointRange:0,allowOverlapX:!1,shape:"flag",stackDistance:12,textAlign:"center", tooltip:{pointFormat:"{point.text}<br/>"},threshold:null,y:-30,fillColor:"#ffffff",lineWidth:1,states:{hover:{lineColor:"#000000",fillColor:"#ccd6eb"}},style:{fontSize:"11px",fontWeight:"bold"}},{sorted:!1,noSharedTooltip:!0,allowDG:!1,takeOrdinalPosition:!1,trackerGroups:["markerGroup"],forceCrop:!0,init:z.prototype.init,pointAttribs:function(d,c){var b=this.options,a=d&&d.color||this.color,f=b.lineColor,g=d&&d.lineWidth;d=d&&d.fillColor||b.fillColor;c&&(d=b.states[c].fillColor,f=b.states[c].lineColor, g=b.states[c].lineWidth);return{fill:d||a,stroke:f||a,"stroke-width":g||b.lineWidth||0}},translate:y.translate,getPlotBox:y.getPlotBox,drawPoints:function(){var f=this.points,c=this.chart,b=c.renderer,a=c.inverted,g=this.options,h=g.y,m,p=this.yAxis,r={},e=[];for(m=f.length;m--;){var k=f[m];var u=(a?k.plotY:k.plotX)>this.xAxis.len;var q=k.plotX;var w=k.stackIndex;var A=k.options.shape||g.shape;var z=k.plotY;"undefined"!==typeof z&&(z=k.plotY+h-("undefined"!==typeof w&&w*g.stackDistance));k.anchorX= w?void 0:k.plotX;var y=w?void 0:k.plotY;var C="flag"!==A;w=k.graphic;"undefined"!==typeof z&&0<=q&&!u?(w||(w=k.graphic=b.label("",null,null,A,null,null,g.useHTML),c.styledMode||w.attr(this.pointAttribs(k)).css(B(g.style,k.style)),w.attr({align:C?"center":"left",width:g.width,height:g.height,"text-align":g.textAlign}).addClass("highcharts-point").add(this.markerGroup),k.graphic.div&&(k.graphic.div.point=k),c.styledMode||w.shadow(g.shadow),w.isNew=!0),0<q&&(q-=w.strokeWidth()%2),A={y:z,anchorY:y},g.allowOverlapX&& (A.x=q,A.anchorX=k.anchorX),w.attr({text:k.options.title||g.title||"A"})[w.isNew?"attr":"animate"](A),g.allowOverlapX||(r[k.plotX]?r[k.plotX].size=Math.max(r[k.plotX].size,w.width):r[k.plotX]={align:C?.5:0,size:w.width,target:q,anchorX:q}),k.tooltipPos=[q,z+p.pos-c.plotTop]):w&&(k.graphic=w.destroy())}g.allowOverlapX||(x(r,function(a){a.plotX=a.anchorX;e.push(a)}),d.distribute(e,a?p.len:this.xAxis.len,100),f.forEach(function(a){var b=a.graphic&&r[a.plotX];b&&(a.graphic[a.graphic.isNew?"attr":"animate"]({x:b.pos+ b.align*b.size,anchorX:a.anchorX}),E(b.pos)?a.graphic.isNew=!1:(a.graphic.attr({x:-9999,anchorX:-9999}),a.graphic.isNew=!0))}));g.useHTML&&v(this.markerGroup,"on",function(a){return d.SVGElement.prototype.on.apply(a.apply(this,[].slice.call(arguments,1)),[].slice.call(arguments,1))})},drawTracker:function(){var d=this.points;q.drawTrackerPoint.apply(this);d.forEach(function(c){var b=c.graphic;b&&C(b.element,"mouseover",function(){0<c.stackIndex&&!c.raised&&(c._y=b.y,b.attr({y:c._y-8}),c.raised=!0); d.forEach(function(a){a!==c&&a.raised&&a.graphic&&(a.graphic.attr({y:a._y}),a.raised=!1)})})})},animate:function(d){d?this.setClip():this.animate=null},setClip:function(){z.prototype.setClip.apply(this,arguments);!1!==this.options.clip&&this.sharedClipKey&&this.markerGroup.clip(this.chart[this.sharedClipKey])},buildKDTree:g,invertGroups:g},{isValid:function(){return D(this.y)||"undefined"===typeof this.y}});h.flag=function(d,c,b,a,g){var f=g&&g.anchorX||d;g=g&&g.anchorY||c;return h.circle(f-1,g-1, 2,2).concat(["M",f,g,"L",d,c+a,d,c,d+b,c,d+b,c+a,d,c+a,"Z"])};F("circle");F("square");p===w&&["circlepin","flag","squarepin"].forEach(function(d){w.prototype.symbols[d]=h[d]});""});K(y,"parts/RangeSelector.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){function y(a){this.init(a)}var F=g.defined,E=g.destroyObjectProperties,D=g.discardElement,x=g.extend,v=g.isNumber,C=g.objectEach,B=g.pick,p=g.pInt,z=g.splat,m=d.addEvent,q=d.Axis;g=d.Chart;var w=d.css,h=d.createElement,f=d.defaultOptions, c=d.fireEvent,b=d.merge;x(f,{rangeSelector:{verticalAlign:"top",buttonTheme:{width:28,height:18,padding:2,zIndex:7},floating:!1,x:0,y:0,height:void 0,inputPosition:{align:"right",x:0,y:0},buttonPosition:{align:"left",x:0,y:0},labelStyle:{color:"#666666"}}});f.lang=b(f.lang,{rangeSelectorZoom:"Zoom",rangeSelectorFrom:"From",rangeSelectorTo:"To"});y.prototype={clickButton:function(a,b){var c=this.chart,d=this.buttonOptions[a],f=c.xAxis[0],g=c.scroller&&c.scroller.getUnionExtremes()||f||{},e=g.dataMin, h=g.dataMax,l=f&&Math.round(Math.min(f.max,B(h,f.max))),p=d.type;g=d._range;var w,A=d.dataGrouping;if(null!==e&&null!==h){c.fixedRange=g;A&&(this.forcedDataGrouping=!0,q.prototype.setDataGrouping.call(f||{chart:this.chart},A,!1),this.frozenStates=d.preserveDataGrouping);if("month"===p||"year"===p)if(f){p={range:d,max:l,chart:c,dataMin:e,dataMax:h};var x=f.minFromRange.call(p);v(p.newMax)&&(l=p.newMax)}else g=d;else if(g)x=Math.max(l-g,e),l=Math.min(x+g,h);else if("ytd"===p)if(f)"undefined"===typeof h&& (e=Number.MAX_VALUE,h=Number.MIN_VALUE,c.series.forEach(function(a){a=a.xData;e=Math.min(a[0],e);h=Math.max(a[a.length-1],h)}),b=!1),l=this.getYTDExtremes(h,e,c.time.useUTC),x=w=l.min,l=l.max;else{this.deferredYTDClick=a;return}else"all"===p&&f&&(x=e,l=h);x+=d._offsetMin;l+=d._offsetMax;this.setSelected(a);if(f)f.setExtremes(x,l,B(b,1),null,{trigger:"rangeSelectorButton",rangeSelectorButton:d});else{var y=z(c.options.xAxis)[0];var C=y.range;y.range=g;var D=y.min;y.min=w;m(c,"load",function(){y.range= C;y.min=D})}}},setSelected:function(a){this.selected=this.options.selected=a},defaultButtons:[{type:"month",count:1,text:"1m"},{type:"month",count:3,text:"3m"},{type:"month",count:6,text:"6m"},{type:"ytd",text:"YTD"},{type:"year",count:1,text:"1y"},{type:"all",text:"All"}],init:function(a){var b=this,d=a.options.rangeSelector,f=d.buttons||[].concat(b.defaultButtons),g=d.selected,h=function(){var a=b.minInput,d=b.maxInput;a&&a.blur&&c(a,"blur");d&&d.blur&&c(d,"blur")};b.chart=a;b.options=d;b.buttons= [];b.buttonOptions=f;this.unMouseDown=m(a.container,"mousedown",h);this.unResize=m(a,"resize",h);f.forEach(b.computeButtonRange);"undefined"!==typeof g&&f[g]&&this.clickButton(g,!1);m(a,"load",function(){a.xAxis&&a.xAxis[0]&&m(a.xAxis[0],"setExtremes",function(c){this.max-this.min!==a.fixedRange&&"rangeSelectorButton"!==c.trigger&&"updatedData"!==c.trigger&&b.forcedDataGrouping&&!b.frozenStates&&this.setDataGrouping(!1,!1)})})},updateButtonStates:function(){var a=this,b=this.chart,c=b.xAxis[0],d= Math.round(c.max-c.min),f=!c.hasVisibleSeries,g=b.scroller&&b.scroller.getUnionExtremes()||c,e=g.dataMin,h=g.dataMax;b=a.getYTDExtremes(h,e,b.time.useUTC);var m=b.min,p=b.max,q=a.selected,w=v(q),x=a.options.allButtonsEnabled,z=a.buttons;a.buttonOptions.forEach(function(b,g){var k=b._range,l=b.type,n=b.count||1,r=z[g],t=0,u=b._offsetMax-b._offsetMin;b=g===q;var v=k>h-e,A=k<c.minRange,y=!1,B=!1;k=k===d;("month"===l||"year"===l)&&d+36E5>=864E5*{month:28,year:365}[l]*n-u&&d-36E5<=864E5*{month:31,year:366}[l]* n+u?k=!0:"ytd"===l?(k=p-m+u===d,y=!b):"all"===l&&(k=c.max-c.min>=h-e,B=!b&&w&&k);l=!x&&(v||A||B||f);n=b&&k||k&&!w&&!y||b&&a.frozenStates;l?t=3:n&&(w=!0,t=2);r.state!==t&&(r.setState(t),0===t&&q===g&&a.setSelected(null))})},computeButtonRange:function(a){var b=a.type,c=a.count||1,d={millisecond:1,second:1E3,minute:6E4,hour:36E5,day:864E5,week:6048E5};if(d[b])a._range=d[b]*c;else if("month"===b||"year"===b)a._range=864E5*{month:30,year:365}[b]*c;a._offsetMin=B(a.offsetMin,0);a._offsetMax=B(a.offsetMax, 0);a._range+=a._offsetMax-a._offsetMin},setInputValue:function(a,b){var c=this.chart.options.rangeSelector,d=this.chart.time,f=this[a+"Input"];F(b)&&(f.previousValue=f.HCTime,f.HCTime=b);f.value=d.dateFormat(c.inputEditDateFormat||"%Y-%m-%d",f.HCTime);this[a+"DateBox"].attr({text:d.dateFormat(c.inputDateFormat||"%b %e, %Y",f.HCTime)})},showInput:function(a){var b=this.inputGroup,c=this[a+"DateBox"];w(this[a+"Input"],{left:b.translateX+c.x+"px",top:b.translateY+"px",width:c.width-2+"px",height:c.height- 2+"px",border:"2px solid silver"})},hideInput:function(a){w(this[a+"Input"],{border:0,width:"1px",height:"1px"});this.setInputValue(a)},drawInput:function(a){function c(){var a=y.value,b=(e.inputDateParser||Date.parse)(a),c=m.xAxis[0],d=m.scroller&&m.scroller.xAxis?m.scroller.xAxis:c,f=d.dataMin;d=d.dataMax;b!==y.previousValue&&(y.previousValue=b,v(b)||(b=a.split("-"),b=Date.UTC(p(b[0]),p(b[1])-1,p(b[2]))),v(b)&&(m.time.useUTC||(b+=6E4*(new Date).getTimezoneOffset()),u?b>g.maxInput.HCTime?b=void 0: b<f&&(b=f):b<g.minInput.HCTime?b=void 0:b>d&&(b=d),"undefined"!==typeof b&&c.setExtremes(u?b:c.min,u?c.max:b,void 0,void 0,{trigger:"rangeSelectorInput"})))}var g=this,m=g.chart,q=m.renderer.style||{},r=m.renderer,e=m.options.rangeSelector,k=g.div,u="min"===a,y,z,A=this.inputGroup;this[a+"Label"]=z=r.label(f.lang[u?"rangeSelectorFrom":"rangeSelectorTo"],this.inputGroup.offset).addClass("highcharts-range-label").attr({padding:2}).add(A);A.offset+=z.width+5;this[a+"DateBox"]=r=r.label("",A.offset).addClass("highcharts-range-input").attr({padding:2, width:e.inputBoxWidth||90,height:e.inputBoxHeight||17,"text-align":"center"}).on("click",function(){g.showInput(a);g[a+"Input"].focus()});m.styledMode||r.attr({stroke:e.inputBoxBorderColor||"#cccccc","stroke-width":1});r.add(A);A.offset+=r.width+(u?10:0);this[a+"Input"]=y=h("input",{name:a,className:"highcharts-range-selector",type:"text"},{top:m.plotTop+"px"},k);m.styledMode||(z.css(b(q,e.labelStyle)),r.css(b({color:"#333333"},q,e.inputStyle)),w(y,x({position:"absolute",border:0,width:"1px",height:"1px", padding:0,textAlign:"center",fontSize:q.fontSize,fontFamily:q.fontFamily,top:"-9999em"},e.inputStyle)));y.onfocus=function(){g.showInput(a)};y.onblur=function(){y===d.doc.activeElement&&c();g.hideInput(a);y.blur()};y.onchange=c;y.onkeypress=function(a){13===a.keyCode&&c()}},getPosition:function(){var a=this.chart,b=a.options.rangeSelector;a="top"===b.verticalAlign?a.plotTop-a.axisOffset[0]:0;return{buttonTop:a+b.buttonPosition.y,inputTop:a+b.inputPosition.y-10}},getYTDExtremes:function(a,b,c){var d= this.chart.time,f=new d.Date(a),g=d.get("FullYear",f);c=c?d.Date.UTC(g,0,1):+new d.Date(g,0,1);b=Math.max(b||0,c);f=f.getTime();return{max:Math.min(a||f,f),min:b}},render:function(a,b){var c=this,d=c.chart,g=d.renderer,l=d.container,e=d.options,k=e.exporting&&!1!==e.exporting.enabled&&e.navigation&&e.navigation.buttonOptions,m=f.lang,p=c.div,q=e.rangeSelector,v=B(e.chart.style&&e.chart.style.zIndex,0)+1;e=q.floating;var w=c.buttons;p=c.inputGroup;var x=q.buttonTheme,y=q.buttonPosition,z=q.inputPosition, C=q.inputEnabled,D=x&&x.states,E=d.plotLeft,F=c.buttonGroup;var K=c.rendered;var M=c.options.verticalAlign,T=d.legend,Z=T&&T.options,S=y.y,R=z.y,X=K||!1,fa=X?"animate":"attr",aa=0,W=0,Y;if(!1!==q.enabled){K||(c.group=K=g.g("range-selector-group").attr({zIndex:7}).add(),c.buttonGroup=F=g.g("range-selector-buttons").add(K),c.zoomText=g.text(m.rangeSelectorZoom,0,15).add(F),d.styledMode||(c.zoomText.css(q.labelStyle),x["stroke-width"]=B(x["stroke-width"],0)),c.buttonOptions.forEach(function(a,b){w[b]= g.button(a.text,0,0,function(d){var e=a.events&&a.events.click,f;e&&(f=e.call(a,d));!1!==f&&c.clickButton(b);c.isActive=!0},x,D&&D.hover,D&&D.select,D&&D.disabled).attr({"text-align":"center"}).add(F)}),!1!==C&&(c.div=p=h("div",null,{position:"relative",height:0,zIndex:v}),l.parentNode.insertBefore(p,l),c.inputGroup=p=g.g("input-group").add(K),p.offset=0,c.drawInput("min"),c.drawInput("max")));c.zoomText[fa]({x:B(E+y.x,E)});var ea=B(E+y.x,E)+c.zoomText.getBBox().width+5;c.buttonOptions.forEach(function(a, b){w[b][fa]({x:ea});ea+=w[b].width+B(q.buttonSpacing,5)});E=d.plotLeft-d.spacing[3];c.updateButtonStates();k&&this.titleCollision(d)&&"top"===M&&"right"===y.align&&y.y+F.getBBox().height-12<(k.y||0)+k.height&&(aa=-40);"left"===y.align?Y=y.x-d.spacing[3]:"right"===y.align&&(Y=y.x+aa-d.spacing[1]);F.align({y:y.y,width:F.getBBox().width,align:y.align,x:Y},!0,d.spacingBox);c.group.placed=X;c.buttonGroup.placed=X;!1!==C&&(aa=k&&this.titleCollision(d)&&"top"===M&&"right"===z.align&&z.y-p.getBBox().height- 12<(k.y||0)+k.height+d.spacing[0]?-40:0,"left"===z.align?Y=E:"right"===z.align&&(Y=-Math.max(d.axisOffset[1],-aa)),p.align({y:z.y,width:p.getBBox().width,align:z.align,x:z.x+Y-2},!0,d.spacingBox),l=p.alignAttr.translateX+p.alignOptions.x-aa+p.getBBox().x+2,k=p.alignOptions.width,m=F.alignAttr.translateX+F.getBBox().x,Y=F.getBBox().width+20,(z.align===y.align||m+Y>l&&l+k>m&&S<R+p.getBBox().height)&&p.attr({translateX:p.alignAttr.translateX+(d.axisOffset[1]>=-aa?0:-aa),translateY:p.alignAttr.translateY+ F.getBBox().height+10}),c.setInputValue("min",a),c.setInputValue("max",b),c.inputGroup.placed=X);c.group.align({verticalAlign:M},!0,d.spacingBox);a=c.group.getBBox().height+20;b=c.group.alignAttr.translateY;"bottom"===M&&(T=Z&&"bottom"===Z.verticalAlign&&Z.enabled&&!Z.floating?T.legendHeight+B(Z.margin,10):0,a=a+T-20,W=b-a-(e?0:q.y)-(d.titleOffset?d.titleOffset[2]:0)-10);if("top"===M)e&&(W=0),d.titleOffset&&d.titleOffset[0]&&(W=d.titleOffset[0]),W+=d.margin[0]-d.spacing[0]||0;else if("middle"===M)if(R=== S)W=0>R?b+void 0:b;else if(R||S)W=0>R||0>S?W-Math.min(R,S):b-a+NaN;c.group.translate(q.x,q.y+Math.floor(W));!1!==C&&(c.minInput.style.marginTop=c.group.translateY+"px",c.maxInput.style.marginTop=c.group.translateY+"px");c.rendered=!0}},getHeight:function(){var a=this.options,b=this.group,c=a.y,d=a.buttonPosition.y,f=a.inputPosition.y;if(a.height)return a.height;a=b?b.getBBox(!0).height+13+c:0;b=Math.min(f,d);if(0>f&&0>d||0<f&&0<d)a+=Math.abs(b);return a},titleCollision:function(a){return!(a.options.title.text|| a.options.subtitle.text)},update:function(a){var c=this.chart;b(!0,c.options.rangeSelector,a);this.destroy();this.init(c);c.rangeSelector.render()},destroy:function(){var a=this,b=a.minInput,c=a.maxInput;a.unMouseDown();a.unResize();E(a.buttons);b&&(b.onfocus=b.onblur=b.onchange=null);c&&(c.onfocus=c.onblur=c.onchange=null);C(a,function(b,c){b&&"chart"!==c&&(b.destroy?b.destroy():b.nodeType&&D(this[c]));b!==y.prototype[c]&&(a[c]=null)},this)}};q.prototype.minFromRange=function(){var a=this.range, b={month:"Month",year:"FullYear"}[a.type],c=this.max,d=this.chart.time,f=function(a,c){var e=new d.Date(a),f=d.get(b,e);d.set(b,e,f+c);f===d.get(b,e)&&d.set("Date",e,0);return e.getTime()-a};if(v(a)){var g=c-a;var e=a}else g=c+f(c,-a.count),this.chart&&(this.chart.fixedRange=c-g);var h=B(this.dataMin,Number.MIN_VALUE);v(g)||(g=h);g<=h&&(g=h,"undefined"===typeof e&&(e=f(g,a.count)),this.newMax=Math.min(g+e,this.dataMax));v(c)||(g=void 0);return g};d.RangeSelector||(m(g,"afterGetContainer",function(){this.options.rangeSelector.enabled&& (this.rangeSelector=new y(this))}),m(g,"beforeRender",function(){var a=this.axes,b=this.rangeSelector;b&&(v(b.deferredYTDClick)&&(b.clickButton(b.deferredYTDClick),delete b.deferredYTDClick),a.forEach(function(a){a.updateNames();a.setScale()}),this.getAxisMargins(),b.render(),a=b.options.verticalAlign,b.options.floating||("bottom"===a?this.extraBottomMargin=!0:"middle"!==a&&(this.extraTopMargin=!0)))}),m(g,"update",function(a){var b=a.options.rangeSelector;a=this.rangeSelector;var c=this.extraBottomMargin, d=this.extraTopMargin;b&&b.enabled&&!F(a)&&(this.options.rangeSelector.enabled=!0,this.rangeSelector=new y(this));this.extraTopMargin=this.extraBottomMargin=!1;a&&(a.render(),b=b&&b.verticalAlign||a.options&&a.options.verticalAlign,a.options.floating||("bottom"===b?this.extraBottomMargin=!0:"middle"!==b&&(this.extraTopMargin=!0)),this.extraBottomMargin!==c||this.extraTopMargin!==d)&&(this.isDirtyBox=!0)}),m(g,"render",function(){var a=this.rangeSelector;a&&!a.options.floating&&(a.render(),a=a.options.verticalAlign, "bottom"===a?this.extraBottomMargin=!0:"middle"!==a&&(this.extraTopMargin=!0))}),m(g,"getMargins",function(){var a=this.rangeSelector;a&&(a=a.getHeight(),this.extraTopMargin&&(this.plotTop+=a),this.extraBottomMargin&&(this.marginBottom+=a))}),g.prototype.callbacks.push(function(a){function b(){c=a.xAxis[0].getExtremes();v(c.min)&&d.render(c.min,c.max)}var c,d=a.rangeSelector;if(d){var f=m(a.xAxis[0],"afterSetExtremes",function(a){d.render(a.min,a.max)});var g=m(a,"redraw",b);b()}m(a,"destroy",function(){d&& (g(),f())})}),d.RangeSelector=y)});K(y,"parts/StockChart.js",[y["parts/Globals.js"],y["parts/Utilities.js"]],function(d,g){var y=g.arrayMax,F=g.arrayMin,E=g.clamp,D=g.defined,x=g.extend,v=g.isNumber,C=g.isString,B=g.pick,p=g.splat;g=d.addEvent;var z=d.Axis,m=d.Chart,q=d.format,w=d.merge,h=d.Point,f=d.Renderer,c=d.Series,b=d.SVGRenderer,a=d.VMLRenderer,l=c.prototype,n=l.init,t=l.processData,I=h.prototype.tooltipFormatter;d.StockChart=d.stockChart=function(a,b,c){var e=C(a)||a.nodeName,f=arguments[e? 1:0],g=f,h=f.series,k=d.getOptions(),l,r=f.chart&&f.chart.panning,n=B(f.navigator&&f.navigator.enabled,k.navigator.enabled,!0),q=r&&/y/.test(r.type),t={startOnTick:!1,endOnTick:!1};f.xAxis=p(f.xAxis||{}).map(function(a,b){return w({minPadding:0,maxPadding:0,overscroll:0,ordinal:!0,title:{text:null},labels:{overflow:"justify"},showLastLabel:!0},k.xAxis,k.xAxis&&k.xAxis[b],a,{type:"datetime",categories:null},n?t:null)});f.yAxis=p(f.yAxis||{}).map(function(a,b){l=B(a.opposite,!0);return w({labels:{y:-2}, opposite:l,showLastLabel:!(!a.categories&&"category"!==a.type),title:{text:null}},k.yAxis,k.yAxis&&k.yAxis[b],a,q?t:null)});f.series=null;f=w({chart:{panning:{enabled:!0,type:"x"},pinchType:"x"},navigator:{enabled:n},scrollbar:{enabled:B(k.scrollbar.enabled,!0)},rangeSelector:{enabled:B(k.rangeSelector.enabled,!0)},title:{text:null},tooltip:{split:B(k.tooltip.split,!0),crosshairs:!0},legend:{enabled:!1}},f,{isStock:!0});f.series=g.series=h;return e?new m(a,f,c):new m(f,b)};g(c,"setOptions",function(a){function b(a){return d.seriesTypes[a]&& c instanceof d.seriesTypes[a]}var c=this,f;this.chart.options.isStock&&(b("column")||b("columnrange")?f={borderWidth:0,shadow:!1}:!b("line")||b("scatter")||b("sma")||(f={marker:{enabled:!1,radius:2}}),f&&(a.plotOptions[this.type]=w(a.plotOptions[this.type],f)))});g(z,"autoLabelAlign",function(a){var b=this.chart,c=this.options;b=b._labelPanes=b._labelPanes||{};var d=this.options.labels;this.chart.options.isStock&&"yAxis"===this.coll&&(c=c.top+","+c.height,!b[c]&&d.enabled&&(15===d.x&&(d.x=0),"undefined"=== typeof d.align&&(d.align="right"),b[c]=this,a.align="right",a.preventDefault()))});g(z,"destroy",function(){var a=this.chart,b=this.options&&this.options.top+","+this.options.height;b&&a._labelPanes&&a._labelPanes[b]===this&&delete a._labelPanes[b]});g(z,"getPlotLinePath",function(a){function b(a){var b="xAxis"===a?"yAxis":"xAxis";a=c.options[b];return v(a)?[g[b][a]]:C(a)?[g.get(a)]:f.map(function(a){return a[b]})}var c=this,f=this.isLinked&&!this.series?this.linkedParent.series:this.series,g=c.chart, h=g.renderer,l=c.left,m=c.top,r,n,p,q,t=[],w=[],x=a.translatedValue,y=a.value,z=a.force;if(g.options.isStock&&!1!==a.acrossPanes&&"xAxis"===c.coll||"yAxis"===c.coll){a.preventDefault();w=b(c.coll);var F=c.isXAxis?g.yAxis:g.xAxis;F.forEach(function(a){if(D(a.options.id)?-1===a.options.id.indexOf("navigator"):1){var b=a.isXAxis?"yAxis":"xAxis";b=D(a.options[b])?g[b][a.options[b]]:g[b][0];c===b&&w.push(a)}});var I=w.length?[]:[c.isXAxis?g.yAxis[0]:g.xAxis[0]];w.forEach(function(a){-1!==I.indexOf(a)|| d.find(I,function(b){return b.pos===a.pos&&b.len===a.len})||I.push(a)});var K=B(x,c.translate(y,null,null,a.old));v(K)&&(c.horiz?I.forEach(function(a){var b;n=a.pos;q=n+a.len;r=p=Math.round(K+c.transB);"pass"!==z&&(r<l||r>l+c.width)&&(z?r=p=E(r,l,l+c.width):b=!0);b||t.push("M",r,n,"L",p,q)}):I.forEach(function(a){var b;r=a.pos;p=r+a.len;n=q=Math.round(m+c.height-K);"pass"!==z&&(n<m||n>m+c.height)&&(z?n=q=E(n,m,m+c.height):b=!0);b||t.push("M",r,n,"L",p,q)}));a.path=0<t.length?h.crispPolyLine(t,a.lineWidth|| 1):null}});b.prototype.crispPolyLine=function(a,b){var c;for(c=0;c<a.length;c+=6)a[c+1]===a[c+4]&&(a[c+1]=a[c+4]=Math.round(a[c+1])-b%2/2),a[c+2]===a[c+5]&&(a[c+2]=a[c+5]=Math.round(a[c+2])+b%2/2);return a};f===a&&(a.prototype.crispPolyLine=b.prototype.crispPolyLine);g(z,"afterHideCrosshair",function(){this.crossLabel&&(this.crossLabel=this.crossLabel.hide())});g(z,"afterDrawCrosshair",function(a){var b,c;if(D(this.crosshair.label)&&this.crosshair.label.enabled&&this.cross){var d=this.chart,f=this.options.crosshair.label, g=this.horiz,h=this.opposite,l=this.left,m=this.top,r=this.crossLabel,n=f.format,p="",t="inside"===this.options.tickPosition,v=!1!==this.crosshair.snap,w=0,y=a.e||this.cross&&this.cross.e,z=a.point;var C=this.lin2log;if(this.isLog){a=C(this.min);var E=C(this.max)}else a=this.min,E=this.max;C=g?"center":h?"right"===this.labelAlign?"right":"left":"left"===this.labelAlign?"left":"center";r||(r=this.crossLabel=d.renderer.label(null,null,null,f.shape||"callout").addClass("highcharts-crosshair-label"+(this.series[0]&& " highcharts-color-"+this.series[0].colorIndex)).attr({align:f.align||C,padding:B(f.padding,8),r:B(f.borderRadius,3),zIndex:2}).add(this.labelGroup),d.styledMode||r.attr({fill:f.backgroundColor||this.series[0]&&this.series[0].color||"#666666",stroke:f.borderColor||"","stroke-width":f.borderWidth||0}).css(x({color:"#ffffff",fontWeight:"normal",fontSize:"11px",textAlign:"center"},f.style)));g?(C=v?z.plotX+l:y.chartX,m+=h?0:this.height):(C=h?this.width+l:0,m=v?z.plotY+m:y.chartY);n||f.formatter||(this.isDatetimeAxis&& (p="%b %d, %Y"),n="{value"+(p?":"+p:"")+"}");p=v?z[this.isXAxis?"x":"y"]:this.toValue(g?y.chartX:y.chartY);r.attr({text:n?q(n,{value:p},d):f.formatter.call(this,p),x:C,y:m,visibility:p<a||p>E?"hidden":"visible"});f=r.getBBox();if(g){if(t&&!h||!t&&h)m=r.y-f.height}else m=r.y-f.height/2;g?(b=l-f.x,c=l+this.width-f.x):(b="left"===this.labelAlign?l:0,c="right"===this.labelAlign?l+this.width:d.chartWidth);r.translateX<b&&(w=b-r.translateX);r.translateX+f.width>=c&&(w=-(r.translateX+f.width-c));r.attr({x:C+ w,y:m,anchorX:g?C:this.opposite?0:d.chartWidth,anchorY:g?this.opposite?d.chartHeight:0:m+f.height/2})}});l.init=function(){n.apply(this,arguments);this.setCompare(this.options.compare)};l.setCompare=function(a){this.modifyValue="value"===a||"percent"===a?function(b,c){var d=this.compareValue;return"undefined"!==typeof b&&"undefined"!==typeof d?(b="value"===a?b-d:b/d*100-(100===this.options.compareBase?0:100),c&&(c.change=b),b):0}:null;this.userOptions.compare=a;this.chart.hasRendered&&(this.isDirty= !0)};l.processData=function(a){var b,c=-1,d=!0===this.options.compareStart?0:1;t.apply(this,arguments);if(this.xAxis&&this.processedYData){var f=this.processedXData;var g=this.processedYData;var h=g.length;this.pointArrayMap&&(c=this.pointArrayMap.indexOf(this.options.pointValKey||this.pointValKey||"y"));for(b=0;b<h-d;b++){var l=g[b]&&-1<c?g[b][c]:g[b];if(v(l)&&f[b+d]>=this.xAxis.min&&0!==l){this.compareValue=l;break}}}};g(c,"afterGetExtremes",function(){if(this.modifyValue){var a=[this.modifyValue(this.dataMin), this.modifyValue(this.dataMax)];this.dataMin=F(a);this.dataMax=y(a)}});z.prototype.setCompare=function(a,b){this.isXAxis||(this.series.forEach(function(b){b.setCompare(a)}),B(b,!0)&&this.chart.redraw())};h.prototype.tooltipFormatter=function(a){var b=this.series.chart.numberFormatter;a=a.replace("{point.change}",(0<this.change?"+":"")+b(this.change,B(this.series.tooltipOptions.changeDecimals,2)));return I.apply(this,[a])};g(c,"render",function(){var a=this.chart;if(!(a.is3d&&a.is3d()||a.polar)&&this.xAxis&& !this.xAxis.isRadial){var b=this.yAxis.len;if(this.xAxis.axisLine){var c=a.plotTop+a.plotHeight-this.yAxis.pos-this.yAxis.len,d=Math.floor(this.xAxis.axisLine.strokeWidth()/2);0<=c&&(b-=Math.max(d-c,0))}!this.clipBox&&this.animate?(this.clipBox=w(a.clipBox),this.clipBox.width=this.xAxis.len,this.clipBox.height=b):a[this.sharedClipKey]&&(a[this.sharedClipKey].animate({width:this.xAxis.len,height:b}),a[this.sharedClipKey+"m"]&&a[this.sharedClipKey+"m"].animate({width:this.xAxis.len}))}});g(m,"update", function(a){a=a.options;"scrollbar"in a&&this.navigator&&(w(!0,this.options.scrollbar,a.scrollbar),this.navigator.update({},!1),delete a.scrollbar)});g(z,"afterSetScale",function(){var a=this,b=a.chart.options.chart&&a.chart.options.chart.panning;if(b&&("y"===b.type||"xy"===b.type)&&!a.isXAxis&&!D(a.panningState)){var c=Number.MAX_VALUE,f=Number.MIN_VALUE;a.series.forEach(function(b){c=Math.min(d.arrayMin(b.yData),c)-(a.min&&a.dataMin?a.dataMin-a.min:0);f=Math.max(d.arrayMax(b.yData),f)+(a.max&&a.dataMax? a.max-a.dataMax:0)});a.panningState={startMin:c,startMax:f}}})});K(y,"masters/modules/stock.src.js",[],function(){});K(y,"masters/highstock.src.js",[y["masters/highcharts.src.js"]],function(d){d.product="Highstock";return d});y["masters/highstock.src.js"]._modules=y;return y["masters/highstock.src.js"]}); //# sourceMappingURL=highstock.js.map
l
execute.rs
use std::collections::HashMap; use log::{error, trace}; use crate::core::{ battle::{ self, ability::{Ability, PassiveAbility}, check::{check, Error}, command::{self, Command}, component::{self, ObjType}, effect::{self, Effect}, event::{self, ActiveEvent, Event}, movement::Path, state::{self, BattleResult, State}, Id, Moves, Phase, PlayerId, PushStrength, Rounds, Strength, Weight, }, map::{self, Dir, PosHex}, utils::{self, roll_dice}, }; #[derive(PartialEq, Clone, Copy, Debug)] pub enum ApplyPhase { Pre, Post, } /// A callback for visualization of the events/effects with the correct state. pub type Cb<'c> = &'c mut dyn FnMut(&State, &Event, ApplyPhase); pub fn execute(state: &mut State, command: &Command, cb: Cb) -> Result<(), Error> { trace!("Simulator: do_command: {:?}", command); if let Err(err) = check(state, command) { error!("Check failed: {:?}", err); return Err(err); } match *command { Command::Create(ref command) => execute_create(state, cb, command), Command::MoveTo(ref command) => execute_move_to(state, cb, command), Command::Attack(ref command) => execute_attack(state, cb, command), Command::EndTurn(ref command) => execute_end_turn(state, cb, command), Command::UseAbility(ref command) => execute_use_ability(state, cb, command), } execute_planned_abilities(state, cb); match *command { Command::Create(_) => {} _ => try_execute_end_battle(state, cb), } Ok(()) } fn do_event(state: &mut State, cb: Cb, event: &Event) { cb(state, event, ApplyPhase::Pre); state.apply(event); cb(state, event, ApplyPhase::Post); } fn execute_move_to(state: &mut State, cb: Cb, command: &command::MoveTo) { let mut cost = Some(Moves(1)); let id = command.id; // prevent enemy from escaping let tie_up_attack_status = try_execute_reaction_attacks(state, cb, id); if tie_up_attack_status == AttackStatus::Hit && state.parts().agent.get_opt(id).is_some() { // A degenerate move event just to spend agent's move point let current_pos = state.parts().pos.get(id).0; let path = Path::new(vec![current_pos]); do_move(state, cb, id, cost.take(), path); return; } if state.parts().agent.get_opt(id).is_none() { return; } for step in command.path.steps() { assert!(state.parts().agent.get_opt(id).is_some()); let path = Path::new(vec![step.from, step.to]); do_move(state, cb, id, cost.take(), path); try_execute_passive_abilities_on_move(state, cb, id); let attack_status = try_execute_reaction_attacks(state, cb, id); let is_alive = state.parts().agent.get_opt(id).is_some(); if attack_status == AttackStatus::Hit || !is_alive { break; } } } fn do_move(state: &mut State, cb: Cb, id: Id, cost: Option<Moves>, path: Path) { let cost = cost.unwrap_or(Moves(0)); let active_event = event::MoveTo { path, cost, id }.into(); let event = Event { active_event, actor_ids: vec![id], instant_effects: Vec::new(), timed_effects: Vec::new(), scheduled_abilities: Vec::new(), }; do_event(state, cb, &event); } fn execute_create(state: &mut State, cb: Cb, command: &command::Create) { let mut components = state.prototype_for(&command.prototype); if let Some(player_id) = command.owner { components.push(component::BelongsTo(player_id).into()); } let name = command.prototype.clone(); components.extend_from_slice(&[ component::Pos(command.pos).into(), component::Meta { name }.into(), ]); let id = state.alloc_id(); let mut instant_effects = Vec::new(); let effect_create = effect::Create { pos: command.pos, prototype: command.prototype.clone(), components, is_teleported: false, } .into(); instant_effects.push((id, vec![effect_create])); let event = Event { active_event: ActiveEvent::Create, actor_ids: vec![id], instant_effects, timed_effects: Vec::new(), scheduled_abilities: Vec::new(), }; do_event(state, cb, &event); } #[derive(PartialEq, Clone, Debug)] enum AttackStatus { Hit, Miss, } fn execute_attack_internal( state: &mut State, cb: Cb, command: &command::Attack, mode: event::AttackMode, ) -> AttackStatus { let attacker_id = command.attacker_id; let target_id = command.target_id; let weapon_type = state.parts().agent.get(attacker_id).weapon_type; let event_attack = event::Attack { attacker_id, target_id, mode, weapon_type, }; let mut context = ExecuteContext::default(); let mut is_kill = false; if let Some(effect) = try_attack(state, attacker_id, target_id) { if let Effect::Kill(_) = effect { is_kill = true; } context.instant_effects.push((target_id, vec![effect])); } let status = if context.instant_effects.is_empty() { let attacker_pos = state.parts().pos.get(attacker_id).0; let dodge = effect::Dodge { attacker_pos }.into(); context.instant_effects.push((target_id, vec![dodge])); AttackStatus::Miss } else { if !is_kill { let c = try_execute_passive_abilities_on_attack(state, attacker_id, target_id); context.merge_with(c); } AttackStatus::Hit }; let event = Event { active_event: event_attack.into(), actor_ids: vec![attacker_id], instant_effects: context.instant_effects, timed_effects: context.timed_effects, scheduled_abilities: context.scheduled_abilities, }; do_event(state, cb, &event); for id in context.moved_actor_ids { try_execute_passive_abilities_on_move(state, cb, id); } status } fn try_execute_passive_ability_burn(state: &mut State, target_id: Id) -> ExecuteContext { let mut context = ExecuteContext::default(); let damage = battle::Strength(1); let target_effects = vec![wound_or_kill(state, target_id, damage)]; context.instant_effects.push((target_id, target_effects)); context } fn try_execute_passive_ability_spike_trap(state: &mut State, target_id: Id) -> ExecuteContext { let mut context = ExecuteContext::default(); let damage = battle::Strength(1); let target_effects = vec![wound_or_kill(state, target_id, damage)]; context.instant_effects.push((target_id, target_effects)); context } fn try_execute_passive_ability_poison(state: &State, target_id: Id) -> ExecuteContext { let mut context = ExecuteContext::default(); if state.parts().strength.get(target_id).strength <= Strength(1) { return context; } let owner = state.parts().belongs_to.get(target_id).0; let effect = effect::Timed { duration: effect::Duration::Rounds(2.into()), phase: Phase::from_player_id(owner), effect: effect::Lasting::Poison, }; context.timed_effects.push((target_id, vec![effect])); context } fn do_passive_ability( state: &mut State, cb: Cb, id: Id, target_pos: PosHex, ability: PassiveAbility, context: ExecuteContext, ) { assert!( !context.instant_effects.is_empty() || !context.timed_effects.is_empty() || !context.scheduled_abilities.is_empty() ); let active_event = event::UsePassiveAbility { pos: target_pos, id, ability, } .into(); let event = Event { active_event, actor_ids: context.actor_ids, instant_effects: context.instant_effects, timed_effects: context.timed_effects, scheduled_abilities: Vec::new(), }; do_event(state, cb, &event); } fn try_execute_passive_abilities_on_move(state: &mut State, cb: Cb, target_id: Id) { try_execute_passive_abilities_tick(state, cb, target_id) } fn try_execute_passive_abilities_tick(state: &mut State, cb: Cb, target_id: Id) { trace!("try_execute_passive_abilities_tick"); if !state.parts().is_exist(target_id) { return; } let target_pos = state.parts().pos.get(target_id).0; let ids = state.parts().passive_abilities.ids_collected(); for id in ids { if !state.parts().is_exist(target_id) { continue; } if state.parts().agent.get_opt(target_id).is_none() { continue; } let abilities = state.parts().passive_abilities.get(id).clone(); let pos = match state.parts().pos.get_opt(id) { Some(pos) => pos.0, None => continue, }; if pos != target_pos { continue; } for &ability in &abilities.0 { assert!(state.parts().is_exist(target_id)); match ability { PassiveAbility::SpikeTrap => { let context = try_execute_passive_ability_spike_trap(state, target_id); do_passive_ability(state, cb, id, target_pos, ability, context); } PassiveAbility::Burn => { let context = try_execute_passive_ability_burn(state, target_id); do_passive_ability(state, cb, id, target_pos, ability, context); } PassiveAbility::Poison => { let context = try_execute_passive_ability_poison(state, target_id); if !context.timed_effects.is_empty() { do_passive_ability(state, cb, id, target_pos, ability, context); } } PassiveAbility::HeavyImpact | PassiveAbility::PoisonAttack | PassiveAbility::Regenerate | PassiveAbility::SpawnPoisonCloudOnDeath => {} } } } } fn try_execute_passive_abilities_on_begin_turn(state: &mut State, cb: Cb) { for id in state::players_agent_ids(state, state.player_id()) { try_execute_passive_abilities_tick(state, cb, id); } // TODO: extract to some self-abilities-method? { let ids = state.parts().passive_abilities.ids_collected(); for id in ids { assert!(state.parts().is_exist(id)); let owner = match state.parts().belongs_to.get_opt(id) { Some(owner) => owner.0, None => continue, }; if state.player_id() != owner { continue; } let abilities = state.parts().passive_abilities.get(id).clone(); for &ability in &abilities.0 { assert!(state.parts().is_exist(id)); if let PassiveAbility::Regenerate = ability { if state.parts().strength.get(id).strength >= state.parts().strength.get(id).base_strength { continue; } let pos = state.parts().pos.get(id).0; let active_event = event::UsePassiveAbility { id, pos, ability }.into(); let mut target_effects = Vec::new(); let strength = Strength(1); target_effects.push(effect::Heal { strength }.into()); let instant_effects = vec![(id, target_effects)]; let event = Event { active_event, actor_ids: vec![id], instant_effects, timed_effects: Vec::new(), scheduled_abilities: Vec::new(), }; do_event(state, cb, &event); } } } } } fn try_execute_passive_abilities_on_attack( state: &mut State, attacker_id: Id, target_id: Id, ) -> ExecuteContext { let mut context = ExecuteContext::default(); let parts = state.parts(); let target_pos = parts.pos.get(target_id).0; let attacker_pos = parts.pos.get(attacker_id).0; if let Some(passive_abilities) = parts.passive_abilities.get_opt(attacker_id) { let abilities = passive_abilities.clone(); for &ability in &abilities.0 { trace!("ability: {:?}", ability); match ability { PassiveAbility::HeavyImpact => { let dir = Dir::get_dir_from_to(attacker_pos, target_pos); let from = target_pos; let strength = PushStrength(Weight::Normal); let blocker_weight = parts.blocker.get(target_id).weight; let to = if strength.can_push(blocker_weight) { Dir::get_neighbor_pos(target_pos, dir) } else { from }; let is_inboard = state.map().is_inboard(to); if to == from || is_inboard && !state::is_tile_blocked(state, to) { let effect = effect::FlyOff { from, to, strength }.into(); context.instant_effects.push((target_id, vec![effect])); context.moved_actor_ids.push(target_id); } } PassiveAbility::PoisonAttack => { let owner = parts.belongs_to.get(target_id).0; let effect = effect::Timed { duration: effect::Duration::Rounds(2.into()), phase: Phase::from_player_id(owner), effect: effect::Lasting::Poison, }; context.timed_effects.push((target_id, vec![effect])); } PassiveAbility::Burn | PassiveAbility::SpikeTrap | PassiveAbility::Poison | PassiveAbility::Regenerate | PassiveAbility::SpawnPoisonCloudOnDeath => (), } } } context } fn try_execute_reaction_attacks(state: &mut State, cb: Cb, target_id: Id) -> AttackStatus { let mut status = AttackStatus::Miss; let target_owner = match state.parts().belongs_to.get_opt(target_id) { Some(belongs_to) => belongs_to.0, None => return status, }; let initial_player_id = state.player_id(); for obj_id in state::enemy_agent_ids(state, initial_player_id) { if state.parts().agent.get_opt(obj_id).is_none() { // check if target is killed continue; } let this_agent_owner = state.parts().belongs_to.get(obj_id).0; if this_agent_owner == target_owner { continue; } let command_attack = command::Attack { attacker_id: obj_id, target_id, }; let command = command_attack.clone().into(); state.set_player_id(this_agent_owner); if check(state, &command).is_err() { continue; } let mode = event::AttackMode::Reactive; let this_attack_status = execute_attack_internal(state, cb, &command_attack, mode); if this_attack_status != AttackStatus::Miss { status = this_attack_status; } } state.set_player_id(initial_player_id); status } fn execute_attack(state: &mut State, cb: Cb, command: &command::Attack) { execute_attack_internal(state, cb, command, event::AttackMode::Active); try_execute_reaction_attacks(state, cb, command.attacker_id); } fn execute_event_end_turn(state: &mut State, cb: Cb) { let player_id_old = state.player_id(); let active_event = event::EndTurn { player_id: player_id_old, } .into(); let mut actor_ids = state::players_agent_ids(state, player_id_old); actor_ids.sort(); let event = Event { active_event, actor_ids, instant_effects: Vec::new(), timed_effects: Vec::new(), scheduled_abilities: Vec::new(), }; do_event(state, cb, &event); } fn execute_event_begin_turn(state: &mut State, cb: Cb) { let player_id_new = state.next_player_id(); let active_event = event::BeginTurn { player_id: player_id_new, } .into(); let mut actor_ids = state::players_agent_ids(state, player_id_new); actor_ids.sort(); let event = Event { active_event, actor_ids, instant_effects: Vec::new(), timed_effects: Vec::new(), scheduled_abilities: Vec::new(), }; do_event(state, cb, &event); } fn execute_planned_abilities(state: &mut State, cb: Cb) { let mut ids = state.parts().schedule.ids_collected(); ids.sort(); for obj_id in ids { let pos = state.parts().pos.get(obj_id).0; let mut activated = Vec::new(); { let schedule = state.parts().schedule.get(obj_id); for planned in &schedule.planned { if planned.rounds.0 <= 0 { trace!("planned ability: ready!"); let c = command::UseAbility { ability: planned.ability, id: obj_id, pos, }; activated.push(c); } } } for command in activated { if state.parts().is_exist(obj_id) { execute_use_ability(state, cb, &command); } } } } fn try_execute_end_battle(state: &mut State, cb: Cb) { for i in 0..state.scenario().players_count { let player_id = PlayerId(i); let enemies_count = state::enemy_agent_ids(state, player_id).len(); if enemies_count == 0 { let result = BattleResult { winner_id: player_id, survivor_types: state::players_agent_types(state, PlayerId(0)), }; let event = Event { active_event: event::EndBattle { result }.into(), actor_ids: Vec::new(), instant_effects: Vec::new(), timed_effects: Vec::new(), scheduled_abilities: Vec::new(), }; do_event(state, cb, &event); } } } // TODO: simplify /// Ticks and kills all the lasting effects. fn execute_effects(state: &mut State, cb: Cb) { let phase = Phase::from_player_id(state.player_id()); for id in state.parts().effects.ids_collected() { for effect in &state.parts().effects.get(id).0.clone() { if effect.phase != phase { continue; } assert!(state.parts().is_exist(id)); { let active_event = event::EffectTick { id, effect: effect.effect, }; let mut target_effects = Vec::new(); match effect.effect { effect::Lasting::Poison => { let strength = state.parts().strength.get(id).strength; if strength > battle::Strength(1) { let damage = battle::Strength(1); target_effects.push(wound_or_kill(state, id, damage)); } } effect::Lasting::Stun => { target_effects.push(Effect::Stun); } effect::Lasting::Bloodlust => target_effects.push(Effect::Bloodlust), } let instant_effects = vec![(id, target_effects)]; let event = Event { active_event: ActiveEvent::EffectTick(active_event), actor_ids: vec![id], instant_effects, timed_effects: Vec::new(), scheduled_abilities: Vec::new(), }; do_event(state, cb, &event); } if !state.parts().is_exist(id) { break; } if state::is_lasting_effect_over(state, id, effect) { let active_event = event::EffectEnd { id, effect: effect.effect, }; let event = Event { active_event: ActiveEvent::EffectEnd(active_event), actor_ids: vec![id], instant_effects: Vec::new(), timed_effects: Vec::new(), scheduled_abilities: Vec::new(), }; do_event(state, cb, &event); } } if !state.parts().is_exist(id) { continue; } } } fn execute_end_turn(state: &mut State, cb: Cb, _: &command::EndTurn) { execute_event_end_turn(state, cb); execute_event_begin_turn(state, cb); try_execute_passive_abilities_on_begin_turn(state, cb); execute_effects(state, cb); } fn start_fire(state: &mut State, pos: PosHex) -> ExecuteContext { let vanish = component::PlannedAbility { rounds: 2.into(), // TODO: Replace this magic number phase: Phase::from_player_id(state.player_id()), ability: Ability::Vanish, }; let mut context = ExecuteContext::default(); if let Some(id) = state::obj_with_passive_ability_at(state, pos, PassiveAbility::Burn) { context.scheduled_abilities.push((id, vec![vanish])); } else { let effect_create = effect_create_object(state, &"fire".into(), pos); let id = state.alloc_id(); context.instant_effects.push((id, vec![effect_create])); context.scheduled_abilities.push((id, vec![vanish])); for target_id in state::agent_ids_at(state, pos) { context.merge_with(try_execute_passive_ability_burn(state, target_id)); } } context } fn create_poison_cloud(state: &mut State, pos: PosHex) -> ExecuteContext { let vanish = component::PlannedAbility { rounds: 2.into(), // TODO: Replace this magic number phase: Phase::from_player_id(state.player_id()), ability: Ability::Vanish, }; let mut context = ExecuteContext::default(); if let Some(id) = state::obj_with_passive_ability_at(state, pos, PassiveAbility::Poison) { context.scheduled_abilities.push((id, vec![vanish])); } else { let effect_create = effect_create_object(state, &"poison_cloud".into(), pos); let id = state.alloc_id(); context.instant_effects.push((id, vec![effect_create])); context.scheduled_abilities.push((id, vec![vanish])); for target_id in state::agent_ids_at(state, pos) { context.merge_with(try_execute_passive_ability_poison(state, target_id)); } } context } fn extend_or_crate_sub_vec<T>(vec: &mut Vec<(Id, Vec<T>)>, id: Id, values: Vec<T>) { if let Some(i) = vec.iter().position(|(this_id, _)| this_id == &id) { vec[i].1.extend(values); } else { vec.push((id, values)); } } fn any_effect_with_id(effects: &[(Id, Vec<Effect>)], expected_id: Id) -> bool { effects.iter().any(|(id, _)| id == &expected_id) } #[must_use] #[derive(Default, Debug, PartialEq, Clone)] struct ExecuteContext { actor_ids: Vec<Id>, moved_actor_ids: Vec<Id>, reaction_attack_targets: Vec<Id>, instant_effects: Vec<(Id, Vec<Effect>)>, timed_effects: Vec<(Id, Vec<effect::Timed>)>, scheduled_abilities: Vec<(Id, Vec<component::PlannedAbility>)>, } impl ExecuteContext { fn merge_with(&mut self, other: Self) { type M<T> = Vec<(Id, Vec<T>)>; fn merge<T>(m: &mut M<T>, other: M<T>) { for (id, values) in other { extend_or_crate_sub_vec(m, id, values); } } self.actor_ids.extend(other.actor_ids); self.moved_actor_ids.extend(other.moved_actor_ids); self.reaction_attack_targets .extend(other.reaction_attack_targets); merge(&mut self.instant_effects, other.instant_effects); merge(&mut self.timed_effects, other.timed_effects); merge(&mut self.scheduled_abilities, other.scheduled_abilities); } } fn execute_use_ability_knockback( state: &mut State, command: &command::UseAbility, ) -> ExecuteContext { let mut context = ExecuteContext::default(); let id = state::blocker_id_at(state, command.pos); let from = command.pos; let strength = PushStrength(Weight::Normal); let actor_pos = state.parts().pos.get(command.id).0; let dir = Dir::get_dir_from_to(actor_pos, command.pos); let blocker_weight = state.parts().blocker.get(id).weight; let to = if strength.can_push(blocker_weight) { Dir::get_neighbor_pos(command.pos, dir) } else { from }; if to == from || state.map().is_inboard(to) && !state::is_tile_blocked(state, to) { let effect = effect::Knockback { from, to, strength }.into(); context.instant_effects.push((id, vec![effect])); context.moved_actor_ids.push(id); } context.actor_ids.push(id); context } fn execute_use_ability_club(state: &mut State, command: &command::UseAbility) -> ExecuteContext
fn execute_use_ability_explode_fire( state: &mut State, command: &command::UseAbility, ) -> ExecuteContext { let mut context = ExecuteContext::default(); assert!(!any_effect_with_id(&context.instant_effects, command.id)); let effects = vec![Effect::Vanish]; context.instant_effects.push((command.id, effects)); context.merge_with(start_fire(state, command.pos)); for dir in map::dirs() { let pos = Dir::get_neighbor_pos(command.pos, dir); if state.map().is_inboard(pos) { context.merge_with(start_fire(state, pos)); } } context } fn execute_use_ability_jump(_: &mut State, command: &command::UseAbility) -> ExecuteContext { let mut context = ExecuteContext::default(); context.moved_actor_ids.push(command.id); context } fn execute_use_ability_long_jump(_: &mut State, command: &command::UseAbility) -> ExecuteContext { let mut context = ExecuteContext::default(); context.moved_actor_ids.push(command.id); context } fn execute_use_ability_dash(_: &mut State, command: &command::UseAbility) -> ExecuteContext { let mut context = ExecuteContext::default(); context.moved_actor_ids.push(command.id); context } fn execute_use_ability_rage(_: &mut State, _: &command::UseAbility) -> ExecuteContext { ExecuteContext::default() } fn execute_use_ability_heal( state: &mut State, command: &command::UseAbility, strength: Strength, ) -> ExecuteContext { let mut context = ExecuteContext::default(); let id = state::blocker_id_at(state, command.pos); let effect = effect::Heal { strength }.into(); context.instant_effects.push((id, vec![effect])); context } fn execute_use_ability_vanish(state: &mut State, command: &command::UseAbility) -> ExecuteContext { let mut context = ExecuteContext::default(); assert!(state.parts().is_exist(command.id)); let effects = vec![Effect::Vanish]; context.instant_effects.push((command.id, effects)); context } fn execute_use_ability_explode_poison( state: &mut State, command: &command::UseAbility, ) -> ExecuteContext { let mut context = ExecuteContext::default(); assert!(!any_effect_with_id(&context.instant_effects, command.id)); let effects = vec![Effect::Vanish]; context.instant_effects.push((command.id, effects)); context.merge_with(create_poison_cloud(state, command.pos)); for dir in map::dirs() { let pos = Dir::get_neighbor_pos(command.pos, dir); if state.map().is_inboard(pos) { context.merge_with(create_poison_cloud(state, pos)); } } context } fn correct_damage_with_armor( state: &State, target_id: Id, damage: battle::Strength, ) -> battle::Strength { let id = target_id; let armor = state::get_armor(state, id); battle::Strength(utils::clamp_min(damage.0 - armor.0, 0)) } fn wound_or_kill(state: &State, id: Id, damage: battle::Strength) -> Effect { let armor_break = battle::Strength(0); wound_break_kill(state, id, damage, armor_break) } fn wound_break_kill( state: &State, id: Id, damage: battle::Strength, armor_break: battle::Strength, ) -> Effect { let parts = state.parts(); let strength = parts.strength.get(id).strength; let armor_break = if let Some(a) = parts.armor.get_opt(id) { utils::clamp_max(armor_break, a.armor) } else { Strength(0) }; let attacker_pos = None; // Let's assume that this is not a directed attack. if strength > damage { effect::Wound { damage, armor_break, attacker_pos, } .into() } else { effect::Kill { attacker_pos }.into() } } // TODO: Return a `Result` or an `Option` (check that attack is possible at all?). // TODO: Return a struct with named fields. // TODO: Move to some other module. pub fn hit_chance(state: &State, attacker_id: Id, target_id: Id) -> (i32, i32) { let parts = state.parts(); let agent_target = parts.agent.get(target_id); let agent_attacker = parts.agent.get(attacker_id); let attacker_strength = parts.strength.get(attacker_id).strength; let attacker_base_strength = parts.strength.get(attacker_id).base_strength; let attacker_wounds = utils::clamp_max(attacker_base_strength.0 - attacker_strength.0, 3); let target_dodge = agent_target.dodge; let attack_accuracy = agent_attacker.attack_accuracy; let attack_strength = agent_attacker.attack_strength; let k_min = attack_accuracy.0 - target_dodge.0 - attacker_wounds; let k_max = k_min + attack_strength.0; (k_min, k_max) } fn try_attack(state: &State, attacker_id: Id, target_id: Id) -> Option<Effect> { let parts = state.parts(); let agent_attacker = state.parts().agent.get(attacker_id); let target_strength = parts.strength.get(target_id).strength; let target_armor = state::get_armor(state, target_id); let attack_strength = agent_attacker.attack_strength; let attacker_pos = Some(state.parts().pos.get(attacker_id).0); let (k_min, k_max) = hit_chance(state, attacker_id, target_id); if state.deterministic_mode() { // I want to be sure that I either will totally miss // or that I'll surely hit the target at a full force. let sure_miss = k_min < 0; let sure_hit = k_min > 10; assert!( sure_miss || sure_hit, "Hit isn't determined: {:?}", (k_min, k_max) ); } let r = roll_dice(0, 11); let damage_raw = Strength(k_max - r); let damage = Strength(utils::clamp(damage_raw.0, 0, attack_strength.0)); if damage_raw < Strength(0) { // That was a total miss return None; } let damage = correct_damage_with_armor(state, target_id, damage); let attack_break = utils::clamp_max(agent_attacker.attack_break, target_armor); let effect = if target_strength > damage { effect::Wound { damage, armor_break: attack_break, attacker_pos, } .into() } else { effect::Kill { attacker_pos }.into() }; Some(effect) } fn execute_use_ability_explode_damage( state: &mut State, command: &command::UseAbility, ) -> ExecuteContext { let mut context = ExecuteContext::default(); let from = state.parts().pos.get(command.id).0; for id in state.parts().agent.ids() { let pos = state.parts().pos.get(id).0; let distance = map::distance_hex(from, pos); if distance.0 > 1 || command.id == id { continue; } let damage = battle::Strength(1); let damage = correct_damage_with_armor(state, id, damage); let armor_break = Strength(1); let effects = vec![wound_break_kill(state, id, damage, armor_break)]; context.instant_effects.push((id, effects)); } assert!(!any_effect_with_id(&context.instant_effects, command.id)); let effects = vec![Effect::Vanish]; context.instant_effects.push((command.id, effects)); context } fn execute_use_ability_explode_push( state: &mut State, command: &command::UseAbility, ) -> ExecuteContext { let mut context = ExecuteContext::default(); let from = state.parts().pos.get(command.id).0; for id in state.parts().blocker.ids() { let pos = state.parts().pos.get(id).0; let distance = map::distance_hex(from, pos); if distance.0 > 1 || command.id == id { continue; } let blocker_weight = state.parts().blocker.get(id).weight; let dir = Dir::get_dir_from_to(from, pos); let to = if PushStrength(Weight::Normal).can_push(blocker_weight) { Dir::get_neighbor_pos(pos, dir) } else { pos }; let mut effects = Vec::new(); if to == pos || (state.map().is_inboard(to) && !state::is_tile_blocked(state, to)) { let effect = effect::Knockback { from: pos, to, strength: PushStrength(Weight::Normal), }; effects.push(effect.into()); if state.parts().agent.get_opt(id).is_some() { context.moved_actor_ids.push(id); } } context.instant_effects.push((id, effects)); } assert!(!any_effect_with_id(&context.instant_effects, command.id)); let effects = vec![Effect::Vanish]; context.instant_effects.push((command.id, effects)); context } fn execute_use_ability_poison(state: &mut State, command: &command::UseAbility) -> ExecuteContext { let mut context = ExecuteContext::default(); let id = state::blocker_id_at(state, command.pos); let owner = state.parts().belongs_to.get(id).0; let phase = Phase::from_player_id(owner); let effect = effect::Timed { duration: effect::Duration::Rounds(2.into()), phase, effect: effect::Lasting::Poison, }; context.timed_effects.push((id, vec![effect])); context.actor_ids.push(id); context } fn effect_create_object(state: &State, prototype: &ObjType, pos: PosHex) -> Effect { let name = prototype.clone(); let mut components = state.prototype_for(prototype); components.extend_from_slice(&[component::Pos(pos).into(), component::Meta { name }.into()]); effect::Create { pos, prototype: prototype.clone(), components, is_teleported: false, } .into() } fn effect_create_agent( state: &State, prototype: &ObjType, player_id: PlayerId, pos: PosHex, ) -> Effect { let name = prototype.clone(); let mut components = state.prototype_for(prototype); components.extend_from_slice(&[ component::Pos(pos).into(), component::Meta { name }.into(), component::BelongsTo(player_id).into(), ]); effect::Create { pos, prototype: prototype.clone(), components, is_teleported: true, } .into() } fn throw_bomb( state: &mut State, command: &command::UseAbility, prototype: &ObjType, rounds: Rounds, ability: Ability, ) -> ExecuteContext { let mut context = ExecuteContext::default(); let pos = state.parts().pos.get(command.id).0; let effect_create = effect_create_object(state, prototype, pos); let id = state.alloc_id(); let effect_throw = effect::Throw { from: pos, to: command.pos, } .into(); let effects = vec![effect_create, effect_throw]; context.instant_effects.push((id, effects)); let planned_ability = component::PlannedAbility { rounds, phase: Phase::from_player_id(state.player_id()), ability, }; context .scheduled_abilities .push((id, vec![planned_ability])); context } fn execute_use_ability_bomb_push( state: &mut State, command: &command::UseAbility, ) -> ExecuteContext { let rounds = 0.into(); let ability = Ability::ExplodePush; throw_bomb(state, command, &"bomb_push".into(), rounds, ability) } fn execute_use_ability_bomb_damage( state: &mut State, command: &command::UseAbility, ) -> ExecuteContext { let ability = Ability::ExplodeDamage; let rounds = 1.into(); throw_bomb(state, command, &"bomb_damage".into(), rounds, ability) } fn execute_use_ability_bomb_fire( state: &mut State, command: &command::UseAbility, ) -> ExecuteContext { let ability = Ability::ExplodeFire; let rounds = 1.into(); throw_bomb(state, command, &"bomb_fire".into(), rounds, ability) } fn execute_use_ability_bomb_poison( state: &mut State, command: &command::UseAbility, ) -> ExecuteContext { let ability = Ability::ExplodePoison; let rounds = 1.into(); throw_bomb(state, command, &"bomb_poison".into(), rounds, ability) } fn execute_use_ability_bomb_demonic( state: &mut State, command: &command::UseAbility, ) -> ExecuteContext { let ability = Ability::ExplodeDamage; let rounds = 1.into(); throw_bomb(state, command, &"bomb_demonic".into(), rounds, ability) } fn execute_use_ability_summon(state: &mut State, command: &command::UseAbility) -> ExecuteContext { let mut context = ExecuteContext::default(); let max_summoned_count = state.parts().summoner.get(command.id).count; let available_typenames = &["imp".into(), "toxic_imp".into(), "imp_bomber".into()]; let existing_agents = existing_agent_typenames(state, state.player_id()); let mut new_agents = Vec::new(); for pos in state::free_neighbor_positions(state, command.pos, max_summoned_count as _) { let prototype = choose_who_to_summon(&existing_agents, &new_agents, available_typenames); let effect_create = effect_create_agent(state, &prototype, state.player_id(), pos); let id = state.alloc_id(); let effects = vec![effect_create, Effect::Stun]; new_agents.push(prototype); context.instant_effects.push((id, effects)); context.moved_actor_ids.push(id); context.reaction_attack_targets.push(id); } context } fn execute_use_ability_bloodlust( state: &mut State, command: &command::UseAbility, ) -> ExecuteContext { let mut context = ExecuteContext::default(); let id = state::blocker_id_at(state, command.pos); if state.parts().belongs_to.get_opt(id).is_some() { let owner = state.parts().belongs_to.get(id).0; let phase = Phase::from_player_id(owner); let effect = effect::Timed { duration: effect::Duration::Rounds(3.into()), phase, effect: effect::Lasting::Bloodlust, }; context.timed_effects.push((id, vec![effect])); } context.actor_ids.push(id); context } fn execute_use_ability(state: &mut State, cb: Cb, command: &command::UseAbility) { let mut context = match command.ability { Ability::Knockback => execute_use_ability_knockback(state, command), Ability::Club => execute_use_ability_club(state, command), Ability::Jump => execute_use_ability_jump(state, command), Ability::LongJump => execute_use_ability_long_jump(state, command), Ability::Dash => execute_use_ability_dash(state, command), Ability::Rage => execute_use_ability_rage(state, command), Ability::Heal => execute_use_ability_heal(state, command, Strength(2)), Ability::GreatHeal => execute_use_ability_heal(state, command, Strength(3)), Ability::Vanish => execute_use_ability_vanish(state, command), Ability::ExplodeFire => execute_use_ability_explode_fire(state, command), Ability::ExplodePoison => execute_use_ability_explode_poison(state, command), Ability::ExplodePush => execute_use_ability_explode_push(state, command), Ability::ExplodeDamage => execute_use_ability_explode_damage(state, command), Ability::Poison => execute_use_ability_poison(state, command), Ability::Bomb => execute_use_ability_bomb_damage(state, command), Ability::BombPush => execute_use_ability_bomb_push(state, command), Ability::BombFire => execute_use_ability_bomb_fire(state, command), Ability::BombPoison => execute_use_ability_bomb_poison(state, command), Ability::BombDemonic => execute_use_ability_bomb_demonic(state, command), Ability::Summon => execute_use_ability_summon(state, command), Ability::Bloodlust => execute_use_ability_bloodlust(state, command), }; context.actor_ids.push(command.id); let active_event = event::UseAbility { id: command.id, pos: command.pos, ability: command.ability, } .into(); let event = Event { active_event, actor_ids: context.actor_ids, instant_effects: context.instant_effects, timed_effects: context.timed_effects, scheduled_abilities: context.scheduled_abilities, }; do_event(state, cb, &event); for id in context.moved_actor_ids { try_execute_passive_abilities_on_move(state, cb, id); } for id in context.reaction_attack_targets { try_execute_reaction_attacks(state, cb, id); } if command.ability != Ability::Dash { try_execute_reaction_attacks(state, cb, command.id); } } fn existing_agent_typenames(state: &State, player_id: PlayerId) -> Vec<ObjType> { let mut existing_agents = Vec::new(); for id in state::players_agent_ids(state, player_id) { let typename = state.parts().meta.get(id).name.clone(); existing_agents.push(typename); } existing_agents } fn choose_who_to_summon( existing_agents: &[ObjType], new_agents: &[ObjType], available_typenames: &[ObjType], ) -> ObjType { assert!(!available_typenames.is_empty()); let agents = existing_agents.iter().chain(new_agents); let mut map = HashMap::new(); for typename in available_typenames { map.insert(typename, 0); } for typename in agents { if let Some(count) = map.get_mut(typename) { *count += 1; } } let (key, _value) = map .into_iter() .min_by_key(|&(_key, value)| value) .expect("The map can't be empty"); key.clone() } #[cfg(test)] mod tests { use crate::core::{ battle::{ effect::{self, Effect}, Id, }, map::PosHex, }; use super::ExecuteContext; // TODO: Don't create Id's manually? Use a mocked State instead. #[test] fn test_merge_with_vector() { let mut context1 = ExecuteContext { actor_ids: vec![Id(0), Id(1)], ..Default::default() }; let context2 = ExecuteContext { actor_ids: vec![Id(2), Id(3)], ..Default::default() }; let context_expected = ExecuteContext { actor_ids: vec![Id(0), Id(1), Id(2), Id(3)], ..Default::default() }; context1.merge_with(context2); assert_eq!(context_expected, context1); } #[test] fn test_merge_with_hashmap() { let mut instant_effects1 = Vec::new(); let attacker_pos = PosHex { q: 0, r: 0 }; let effect_kill: Effect = effect::Kill { attacker_pos: Some(attacker_pos), } .into(); instant_effects1.push((Id(0), vec![effect_kill.clone(), Effect::Stun])); let mut context1 = ExecuteContext { instant_effects: instant_effects1, ..Default::default() }; let effect_dodge = effect::Dodge { attacker_pos }; let instant_effects2 = vec![(Id(0), vec![Effect::Vanish, effect_dodge.clone().into()])]; let context2 = ExecuteContext { instant_effects: instant_effects2, ..Default::default() }; let instant_effects_expected = vec![( Id(0), vec![ effect_kill, Effect::Stun, Effect::Vanish, effect_dodge.into(), ], )]; let context_expected = ExecuteContext { instant_effects: instant_effects_expected, ..Default::default() }; context1.merge_with(context2); assert_eq!(context_expected, context1); } }
{ let mut context = ExecuteContext::default(); let id = state::blocker_id_at(state, command.pos); if state.parts().belongs_to.get_opt(id).is_some() { let owner = state.parts().belongs_to.get(id).0; let phase = Phase::from_player_id(owner); let effect = effect::Timed { duration: effect::Duration::Rounds(1.into()), phase, effect: effect::Lasting::Stun, }; context.timed_effects.push((id, vec![effect])); extend_or_crate_sub_vec(&mut context.instant_effects, id, vec![Effect::Stun]); } context.actor_ids.push(id); context }
code.py
import time import board from analogio import AnalogIn from adafruit_crickit import crickit import neopixel print("Peltier Module Demo") pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, auto_write=False) def show_value(time_val): # Show time on NeoPixels on CPX
TMP36 = AnalogIn(board.A3) # TMP36 connected to A3, power & ground POT = AnalogIn(board.A7) # potentiometer connected to A7, power & ground peltier = crickit.dc_motor_2 # Drive the Peltier from Motor 2 Output while True: # Loop forever voltage = TMP36.value * 3.3 / 65536.0 tempC = (voltage - 0.5) * 100.0 tempF = (tempC * 9.0 / 5.0) + 32.0 cool_value = POT.value / 6553.6 # convert 0.0 to 10.0 # timing can be zero or can be 1 second to 10 seconds # between 0 and 1 is too short a time for a Peltier module if cool_value < 0.2: cool_value = 0.0 if 1.0 > cool_value >= 0.2: cool_value = 1.0 print((tempF, cool_value)) # Show in REPL show_value(cool_value) # Show on NeoPixels # Peltier cannot be PWM - either off or on # Use potentiometer read to set seconds b if cool_value > 0: peltier.throttle = 0.0 # turn off time.sleep(cool_value) # wait peltier.throttle = 1.0 # turn on time.sleep(10.0 - cool_value) # wait
num_pixels = int(10-time_val) for i in range(num_pixels): pixels[i] = (10*(i+1), 0, 0) for i in range(num_pixels, 10): pixels[i] = (0, 0, 0) pixels.show()
10-19_13.py
from typing import FrozenSet, Tuple import pysmt.typing as types from pysmt.environment import Environment as PysmtEnv from pysmt.fnode import FNode from utils import symb_to_next from hint import Hint, Location def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode, FNode]:
def hints(env: PysmtEnv) -> FrozenSet[Hint]: assert isinstance(env, PysmtEnv) mgr = env.formula_manager pc = mgr.Symbol("pc", types.INT) x = mgr.Symbol("x", types.INT) y = mgr.Symbol("y", types.INT) z = mgr.Symbol("z", types.INT) symbs = frozenset([pc, x, y, z]) x_pc = symb_to_next(mgr, pc) x_x = symb_to_next(mgr, x) x_y = symb_to_next(mgr, y) x_z = symb_to_next(mgr, z) res = [] i_0 = mgr.Int(0) i_1 = mgr.Int(1) i_2 = mgr.Int(2) i_3 = mgr.Int(3) loc0 = Location(env, mgr.GE(y, i_3)) loc0.set_progress(1, mgr.Equals(x_y, mgr.Plus(y, i_1))) loc1 = Location(env, mgr.GE(y, i_3)) loc1.set_progress(2, mgr.Equals(x_y, y)) loc2 = Location(env, mgr.GE(y, i_3)) loc2.set_progress(2, mgr.Equals(x_y, mgr.Plus(y, i_1))) h_y = Hint("h_y4", env, frozenset([y]), symbs) h_y.set_locs([loc0, loc1, loc2]) res.append(h_y) stutter = mgr.Equals(x_x, x) loc0 = Location(env, mgr.GT(x, i_0), mgr.And(mgr.GT(y, i_1), mgr.GT(z, i_1))) loc0.set_progress(1, mgr.GE(x_x, mgr.Minus(mgr.Times(y, z), i_1))) loc1 = Location(env, mgr.GT(x, i_0)) loc1.set_progress(0, mgr.Equals(x_x, mgr.Plus(x, i_1))) h_x = Hint("h_x2", env, frozenset([x]), symbs) h_x.set_locs([loc0, loc1]) res.append(h_x) loc0 = Location(env, mgr.GT(x, i_3), mgr.And(mgr.GT(y, i_1), mgr.GT(z, i_1))) loc0.set_progress(1, mgr.GE(x_x, mgr.Minus(mgr.Times(y, z), i_1))) loc1 = Location(env, mgr.GT(x, i_0), mgr.GE(y, i_1)) loc1.set_progress(0, mgr.Equals(x_x, mgr.Plus(x, y))) h_x = Hint("h_x3", env, frozenset([x]), symbs) h_x.set_locs([loc0, loc1]) res.append(h_x) loc0 = Location(env, mgr.GE(z, i_0)) loc0.set_progress(1, mgr.Equals(x_z, z)) loc1 = Location(env, mgr.GE(z, i_0)) loc1.set_progress(0, mgr.Equals(x_z, mgr.Plus(z, i_3))) h_z = Hint("h_z4", env, frozenset([z]), symbs) h_z.set_locs([loc0, loc1]) res.append(h_z) loc0 = Location(env, mgr.GE(z, i_3)) loc0.set_progress(0, mgr.GT(x_z, z)) h_z = Hint("h_z1", env, frozenset([z]), symbs) h_z.set_locs([loc0]) res.append(h_z) loc = Location(env, mgr.LE(z, i_0)) loc.set_progress(0, mgr.Equals(x_z, z)) h_z = Hint("h_z0", env, frozenset([z]), symbs) h_z.set_locs([loc]) res.append(h_z) loc0 = Location(env, mgr.GE(y, i_3)) loc0.set_progress(1, mgr.Equals(x_y, mgr.Plus(y, i_1))) loc1 = Location(env, mgr.GE(y, i_3), mgr.GE(x, i_2)) loc1.set_progress(0, mgr.Equals(x_y, mgr.Plus(y, x))) h_y = Hint("h_y3", env, frozenset([y]), symbs) h_y.set_locs([loc0, loc1]) res.append(h_y) stutter = mgr.Equals(x_y, y) loc0 = Location(env, mgr.GE(y, i_3)) loc0.set_progress(1, mgr.Equals(x_y, mgr.Plus(y, i_1))) loc1 = Location(env, mgr.GE(y, i_3), mgr.GE(z, i_2)) loc1.set_progress(0, mgr.Equals(x_y, mgr.Plus(y, z))) h_y = Hint("h_y2", env, frozenset([y]), symbs) h_y.set_locs([loc0, loc1]) res.append(h_y) loc0 = Location(env, mgr.Equals(pc, i_2)) loc0.set_progress(1, mgr.GT(x_pc, i_2)) loc1 = Location(env, mgr.GE(pc, i_3)) loc1.set_progress(0, mgr.Equals(x_pc, i_2)) h_pc = Hint("h_pc3", env, frozenset([pc]), symbs) h_pc.set_locs([loc0, loc1]) res.append(h_pc) loc0 = Location(env, mgr.GE(z, i_3), mgr.GE(y, i_0)) loc0.set_progress(1, mgr.Equals(x_z, y)) loc1 = Location(env, mgr.GE(z, i_0), mgr.GE(x, i_3)) loc1.set_progress(0, mgr.GE(x_z, mgr.Plus(z, x))) h_z = Hint("h_z3", env, frozenset([z]), symbs) h_z.set_locs([loc0, loc1]) res.append(h_z) return frozenset(res)
assert isinstance(env, PysmtEnv) mgr = env.formula_manager pc = mgr.Symbol("pc", types.INT) x = mgr.Symbol("x", types.INT) y = mgr.Symbol("y", types.INT) z = mgr.Symbol("z", types.INT) x_pc = symb_to_next(mgr, pc) x_x = symb_to_next(mgr, x) x_y = symb_to_next(mgr, y) x_z = symb_to_next(mgr, z) symbols = frozenset([pc, x, y, z]) n_locs = 5 int_bound = n_locs pcs = [] x_pcs = [] ints = [mgr.Int(i) for i in range(int_bound)] for l in range(n_locs): n = ints[l] pcs.append(mgr.Equals(pc, n)) x_pcs.append(mgr.Equals(x_pc, n)) m_1 = mgr.Int(-1) pcend = mgr.Equals(pc, m_1) x_pcend = mgr.Equals(x_pc, m_1) # initial location. init = pcs[0] # control flow graph. cfg = mgr.And( # pc = -1 : -1, mgr.Implies(pcend, x_pcend), # pc = 0 & !(y >= 1) : -1, mgr.Implies(mgr.And(pcs[0], mgr.Not(mgr.GE(y, ints[1]))), x_pcend), # pc = 0 & y >= 1 : 1, mgr.Implies(mgr.And(pcs[0], mgr.GE(y, ints[1])), x_pcs[1]), # pc = 1 & !(z >= 1) : -1, mgr.Implies(mgr.And(pcs[1], mgr.Not(mgr.GE(z, ints[1]))), x_pcend), # pc = 1 & z >= 1 : 2, mgr.Implies(mgr.And(pcs[1], mgr.GE(z, ints[1])), x_pcs[2]), # pc = 2 & !(x >= 0) : -1, mgr.Implies(mgr.And(pcs[2], mgr.Not(mgr.GE(x, ints[0]))), x_pcend), # pc = 2 & x >= 0 : 3, mgr.Implies(mgr.And(pcs[2], mgr.GE(x, ints[0])), x_pcs[3]), # pc = 3 : 4, mgr.Implies(pcs[3], x_pcs[4]), # pc = 4 : 2, mgr.Implies(pcs[4], x_pcs[2])) # transition labels. labels = mgr.And( # (pc = -1 & pc' = -1) -> (x' = x & y' = y & z' = z), mgr.Implies( mgr.And(pcend, x_pcend), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 0 & pc' = -1) -> (x' = x & y' = y & z' = z), mgr.Implies( mgr.And(pcs[0], x_pcend), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 0 & pc' = 1) -> (x' = x & y' = y & z' = z), mgr.Implies( mgr.And(pcs[0], x_pcs[1]), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 1 & pc' = -1) -> (x' = x & y' = y & z' = z), mgr.Implies( mgr.And(pcs[1], x_pcend), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 1 & pc' = 2) -> (x' = x & y' = y & z' = z), mgr.Implies( mgr.And(pcs[1], x_pcs[2]), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 2 & pc' = -1) -> (x' = x & y' = y & z' = z), mgr.Implies( mgr.And(pcs[2], x_pcend), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 2 & pc' = 3) -> (x' = x & y' = y & z' = z), mgr.Implies( mgr.And(pcs[2], x_pcs[3]), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 3 & pc' = 4) -> (x' = y*z - 1 & y' = y & z' = z), mgr.Implies( mgr.And(pcs[3], x_pcs[4]), mgr.And(mgr.Equals(x_x, mgr.Minus(mgr.Times(y, z), ints[1])), mgr.Equals(x_y, y), mgr.Equals(x_z, z))), # (pc = 4 & pc' = 2) -> (x' = x & y' = y+1 & z' = z), mgr.Implies( mgr.And(pcs[4], x_pcs[2]), mgr.And(mgr.Equals(x_x, x), mgr.Equals(x_y, mgr.Plus(y, ints[1])), mgr.Equals(x_z, z)))) # transition relation. trans = mgr.And(cfg, labels) # fairness. fairness = mgr.Not(pcend) return symbols, init, trans, fairness
raw.rs
// Copyright 2018-2020, Wayfair GmbH // // 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. // We want to keep the names here #![allow(clippy::module_name_repetitions)] use super::super::raw::*; use super::*; use crate::impl_expr; fn up_params<'script, 'registry>( params: WithExprsRaw<'script>, helper: &mut Helper<'script, 'registry>, ) -> Result<HashMap<String, Value<'script>>> { params .into_iter() .map(|(name, value)| Ok((name.id.to_string(), reduce2(value.up(helper)?, &helper)?))) .collect() } fn up_maybe_params<'script, 'registry>( params: Option<WithExprsRaw<'script>>, helper: &mut Helper<'script, 'registry>, ) -> Result<Option<HashMap<String, Value<'script>>>> { params.map(|params| up_params(params, helper)).transpose() } #[derive(Debug, PartialEq, Serialize)] #[allow(clippy::module_name_repetitions)] pub struct QueryRaw<'script> { pub(crate) stmts: StmtsRaw<'script>, } impl<'script> QueryRaw<'script> { pub(crate) fn up_script<'registry>( self, reg: &'registry Registry, aggr_reg: &'registry AggrRegistry, ) -> Result<(Query<'script>, usize, Vec<Warning>)> { let mut helper = Helper::new(reg, aggr_reg); Ok(( Query { stmts: self.stmts.up(&mut helper)?, node_meta: helper.meta, }, helper.locals.len(), helper.warnings, )) } } /// we're forced to make this pub because of lalrpop #[derive(Clone, Debug, PartialEq, Serialize)] pub enum StmtRaw<'script> { /// we're forced to make this pub because of lalrpop WindowDecl(WindowDeclRaw<'script>), /// we're forced to make this pub because of lalrpop OperatorDecl(OperatorDeclRaw<'script>), /// we're forced to make this pub because of lalrpop ScriptDecl(ScriptDeclRaw<'script>), /// we're forced to make this pub because of lalrpop Stream(StreamStmtRaw), /// we're forced to make this pub because of lalrpop Operator(OperatorStmtRaw<'script>), /// we're forced to make this pub because of lalrpop Script(ScriptStmtRaw<'script>), /// we're forced to make this pub because of lalrpop Select(Box<SelectRaw<'script>>), } impl<'script> Upable<'script> for StmtRaw<'script> { type Target = Stmt<'script>; fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> { match self { StmtRaw::Select(stmt) => { let mut aggregates = Vec::new(); let mut consts = HashMap::new(); let mut locals = HashMap::new(); helper.swap(&mut aggregates, &mut consts, &mut locals); let stmt: Select<'script> = stmt.up(helper)?; helper.swap(&mut aggregates, &mut consts, &mut locals); // We know that select statements have exactly three consts let consts = vec![Value::null(), Value::null(), Value::null()]; Ok(Stmt::Select(SelectStmt { stmt: Box::new(stmt), aggregates, consts, locals: locals.len(), node_meta: helper.meta.clone(), })) } StmtRaw::Stream(stmt) => Ok(Stmt::Stream(stmt.up(helper)?)), StmtRaw::OperatorDecl(stmt) => Ok(Stmt::OperatorDecl(stmt.up(helper)?)), StmtRaw::Operator(stmt) => Ok(Stmt::Operator(stmt.up(helper)?)), StmtRaw::ScriptDecl(stmt) => { let stmt: ScriptDecl<'script> = stmt.up(helper)?; Ok(Stmt::ScriptDecl(stmt)) } StmtRaw::Script(stmt) => Ok(Stmt::Script(stmt.up(helper)?)), StmtRaw::WindowDecl(stmt) => { let stmt: WindowDecl<'script> = stmt.up(helper)?; Ok(Stmt::WindowDecl(stmt)) } } } } /// we're forced to make this pub because of lalrpop #[derive(Clone, Debug, PartialEq, Serialize)] pub struct
<'script> { pub(crate) start: Location, pub(crate) end: Location, pub(crate) kind: OperatorKindRaw, pub(crate) id: String, pub(crate) params: Option<WithExprsRaw<'script>>, } impl<'script> Upable<'script> for OperatorDeclRaw<'script> { type Target = OperatorDecl<'script>; fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> { let operator_decl = OperatorDecl { mid: helper.add_meta(self.start, self.end), id: self.id, kind: self.kind.up(helper)?, params: up_maybe_params(self.params, helper)?, }; helper.operators.push(operator_decl.clone()); Ok(operator_decl) } } /// we're forced to make this pub because of lalrpop #[derive(Clone, Debug, PartialEq, Serialize)] pub struct OperatorStmtRaw<'script> { pub(crate) start: Location, pub(crate) end: Location, pub(crate) id: String, pub(crate) target: String, pub(crate) params: Option<WithExprsRaw<'script>>, } impl_expr!(OperatorStmtRaw); impl<'script> Upable<'script> for OperatorStmtRaw<'script> { type Target = OperatorStmt<'script>; fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> { Ok(OperatorStmt { mid: helper.add_meta(self.start, self.end), id: self.id, target: self.target, params: up_maybe_params(self.params, helper)?, }) } } /// we're forced to make this pub because of lalrpop #[derive(Clone, Debug, PartialEq, Serialize)] pub struct ScriptDeclRaw<'script> { pub(crate) start: Location, pub(crate) end: Location, pub(crate) id: String, pub(crate) params: Option<WithExprsRaw<'script>>, pub(crate) script: ScriptRaw<'script>, } impl<'script> Upable<'script> for ScriptDeclRaw<'script> { type Target = ScriptDecl<'script>; fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> { // Inject consts let (script, mut warnings) = self.script.up_script(helper.reg, helper.aggr_reg)?; helper.warnings.append(&mut warnings); helper.warnings.sort(); helper.warnings.dedup(); let script_decl = ScriptDecl { mid: helper.add_meta(self.start, self.end), id: self.id, params: up_maybe_params(self.params, helper)?, script, }; helper.scripts.push(script_decl.clone()); Ok(script_decl) } } /// we're forced to make this pub because of lalrpop #[derive(Clone, Debug, PartialEq, Serialize)] pub struct ScriptStmtRaw<'script> { pub(crate) start: Location, pub(crate) end: Location, pub(crate) id: String, pub(crate) target: String, pub(crate) params: Option<WithExprsRaw<'script>>, } impl<'script> Upable<'script> for ScriptStmtRaw<'script> { type Target = ScriptStmt<'script>; fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> { // let (script, mut warnings) = self.script.up_script(helper.reg, helper.aggr_reg)?; // helper.warnings.append(&mut warnings); Ok(ScriptStmt { mid: helper.add_meta(self.start, self.end), id: self.id, params: up_maybe_params(self.params, helper)?, target: self.target, }) } } /// we're forced to make this pub because of lalrpop #[derive(Clone, Debug, PartialEq, Serialize)] pub struct WindowDeclRaw<'script> { pub(crate) start: Location, pub(crate) end: Location, pub(crate) id: String, pub(crate) kind: WindowKind, pub(crate) params: WithExprsRaw<'script>, pub(crate) script: Option<ScriptRaw<'script>>, } impl<'script> Upable<'script> for WindowDeclRaw<'script> { type Target = WindowDecl<'script>; fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> { let mut maybe_script = self .script .map(|s| s.up_script(helper.reg, helper.aggr_reg)) .transpose()?; if let Some((_, ref mut warnings)) = maybe_script { helper.warnings.append(warnings); helper.warnings.sort(); helper.warnings.dedup(); }; Ok(WindowDecl { mid: helper.add_meta(self.start, self.end), id: self.id, kind: self.kind, params: up_params(self.params, helper)?, script: maybe_script.map(|s| s.0), }) } } /// we're forced to make this pub because of lalrpop #[derive(Clone, Debug, PartialEq, Serialize)] pub struct WindowDefnRaw { pub(crate) start: Location, pub(crate) end: Location, /// ID of the window pub id: String, } /// we're forced to make this pub because of lalrpop #[derive(Clone, Debug, PartialEq, Serialize)] pub struct SelectRaw<'script> { pub(crate) start: Location, pub(crate) end: Location, pub(crate) from: (IdentRaw<'script>, Option<IdentRaw<'script>>), pub(crate) into: (IdentRaw<'script>, Option<IdentRaw<'script>>), pub(crate) target: ImutExprRaw<'script>, pub(crate) maybe_where: Option<ImutExprRaw<'script>>, pub(crate) maybe_having: Option<ImutExprRaw<'script>>, pub(crate) maybe_group_by: Option<GroupByRaw<'script>>, pub(crate) windows: Option<Vec<WindowDefnRaw>>, } impl_expr!(SelectRaw); impl<'script> Upable<'script> for SelectRaw<'script> { type Target = Select<'script>; fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> { if !helper.consts.is_empty() { return error_no_consts(&(self.start, self.end), &self.target, &helper.meta); } // reserve const ids for builtin const helper.consts.insert("window".to_owned(), WINDOW_CONST_ID); helper.consts.insert("group".to_owned(), GROUP_CONST_ID); helper.consts.insert("args".to_owned(), ARGS_CONST_ID); let target = self.target.up(helper)?; if helper.has_locals() { return error_no_locals(&(self.start, self.end), &target, &helper.meta); }; let maybe_having = self.maybe_having.up(helper)?; if helper.has_locals() { if let Some(definitely) = maybe_having { return error_no_locals(&(self.start, self.end), &definitely, &helper.meta); } }; if helper.consts.remove("window") != Some(WINDOW_CONST_ID) || helper.consts.remove("group") != Some(GROUP_CONST_ID) || helper.consts.remove("args") != Some(ARGS_CONST_ID) || !helper.consts.is_empty() { return error_no_consts(&(self.start, self.end), &target, &helper.meta); } let maybe_where = self.maybe_where.up(helper)?; if helper.has_locals() { if let Some(definitely) = maybe_where { return error_no_locals(&(self.start, self.end), &definitely, &helper.meta); } }; let maybe_group_by = self.maybe_group_by.up(helper)?; if helper.has_locals() { if let Some(definitely) = maybe_group_by { return error_no_locals(&(self.start, self.end), &definitely, &helper.meta); } }; let windows = self.windows.unwrap_or_default(); let from = match self.from { (stream, None) => { let mut port = stream.clone(); port.id = Cow::Borrowed("out"); (stream, port) } (stream, Some(port)) => (stream, port), }; let into = match self.into { (stream, None) => { let mut port = stream.clone(); port.id = Cow::Borrowed("in"); (stream, port) } (stream, Some(port)) => (stream, port), }; Ok(Select { mid: helper.add_meta(self.start, self.end), from: (from.0.up(helper)?, from.1.up(helper)?), into: (into.0.up(helper)?, into.1.up(helper)?), target: ImutExpr(target), maybe_where: maybe_where.map(ImutExpr), maybe_having: maybe_having.map(ImutExpr), maybe_group_by, windows, }) } } /// we're forced to make this pub because of lalrpop #[derive(Clone, Debug, PartialEq, Serialize)] pub enum GroupByRaw<'script> { /// we're forced to make this pub because of lalrpop Expr { /// we're forced to make this pub because of lalrpop start: Location, /// we're forced to make this pub because of lalrpop end: Location, /// we're forced to make this pub because of lalrpop expr: ImutExprRaw<'script>, }, /// we're forced to make this pub because of lalrpop Set { /// we're forced to make this pub because of lalrpop start: Location, /// we're forced to make this pub because of lalrpop end: Location, /// we're forced to make this pub because of lalrpop items: Vec<GroupByRaw<'script>>, }, /// we're forced to make this pub because of lalrpop Each { /// we're forced to make this pub because of lalrpop start: Location, /// we're forced to make this pub because of lalrpop end: Location, /// we're forced to make this pub because of lalrpop expr: ImutExprRaw<'script>, }, } impl<'script> Upable<'script> for GroupByRaw<'script> { type Target = GroupBy<'script>; fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> { Ok(match self { GroupByRaw::Expr { start, end, expr } => GroupBy(GroupByInt::Expr { mid: helper.add_meta(start, end), expr: expr.up(helper)?, }), GroupByRaw::Each { start, end, expr } => GroupBy(GroupByInt::Each { mid: helper.add_meta(start, end), expr: expr.up(helper)?, }), GroupByRaw::Set { start, end, items } => GroupBy(GroupByInt::Set { mid: helper.add_meta(start, end), items: items.up(helper)?, }), }) } } /// we're forced to make this pub because of lalrpop #[derive(Clone, Debug, PartialEq, Serialize)] pub struct OperatorKindRaw { pub(crate) start: Location, pub(crate) end: Location, pub(crate) module: String, pub(crate) operation: String, } impl BaseExpr for OperatorKindRaw { fn s(&self, _meta: &NodeMetas) -> Location { self.start } fn e(&self, _meta: &NodeMetas) -> Location { self.end } fn mid(&self) -> usize { 0 } } impl<'script> Upable<'script> for OperatorKindRaw { type Target = OperatorKind; fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> { Ok(OperatorKind { mid: helper.add_meta(self.start, self.end), module: self.module, operation: self.operation, }) } } /// we're forced to make this pub because of lalrpop #[derive(Clone, Debug, PartialEq, Serialize)] pub struct StreamStmtRaw { pub(crate) start: Location, pub(crate) end: Location, pub(crate) id: String, } impl<'script> Upable<'script> for StreamStmtRaw { type Target = StreamStmt; fn up<'registry>(self, helper: &mut Helper<'script, 'registry>) -> Result<Self::Target> { Ok(StreamStmt { mid: helper.add_meta(self.start, self.end), id: self.id, }) } } pub type StmtsRaw<'script> = Vec<StmtRaw<'script>>;
OperatorDeclRaw
main.rs
//! Board file for LowRISC OpenTitan RISC-V development platform. //! //! - <https://opentitan.org/> #![no_std] // Disable this attribute when documenting, as a workaround for // https://github.com/rust-lang/rust/issues/62184. #![cfg_attr(not(doc), no_main)] #![feature(const_in_array_repeat_expressions)] use capsules::virtual_alarm::{MuxAlarm, VirtualMuxAlarm}; use capsules::virtual_hmac::VirtualMuxHmac; use earlgrey::chip::EarlGreyDefaultPeripherals; use kernel::capabilities; use kernel::common::dynamic_deferred_call::{DynamicDeferredCall, DynamicDeferredCallClientState}; use kernel::component::Component; use kernel::hil; use kernel::hil::i2c::I2CMaster; use kernel::hil::time::Alarm; use kernel::Chip; use kernel::Platform; use kernel::{create_capability, debug, static_init}; use rv32i::csr; use capsules::vpp::process::VppProcess; use capsules::vpp::vppkernel::VppKernel; #[allow(dead_code)] mod aes_test; #[allow(dead_code)] mod multi_alarm_test; pub mod io; pub mod usb; use capsules::vpp::vppkernel::NUM_PROCS; use capsules::vpp::mloi::{MK_MAILBOX_LIMIT, MK_IPC_LIMIT}; use capsules::vpp::mailbox::mbox; use capsules::vpp::ipc::ipc; // Actual memory for holding the active process structures. Need an empty list // at least. static mut PROCESSES: [Option<&'static dyn kernel::procs::ProcessType>; NUM_PROCS] = [None;NUM_PROCS]; static mut VPP_PROCESSES: [Option<VppProcess>;NUM_PROCS] = [None;NUM_PROCS]; static mut MBOX_ARRAY: [Option<mbox>;MK_MAILBOX_LIMIT] = [None;MK_MAILBOX_LIMIT]; static mut IPC_ARRAY : [Option<ipc>; MK_IPC_LIMIT] = [None;MK_IPC_LIMIT]; static mut CHIP: Option< &'static earlgrey::chip::EarlGrey<VirtualMuxAlarm<'static, earlgrey::timer::RvTimer>>, > = None; // How should the kernel respond when a process faults. const FAULT_RESPONSE: kernel::procs::FaultResponse = kernel::procs::FaultResponse::Panic; /// Dummy buffer that causes the linker to reserve enough space for the stack. #[no_mangle] #[link_section = ".stack_buffer"] pub static mut STACK_MEMORY: [u8; 0x1000] = [0; 0x1000]; /// A structure representing this platform that holds references to all /// capsules for this platform. We've included an alarm and console. struct OpenTitan { led: &'static capsules::led::LED<'static, earlgrey::gpio::GpioPin<'static>>, gpio: &'static capsules::gpio::GPIO<'static, earlgrey::gpio::GpioPin<'static>>, console: &'static capsules::console::Console<'static>, ipc: kernel::ipc::IPC, alarm: &'static capsules::alarm::AlarmDriver< 'static, VirtualMuxAlarm<'static, earlgrey::timer::RvTimer<'static>>, >, hmac: &'static capsules::hmac::HmacDriver< 'static, VirtualMuxHmac<'static, lowrisc::hmac::Hmac<'static>, [u8; 32]>, [u8; 32], >, lldb: &'static capsules::low_level_debug::LowLevelDebug< 'static, capsules::virtual_uart::UartDevice<'static>, >, i2c_master: &'static capsules::i2c_master::I2CMasterDriver<lowrisc::i2c::I2c<'static>>, pm : &'static capsules::vpp::pmsyscall::ProcessManager, vpp_driver: &'static capsules::vpp::vppkernel::vpp_kernel_driver, nonvolatile_storage: &'static capsules::nonvolatile_storage_driver::NonvolatileStorage<'static>, // vpmdriver: &'static capsules::vpp::ProcessManagerConsoleCap::VPMDriver, // testdriver: &'static capsules::vpp::SubTest::Test, } /// Mapping of integer syscalls to objects that implement syscalls. impl Platform for OpenTitan { fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R where F: FnOnce(Option<&dyn kernel::Driver>) -> R, { match driver_num { capsules::vpp::vppkernel::DRIVER_NUM => f(Some(self.vpp_driver)), // 0x9000A => f(Some(self.testdriver)), 0x90003 => f(Some(self.pm)), // 0x90004 => f(Some(self.vpmdriver)), capsules::led::DRIVER_NUM => f(Some(self.led)), capsules::hmac::DRIVER_NUM => f(Some(self.hmac)), capsules::gpio::DRIVER_NUM => f(Some(self.gpio)), capsules::console::DRIVER_NUM => f(Some(self.console)), kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)), capsules::alarm::DRIVER_NUM => f(Some(self.alarm)), capsules::low_level_debug::DRIVER_NUM => f(Some(self.lldb)), capsules::i2c_master::DRIVER_NUM => f(Some(self.i2c_master)), capsules::nonvolatile_storage_driver::DRIVER_NUM => f(Some(self.nonvolatile_storage)), _ => f(None), } } } /// Reset Handler. /// /// This function is called from the arch crate after some very basic RISC-V /// setup. #[no_mangle] pub unsafe fn
() { // Basic setup of the platform. rv32i::init_memory(); // Ibex-specific handler earlgrey::chip::configure_trap_handler(); let peripherals = static_init!( EarlGreyDefaultPeripherals, EarlGreyDefaultPeripherals::new() ); // initialize capabilities let process_mgmt_cap = create_capability!(capabilities::ProcessManagementCapability); let memory_allocation_cap = create_capability!(capabilities::MemoryAllocationCapability); let grant_cap = create_capability!(capabilities::MemoryAllocationCapability); let main_loop_cap = create_capability!(capabilities::MainLoopCapability); let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(&PROCESSES)); let dynamic_deferred_call_clients = static_init!([DynamicDeferredCallClientState; 1], Default::default()); let dynamic_deferred_caller = static_init!( DynamicDeferredCall, DynamicDeferredCall::new(dynamic_deferred_call_clients) ); DynamicDeferredCall::set_global_instance(dynamic_deferred_caller); // Configure kernel debug gpios as early as possible kernel::debug::assign_gpios( Some(&earlgrey::gpio::PORT[7]), // First LED None, None, ); // Create a shared UART channel for the console and for kernel debug. let uart_mux = components::console::UartMuxComponent::new( &earlgrey::uart::UART0, earlgrey::uart::UART0_BAUDRATE, dynamic_deferred_caller, ) .finalize(()); uart_mux.initialize(); // Setup the console. let console = components::console::ConsoleComponent::new(board_kernel, uart_mux).finalize(()); // let process_console = // components::process_console::ProcessConsoleComponent::new(board_kernel, uart_mux) // .finalize(()); // Create the debugger object that handles calls to `debug!()`. components::debug_writer::DebugWriterComponent::new(uart_mux).finalize(()); let lldb = components::lldb::LowLevelDebugComponent::new(board_kernel, uart_mux).finalize(()); // LEDs // Start with half on and half off let led = components::led::LedsComponent::new(components::led_component_helper!( earlgrey::gpio::GpioPin, ( &earlgrey::gpio::PORT[8], kernel::hil::gpio::ActivationMode::ActiveHigh ), ( &earlgrey::gpio::PORT[9], kernel::hil::gpio::ActivationMode::ActiveHigh ), ( &earlgrey::gpio::PORT[10], kernel::hil::gpio::ActivationMode::ActiveHigh ), ( &earlgrey::gpio::PORT[11], kernel::hil::gpio::ActivationMode::ActiveHigh ), ( &earlgrey::gpio::PORT[12], kernel::hil::gpio::ActivationMode::ActiveHigh ), ( &earlgrey::gpio::PORT[13], kernel::hil::gpio::ActivationMode::ActiveHigh ), ( &earlgrey::gpio::PORT[14], kernel::hil::gpio::ActivationMode::ActiveHigh ), ( &earlgrey::gpio::PORT[15], kernel::hil::gpio::ActivationMode::ActiveHigh ) )) .finalize(components::led_component_buf!(earlgrey::gpio::GpioPin)); let gpio = components::gpio::GpioComponent::new( board_kernel, components::gpio_component_helper!( earlgrey::gpio::GpioPin, 0 => &earlgrey::gpio::PORT[0], 1 => &earlgrey::gpio::PORT[1], 2 => &earlgrey::gpio::PORT[2], 3 => &earlgrey::gpio::PORT[3], 4 => &earlgrey::gpio::PORT[4], 5 => &earlgrey::gpio::PORT[5], 6 => &earlgrey::gpio::PORT[6], 7 => &earlgrey::gpio::PORT[15] ), ) .finalize(components::gpio_component_buf!(earlgrey::gpio::GpioPin)); let alarm = &earlgrey::timer::TIMER; // Create a shared virtualization mux layer on top of a single hardware // alarm. let mux_alarm = static_init!( MuxAlarm<'static, earlgrey::timer::RvTimer>, MuxAlarm::new(alarm) ); hil::time::Alarm::set_alarm_client(&earlgrey::timer::TIMER, mux_alarm); // Alarm let virtual_alarm_user = static_init!( VirtualMuxAlarm<'static, earlgrey::timer::RvTimer>, VirtualMuxAlarm::new(mux_alarm) ); let scheduler_timer_virtual_alarm = static_init!( VirtualMuxAlarm<'static, earlgrey::timer::RvTimer>, VirtualMuxAlarm::new(mux_alarm) ); let alarm = static_init!( capsules::alarm::AlarmDriver<'static, VirtualMuxAlarm<'static, earlgrey::timer::RvTimer>>, capsules::alarm::AlarmDriver::new( virtual_alarm_user, board_kernel.create_grant(&memory_allocation_cap) ) ); hil::time::Alarm::set_alarm_client(virtual_alarm_user, alarm); // let vpp_kernel = static_init!(VppKernel, // VppKernel::new(&VPP_PROCESSES,&MBOX_ARRAY,&IPC_ARRAY,board_kernel,virtual_alarm_user)); let vpp_kernel = static_init!(VppKernel, VppKernel::new(&VPP_PROCESSES,&MBOX_ARRAY,&IPC_ARRAY,board_kernel)); let chip = static_init!( earlgrey::chip::EarlGrey<VirtualMuxAlarm<'static, earlgrey::timer::RvTimer>>, earlgrey::chip::EarlGrey::new(scheduler_timer_virtual_alarm) ); scheduler_timer_virtual_alarm.set_alarm_client(chip.scheduler_timer()); CHIP = Some(chip); // Need to enable all interrupts for Tock Kernel chip.enable_plic_interrupts(); // enable interrupts globally csr::CSR .mie .modify(csr::mie::mie::msoft::SET + csr::mie::mie::mtimer::SET + csr::mie::mie::mext::SET); csr::CSR.mstatus.modify(csr::mstatus::mstatus::mie::SET); let hmac_data_buffer = static_init!([u8; 64], [0; 64]); let hmac_dest_buffer = static_init!([u8; 32], [0; 32]); let mux_hmac = components::hmac::HmacMuxComponent::new(&earlgrey::hmac::HMAC).finalize( components::hmac_mux_component_helper!(lowrisc::hmac::Hmac, [u8; 32]), ); let hmac = components::hmac::HmacComponent::new( board_kernel, &mux_hmac, hmac_data_buffer, hmac_dest_buffer, ) .finalize(components::hmac_component_helper!( lowrisc::hmac::Hmac, [u8; 32] )); let i2c_master = static_init!( capsules::i2c_master::I2CMasterDriver<lowrisc::i2c::I2c<'static>>, capsules::i2c_master::I2CMasterDriver::new( &earlgrey::i2c::I2C, &mut capsules::i2c_master::BUF, board_kernel.create_grant(&memory_allocation_cap) ) ); earlgrey::i2c::I2C.set_master_client(i2c_master); // Syscall driver to vpp kernel let vpp_driver = static_init!(capsules::vpp::vppkernel::vpp_kernel_driver, capsules::vpp::vppkernel::vpp_kernel_driver::new(vpp_kernel)); // useless Syscall Driver let pm = static_init!(capsules::vpp::pmsyscall::ProcessManager, capsules::vpp::pmsyscall::ProcessManager::new()); // Capsules to test Subscribe Syscall using grant // let testdriver = static_init!(capsules::vpp::SubTest::Test, // capsules::vpp::SubTest::Test::new(board_kernel.create_grant(&memory_allocation_cap))); // testdriver.trigger_callback(); extern "C" { /// Beginning on the ROM region containing app images. static _sstorage: u8; static _estorage: u8; } // Flash let nonvolatile_storage = components::nonvolatile_storage::NonvolatileStorageComponent::new( board_kernel, &peripherals.flash_ctrl, 0x20000000, // Start address for userspace accessible region 0x8000, // Length of userspace accessible region &_sstorage as *const u8 as usize, // Start address of kernel region &_estorage as *const u8 as usize - &_sstorage as *const u8 as usize, // Length of kernel region ) .finalize(components::nv_storage_component_helper!( lowrisc::flash_ctrl::FlashCtrl )); let vpp_process_console = capsules::vpp::ProcessManagerConsoleCap ::ProcessConsoleComponent::new(vpp_kernel,uart_mux) .finalize(()); vpp_process_console.start(); debug!("OpenTitan initialisation complete. Entering main loop"); let opentitan = OpenTitan { gpio: gpio, led: led, console: console, ipc: kernel::ipc::IPC::new(board_kernel,&grant_cap), alarm: alarm, hmac, lldb: lldb, //usb, i2c_master, pm, vpp_driver, nonvolatile_storage }; // USB support is currently broken in the OpenTitan hardware // See https://github.com/lowRISC/opentitan/issues/2598 for more details // let usb = usb::UsbComponent::new(board_kernel).finalize(()); capsules::vpp::process::load_vpp_processes( board_kernel, chip, // app_flash, // app_memory, &mut PROCESSES, &mut VPP_PROCESSES, &mut MBOX_ARRAY, &mut IPC_ARRAY, FAULT_RESPONSE, &process_mgmt_cap) .unwrap_or_else(|err| { debug!("Error loading processes!"); debug!("{:?}", err); }); //_vpp_kernel._mk_resume_process(0); //_vpp_kernel._mk_resume_process(1); //panic!("Panic"); let scheduler = components::sched::priority::PriorityComponent::new(board_kernel).finalize(()); board_kernel.kernel_loop(&opentitan, chip, Some(&opentitan.ipc), scheduler, &main_loop_cap); }
reset_handler
todos.client.resources.js
(function() { 'use strict'; angular.module('todos') .service('TodoResources', TodoResources); TodoResources.$inject = ['TodoConsts']; function
(TodoConsts) { this.todosPath = TodoConsts.api.path.todos; this.todosParamNoCache = TodoConsts.api.param.noCache; } })();
TodoResources
utils.py
def hashable(x): try: hash(x) return True except TypeError: return False def transitive_get(key, d): """ Transitive dict.get >>> d = {1: 2, 2: 3, 3: 4} >>> d.get(1) 2 >>> transitive_get(1, d) 4 """ while hashable(key) and key in d: key = d[key] return key def raises(err, lamda): try: lamda() return False except err: return True # Taken from theano/theano/gof/sched.py # Avoids licensing issues because this was written by Matthew Rocklin def
(edges): """ Topological sort algorithm by Kahn [1] - O(nodes + vertices) inputs: edges - a dict of the form {a: {b, c}} where b and c depend on a outputs: L - an ordered list of nodes that satisfy the dependencies of edges >>> _toposort({1: (2, 3), 2: (3, )}) [1, 2, 3] Closely follows the wikipedia page [2] [1] Kahn, Arthur B. (1962), "Topological sorting of large networks", Communications of the ACM [2] http://en.wikipedia.org/wiki/Toposort#Algorithms """ incoming_edges = reverse_dict(edges) incoming_edges = dict((k, set(val)) for k, val in incoming_edges.items()) S = set((v for v in edges if v not in incoming_edges)) L = [] while S: n = S.pop() L.append(n) for m in edges.get(n, ()): assert n in incoming_edges[m] incoming_edges[m].remove(n) if not incoming_edges[m]: S.add(m) if any(incoming_edges.get(v, None) for v in edges): raise ValueError("Input has cycles") return L def reverse_dict(d): """Reverses direction of dependence dict >>> d = {'a': (1, 2), 'b': (2, 3), 'c':()} >>> reverse_dict(d) # doctest: +SKIP {1: ('a',), 2: ('a', 'b'), 3: ('b',)} :note: dict order are not deterministic. As we iterate on the input dict, it make the output of this function depend on the dict order. So this function output order should be considered as undeterministic. """ result = {} # type: ignore[var-annotated] for key in d: for val in d[key]: result[val] = result.get(val, tuple()) + (key, ) return result def xfail(func): try: func() raise Exception("XFailed test passed") # pragma:nocover except Exception: pass def freeze(d): """ Freeze container to hashable form >>> freeze(1) 1 >>> freeze([1, 2]) (1, 2) >>> freeze({1: 2}) # doctest: +SKIP frozenset([(1, 2)]) """ if isinstance(d, dict): return frozenset(map(freeze, d.items())) if isinstance(d, set): return frozenset(map(freeze, d)) if isinstance(d, (tuple, list)): return tuple(map(freeze, d)) return d
_toposort
main.rs
use ferris_says::say; use std::io::{stdout, BufWriter}; fn main() { let stdout = stdout(); let out = b"Hello, zhanghe.cool!"; let width = 24;
let mut writer = BufWriter::new(stdout.lock()); say(out, width, &mut writer).unwrap(); }
graphite.py
# coding=utf-8 """ Send metrics to a [graphite](http://graphite.wikidot.com/) using the default interface. Graphite is an enterprise-scale monitoring tool that runs well on cheap hardware. It was originally designed and written by Chris Davis at Orbitz in 2006 as side project that ultimately grew to be a foundational monitoring tool. In 2008, Orbitz allowed Graphite to be released under the open source Apache 2.0 license. Since then Chris has continued to work on Graphite and has deployed it at other companies including Sears, where it serves as a pillar of the e-commerce monitoring system. Today many [large companies](http://graphite.readthedocs.org/en/latest/who-is-using.html) use it. """ from Handler import Handler import socket class
(Handler): """ Implements the abstract Handler class, sending data to graphite """ def __init__(self, config=None): """ Create a new instance of the GraphiteHandler class """ # Initialize Handler Handler.__init__(self, config) # Initialize Data self.socket = None # Initialize Options self.proto = self.config['proto'].lower().strip() self.host = self.config['host'] self.port = int(self.config['port']) self.timeout = float(self.config['timeout']) self.keepalive = bool(self.config['keepalive']) self.keepaliveinterval = int(self.config['keepaliveinterval']) self.batch_size = int(self.config['batch']) self.max_backlog_multiplier = int( self.config['max_backlog_multiplier']) self.trim_backlog_multiplier = int( self.config['trim_backlog_multiplier']) self.flow_info = self.config['flow_info'] self.scope_id = self.config['scope_id'] self.metrics = [] # Connect self._connect() def get_default_config_help(self): """ Returns the help text for the configuration options for this handler """ config = super(GraphiteHandler, self).get_default_config_help() config.update({ 'host': 'Hostname', 'port': 'Port', 'proto': 'udp, udp4, udp6, tcp, tcp4, or tcp6', 'timeout': '', 'batch': 'How many to store before sending to the graphite server', 'max_backlog_multiplier': 'how many batches to store before trimming', # NOQA 'trim_backlog_multiplier': 'Trim down how many batches', 'keepalive': 'Enable keepalives for tcp streams', 'keepaliveinterval': 'How frequently to send keepalives', 'flow_info': 'IPv6 Flow Info', 'scope_id': 'IPv6 Scope ID', }) return config def get_default_config(self): """ Return the default config for the handler """ config = super(GraphiteHandler, self).get_default_config() config.update({ 'host': 'localhost', 'port': 2003, 'proto': 'tcp', 'timeout': 15, 'batch': 1, 'max_backlog_multiplier': 5, 'trim_backlog_multiplier': 4, 'keepalive': 0, 'keepaliveinterval': 10, 'flow_info': 0, 'scope_id': 0, }) return config def __del__(self): """ Destroy instance of the GraphiteHandler class """ self._close() def process(self, metric): """ Process a metric by sending it to graphite """ # Append the data to the array as a string self.metrics.append(str(metric)) if len(self.metrics) >= self.batch_size: self._send() def flush(self): """Flush metrics in queue""" self._send() def _send_data(self, data): """ Try to send all data in buffer. """ try: self.socket.sendall(data) self._reset_errors() except: self._close() self._throttle_error("GraphiteHandler: Socket error, " "trying reconnect.") self._connect() try: self.socket.sendall(data) except: return self._reset_errors() def _send(self): """ Send data to graphite. Data that can not be sent will be queued. """ # Check to see if we have a valid socket. If not, try to connect. try: try: if self.socket is None: self.log.debug("GraphiteHandler: Socket is not connected. " "Reconnecting.") self._connect() if self.socket is None: self.log.debug("GraphiteHandler: Reconnect failed.") else: # Send data to socket self._send_data(''.join(self.metrics)) self.metrics = [] except Exception: self._close() self._throttle_error("GraphiteHandler: Error sending metrics.") raise finally: if len(self.metrics) >= ( self.batch_size * self.max_backlog_multiplier): trim_offset = (self.batch_size * self.trim_backlog_multiplier * -1) self.log.warn('GraphiteHandler: Trimming backlog. Removing' + ' oldest %d and keeping newest %d metrics', len(self.metrics) - abs(trim_offset), abs(trim_offset)) self.metrics = self.metrics[trim_offset:] def _connect(self): """ Connect to the graphite server """ if (self.proto == 'udp'): stream = socket.SOCK_DGRAM else: stream = socket.SOCK_STREAM if (self.proto[-1] == '4'): family = socket.AF_INET connection_struct = (self.host, self.port) elif (self.proto[-1] == '6'): family = socket.AF_INET6 connection_struct = (self.host, self.port, self.flow_info, self.scope_id) else: connection_struct = (self.host, self.port) try: addrinfo = socket.getaddrinfo(self.host, self.port, 0, stream) except socket.gaierror, ex: self.log.error("GraphiteHandler: Error looking up graphite host" " '%s' - %s", self.host, ex) return if (len(addrinfo) > 0): family = addrinfo[0][0] if (family == socket.AF_INET6): connection_struct = (self.host, self.port, self.flow_info, self.scope_id) else: family = socket.AF_INET # Create socket self.socket = socket.socket(family, stream) if self.socket is None: # Log Error self.log.error("GraphiteHandler: Unable to create socket.") # Close Socket self._close() return # Enable keepalives? if self.proto != 'udp' and self.keepalive: self.log.error("GraphiteHandler: Setting socket keepalives...") self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, self.keepaliveinterval) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, self.keepaliveinterval) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 3) # Set socket timeout self.socket.settimeout(self.timeout) # Connect to graphite server try: self.socket.connect(connection_struct) # Log self.log.debug("GraphiteHandler: Established connection to " "graphite server %s:%d.", self.host, self.port) except Exception, ex: # Log Error self._throttle_error("GraphiteHandler: Failed to connect to " "%s:%i. %s.", self.host, self.port, ex) # Close Socket self._close() return def _close(self): """ Close the socket """ if self.socket is not None: self.socket.close() self.socket = None
GraphiteHandler
transaction.go
// Copyright 2019 NetApp, Inc. All Rights Reserved. package v1 import ( "encoding/json" "github.com/netapp/trident/storage" "github.com/netapp/trident/utils" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // NewTridentTransaction creates a new storage class CRD object from a VolumeTransaction object func
(txn *storage.VolumeTransaction) (*TridentTransaction, error) { transaction := &TridentTransaction{ TypeMeta: metav1.TypeMeta{ APIVersion: "trident.netapp.io/v1", Kind: "TridentTransaction", }, ObjectMeta: metav1.ObjectMeta{ Name: NameFix(txn.Name()), Finalizers: GetTridentFinalizers(), }, } if err := transaction.Apply(txn); err != nil { return nil, err } return transaction, nil } // Apply applies changes from an operation and internal // storage.VolumeConfig object to its Kubernetes CRD equivalent func (in *TridentTransaction) Apply(txn *storage.VolumeTransaction) error { if NameFix(txn.Name()) != in.ObjectMeta.Name { return ErrNamesDontMatch } transaction, err := json.Marshal(txn) if err != nil { return err } in.Transaction.Raw = transaction return nil } // Persistent converts a Kubernetes CRD object into its // operation and internal storage.VolumeConfig func (in *TridentTransaction) Persistent() (*storage.VolumeTransaction, error) { persistent := &storage.VolumeTransaction{} if err := json.Unmarshal(in.Transaction.Raw, persistent); err != nil { return nil, err } return persistent, nil } func (in *TridentTransaction) GetObjectMeta() metav1.ObjectMeta { return in.ObjectMeta } func (in *TridentTransaction) GetFinalizers() []string { if in.ObjectMeta.Finalizers != nil { return in.ObjectMeta.Finalizers } return []string{} } func (in *TridentTransaction) HasTridentFinalizers() bool { for _, finalizerName := range GetTridentFinalizers() { if utils.SliceContainsString(in.ObjectMeta.Finalizers, finalizerName) { return true } } return false } func (in *TridentTransaction) RemoveTridentFinalizers() { for _, finalizerName := range GetTridentFinalizers() { in.ObjectMeta.Finalizers = utils.RemoveStringFromSlice(in.ObjectMeta.Finalizers, finalizerName) } }
NewTridentTransaction
build_reduced_graph.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Reduced graph building //! //! Here we build the "reduced graph": the graph of the module tree without //! any imports resolved. use macros::{InvocationData, LegacyScope}; use resolve_imports::ImportDirective; use resolve_imports::ImportDirectiveSubclass::{self, GlobImport, SingleImport}; use {Module, ModuleData, ModuleKind, NameBinding, NameBindingKind, ToNameBinding}; use {Resolver, ResolverArenas}; use Namespace::{self, TypeNS, ValueNS, MacroNS}; use {resolve_error, resolve_struct_error, ResolutionError}; use rustc::middle::cstore::LoadedMacro; use rustc::hir::def::*; use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId}; use rustc::ty; use std::cell::Cell; use std::rc::Rc; use syntax::ast::{Name, Ident}; use syntax::attr; use syntax::ast::{self, Block, ForeignItem, ForeignItemKind, Item, ItemKind}; use syntax::ast::{Mutability, StmtKind, TraitItem, TraitItemKind}; use syntax::ast::{Variant, ViewPathGlob, ViewPathList, ViewPathSimple}; use syntax::ext::base::SyntaxExtension; use syntax::ext::base::Determinacy::Undetermined; use syntax::ext::expand::mark_tts; use syntax::ext::hygiene::Mark; use syntax::ext::tt::macro_rules; use syntax::parse::token; use syntax::symbol::keywords; use syntax::visit::{self, Visitor}; use syntax_pos::{Span, DUMMY_SP}; impl<'a> ToNameBinding<'a> for (Module<'a>, ty::Visibility, Span, Mark) { fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> { arenas.alloc_name_binding(NameBinding { kind: NameBindingKind::Module(self.0), vis: self.1, span: self.2, expansion: self.3, }) } } impl<'a> ToNameBinding<'a> for (Def, ty::Visibility, Span, Mark) { fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> { arenas.alloc_name_binding(NameBinding { kind: NameBindingKind::Def(self.0), vis: self.1, span: self.2, expansion: self.3, }) } } #[derive(Default, PartialEq, Eq)] struct LegacyMacroImports { import_all: Option<Span>, imports: Vec<(Name, Span)>, reexports: Vec<(Name, Span)>, } impl<'a> Resolver<'a> { /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined; /// otherwise, reports an error. fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T) where T: ToNameBinding<'a>, { let binding = def.to_name_binding(self.arenas); if let Err(old_binding) = self.try_define(parent, ident, ns, binding) { self.report_conflict(parent, ident, ns, old_binding, &binding); } } fn block_needs_anonymous_module(&mut self, block: &Block) -> bool { // If any statements are items, we need to create an anonymous module block.stmts.iter().any(|statement| match statement.node { StmtKind::Item(_) | StmtKind::Mac(_) => true, _ => false, }) } fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Name>) { if !field_names.is_empty() { self.field_names.insert(def_id, field_names); } } /// Constructs the reduced graph for one item. fn build_reduced_graph_for_item(&mut self, item: &Item, expansion: Mark) { let parent = self.current_module; let ident = item.ident; let sp = item.span; let vis = self.resolve_visibility(&item.vis); match item.node { ItemKind::Use(ref view_path) => { // Extract and intern the module part of the path. For // globs and lists, the path is found directly in the AST; // for simple paths we have to munge the path a little. let mut module_path: Vec<_> = match view_path.node { ViewPathSimple(_, ref full_path) => { full_path.segments .split_last() .unwrap() .1 .iter() .map(|seg| seg.identifier) .collect() } ViewPathGlob(ref module_ident_path) | ViewPathList(ref module_ident_path, _) => { module_ident_path.segments .iter() .map(|seg| seg.identifier) .collect() } }; // This can be removed once warning cycle #36888 is complete. if module_path.len() >= 2 && module_path[0].name == keywords::CrateRoot.name() && token::Ident(module_path[1]).is_path_segment_keyword() { module_path.remove(0); } // Build up the import directives. let is_prelude = attr::contains_name(&item.attrs, "prelude_import"); match view_path.node { ViewPathSimple(mut binding, ref full_path) => { let mut source = full_path.segments.last().unwrap().identifier; let source_name = source.name; if source_name == "mod" || source_name == "self" { resolve_error(self, view_path.span, ResolutionError::SelfImportsOnlyAllowedWithin); } else if source_name == "$crate" && full_path.segments.len() == 1 { let crate_root = self.resolve_crate_var(source.ctxt); let crate_name = match crate_root.kind { ModuleKind::Def(_, name) => name, ModuleKind::Block(..) => unreachable!(), }; source.name = crate_name; if binding.name == "$crate" { binding.name = crate_name; } self.session.struct_span_warn(item.span, "`$crate` may not be imported") .note("`use $crate;` was erroneously allowed and \ will become a hard error in a future release") .emit(); } let subclass = SingleImport { target: binding, source: source, result: self.per_ns(|_, _| Cell::new(Err(Undetermined))), type_ns_only: false, }; self.add_import_directive( module_path, subclass, view_path.span, item.id, vis, expansion, ); } ViewPathList(_, ref source_items) => { // Make sure there's at most one `mod` import in the list. let mod_spans = source_items.iter().filter_map(|item| { if item.node.name.name == keywords::SelfValue.name() { Some(item.span) } else { None } }).collect::<Vec<Span>>(); if mod_spans.len() > 1 { let mut e = resolve_struct_error(self, mod_spans[0], ResolutionError::SelfImportCanOnlyAppearOnceInTheList); for other_span in mod_spans.iter().skip(1) { e.span_note(*other_span, "another `self` import appears here"); } e.emit(); } for source_item in source_items { let node = source_item.node; let (module_path, ident, rename, type_ns_only) = { if node.name.name != keywords::SelfValue.name() { let rename = node.rename.unwrap_or(node.name); (module_path.clone(), node.name, rename, false) } else { let ident = *module_path.last().unwrap(); if ident.name == keywords::CrateRoot.name() { resolve_error( self, source_item.span, ResolutionError:: SelfImportOnlyInImportListWithNonEmptyPrefix ); continue; } let module_path = module_path.split_last().unwrap().1; let rename = node.rename.unwrap_or(ident); (module_path.to_vec(), ident, rename, true) } }; let subclass = SingleImport { target: rename, source: ident, result: self.per_ns(|_, _| Cell::new(Err(Undetermined))), type_ns_only: type_ns_only, }; let id = source_item.node.id; self.add_import_directive( module_path, subclass, source_item.span, id, vis, expansion, ); } } ViewPathGlob(_) => { let subclass = GlobImport { is_prelude: is_prelude, max_vis: Cell::new(ty::Visibility::Invisible), }; self.add_import_directive( module_path, subclass, view_path.span, item.id, vis, expansion, ); } } } ItemKind::ExternCrate(_) => { self.crate_loader.process_item(item, &self.definitions); // n.b. we don't need to look at the path option here, because cstore already did let crate_id = self.session.cstore.extern_mod_stmt_cnum(item.id).unwrap(); let module = self.get_extern_crate_root(crate_id); self.populate_module_if_necessary(module); let used = self.process_legacy_macro_imports(item, module, expansion); let binding = (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.arenas); let directive = self.arenas.alloc_import_directive(ImportDirective { id: item.id, parent: parent, imported_module: Cell::new(Some(module)), subclass: ImportDirectiveSubclass::ExternCrate, span: item.span, module_path: Vec::new(), vis: Cell::new(vis), expansion: expansion, used: Cell::new(used), }); self.potentially_unused_imports.push(directive); let imported_binding = self.import(binding, directive); self.define(parent, ident, TypeNS, imported_binding); } ItemKind::Mod(..) if item.ident == keywords::Invalid.ident() => {} // Crate root ItemKind::Mod(..) => { let def_id = self.definitions.local_def_id(item.id); let module_kind = ModuleKind::Def(Def::Mod(def_id), ident.name); let module = self.arenas.alloc_module(ModuleData { no_implicit_prelude: parent.no_implicit_prelude || { attr::contains_name(&item.attrs, "no_implicit_prelude") }, ..ModuleData::new(Some(parent), module_kind, def_id) }); self.define(parent, ident, TypeNS, (module, vis, sp, expansion)); self.module_map.insert(def_id, module); // Descend into the module. self.current_module = module; } ItemKind::ForeignMod(..) => self.crate_loader.process_item(item, &self.definitions), // These items live in the value namespace. ItemKind::Static(_, m, _) => { let mutbl = m == Mutability::Mutable; let def = Def::Static(self.definitions.local_def_id(item.id), mutbl); self.define(parent, ident, ValueNS, (def, vis, sp, expansion)); } ItemKind::Const(..) => { let def = Def::Const(self.definitions.local_def_id(item.id)); self.define(parent, ident, ValueNS, (def, vis, sp, expansion)); } ItemKind::Fn(..) => { let def = Def::Fn(self.definitions.local_def_id(item.id)); self.define(parent, ident, ValueNS, (def, vis, sp, expansion)); } // These items live in the type namespace. ItemKind::Ty(..) => { let def = Def::TyAlias(self.definitions.local_def_id(item.id)); self.define(parent, ident, TypeNS, (def, vis, sp, expansion)); } ItemKind::Enum(ref enum_definition, _) => { let def = Def::Enum(self.definitions.local_def_id(item.id)); let module_kind = ModuleKind::Def(def, ident.name); let module = self.new_module(parent, module_kind, parent.normal_ancestor_id); self.define(parent, ident, TypeNS, (module, vis, sp, expansion)); for variant in &(*enum_definition).variants { self.build_reduced_graph_for_variant(variant, module, vis, expansion); } } // These items live in both the type and value namespaces. ItemKind::Struct(ref struct_def, _) => { // Define a name in the type namespace. let def = Def::Struct(self.definitions.local_def_id(item.id)); self.define(parent, ident, TypeNS, (def, vis, sp, expansion)); // If this is a tuple or unit struct, define a name // in the value namespace as well. if !struct_def.is_struct() { let ctor_def = Def::StructCtor(self.definitions.local_def_id(struct_def.id()), CtorKind::from_ast(struct_def)); self.define(parent, ident, ValueNS, (ctor_def, vis, sp, expansion)); } // Record field names for error reporting. let field_names = struct_def.fields().iter().filter_map(|field| { self.resolve_visibility(&field.vis); field.ident.map(|ident| ident.name) }).collect(); let item_def_id = self.definitions.local_def_id(item.id); self.insert_field_names(item_def_id, field_names); } ItemKind::Union(ref vdata, _) => { let def = Def::Union(self.definitions.local_def_id(item.id)); self.define(parent, ident, TypeNS, (def, vis, sp, expansion)); // Record field names for error reporting. let field_names = vdata.fields().iter().filter_map(|field| { self.resolve_visibility(&field.vis); field.ident.map(|ident| ident.name) }).collect(); let item_def_id = self.definitions.local_def_id(item.id); self.insert_field_names(item_def_id, field_names); } ItemKind::DefaultImpl(..) | ItemKind::Impl(..) => {} ItemKind::Trait(..) => { let def_id = self.definitions.local_def_id(item.id); // Add all the items within to a new module. let module_kind = ModuleKind::Def(Def::Trait(def_id), ident.name); let module = self.new_module(parent, module_kind, parent.normal_ancestor_id); self.define(parent, ident, TypeNS, (module, vis, sp, expansion)); self.current_module = module; } ItemKind::Mac(_) => panic!("unexpanded macro in resolve!"), } } // Constructs the reduced graph for one variant. Variants exist in the // type and value namespaces. fn build_reduced_graph_for_variant(&mut self, variant: &Variant, parent: Module<'a>, vis: ty::Visibility, expansion: Mark)
/// Constructs the reduced graph for one foreign item. fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem, expansion: Mark) { let def = match item.node { ForeignItemKind::Fn(..) => { Def::Fn(self.definitions.local_def_id(item.id)) } ForeignItemKind::Static(_, m) => { Def::Static(self.definitions.local_def_id(item.id), m) } }; let parent = self.current_module; let vis = self.resolve_visibility(&item.vis); self.define(parent, item.ident, ValueNS, (def, vis, item.span, expansion)); } fn build_reduced_graph_for_block(&mut self, block: &Block) { let parent = self.current_module; if self.block_needs_anonymous_module(block) { let module = self.new_module(parent, ModuleKind::Block(block.id), parent.normal_ancestor_id); self.block_map.insert(block.id, module); self.current_module = module; // Descend into the block. } } /// Builds the reduced graph for a single item in an external crate. fn build_reduced_graph_for_external_crate_def(&mut self, parent: Module<'a>, child: Export) { let ident = Ident::with_empty_ctxt(child.name); let def = child.def; let def_id = def.def_id(); let vis = self.session.cstore.visibility(def_id); match def { Def::Mod(..) | Def::Enum(..) => { let module = self.new_module(parent, ModuleKind::Def(def, ident.name), def_id); self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, Mark::root())); } Def::Variant(..) | Def::TyAlias(..) => { self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, Mark::root())); } Def::Fn(..) | Def::Static(..) | Def::Const(..) | Def::VariantCtor(..) | Def::StructCtor(..) => { self.define(parent, ident, ValueNS, (def, vis, DUMMY_SP, Mark::root())); } Def::Trait(..) => { let module_kind = ModuleKind::Def(def, ident.name); let module = self.new_module(parent, module_kind, parent.normal_ancestor_id); self.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, Mark::root())); for child in self.session.cstore.item_children(def_id) { let ns = if let Def::AssociatedTy(..) = child.def { TypeNS } else { ValueNS }; let ident = Ident::with_empty_ctxt(child.name); self.define(module, ident, ns, (child.def, ty::Visibility::Public, DUMMY_SP, Mark::root())); let has_self = self.session.cstore.associated_item(child.def.def_id()) .map_or(false, |item| item.method_has_self_argument); self.trait_item_map.insert((def_id, child.name, ns), (child.def, has_self)); } module.populated.set(true); } Def::Struct(..) | Def::Union(..) => { self.define(parent, ident, TypeNS, (def, vis, DUMMY_SP, Mark::root())); // Record field names for error reporting. let field_names = self.session.cstore.struct_field_names(def_id); self.insert_field_names(def_id, field_names); } Def::Macro(..) => { self.define(parent, ident, MacroNS, (def, vis, DUMMY_SP, Mark::root())); } _ => bug!("unexpected definition: {:?}", def) } } fn get_extern_crate_root(&mut self, cnum: CrateNum) -> Module<'a> { let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX }; let name = self.session.cstore.crate_name(cnum); let macros_only = self.session.cstore.dep_kind(cnum).macros_only(); let module_kind = ModuleKind::Def(Def::Mod(def_id), name); let arenas = self.arenas; *self.extern_crate_roots.entry((cnum, macros_only)).or_insert_with(|| { arenas.alloc_module(ModuleData::new(None, module_kind, def_id)) }) } pub fn get_macro(&mut self, def: Def) -> Rc<SyntaxExtension> { let def_id = match def { Def::Macro(def_id) => def_id, _ => panic!("Expected Def::Macro(..)"), }; if let Some(ext) = self.macro_map.get(&def_id) { return ext.clone(); } let mut macro_rules = match self.session.cstore.load_macro(def_id, &self.session) { LoadedMacro::MacroRules(macro_rules) => macro_rules, LoadedMacro::ProcMacro(ext) => return ext, }; let mark = Mark::fresh(); let invocation = self.arenas.alloc_invocation_data(InvocationData { module: Cell::new(self.get_extern_crate_root(def_id.krate)), def_index: CRATE_DEF_INDEX, const_integer: false, legacy_scope: Cell::new(LegacyScope::Empty), expansion: Cell::new(LegacyScope::Empty), }); self.invocations.insert(mark, invocation); macro_rules.body = mark_tts(&macro_rules.body, mark); let ext = Rc::new(macro_rules::compile(&self.session.parse_sess, &macro_rules)); self.macro_map.insert(def_id, ext.clone()); ext } /// Ensures that the reduced graph rooted at the given external module /// is built, building it if it is not. pub fn populate_module_if_necessary(&mut self, module: Module<'a>) { if module.populated.get() { return } for child in self.session.cstore.item_children(module.def_id().unwrap()) { self.build_reduced_graph_for_external_crate_def(module, child); } module.populated.set(true) } fn legacy_import_macro(&mut self, name: Name, binding: &'a NameBinding<'a>, span: Span, allow_shadowing: bool) { self.macro_names.insert(name); if self.builtin_macros.insert(name, binding).is_some() && !allow_shadowing { let msg = format!("`{}` is already in scope", name); let note = "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)"; self.session.struct_span_err(span, &msg).note(note).emit(); } } // This returns true if we should consider the underlying `extern crate` to be used. fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>, expansion: Mark) -> bool { let allow_shadowing = expansion == Mark::root(); let legacy_imports = self.legacy_macro_imports(&item.attrs); let mut used = legacy_imports != LegacyMacroImports::default(); // `#[macro_use]` and `#[macro_reexport]` are only allowed at the crate root. if self.current_module.parent.is_some() && used { span_err!(self.session, item.span, E0468, "an `extern crate` loading macros must be at the crate root"); } else if !self.use_extern_macros && !used && self.session.cstore.dep_kind(module.def_id().unwrap().krate).macros_only() { let msg = "custom derive crates and `#[no_link]` crates have no effect without \ `#[macro_use]`"; self.session.span_warn(item.span, msg); used = true; // Avoid the normal unused extern crate warning } let (graph_root, arenas) = (self.graph_root, self.arenas); let macro_use_directive = |span| arenas.alloc_import_directive(ImportDirective { id: item.id, parent: graph_root, imported_module: Cell::new(Some(module)), subclass: ImportDirectiveSubclass::MacroUse, span: span, module_path: Vec::new(), vis: Cell::new(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))), expansion: expansion, used: Cell::new(false), }); if let Some(span) = legacy_imports.import_all { let directive = macro_use_directive(span); self.potentially_unused_imports.push(directive); module.for_each_child(|ident, ns, binding| if ns == MacroNS { let imported_binding = self.import(binding, directive); self.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing); }); } else { for (name, span) in legacy_imports.imports { let ident = Ident::with_empty_ctxt(name); let result = self.resolve_ident_in_module(module, ident, MacroNS, false, None); if let Ok(binding) = result { let directive = macro_use_directive(span); self.potentially_unused_imports.push(directive); let imported_binding = self.import(binding, directive); self.legacy_import_macro(name, imported_binding, span, allow_shadowing); } else { span_err!(self.session, span, E0469, "imported macro not found"); } } } for (name, span) in legacy_imports.reexports { self.session.cstore.export_macros(module.def_id().unwrap().krate); let ident = Ident::with_empty_ctxt(name); let result = self.resolve_ident_in_module(module, ident, MacroNS, false, None); if let Ok(binding) = result { self.macro_exports.push(Export { name: name, def: binding.def() }); } else { span_err!(self.session, span, E0470, "reexported macro not found"); } } used } // does this attribute list contain "macro_use"? fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool { for attr in attrs { if attr.check_name("macro_escape") { let msg = "macro_escape is a deprecated synonym for macro_use"; let mut err = self.session.struct_span_warn(attr.span, msg); if let ast::AttrStyle::Inner = attr.style { err.help("consider an outer attribute, #[macro_use] mod ...").emit(); } else { err.emit(); } } else if !attr.check_name("macro_use") { continue; } if !attr.is_word() { self.session.span_err(attr.span, "arguments to macro_use are not allowed here"); } return true; } false } fn legacy_macro_imports(&mut self, attrs: &[ast::Attribute]) -> LegacyMacroImports { let mut imports = LegacyMacroImports::default(); for attr in attrs { if attr.check_name("macro_use") { match attr.meta_item_list() { Some(names) => for attr in names { if let Some(word) = attr.word() { imports.imports.push((word.name(), attr.span())); } else { span_err!(self.session, attr.span(), E0466, "bad macro import"); } }, None => imports.import_all = Some(attr.span), } } else if attr.check_name("macro_reexport") { let bad_macro_reexport = |this: &mut Self, span| { span_err!(this.session, span, E0467, "bad macro reexport"); }; if let Some(names) = attr.meta_item_list() { for attr in names { if let Some(word) = attr.word() { imports.reexports.push((word.name(), attr.span())); } else { bad_macro_reexport(self, attr.span()); } } } else { bad_macro_reexport(self, attr.span()); } } } imports } } pub struct BuildReducedGraphVisitor<'a, 'b: 'a> { pub resolver: &'a mut Resolver<'b>, pub legacy_scope: LegacyScope<'b>, pub expansion: Mark, } impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { fn visit_invoc(&mut self, id: ast::NodeId) -> &'b InvocationData<'b> { let mark = Mark::from_placeholder_id(id); self.resolver.current_module.unresolved_invocations.borrow_mut().insert(mark); let invocation = self.resolver.invocations[&mark]; invocation.module.set(self.resolver.current_module); invocation.legacy_scope.set(self.legacy_scope); invocation } } macro_rules! method { ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => { fn $visit(&mut self, node: &'a $ty) { if let $invoc(..) = node.node { self.visit_invoc(node.id); } else { visit::$walk(self, node); } } } } impl<'a, 'b> Visitor<'a> for BuildReducedGraphVisitor<'a, 'b> { method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item); method!(visit_expr: ast::Expr, ast::ExprKind::Mac, walk_expr); method!(visit_pat: ast::Pat, ast::PatKind::Mac, walk_pat); method!(visit_ty: ast::Ty, ast::TyKind::Mac, walk_ty); fn visit_item(&mut self, item: &'a Item) { let macro_use = match item.node { ItemKind::Mac(ref mac) => { if mac.node.path.segments.is_empty() { self.legacy_scope = LegacyScope::Expansion(self.visit_invoc(item.id)); } else { self.resolver.define_macro(item, &mut self.legacy_scope); } return } ItemKind::Mod(..) => self.resolver.contains_macro_use(&item.attrs), _ => false, }; let (parent, legacy_scope) = (self.resolver.current_module, self.legacy_scope); self.resolver.build_reduced_graph_for_item(item, self.expansion); visit::walk_item(self, item); self.resolver.current_module = parent; if !macro_use { self.legacy_scope = legacy_scope; } } fn visit_stmt(&mut self, stmt: &'a ast::Stmt) { if let ast::StmtKind::Mac(..) = stmt.node { self.legacy_scope = LegacyScope::Expansion(self.visit_invoc(stmt.id)); } else { visit::walk_stmt(self, stmt); } } fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) { self.resolver.build_reduced_graph_for_foreign_item(foreign_item, self.expansion); visit::walk_foreign_item(self, foreign_item); } fn visit_block(&mut self, block: &'a Block) { let (parent, legacy_scope) = (self.resolver.current_module, self.legacy_scope); self.resolver.build_reduced_graph_for_block(block); visit::walk_block(self, block); self.resolver.current_module = parent; self.legacy_scope = legacy_scope; } fn visit_trait_item(&mut self, item: &'a TraitItem) { let parent = self.resolver.current_module; let def_id = parent.def_id().unwrap(); if let TraitItemKind::Macro(_) = item.node { self.visit_invoc(item.id); return } // Add the item to the trait info. let item_def_id = self.resolver.definitions.local_def_id(item.id); let (def, ns, has_self) = match item.node { TraitItemKind::Const(..) => (Def::AssociatedConst(item_def_id), ValueNS, false), TraitItemKind::Method(ref sig, _) => (Def::Method(item_def_id), ValueNS, sig.decl.has_self()), TraitItemKind::Type(..) => (Def::AssociatedTy(item_def_id), TypeNS, false), TraitItemKind::Macro(_) => bug!(), // handled above }; self.resolver.trait_item_map.insert((def_id, item.ident.name, ns), (def, has_self)); let vis = ty::Visibility::Public; self.resolver.define(parent, item.ident, ns, (def, vis, item.span, self.expansion)); self.resolver.current_module = parent.parent.unwrap(); // nearest normal ancestor visit::walk_trait_item(self, item); self.resolver.current_module = parent; } }
{ let ident = variant.node.name; let def_id = self.definitions.local_def_id(variant.node.data.id()); // Define a name in the type namespace. let def = Def::Variant(def_id); self.define(parent, ident, TypeNS, (def, vis, variant.span, expansion)); // Define a constructor name in the value namespace. // Braced variants, unlike structs, generate unusable names in // value namespace, they are reserved for possible future use. let ctor_kind = CtorKind::from_ast(&variant.node.data); let ctor_def = Def::VariantCtor(def_id, ctor_kind); self.define(parent, ident, ValueNS, (ctor_def, vis, variant.span, expansion)); }
get-unique-id-worker.ts
let UNIQUE_ID_WORKER: Worker = null; const getUniqueIdWorker = (): Worker => { if (typeof Worker !== 'undefined' && UNIQUE_ID_WORKER === null) { UNIQUE_ID_WORKER = new Worker(new URL('../workers/id-generator.worker', import.meta.url), { type: 'module', }); } return UNIQUE_ID_WORKER; };
export default getUniqueIdWorker;
test_decision.py
# mypy: allow-untyped-defs from unittest import mock import pytest from tools.ci.tc import decision @pytest.mark.parametrize("run_jobs,tasks,expected", [ ([], {"task-no-schedule-if": {}}, ["task-no-schedule-if"]), ([], {"task-schedule-if-no-run-job": {"schedule-if": {}}}, []), (["job"], {"job-present": {"schedule-if": {"run-job": ["other-job", "job"]}}}, ["job-present"]), (["job"], {"job-missing": {"schedule-if": {"run-job": ["other-job"]}}}, []), (["all"], {"job-all": {"schedule-if": {"run-job": ["other-job"]}}}, ["job-all"]), (["job"], {"job-1": {"schedule-if": {"run-job": ["job"]}}, "job-2": {"schedule-if": {"run-job": ["other-job"]}}}, ["job-1"]), ]) def test_filter_schedule_if(run_jobs, tasks, expected): with mock.patch("tools.ci.tc.decision.get_run_jobs", return_value=run_jobs) as get_run_jobs: assert (decision.filter_schedule_if({}, tasks) == {name: tasks[name] for name in expected}) get_run_jobs.call_count in (0, 1) @pytest.mark.parametrize("msg,expected", [ ("Some initial line\n\ntc-jobs:foo,bar", {"foo", "bar"}), ("Some initial line\n\ntc-jobs:foo, bar", {"foo", "bar"}), ("tc-jobs:foo, bar \nbaz", {"foo", "bar"}), ("tc-jobs:all", {"all"}), ("", set()), ("tc-jobs:foo\ntc-jobs:bar", {"foo"})]) @pytest.mark.parametrize("event", [ {"commits": [{"message": "<message>"}]}, {"pull_request": {"body": "<message>"}} ]) def test_extra_jobs_pr(msg, expected, event):
def sub(obj): """Copy obj, except if it's a string with the value <message> replace it with the value of the msg argument""" if isinstance(obj, dict): return {key: sub(value) for (key, value) in obj.items()} elif isinstance(obj, list): return [sub(value) for value in obj] elif obj == "<message>": return msg return obj event = sub(event) assert decision.get_extra_jobs(event) == expected
type_is.rs
/* * Copyright 2018 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ //! Test for type-is optimizations. use crate as starlark; use crate::{ assert::Assert, environment::GlobalsBuilder, eval::{Def, FrozenDef}, values::{Value, ValueLike}, }; #[starlark_module] fn globals(builder: &mut GlobalsBuilder) { fn
(value: Value<'v>) -> anyhow::Result<bool> { Ok(if let Some(def) = value.downcast_ref::<FrozenDef>() { def.def_info.inline_def_body.is_some() } else if let Some(def) = value.downcast_ref::<Def>() { def.def_info.inline_def_body.is_some() } else { panic!("not def") }) } } #[test] fn returns_type_is() { let mut a = Assert::new(); a.globals_add(globals); a.module( "types.star", "\ def is_list(x): return type(x) == type([]) ", ); a.pass( "\ load('types.star', 'is_list') assert_true(returns_type_is(is_list)) assert_true(is_list([])) assert_false(is_list({})) ", ); } #[test] fn does_not_return_type_is() { let mut a = Assert::new(); a.globals_add(globals); a.pass( "\ def is_not_list(x): return type(x) != type([]) def something_else(x, y): return type(x) == type([]) assert_false(returns_type_is(is_not_list)) assert_false(returns_type_is(something_else)) ", ); }
returns_type_is
layoutWidgets.spec.js
/// <reference types="Cypress" /> const md5 = require('blueimp-md5'); context('Layout widgets', () => { before(() => { cy.visit('http://localhost:3000/examples/components/vue-ncform/_layout-widgets.html') }) it('layout:v & collapsed: false', () => { let id = md5('layout:v & collapsed: false'); cy.get(`[data-cy=${id}]`).within(() => { cy.get('legend').contains('user').as('userLegend'); cy.get('@userLegend').next().should('be.visible'); cy.get('@userLegend').next().then($dom => { expect($dom.find('label').offset().top).to.be.lessThan($dom.find('input').offset().top); expect($dom.find('label').offset().left).to.be.equal($dom.find('input').offset().left); }) cy.get('@userLegend').click(); cy.get('@userLegend').next().should('not.be.visible'); }) }) it('layout:h & collapsed: true', () => { let id = md5('layout:h & collapsed: true'); cy.get(`[data-cy=${id}]`).within(() => { cy.get('legend').contains('user').as('userLegend'); cy.get('@userLegend').next().should('not.be.visible'); cy.get('@userLegend').click(); cy.get('@userLegend').next().should('be.visible'); cy.get('@userLegend').next().then($dom => { expect($dom.find('label').offset().top).to.be.equal($dom.find('input').offset().top); expect($dom.find('label').offset().left).to.be.lessThan($dom.find('input').offset().left); }) }) }) it('disableCollapse: true', () => { let id = md5('disableCollapse: true'); cy.get(`[data-cy=${id}]`).within(() => { cy.get('legend').contains('user').as('userLegend'); cy.get('@userLegend').next().should('be.visible'); cy.get('@userLegend').click(); cy.get('@userLegend').next().should('be.visible'); }) }) it('array: all disableXXX are true', () => { let id = md5('array: all disableXXX are true'); cy.get(`[data-cy=${id}]`).within(() => { cy.get('legend').contains('user').as('userLegend'); cy.get('@userLegend').parent().children('div').should('be.visible'); cy.get('@userLegend').click(); cy.get('@userLegend').parent().children('div').should('be.visible'); cy.get('@userLegend').parent().find('button').should('not.exist'); }) }) it('array: some rows can not be deleted', () => { let id = md5('array: some rows can not be deleted'); cy.get(`[data-cy=${id}]`).within(() => { cy.get('legend').contains('user').as('userLegend'); cy.get('@userLegend').next().find('button.btn-danger').should('not.exist'); cy.get('@userLegend').next().next().find('button.btn-danger').should('exist'); }) }) it('array: collapsed / itemCollapse true and txts change', () => { let id = md5('array: collapsed / itemCollapse true and txts change'); cy.get(`[data-cy=${id}]`).within(() => { cy.get('legend').contains('user').as('userLegend'); cy.get('@userLegend').parent().children('div').should('not.be.visible'); cy.get('@userLegend').click(); cy.get('@userLegend').parent().children('div').should('be.visible'); cy.get('@userLegend').parent().find('input').should('not.be.visible'); cy.get('@userLegend').parent().find('button').contains('Expand').click(); cy.get('@userLegend').parent().find('input').should('be.visible'); cy.get('@userLegend').parent().find('button').contains('Add Item').should('exist'); cy.get('@userLegend').parent().find('button').contains('Remove All').should('exist'); }) }) it('table: all disableXXX are true', () => { let id = md5('table: all disableXXX are true'); cy.get(`[data-cy=${id}]`).within(() => { cy.get('legend').contains('user').as('userLegend'); cy.get('@userLegend').next().should('be.visible'); cy.get('@userLegend').click(); cy.get('@userLegend').next().should('be.visible'); cy.get('@userLegend').next().find('button').should('not.exist'); }) }) it('table: collapsed true and txts change', () => { let id = md5('table: collapsed true and txts change'); cy.get(`[data-cy=${id}]`).within(() => { cy.get('legend').contains('user').as('userLegend'); cy.get('@userLegend').next().should('not.be.visible'); cy.get('@userLegend').click(); cy.get('@userLegend').next().should('be.visible');
}) it('table: some rows can be deleted', () => { let id = md5('table: some rows can be deleted'); cy.get(`[data-cy=${id}]`).within(() => { cy.get('legend').contains('user').as('userLegend'); cy.get('@userLegend').next().find('button.btn-danger').should('have.length', 1); }) }) it('table: set colums width', () => { let id = md5('table: set colums width'); cy.get(`[data-cy=${id}]`).within(() => { cy.get('thead th:last-child').should('have.prop', 'offsetWidth', 200); }) }) it('array: showOneIfEmpty is true - No extra blank row when there has initial value', () => { let id = md5('array: showOneIfEmpty is true - No extra blank row when there has initial value'); cy.get(`[data-cy=${id}]`).within(() => { cy.get('input').should('have.length', 1); }) }) })
cy.get('@userLegend').next().find('button').contains('Add Item').should('exist'); cy.get('@userLegend').next().find('button').contains('Remove All').should('exist'); })
json.rs
extern crate pm_lexer as lexer; use pomelo::pomelo; use std::collections::HashMap; #[derive(Debug, Clone)] pub enum JObject { JDict(HashMap<String, JObject>), JArray(Vec<JObject>), JNumber(i64), JString(String), JBool(bool), JNull, } impl std::str::FromStr for JObject { type Err = String; fn from_str(input: &str) -> Result<JObject, String> { let mut p = json::Parser::new(); let tok_stream = input.parse().map_err(|_| "Lexer Error")?; lexer::parse::<String, _>(tok_stream, |tk| { use proc_macro2::TokenTree; let tk = match tk { TokenTree::Punct(p) => match p.as_char() { '{' => json::Token::LBrace, '}' => json::Token::RBrace, '[' => json::Token::LBracket, ']' => json::Token::RBracket, ',' => json::Token::Comma, ':' => json::Token::Colon, c => { return Err(format!("Invalid character '{}'", c)); } } TokenTree::Literal(l) => { let s = l.to_string(); if s.starts_with('"') && s.ends_with('"') { let bs = s.into_bytes(); let s = std::str::from_utf8(&bs[1..bs.len()-1]).unwrap().to_string(); json::Token::JString(s) } else { let i = s.parse().map_err(|_| "Invalid integer value")?; json::Token::JNumber(i) } } TokenTree::Ident(i) => { let s = i.to_string(); if s == "true" { json::Token::JBool(true) } else if s == "false" { json::Token::JBool(false) } else if s == "null" { json::Token::JNull } else { return Err(format!("Invalid token '{}'", s)); } } _ => unimplemented!() }; p.parse(tk).map_err(|_| "Parser error")?; Ok(()) })?; let j = p.end_of_input().map_err(|_| "Parser error")?; Ok(j) } } pomelo! { %module json; %include { use super::JObject; use std::collections::HashMap; } %token #[derive(Debug)] pub enum Token {}; %type start JObject; %type jobject JObject; %type jdict JObject; %type jarray JObject; %type JNumber i64; %type JString String; %type JBool bool; %type jobject_list Vec<JObject>; %type jitem_list HashMap<String, JObject>; %type jitem (String, JObject); start ::= jobject(J) { J } jobject ::= jdict(D) { D } jobject ::= jarray(A) { A } jobject ::= JNumber(N) { JObject::JNumber(N) } jobject ::= JString(S) { JObject::JString(S) } jobject ::= JBool(B) { JObject::JBool(B) } jobject ::= JNull { JObject::JNull } jdict ::= LBrace jitem_list?(D) RBrace { JObject::JDict(D.unwrap_or_else(HashMap::new)) } jarray ::= LBracket jobject_list?(A) RBracket { JObject::JArray(A.unwrap_or_else(Vec::new)) } jobject_list ::= jobject(J) { vec![J] } jobject_list ::= jobject_list(mut A) Comma jobject(J) { A.push(J); A } jitem_list ::= jitem((K,V)) { let mut d = HashMap::new(); d.insert(K, V); d } jitem_list ::= jitem_list(mut A) Comma jitem((K,V)) { A.insert(K, V); A } jitem ::= JString(K) Colon jobject(V) { (K, V) } } fn main()
{ let args = std::env::args().skip(1); for arg in args { println!("arg: '{}'", arg); match arg.parse() { Ok::<JObject,_>(j) => println!("JSON: '{:#?}'", j), Err(e) => println!("Err: '{:#?}'", e) } } }
tail.rs
// * This file is part of the uutils coreutils package. // * // * (c) Morten Olsen Lysgaard <[email protected]> // * (c) Alexander Batischev <[email protected]> // * (c) Thomas Queiroz <[email protected]> // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. // spell-checker:ignore (ToDO) seekable seek'd tail'ing ringbuffer ringbuf #[macro_use] extern crate clap; #[macro_use] extern crate uucore; mod chunks; mod lines; mod parse; mod platform; use chunks::ReverseChunks; use lines::lines; use clap::{App, AppSettings, Arg}; use std::collections::VecDeque; use std::ffi::OsString; use std::fmt; use std::fs::{File, Metadata}; use std::io::{stdin, stdout, BufRead, BufReader, Read, Seek, SeekFrom, Write}; use std::path::Path; use std::thread::sleep; use std::time::Duration; use uucore::display::Quotable; use uucore::error::{FromIo, UResult, USimpleError}; use uucore::parse_size::{parse_size, ParseSizeError}; use uucore::ringbuffer::RingBuffer; #[cfg(unix)] use crate::platform::stdin_is_pipe_or_fifo; #[cfg(unix)] use std::os::unix::fs::MetadataExt; const ABOUT: &str = "\ Print the last 10 lines of each FILE to standard output.\n\ With more than one FILE, precede each with a header giving the file name.\n\ With no FILE, or when FILE is -, read standard input.\n\ \n\ Mandatory arguments to long flags are mandatory for short flags too.\ "; const USAGE: &str = "tail [FLAG]... [FILE]..."; pub mod options { pub mod verbosity { pub static QUIET: &str = "quiet"; pub static VERBOSE: &str = "verbose"; } pub static BYTES: &str = "bytes"; pub static FOLLOW: &str = "follow"; pub static LINES: &str = "lines"; pub static PID: &str = "pid"; pub static SLEEP_INT: &str = "sleep-interval"; pub static ZERO_TERM: &str = "zero-terminated"; pub static ARG_FILES: &str = "files"; } #[derive(Debug)] enum FilterMode { Bytes(usize), Lines(usize, u8), // (number of lines, delimiter) } impl Default for FilterMode { fn default() -> Self { FilterMode::Lines(10, b'\n') } } #[derive(Debug, Default)] struct Settings { quiet: bool, verbose: bool, mode: FilterMode, sleep_msec: u32, beginning: bool, follow: bool, pid: platform::Pid, files: Vec<String>, } impl Settings { pub fn get_from(args: impl uucore::Args) -> Result<Self, String> { let matches = uu_app().get_matches_from(arg_iterate(args)?); let mut settings: Settings = Settings { sleep_msec: 1000, follow: matches.is_present(options::FOLLOW), ..Default::default() }; if settings.follow { if let Some(n) = matches.value_of(options::SLEEP_INT) { let parsed: Option<u32> = n.parse().ok(); if let Some(m) = parsed { settings.sleep_msec = m * 1000 } } } if let Some(pid_str) = matches.value_of(options::PID) { if let Ok(pid) = pid_str.parse() { settings.pid = pid; if pid != 0 { if !settings.follow { show_warning!("PID ignored; --pid=PID is useful only when following"); } if !platform::supports_pid_checks(pid) { show_warning!("--pid=PID is not supported on this system"); settings.pid = 0; } } } } let mode_and_beginning = if let Some(arg) = matches.value_of(options::BYTES) { match parse_num(arg) { Ok((n, beginning)) => (FilterMode::Bytes(n), beginning), Err(e) => return Err(format!("invalid number of bytes: {}", e)), } } else if let Some(arg) = matches.value_of(options::LINES) { match parse_num(arg) { Ok((n, beginning)) => (FilterMode::Lines(n, b'\n'), beginning), Err(e) => return Err(format!("invalid number of lines: {}", e)), } } else { (FilterMode::Lines(10, b'\n'), false) }; settings.mode = mode_and_beginning.0; settings.beginning = mode_and_beginning.1; if matches.is_present(options::ZERO_TERM) { if let FilterMode::Lines(count, _) = settings.mode { settings.mode = FilterMode::Lines(count, 0); } } settings.verbose = matches.is_present(options::verbosity::VERBOSE); settings.quiet = matches.is_present(options::verbosity::QUIET); settings.files = match matches.values_of(options::ARG_FILES) { Some(v) => v.map(|s| s.to_owned()).collect(), None => vec!["-".to_owned()], }; Ok(settings) } } #[allow(clippy::cognitive_complexity)] #[uucore_procs::gen_uumain] pub fn uumain(args: impl uucore::Args) -> UResult<()> { let args = match Settings::get_from(args) { Ok(o) => o, Err(s) => { return Err(USimpleError::new(1, s)); } }; uu_tail(&args) } fn uu_tail(settings: &Settings) -> UResult<()> { let multiple = settings.files.len() > 1; let mut first_header = true; let mut readers: Vec<(Box<dyn BufRead>, &String)> = Vec::new(); #[cfg(unix)] let stdin_string = String::from("standard input"); for filename in &settings.files { let use_stdin = filename.as_str() == "-"; if (multiple || settings.verbose) && !settings.quiet { if !first_header { println!(); } if use_stdin { println!("==> standard input <=="); } else { println!("==> {} <==", filename); } } first_header = false; if use_stdin { let mut reader = BufReader::new(stdin()); unbounded_tail(&mut reader, settings)?; // Don't follow stdin since there are no checks for pipes/FIFOs // // FIXME windows has GetFileType which can determine if the file is a pipe/FIFO // so this check can also be performed #[cfg(unix)] { /* POSIX specification regarding tail -f If the input file is a regular file or if the file operand specifies a FIFO, do not terminate after the last line of the input file has been copied, but read and copy further bytes from the input file when they become available. If no file operand is specified and standard input is a pipe or FIFO, the -f option shall be ignored. If the input file is not a FIFO, pipe, or regular file, it is unspecified whether or not the -f option shall be ignored. */ if settings.follow && !stdin_is_pipe_or_fifo() { readers.push((Box::new(reader), &stdin_string)); } } } else { let path = Path::new(filename); if path.is_dir() { continue; } let mut file = File::open(&path) .map_err_context(|| format!("cannot open {} for reading", filename.quote()))?; let md = file.metadata().unwrap(); if is_seekable(&mut file) && get_block_size(&md) > 0 { bounded_tail(&mut file, &settings.mode, settings.beginning); if settings.follow { let reader = BufReader::new(file); readers.push((Box::new(reader), filename)); } } else { let mut reader = BufReader::new(file); unbounded_tail(&mut reader, settings)?; if settings.follow { readers.push((Box::new(reader), filename)); } } } } if settings.follow { follow(&mut readers[..], settings)?; } Ok(()) } fn arg_iterate<'a>( mut args: impl uucore::Args + 'a, ) -> Result<Box<dyn Iterator<Item = OsString> + 'a>, String> {
let first = args.next().unwrap(); if let Some(second) = args.next() { if let Some(s) = second.to_str() { match parse::parse_obsolete(s) { Some(Ok(iter)) => Ok(Box::new(vec![first].into_iter().chain(iter).chain(args))), Some(Err(e)) => match e { parse::ParseError::Syntax => Err(format!("bad argument format: {}", s.quote())), parse::ParseError::Overflow => Err(format!( "invalid argument: {} Value too large for defined datatype", s.quote() )), }, None => Ok(Box::new(vec![first, second].into_iter().chain(args))), } } else { Err("bad argument encoding".to_owned()) } } else { Ok(Box::new(vec![first].into_iter())) } } pub fn uu_app<'a>() -> App<'a> { App::new(uucore::util_name()) .version(crate_version!()) .about(ABOUT) .override_usage(USAGE) .setting(AppSettings::InferLongArgs) .arg( Arg::new(options::BYTES) .short('c') .long(options::BYTES) .takes_value(true) .allow_hyphen_values(true) .overrides_with_all(&[options::BYTES, options::LINES]) .help("Number of bytes to print"), ) .arg( Arg::new(options::FOLLOW) .short('f') .long(options::FOLLOW) .help("Print the file as it grows"), ) .arg( Arg::new(options::LINES) .short('n') .long(options::LINES) .takes_value(true) .allow_hyphen_values(true) .overrides_with_all(&[options::BYTES, options::LINES]) .help("Number of lines to print"), ) .arg( Arg::new(options::PID) .long(options::PID) .takes_value(true) .help("with -f, terminate after process ID, PID dies"), ) .arg( Arg::new(options::verbosity::QUIET) .short('q') .long(options::verbosity::QUIET) .visible_alias("silent") .overrides_with_all(&[options::verbosity::QUIET, options::verbosity::VERBOSE]) .help("never output headers giving file names"), ) .arg( Arg::new(options::SLEEP_INT) .short('s') .takes_value(true) .long(options::SLEEP_INT) .help("Number or seconds to sleep between polling the file when running with -f"), ) .arg( Arg::new(options::verbosity::VERBOSE) .short('v') .long(options::verbosity::VERBOSE) .overrides_with_all(&[options::verbosity::QUIET, options::verbosity::VERBOSE]) .help("always output headers giving file names"), ) .arg( Arg::new(options::ZERO_TERM) .short('z') .long(options::ZERO_TERM) .help("Line delimiter is NUL, not newline"), ) .arg( Arg::new(options::ARG_FILES) .multiple_occurrences(true) .takes_value(true) .min_values(1), ) } /// Continually check for new data in the given readers, writing any to stdout. fn follow<T: BufRead>(readers: &mut [(T, &String)], settings: &Settings) -> UResult<()> { if readers.is_empty() || !settings.follow { return Ok(()); } let mut last = readers.len() - 1; let mut read_some = false; let mut process = platform::ProcessChecker::new(settings.pid); let mut stdout = stdout(); loop { sleep(Duration::new(0, settings.sleep_msec * 1000)); let pid_is_dead = !read_some && settings.pid != 0 && process.is_dead(); read_some = false; for (i, (reader, filename)) in readers.iter_mut().enumerate() { // Print all new content since the last pass loop { let mut datum = vec![]; match reader.read_until(b'\n', &mut datum) { Ok(0) => break, Ok(_) => { read_some = true; if i != last { println!("\n==> {} <==", filename); last = i; } stdout .write_all(&datum) .map_err_context(|| String::from("write error"))?; } Err(err) => return Err(USimpleError::new(1, err.to_string())), } } } if pid_is_dead { break; } } Ok(()) } /// Find the index after the given number of instances of a given byte. /// /// This function reads through a given reader until `num_delimiters` /// instances of `delimiter` have been seen, returning the index of /// the byte immediately following that delimiter. If there are fewer /// than `num_delimiters` instances of `delimiter`, this returns the /// total number of bytes read from the `reader` until EOF. /// /// # Errors /// /// This function returns an error if there is an error during reading /// from `reader`. /// /// # Examples /// /// Basic usage: /// /// ```rust,ignore /// use std::io::Cursor; /// /// let mut reader = Cursor::new("a\nb\nc\nd\ne\n"); /// let i = forwards_thru_file(&mut reader, 2, b'\n').unwrap(); /// assert_eq!(i, 4); /// ``` /// /// If `num_delimiters` is zero, then this function always returns /// zero: /// /// ```rust,ignore /// use std::io::Cursor; /// /// let mut reader = Cursor::new("a\n"); /// let i = forwards_thru_file(&mut reader, 0, b'\n').unwrap(); /// assert_eq!(i, 0); /// ``` /// /// If there are fewer than `num_delimiters` instances of `delimiter` /// in the reader, then this function returns the total number of /// bytes read: /// /// ```rust,ignore /// use std::io::Cursor; /// /// let mut reader = Cursor::new("a\n"); /// let i = forwards_thru_file(&mut reader, 2, b'\n').unwrap(); /// assert_eq!(i, 2); /// ``` fn forwards_thru_file<R>( reader: &mut R, num_delimiters: usize, delimiter: u8, ) -> std::io::Result<usize> where R: Read, { let mut reader = BufReader::new(reader); let mut buf = vec![]; let mut total = 0; for _ in 0..num_delimiters { match reader.read_until(delimiter, &mut buf) { Ok(0) => { return Ok(total); } Ok(n) => { total += n; buf.clear(); continue; } Err(e) => { return Err(e); } } } Ok(total) } /// Iterate over bytes in the file, in reverse, until we find the /// `num_delimiters` instance of `delimiter`. The `file` is left seek'd to the /// position just after that delimiter. fn backwards_thru_file(file: &mut File, num_delimiters: usize, delimiter: u8) { // This variable counts the number of delimiters found in the file // so far (reading from the end of the file toward the beginning). let mut counter = 0; for (block_idx, slice) in ReverseChunks::new(file).enumerate() { // Iterate over each byte in the slice in reverse order. let mut iter = slice.iter().enumerate().rev(); // Ignore a trailing newline in the last block, if there is one. if block_idx == 0 { if let Some(c) = slice.last() { if *c == delimiter { iter.next(); } } } // For each byte, increment the count of the number of // delimiters found. If we have found more than the specified // number of delimiters, terminate the search and seek to the // appropriate location in the file. for (i, ch) in iter { if *ch == delimiter { counter += 1; if counter >= num_delimiters { // After each iteration of the outer loop, the // cursor in the file is at the *beginning* of the // block, so seeking forward by `i + 1` bytes puts // us right after the found delimiter. file.seek(SeekFrom::Current((i + 1) as i64)).unwrap(); return; } } } } } /// When tail'ing a file, we do not need to read the whole file from start to /// finish just to find the last n lines or bytes. Instead, we can seek to the /// end of the file, and then read the file "backwards" in blocks of size /// `BLOCK_SIZE` until we find the location of the first line/byte. This ends up /// being a nice performance win for very large files. fn bounded_tail(file: &mut File, mode: &FilterMode, beginning: bool) { // Find the position in the file to start printing from. match (mode, beginning) { (FilterMode::Lines(count, delimiter), false) => { backwards_thru_file(file, *count, *delimiter); } (FilterMode::Lines(count, delimiter), true) => { let i = forwards_thru_file(file, (*count).max(1) - 1, *delimiter).unwrap(); file.seek(SeekFrom::Start(i as u64)).unwrap(); } (FilterMode::Bytes(count), false) => { file.seek(SeekFrom::End(-(*count as i64))).unwrap(); } (FilterMode::Bytes(count), true) => { // GNU `tail` seems to index bytes and lines starting at 1, not // at 0. It seems to treat `+0` and `+1` as the same thing. file.seek(SeekFrom::Start(((*count).max(1) - 1) as u64)) .unwrap(); } } // Print the target section of the file. let stdout = stdout(); let mut stdout = stdout.lock(); std::io::copy(file, &mut stdout).unwrap(); } /// Collect the last elements of an iterator into a `VecDeque`. /// /// This function returns a [`VecDeque`] containing either the last /// `count` elements of `iter`, an [`Iterator`] over [`Result`] /// instances, or all but the first `count` elements of `iter`. If /// `beginning` is `true`, then all but the first `count` elements are /// returned. /// /// # Panics /// /// If any element of `iter` is an [`Err`], then this function panics. fn unbounded_tail_collect<T, E>( iter: impl Iterator<Item = Result<T, E>>, count: usize, beginning: bool, ) -> VecDeque<T> where E: fmt::Debug, { if beginning { // GNU `tail` seems to index bytes and lines starting at 1, not // at 0. It seems to treat `+0` and `+1` as the same thing. let i = count.max(1) - 1; iter.skip(i as usize).map(|r| r.unwrap()).collect() } else { RingBuffer::from_iter(iter.map(|r| r.unwrap()), count as usize).data } } fn unbounded_tail<T: Read>(reader: &mut BufReader<T>, settings: &Settings) -> UResult<()> { // Read through each line/char and store them in a ringbuffer that always // contains count lines/chars. When reaching the end of file, output the // data in the ringbuf. match settings.mode { FilterMode::Lines(count, _) => { for line in unbounded_tail_collect(lines(reader), count, settings.beginning) { print!("{}", line); } } FilterMode::Bytes(count) => { for byte in unbounded_tail_collect(reader.bytes(), count, settings.beginning) { if let Err(err) = stdout().write(&[byte]) { return Err(USimpleError::new(1, err.to_string())); } } } } Ok(()) } fn is_seekable<T: Seek>(file: &mut T) -> bool { file.seek(SeekFrom::Current(0)).is_ok() && file.seek(SeekFrom::End(0)).is_ok() && file.seek(SeekFrom::Start(0)).is_ok() } fn parse_num(src: &str) -> Result<(usize, bool), ParseSizeError> { let mut size_string = src.trim(); let mut starting_with = false; if let Some(c) = size_string.chars().next() { if c == '+' || c == '-' { // tail: '-' is not documented (8.32 man pages) size_string = &size_string[1..]; if c == '+' { starting_with = true; } } } else { return Err(ParseSizeError::ParseFailure(src.to_string())); } parse_size(size_string).map(|n| (n, starting_with)) } fn get_block_size(md: &Metadata) -> u64 { #[cfg(unix)] { md.blocks() } #[cfg(not(unix))] { md.len() } } #[cfg(test)] mod tests { use crate::forwards_thru_file; use std::io::Cursor; #[test] fn test_forwards_thru_file_zero() { let mut reader = Cursor::new("a\n"); let i = forwards_thru_file(&mut reader, 0, b'\n').unwrap(); assert_eq!(i, 0); } #[test] fn test_forwards_thru_file_basic() { // 01 23 45 67 89 let mut reader = Cursor::new("a\nb\nc\nd\ne\n"); let i = forwards_thru_file(&mut reader, 2, b'\n').unwrap(); assert_eq!(i, 4); } #[test] fn test_forwards_thru_file_past_end() { let mut reader = Cursor::new("x\n"); let i = forwards_thru_file(&mut reader, 2, b'\n').unwrap(); assert_eq!(i, 2); } }
// argv[0] is always present
model.py
#!/usr/bin/env python3 import sqlite3, json, time, sys, os from housepy import config, log, util def db_call(f): def wrapper(*args): connection = sqlite3.connect(os.path.abspath(os.path.join(os.path.dirname(__file__), "data.db"))) connection.row_factory = sqlite3.Row db = connection.cursor() results = f(db, *args) connection.commit() connection.close() return results return wrapper @db_call def init(db): try: db.execute("CREATE TABLE IF NOT EXISTS clips (t INTEGER, hit_id TEXT, posted INTEGER)") db.execute("CREATE UNIQUE INDEX IF NOT EXISTS clips_t ON clips(t)") except Exception as e: log.error(log.exc(e)) return init() @db_call def add_clip(db, t, hit_id): try: db.execute("INSERT INTO clips (t, hit_id, posted) VALUES (?, ?, 0)", (t, hit_id)) except Exception as e: log.error(log.exc(e)) return log.info("Added clip %s %s" % (t, hit_id)) @db_call def get_recent(db): t = util.timestamp() db.execute("SELECT * FROM clips WHERE t>=? AND posted=0", (t - config['lag'],)) clips = [dict(clip) for clip in db.fetchall()] return clips @db_call def mark_clip(db, t):
log.info("Marking clip %s" % t) try: db.execute("UPDATE clips SET posted=1 WHERE t=?", (t,)) except Exception as e: log.error(log.exc(e)) return
client_test.go
package test import (
) func TestClient(t *testing.T) { emulator := DofusServerEmulator{} go emulator.startClient() emulator.Start(t) } func TestWithDebug(t *testing.T) { emulator := DofusServerEmulator{} go emulator.Start(t) emulator.startClient() }
"testing"
improv_rnn_sequence_generator.py
# Copyright 2016 Google Inc. 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. """Melody-over-chords RNN generation code as a SequenceGenerator interface.""" from functools import partial # internal imports from magenta.models.improv_rnn import improv_rnn_model import magenta.music as mm class ImprovRnnSequenceGenerator(mm.BaseSequenceGenerator): """Improv RNN generation code as a SequenceGenerator interface.""" def __init__(self, model, details, steps_per_quarter=4, checkpoint=None, bundle=None): """Creates an ImprovRnnSequenceGenerator. Args: model: Instance of ImprovRnnModel. details: A generator_pb2.GeneratorDetails for this generator. steps_per_quarter: What precision to use when quantizing the melody and chords. How many steps per quarter note. checkpoint: Where to search for the most recent model checkpoint. Mutually exclusive with `bundle`. bundle: A GeneratorBundle object that includes both the model checkpoint and metagraph. Mutually exclusive with `checkpoint`. """ super(ImprovRnnSequenceGenerator, self).__init__( model, details, checkpoint, bundle) self.steps_per_quarter = steps_per_quarter def _generate(self, input_sequence, generator_options): if len(generator_options.input_sections) > 1: raise mm.SequenceGeneratorException( 'This model supports at most one input_sections message, but got %s' % len(generator_options.input_sections)) if len(generator_options.generate_sections) != 1: raise mm.SequenceGeneratorException( 'This model supports only 1 generate_sections message, but got %s' % len(generator_options.generate_sections)) qpm = (input_sequence.tempos[0].qpm if input_sequence and input_sequence.tempos else mm.DEFAULT_QUARTERS_PER_MINUTE)
generate_section = generator_options.generate_sections[0] if generator_options.input_sections: # Use primer melody from input section only. Take backing chords from # beginning of input section through end of generate section. input_section = generator_options.input_sections[0] primer_sequence = mm.trim_note_sequence( input_sequence, input_section.start_time, input_section.end_time) backing_sequence = mm.trim_note_sequence( input_sequence, input_section.start_time, generate_section.end_time) input_start_step = mm.quantize_to_step( input_section.start_time, steps_per_second, quantize_cutoff=0.0) else: # No input section. Take primer melody from the beginning of the sequence # up until the start of the generate section. primer_sequence = mm.trim_note_sequence( input_sequence, 0.0, generate_section.start_time) backing_sequence = mm.trim_note_sequence( input_sequence, 0.0, generate_section.end_time) input_start_step = 0 last_end_time = (max(n.end_time for n in primer_sequence.notes) if primer_sequence.notes else 0) if last_end_time >= generate_section.start_time: raise mm.SequenceGeneratorException( 'Got GenerateSection request for section that is before or equal to ' 'the end of the input section. This model can only extend melodies. ' 'Requested start time: %s, Final note end time: %s' % (generate_section.start_time, last_end_time)) # Quantize the priming and backing sequences. quantized_primer_sequence = mm.quantize_note_sequence( primer_sequence, self.steps_per_quarter) quantized_backing_sequence = mm.quantize_note_sequence( backing_sequence, self.steps_per_quarter) # Setting gap_bars to infinite ensures that the entire input will be used. extracted_melodies, _ = mm.extract_melodies( quantized_primer_sequence, search_start_step=input_start_step, min_bars=0, min_unique_pitches=1, gap_bars=float('inf'), ignore_polyphonic_notes=True) assert len(extracted_melodies) <= 1 start_step = mm.quantize_to_step( generate_section.start_time, steps_per_second, quantize_cutoff=0.0) # Note that when quantizing end_step, we set quantize_cutoff to 1.0 so it # always rounds down. This avoids generating a sequence that ends at 5.0 # seconds when the requested end time is 4.99. end_step = mm.quantize_to_step( generate_section.end_time, steps_per_second, quantize_cutoff=1.0) if extracted_melodies and extracted_melodies[0]: melody = extracted_melodies[0] else: # If no melody could be extracted, create an empty melody that starts 1 # step before the request start_step. This will result in 1 step of # silence when the melody is extended below. steps_per_bar = int( mm.steps_per_bar_in_quantized_sequence(quantized_primer_sequence)) melody = mm.Melody([], start_step=max(0, start_step - 1), steps_per_bar=steps_per_bar, steps_per_quarter=self.steps_per_quarter) extracted_chords, _ = mm.extract_chords(quantized_backing_sequence) chords = extracted_chords[0] # Make sure that chords and melody start on the same step. if chords.start_step < melody.start_step: chords.set_length(len(chords) - melody.start_step + chords.start_step) assert chords.end_step == end_step # Ensure that the melody extends up to the step we want to start generating. melody.set_length(start_step - melody.start_step) # Extract generation arguments from generator options. arg_types = { 'temperature': lambda arg: arg.float_value, 'beam_size': lambda arg: arg.int_value, 'branch_factor': lambda arg: arg.int_value, 'steps_per_iteration': lambda arg: arg.int_value } args = dict((name, value_fn(generator_options.args[name])) for name, value_fn in arg_types.items() if name in generator_options.args) generated_melody = self._model.generate_melody(melody, chords, **args) generated_lead_sheet = mm.LeadSheet(generated_melody, chords) generated_sequence = generated_lead_sheet.to_sequence(qpm=qpm) assert (generated_sequence.total_time - generate_section.end_time) <= 1e-5 return generated_sequence def get_generator_map(): """Returns a map from the generator ID to a SequenceGenerator class creator. Binds the `config` argument so that the arguments match the BaseSequenceGenerator class constructor. Returns: Map from the generator ID to its SequenceGenerator class creator with a bound `config` argument. """ def create_sequence_generator(config, **kwargs): return ImprovRnnSequenceGenerator( improv_rnn_model.ImprovRnnModel(config), config.details, steps_per_quarter=config.steps_per_quarter, **kwargs) return {key: partial(create_sequence_generator, config) for (key, config) in improv_rnn_model.default_configs.items()}
steps_per_second = mm.steps_per_quarter_to_steps_per_second( self.steps_per_quarter, qpm)
test_rbd_mirror.py
import pytest import json class TestRbdMirrors(object): @pytest.mark.no_docker def test_rbd_mirror_is_installed(self, node, host): assert host.package("rbd-mirror").is_installed def test_rbd_mirror_service_enabled_and_running(self, node, host): service_name = "ceph-rbd-mirror@rbd-mirror.{hostname}".format( hostname=node["vars"]["inventory_hostname"] ) s = host.service(service_name) assert s.is_enabled assert s.is_running def test_rbd_mirror_is_up(self, node, host, setup):
hostname = node["vars"]["inventory_hostname"] cluster = setup["cluster_name"] container_binary = setup["container_binary"] daemons = [] if node['docker']: container_exec_cmd = '{container_binary} exec ceph-rbd-mirror-{hostname}'.format( # noqa E501 hostname=hostname, container_binary=container_binary) else: container_exec_cmd = '' hostname = node["vars"]["inventory_hostname"] cluster = setup['cluster_name'] cmd = "sudo {container_exec_cmd} ceph --name client.bootstrap-rbd-mirror --keyring /var/lib/ceph/bootstrap-rbd-mirror/{cluster}.keyring --cluster={cluster} --connect-timeout 5 -f json -s".format( # noqa E501 container_exec_cmd=container_exec_cmd, hostname=hostname, cluster=cluster ) output = host.check_output(cmd) status = json.loads(output) daemon_ids = [i for i in status["servicemap"]["services"] ["rbd-mirror"]["daemons"].keys() if i != "summary"] for daemon_id in daemon_ids: daemons.append(status["servicemap"]["services"]["rbd-mirror"] ["daemons"][daemon_id]["metadata"]["hostname"]) assert hostname in daemons
functions.rs
extern crate libsqlite3_sys as ffi; use super::raw::RawConnection; use super::serialized_value::SerializedValue; use super::{Sqlite, SqliteAggregateFunction, SqliteValue}; use crate::deserialize::{FromSqlRow, StaticallySizedRow}; use crate::result::{DatabaseErrorKind, Error, QueryResult}; use crate::row::{Field, PartialRow, Row, RowIndex}; use crate::serialize::{IsNull, Output, ToSql}; use crate::sql_types::HasSqlType; use std::marker::PhantomData; pub fn register<ArgsSqlType, RetSqlType, Args, Ret, F>( conn: &RawConnection, fn_name: &str, deterministic: bool, mut f: F, ) -> QueryResult<()> where F: FnMut(&RawConnection, Args) -> Ret + std::panic::UnwindSafe + Send + 'static, Args: FromSqlRow<ArgsSqlType, Sqlite> + StaticallySizedRow<ArgsSqlType, Sqlite>, Ret: ToSql<RetSqlType, Sqlite>, Sqlite: HasSqlType<RetSqlType>, { let fields_needed = Args::FIELD_COUNT; if fields_needed > 127 { return Err(Error::DatabaseError( DatabaseErrorKind::UnableToSendCommand, Box::new("SQLite functions cannot take more than 127 parameters".to_string()), )); } conn.register_sql_function(fn_name, fields_needed, deterministic, move |conn, args| { let args = build_sql_function_args::<ArgsSqlType, Args>(args)?; let result = f(conn, args); process_sql_function_result::<RetSqlType, Ret>(result) })?; Ok(()) } pub fn register_noargs<RetSqlType, Ret, F>( conn: &RawConnection, fn_name: &str, deterministic: bool, mut f: F, ) -> QueryResult<()> where F: FnMut() -> Ret + std::panic::UnwindSafe + Send + 'static, Ret: ToSql<RetSqlType, Sqlite>, Sqlite: HasSqlType<RetSqlType>, { conn.register_sql_function(fn_name, 0, deterministic, move |_, _| { let result = f(); process_sql_function_result::<RetSqlType, Ret>(result) })?; Ok(()) } pub fn
<ArgsSqlType, RetSqlType, Args, Ret, A>( conn: &RawConnection, fn_name: &str, ) -> QueryResult<()> where A: SqliteAggregateFunction<Args, Output = Ret> + 'static + Send + std::panic::UnwindSafe, Args: FromSqlRow<ArgsSqlType, Sqlite> + StaticallySizedRow<ArgsSqlType, Sqlite>, Ret: ToSql<RetSqlType, Sqlite>, Sqlite: HasSqlType<RetSqlType>, { let fields_needed = Args::FIELD_COUNT; if fields_needed > 127 { return Err(Error::DatabaseError( DatabaseErrorKind::UnableToSendCommand, Box::new("SQLite functions cannot take more than 127 parameters".to_string()), )); } conn.register_aggregate_function::<ArgsSqlType, RetSqlType, Args, Ret, A>( fn_name, fields_needed, )?; Ok(()) } pub(crate) fn build_sql_function_args<ArgsSqlType, Args>( args: &[*mut ffi::sqlite3_value], ) -> Result<Args, Error> where Args: FromSqlRow<ArgsSqlType, Sqlite>, { let row = FunctionRow::new(args); Args::build_from_row(&row).map_err(Error::DeserializationError) } pub(crate) fn process_sql_function_result<RetSqlType, Ret>( result: Ret, ) -> QueryResult<SerializedValue> where Ret: ToSql<RetSqlType, Sqlite>, Sqlite: HasSqlType<RetSqlType>, { let mut metadata_lookup = (); let mut buf = Output::new(Vec::new(), &mut metadata_lookup); let is_null = result.to_sql(&mut buf).map_err(Error::SerializationError)?; let bytes = if let IsNull::Yes = is_null { None } else { Some(buf.into_inner()) }; Ok(SerializedValue { ty: Sqlite::metadata(&mut ()), data: bytes, }) } #[derive(Clone)] struct FunctionRow<'a> { args: &'a [*mut ffi::sqlite3_value], } impl<'a> FunctionRow<'a> { fn new(args: &'a [*mut ffi::sqlite3_value]) -> Self { Self { args } } } impl<'a> Row<'a, Sqlite> for FunctionRow<'a> { type Field = FunctionArgument<'a>; type InnerPartialRow = Self; fn field_count(&self) -> usize { self.args.len() } fn get<I>(&self, idx: I) -> Option<Self::Field> where Self: crate::row::RowIndex<I>, { let idx = self.idx(idx)?; self.args.get(idx).map(|arg| FunctionArgument { arg: *arg, p: PhantomData, }) } fn partial_row(&self, range: std::ops::Range<usize>) -> PartialRow<Self::InnerPartialRow> { PartialRow::new(self, range) } } impl<'a> RowIndex<usize> for FunctionRow<'a> { fn idx(&self, idx: usize) -> Option<usize> { if idx < self.args.len() { Some(idx) } else { None } } } impl<'a, 'b> RowIndex<&'a str> for FunctionRow<'b> { fn idx(&self, _idx: &'a str) -> Option<usize> { None } } struct FunctionArgument<'a> { arg: *mut ffi::sqlite3_value, p: PhantomData<&'a ()>, } impl<'a> Field<'a, Sqlite> for FunctionArgument<'a> { fn field_name(&self) -> Option<&'a str> { None } fn is_null(&self) -> bool { self.value().is_none() } fn value(&self) -> Option<crate::backend::RawValue<'a, Sqlite>> { unsafe { SqliteValue::new(self.arg) } } }
register_aggregate
PressureTest.qunit.ts
import { Backend } from "../Backend"; import { Options } from "../Options"; /** * PressureTest is about trying to trip up Ob2ss with edge-cases, tricky situations, and other mayhem. While * not everything will get fixed, it's nice to see what can happen. */ function pressureTest(QUnit:QUnit){ const options = new Options(); const Ob2ss = new Backend(options); const spreadsheet = SpreadsheetApp.openById('1w7lhdf2wSi4JkmlWWirydF9eYNhnb22FnjYYNhNBtAI'); QUnit.module('Testing Adding.'); QUnit.test("Adding strange objects.", (assert) => { Ob2ss.open(spreadsheet); let table = Ob2ss.getTableByName('default'); let date1 = new Date(1653924474000); let date2 = new Date("123456"); let trickyTestObj = { 'string': '/notreally/&bsp;', 'equation': '=ISNA("12")', 'naughtyArray': [ , 2, 3, "4"], 'dates': [ date1, date2] }; table.addAppend([trickyTestObj]); let expected = { "dates": [ "Mon May 30 2022 11:27:54 GMT-0400 (Eastern Daylight Time)", "Tue Jan 01 123456 00:00:00 GMT-0500 (Eastern Standard Time)" ], "equation": false, "naughtyArray": [ undefined, 2, 3, 4 ], "string": "/notreally/&bsp;" }; let result = table.getLast()[0]; assert.deepEqual(result, expected, 'Mild object transformation occurred.'); table.destroy(); }); QUnit.module('Testing Updating.'); QUnit.test("Adding strange objects.", (assert) => { }); QUnit.module('Testing Reading.'); QUnit.module('Testing Deleting.'); } function
(){ // SPECIFIC TESTS let spreadsheetId = '1w7lhdf2wSi4JkmlWWirydF9eYNhnb22FnjYYNhNBtAI'; let spreadsheet = SpreadsheetApp.openById(spreadsheetId); let Ob2ss = new Backend(); Ob2ss.open(spreadsheet); let table = Ob2ss.getTableByName('default'); let date1 = new Date("1653924474000"); let date2 = new Date("123456"); let trickyTestObj = { 'string': '/notreally/&bsp;', 'equation': '=ISNA("12")', 'naughtyArray': [ , 2, 3, "4"], 'dates': [ new Date(), new Date("123456")] }; table.addAppend([trickyTestObj]); Logger.log(table.getCount()); Logger.log(table.getLast()[0]); }
testHeaderOffset
bengali_deepoffense_config.py
from multiprocessing import cpu_count TEMP_DIRECTORY = "temp/data" TRAIN_FILE = "train.tsv" TEST_FILE = "test.tsv" DEV_RESULT_FILE = "dev_result.tsv" DEV_EVAL_FILE = 'dev_eval.txt' RESULT_FILE = "result.csv" SUBMISSION_FOLDER = "transformers" SUBMISSION_FILE = "transformers" MODEL_TYPE = "xlmroberta" MODEL_NAME = "xlm-roberta-large" LANGUAGE_FINETUNE =False SEED = 777 # training instances = 7000 > if batch size=8, batches = 875 > evaluate during training steps -> 80 or 175 args = { 'output_dir': 'temp/outputs/', "best_model_dir": "temp/outputs/best_model", 'cache_dir': 'temp/cache_dir/', 'fp16': False, 'fp16_opt_level': 'O1', 'max_seq_length': 128, # 128 'train_batch_size': 8, 'gradient_accumulation_steps': 1, 'eval_batch_size': 8, 'num_train_epochs': 3, 'weight_decay': 0, 'learning_rate': 1e-5, 'adam_epsilon': 1e-8, 'warmup_ratio': 0.06, 'warmup_steps': 0, 'max_grad_norm': 1.0, 'do_lower_case': False, 'n_fold': 3, 'logging_steps': 60, 'save_steps': 60, "no_cache": False, "no_save": False, "save_recent_only": True, 'save_model_every_epoch': True, 'evaluate_during_training': True, "evaluate_during_training_silent": True, 'evaluate_during_training_steps': 60, "evaluate_during_training_verbose": True, 'use_cached_eval_features': False, "save_best_model": True, 'save_eval_checkpoints': True, 'tensorboard_dir': None, "save_optimizer_and_scheduler": True, 'overwrite_output_dir': True, 'reprocess_input_data': True, 'process_count': cpu_count() - 2 if cpu_count() > 2 else 1, 'n_gpu': 1, 'use_multiprocessing': True, "multiprocessing_chunksize": 500, 'silent': False, 'wandb_project': None, 'wandb_kwargs': {}, "use_early_stopping": True, "early_stopping_patience": 10, "early_stopping_delta": 0, "early_stopping_metric": "eval_loss", "early_stopping_metric_minimize": True, "early_stopping_consider_epochs": False, "manual_seed": SEED, "config": {}, "local_rank": -1, "encoding": None, } language_modeling_args = { 'output_dir': 'temp/lm/outputs/', "best_model_dir": "temp/lm/outputs/best_model", 'cache_dir': 'temp/lm/cache_dir/', 'fp16': False, 'fp16_opt_level': 'O1', 'max_seq_length': 152, # 128 'train_batch_size': 8, 'gradient_accumulation_steps': 1, 'eval_batch_size': 8, 'num_train_epochs': 2, 'weight_decay': 0, 'learning_rate': 1e-5, 'adam_epsilon': 1e-8, 'warmup_ratio': 0.06, 'warmup_steps': 0, 'max_grad_norm': 1.0, 'do_lower_case': False, 'logging_steps': 80, 'save_steps': 80, "no_cache": False, "no_save": False, "save_recent_only": True, 'save_model_every_epoch': True, 'evaluate_during_training': True, "evaluate_during_training_silent": True, 'evaluate_during_training_steps': 80, "evaluate_during_training_verbose": True, 'use_cached_eval_features': False, "save_best_model": True, 'save_eval_checkpoints': True, 'tensorboard_dir': None, "save_optimizer_and_scheduler": True, 'overwrite_output_dir': True, 'reprocess_input_data': True, 'process_count': cpu_count() - 2 if cpu_count() > 2 else 1, 'n_gpu': 1, 'use_multiprocessing': True, "multiprocessing_chunksize": 500, 'silent': False, 'wandb_project': None, 'wandb_kwargs': {}, "use_early_stopping": True,
"early_stopping_metric": "eval_loss", "early_stopping_metric_minimize": True, "early_stopping_consider_epochs": False, "manual_seed": SEED, "config": {}, "local_rank": -1, "encoding": None, }
"early_stopping_patience": 10, "early_stopping_delta": 0,
statevector.py
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Statevector quantum state class. """ import copy import re import warnings from numbers import Number import numpy as np from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.instruction import Instruction from qiskit.exceptions import QiskitError from qiskit.quantum_info.states.quantum_state import QuantumState from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.predicates import matrix_equal class Statevector(QuantumState): """Statevector class""" def __init__(self, data, dims=None): """Initialize a statevector object. Args: data (vector_like): a complex statevector. dims (int or tuple or list): Optional. The subsystem dimension of the state (See additional information). Raises: QiskitError: if input data is not valid. Additional Information: The ``dims`` kwarg can be None, an integer, or an iterable of integers. * ``Iterable`` -- the subsystem dimensions are the values in the list with the total number of subsystems given by the length of the list. * ``Int`` or ``None`` -- the length of the input vector specifies the total dimension of the density matrix. If it is a power of two the state will be initialized as an N-qubit state. If it is not a power of two the state will have a single d-dimensional subsystem. """ if isinstance(data, (list, np.ndarray)): # Finally we check if the input is a raw vector in either a # python list or numpy array format. self._data = np.asarray(data, dtype=complex) elif isinstance(data, Statevector): self._data = data._data if dims is None: dims = data._dims elif isinstance(data, Operator): # We allow conversion of column-vector operators to Statevectors input_dim, _ = data.dim if input_dim != 1: raise QiskitError("Input Operator is not a column-vector.") self._data = np.ravel(data.data) else: raise QiskitError("Invalid input data format for Statevector") # Check that the input is a numpy vector or column-vector numpy # matrix. If it is a column-vector matrix reshape to a vector. ndim = self._data.ndim shape = self._data.shape if ndim != 1: if ndim == 2 and shape[1] == 1: self._data = np.reshape(self._data, shape[0]) elif ndim != 2 or shape[1] != 1: raise QiskitError("Invalid input: not a vector or column-vector.") super().__init__(self._automatic_dims(dims, shape[0])) def __eq__(self, other): return super().__eq__(other) and np.allclose( self._data, other._data, rtol=self.rtol, atol=self.atol) def __repr__(self): prefix = 'Statevector(' pad = len(prefix) * ' ' return '{}{},\n{}dims={})'.format( prefix, np.array2string( self.data, separator=', ', prefix=prefix), pad, self._dims) @property def data(self): """Return data.""" return self._data def is_valid(self, atol=None, rtol=None): """Return True if a Statevector has norm 1.""" if atol is None: atol = self.atol if rtol is None: rtol = self.rtol norm = np.linalg.norm(self.data) return np.allclose(norm, 1, rtol=rtol, atol=atol) def to_operator(self): """Convert state to a rank-1 projector operator""" mat = np.outer(self.data, np.conj(self.data)) return Operator(mat, input_dims=self.dims(), output_dims=self.dims()) def conjugate(self): """Return the conjugate of the operator.""" return Statevector(np.conj(self.data), dims=self.dims()) def trace(self): """Return the trace of the quantum state as a density matrix.""" return np.sum(np.abs(self.data) ** 2) def purity(self): """Return the purity of the quantum state.""" # For a valid statevector the purity is always 1, however if we simply # have an arbitrary vector (not correctly normalized) then the # purity is equivalent to the trace squared: # P(|psi>) = Tr[|psi><psi|psi><psi|] = |<psi|psi>|^2 return self.trace() ** 2 def tensor(self, other): """Return the tensor product state self ⊗ other. Args: other (Statevector): a quantum state object. Returns: Statevector: the tensor product operator self ⊗ other. Raises: QiskitError: if other is not a quantum state. """ if not isinstance(other, Statevector): other = Statevector(other) dims = other.dims() + self.dims() data = np.kron(self._data, other._data) return Statevector(data, dims) def expand(self, other): """Return the tensor product state other ⊗ self. Args: other (Statevector): a quantum state object. Returns: Statevector: the tensor product state other ⊗ self. Raises: QiskitError: if other is not a quantum state. """ if not isinstance(other, Statevector): other = Statevector(other) dims = self.dims() + other.dims() data = np.kron(other._data, self._data) return Statevector(data, dims) def _add(self, other): """Return the linear combination self + other. Args: other (Statevector): a quantum state object. Returns: Statevector: the linear combination self + other. Raises: QiskitError: if other is not a quantum state, or has incompatible dimensions. """ if not isinstance(other, Statevector): other = Statevector(other) if self.dim != other.dim: raise QiskitError("other Statevector has different dimensions.") return Statevector(self.data + other.data, self.dims()) def _multiply(self, other): """Return the scalar multiplied state self * other. Args: other (complex): a complex number. Returns: Statevector: the scalar multiplied state other * self. Raises: QiskitError: if other is not a valid complex number. """ if not isinstance(other, Number): raise QiskitError("other is not a number") return Statevector(other * self.data, self.dims()) def evolve(self, other, qargs=None): """Evolve a quantum state by the operator. Args: other (Operator): The operator to evolve by. qargs (list): a list of Statevector subsystem positions to apply the operator on. Returns: Statevector: the output quantum state. Raises: QiskitError: if the operator dimension does not match the specified Statevector subsystem dimensions. """ if qargs is None: qargs = getattr(other, 'qargs', None) # Get return vector ret = copy.copy(self) # Evolution by a circuit or instruction if isinstance(other, QuantumCircuit): other = other.to_instruction() if isinstance(other, Instruction): if self.
# Evolution by an Operator if not isinstance(other, Operator): other = Operator(other) # check dimension if self.dims(qargs) != other.input_dims(): raise QiskitError( "Operator input dimensions are not equal to statevector subsystem dimensions." ) return Statevector._evolve_operator(ret, other, qargs=qargs) def equiv(self, other, rtol=None, atol=None): """Return True if statevectors are equivalent up to global phase. Args: other (Statevector): a statevector object. rtol (float): relative tolerance value for comparison. atol (float): absolute tolerance value for comparison. Returns: bool: True if statevectors are equivalent up to global phase. """ if not isinstance(other, Statevector): try: other = Statevector(other) except QiskitError: return False if self.dim != other.dim: return False if atol is None: atol = self.atol if rtol is None: rtol = self.rtol return matrix_equal(self.data, other.data, ignore_phase=True, rtol=rtol, atol=atol) def expectation_value(self, oper, qargs=None): """Compute the expectation value of an operator. Args: oper (Operator): an operator to evaluate expval of. qargs (None or list): subsystems to apply operator on. Returns: complex: the expectation value. """ val = self.evolve(oper, qargs=qargs) conj = self.conjugate() return np.dot(conj.data, val.data) def probabilities(self, qargs=None, decimals=None): """Return the subsystem measurement probability vector. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. Args: qargs (None or list): subsystems to return probabilities for, if None return for all subsystems (Default: None). decimals (None or int): the number of decimal places to round values. If None no rounding is done (Default: None). Returns: np.array: The Numpy vector array of probabilities. Examples: Consider a 2-qubit product state :math:`|\\psi\\rangle=|+\\rangle\\otimes|0\\rangle`. .. jupyter-execute:: from qiskit.quantum_info import Statevector psi = Statevector.from_label('+0') # Probabilities for measuring both qubits probs = psi.probabilities() print('probs: {}'.format(probs)) # Probabilities for measuring only qubit-0 probs_qubit_0 = psi.probabilities([0]) print('Qubit-0 probs: {}'.format(probs_qubit_0)) # Probabilities for measuring only qubit-1 probs_qubit_1 = psi.probabilities([1]) print('Qubit-1 probs: {}'.format(probs_qubit_1)) We can also permute the order of qubits in the ``qargs`` list to change the qubit position in the probabilities output .. jupyter-execute:: from qiskit.quantum_info import Statevector psi = Statevector.from_label('+0') # Probabilities for measuring both qubits probs = psi.probabilities([0, 1]) print('probs: {}'.format(probs)) # Probabilities for measuring both qubits # but swapping qubits 0 and 1 in output probs_swapped = psi.probabilities([1, 0]) print('Swapped probs: {}'.format(probs_swapped)) """ probs = self._subsystem_probabilities( np.abs(self.data) ** 2, self._dims, qargs=qargs) if decimals is not None: probs = probs.round(decimals=decimals) return probs def reset(self, qargs=None): """Reset state or subsystems to the 0-state. Args: qargs (list or None): subsystems to reset, if None all subsystems will be reset to their 0-state (Default: None). Returns: Statevector: the reset state. Additional Information: If all subsystems are reset this will return the ground state on all subsystems. If only a some subsystems are reset this function will perform a measurement on those subsystems and evolve the subsystems so that the collapsed post-measurement states are rotated to the 0-state. The RNG seed for this sampling can be set using the :meth:`seed` method. """ if qargs is None: # Resetting all qubits does not require sampling or RNG state = np.zeros(self._dim, dtype=complex) state[0] = 1 return Statevector(state, dims=self._dims) # Sample a single measurement outcome dims = self.dims(qargs) probs = self.probabilities(qargs) sample = self._rng.choice(len(probs), p=probs, size=1) # Convert to projector for state update proj = np.zeros(len(probs), dtype=complex) proj[sample] = 1 / np.sqrt(probs[sample]) # Rotate outcome to 0 reset = np.eye(len(probs)) reset[0, 0] = 0 reset[sample, sample] = 0 reset[0, sample] = 1 # compose with reset projection reset = np.dot(reset, np.diag(proj)) return self.evolve( Operator(reset, input_dims=dims, output_dims=dims), qargs=qargs) def to_counts(self): """Returns the statevector as a counts dict of probabilities. DEPRECATED: use :meth:`probabilities_dict` instead. Returns: dict: Counts of probabilities. """ warnings.warn( 'The `Statevector.to_counts` method is deprecated as of 0.13.0,' ' and will be removed no earlier than 3 months after that ' 'release date. You should use the `Statevector.probabilities_dict`' ' method instead.', DeprecationWarning, stacklevel=2) return self.probabilities_dict() @classmethod def from_label(cls, label): """Return a tensor product of Pauli X,Y,Z eigenstates. .. list-table:: Single-qubit state labels :header-rows: 1 * - Label - Statevector * - ``"0"`` - :math:`[1, 0]` * - ``"1"`` - :math:`[0, 1]` * - ``"+"`` - :math:`[1 / \\sqrt{2}, 1 / \\sqrt{2}]` * - ``"-"`` - :math:`[1 / \\sqrt{2}, -1 / \\sqrt{2}]` * - ``"r"`` - :math:`[1 / \\sqrt{2}, i / \\sqrt{2}]` * - ``"l"`` - :math:`[1 / \\sqrt{2}, -i / \\sqrt{2}]` Args: label (string): a eigenstate string ket label (see table for allowed values). Returns: Statevector: The N-qubit basis state density matrix. Raises: QiskitError: if the label contains invalid characters, or the length of the label is larger than an explicitly specified num_qubits. """ # Check label is valid if re.match(r'^[01rl\-+]+$', label) is None: raise QiskitError('Label contains invalid characters.') # We can prepare Z-eigenstates by converting the computational # basis bit-string to an integer and preparing that unit vector # However, for X-basis states, we will prepare a Z-eigenstate first # then apply Hadamard gates to rotate 0 and 1s to + and -. z_label = label xy_states = False if re.match('^[01]+$', label) is None: # We have X or Y eigenstates so replace +,r with 0 and # -,l with 1 and prepare the corresponding Z state xy_states = True z_label = z_label.replace('+', '0') z_label = z_label.replace('r', '0') z_label = z_label.replace('-', '1') z_label = z_label.replace('l', '1') # Initialize Z eigenstate vector num_qubits = len(label) data = np.zeros(1 << num_qubits, dtype=complex) pos = int(z_label, 2) data[pos] = 1 state = Statevector(data) if xy_states: # Apply hadamards to all qubits in X eigenstates x_mat = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2) # Apply S.H to qubits in Y eigenstates y_mat = np.dot(np.diag([1, 1j]), x_mat) for qubit, char in enumerate(reversed(label)): if char in ['+', '-']: state = state.evolve(x_mat, qargs=[qubit]) elif char in ['r', 'l']: state = state.evolve(y_mat, qargs=[qubit]) return state @staticmethod def from_int(i, dims): """Return a computational basis statevector. Args: i (int): the basis state element. dims (int or tuple or list): The subsystem dimensions of the statevector (See additional information). Returns: Statevector: The computational basis state :math:`|i\\rangle`. Additional Information: The ``dims`` kwarg can be an integer or an iterable of integers. * ``Iterable`` -- the subsystem dimensions are the values in the list with the total number of subsystems given by the length of the list. * ``Int`` -- the integer specifies the total dimension of the state. If it is a power of two the state will be initialized as an N-qubit state. If it is not a power of two the state will have a single d-dimensional subsystem. """ size = np.product(dims) state = np.zeros(size, dtype=complex) state[i] = 1.0 return Statevector(state, dims=dims) @classmethod def from_instruction(cls, instruction): """Return the output statevector of an instruction. The statevector is initialized in the state :math:`|{0,\\ldots,0}\\rangle` of the same number of qubits as the input instruction or circuit, evolved by the input instruction, and the output statevector returned. Args: instruction (qiskit.circuit.Instruction or QuantumCircuit): instruction or circuit Returns: Statevector: The final statevector. Raises: QiskitError: if the instruction contains invalid instructions for the statevector simulation. """ # Convert circuit to an instruction if isinstance(instruction, QuantumCircuit): instruction = instruction.to_instruction() # Initialize an the statevector in the all |0> state init = np.zeros(2 ** instruction.num_qubits, dtype=complex) init[0] = 1.0 vec = Statevector(init, dims=instruction.num_qubits * (2,)) return Statevector._evolve_instruction(vec, instruction) def to_dict(self, decimals=None): r"""Convert the statevector to dictionary form. This dictionary representation uses a Ket-like notation where the dictionary keys are qudit strings for the subsystem basis vectors. If any subsystem has a dimension greater than 10 comma delimiters are inserted between integers so that subsystems can be distinguished. Args: decimals (None or int): the number of decimal places to round values. If None no rounding is done (Default: None). Returns: dict: the dictionary form of the Statevector. Example: The ket-form of a 2-qubit statevector :math:`|\psi\rangle = |-\rangle\otimes |0\rangle` .. jupyter-execute:: from qiskit.quantum_info import Statevector psi = Statevector.from_label('-0') print(psi.to_dict()) For non-qubit subsystems the integer range can go from 0 to 9. For example in a qutrit system .. jupyter-execute:: import numpy as np from qiskit.quantum_info import Statevector vec = np.zeros(9) vec[0] = 1 / np.sqrt(2) vec[-1] = 1 / np.sqrt(2) psi = Statevector(vec, dims=(3, 3)) print(psi.to_dict()) For large subsystem dimensions delimeters are required. The following example is for a 20-dimensional system consisting of a qubit and 10-dimensional qudit. .. jupyter-execute:: import numpy as np from qiskit.quantum_info import Statevector vec = np.zeros(2 * 10) vec[0] = 1 / np.sqrt(2) vec[-1] = 1 / np.sqrt(2) psi = Statevector(vec, dims=(2, 10)) print(psi.to_dict()) """ return self._vector_to_dict(self.data, self._dims, decimals=decimals, string_labels=True) @property def _shape(self): """Return the tensor shape of the matrix operator""" return tuple(reversed(self.dims())) @staticmethod def _evolve_operator(statevec, oper, qargs=None): """Evolve a qudit statevector""" is_qubit = bool(statevec.num_qubits and oper.num_qubits) if qargs is None: # Full system evolution statevec._data = np.dot(oper._data, statevec._data) if not is_qubit: statevec._set_dims(oper._output_dims) return statevec # Calculate contraction dimensions if is_qubit: # Qubit contraction new_dim = statevec._dim num_qargs = statevec.num_qubits else: # Qudit contraction new_dims = list(statevec._dims) for i, qubit in enumerate(qargs): new_dims[qubit] = oper._output_dims[i] new_dim = np.product(new_dims) num_qargs = len(new_dims) # Get transpose axes indices = [num_qargs - 1 - i for i in reversed(qargs)] axes = indices + [i for i in range(num_qargs) if i not in indices] axes_inv = np.argsort(axes).tolist() # Calculate contraction dimensions if is_qubit: pre_tensor_shape = num_qargs * (2,) post_tensor_shape = pre_tensor_shape contract_shape = (1 << oper.num_qubits, 1 << (num_qargs - oper.num_qubits)) else: contract_dim = np.product(oper._input_dims) pre_tensor_shape = statevec._shape contract_shape = (contract_dim, statevec._dim // contract_dim) post_tensor_shape = list(reversed(oper._output_dims)) + [ pre_tensor_shape[i] for i in range(num_qargs) if i not in indices] # reshape input for contraction statevec._data = np.reshape(np.transpose( np.reshape(statevec.data, pre_tensor_shape), axes), contract_shape) statevec._data = np.reshape(np.dot(oper.data, statevec._data), post_tensor_shape) statevec._data = np.reshape(np.transpose(statevec._data, axes_inv), new_dim) # Update dimension if not is_qubit: statevec._set_dims(new_dims) return statevec @staticmethod def _evolve_instruction(statevec, obj, qargs=None): """Update the current Statevector by applying an instruction.""" from qiskit.circuit.reset import Reset from qiskit.circuit.barrier import Barrier mat = Operator._instruction_to_matrix(obj) if mat is not None: # Perform the composition and inplace update the current state # of the operator return Statevector._evolve_operator(statevec, Operator(mat), qargs=qargs) # Special instruction types if isinstance(obj, Reset): statevec._data = statevec.reset(qargs)._data return statevec if isinstance(obj, Barrier): return statevec # If the instruction doesn't have a matrix defined we use its # circuit decomposition definition if it exists, otherwise we # cannot compose this gate and raise an error. if obj.definition is None: raise QiskitError('Cannot apply Instruction: {}'.format(obj.name)) if not isinstance(obj.definition, QuantumCircuit): raise QiskitError('{} instruction definition is {}; expected QuantumCircuit'.format( obj.name, type(obj.definition))) if obj.definition.global_phase: statevec._data *= np.exp(1j * float(obj.definition.global_phase)) qubits = {qubit: i for i, qubit in enumerate(obj.definition.qubits)} for instr, qregs, cregs in obj.definition: if cregs: raise QiskitError( 'Cannot apply instruction with classical registers: {}'.format( instr.name)) # Get the integer position of the flat register if qargs is None: new_qargs = [qubits[tup] for tup in qregs] else: new_qargs = [qargs[qubits[tup]] for tup in qregs] Statevector._evolve_instruction(statevec, instr, qargs=new_qargs) return statevec
num_qubits is None: raise QiskitError("Cannot apply QuantumCircuit to non-qubit Statevector.") return self._evolve_instruction(ret, other, qargs=qargs)
daemon_windows.go
package daemon import ( "fmt" "os" "strings" "github.com/Microsoft/hcsshim" "github.com/Sirupsen/logrus" "github.com/docker/docker/api/types" pblkiodev "github.com/docker/docker/api/types/blkiodev" containertypes "github.com/docker/docker/api/types/container" "github.com/docker/docker/container" "github.com/docker/docker/image" "github.com/docker/docker/pkg/idtools" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/platform" "github.com/docker/docker/pkg/sysinfo" "github.com/docker/docker/pkg/system" "github.com/docker/docker/runconfig" "github.com/docker/libnetwork" nwconfig "github.com/docker/libnetwork/config" winlibnetwork "github.com/docker/libnetwork/drivers/windows" "github.com/docker/libnetwork/netlabel" "github.com/docker/libnetwork/options" blkiodev "github.com/opencontainers/runc/libcontainer/configs" ) const ( defaultNetworkSpace = "172.16.0.0/12" platformSupported = true windowsMinCPUShares = 1 windowsMaxCPUShares = 10000 ) func getBlkioWeightDevices(config *containertypes.HostConfig) ([]blkiodev.WeightDevice, error) { return nil, nil } func parseSecurityOpt(container *container.Container, config *containertypes.HostConfig) error { return nil } func getBlkioReadIOpsDevices(config *containertypes.HostConfig) ([]blkiodev.ThrottleDevice, error) { return nil, nil } func getBlkioWriteIOpsDevices(config *containertypes.HostConfig) ([]blkiodev.ThrottleDevice, error) { return nil, nil } func getBlkioReadBpsDevices(config *containertypes.HostConfig) ([]blkiodev.ThrottleDevice, error) { return nil, nil } func getBlkioWriteBpsDevices(config *containertypes.HostConfig) ([]blkiodev.ThrottleDevice, error) { return nil, nil } func setupInitLayer(initLayer string, rootUID, rootGID int) error { return nil } func checkKernel() error { return nil } func (daemon *Daemon) getCgroupDriver() string { return "" } // adaptContainerSettings is called during container creation to modify any // settings necessary in the HostConfig structure. func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConfig, adjustCPUShares bool) error { if hostConfig == nil { return nil } if hostConfig.CPUShares < 0 { logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, windowsMinCPUShares) hostConfig.CPUShares = windowsMinCPUShares } else if hostConfig.CPUShares > windowsMaxCPUShares { logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, windowsMaxCPUShares) hostConfig.CPUShares = windowsMaxCPUShares } return nil } func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysinfo.SysInfo) ([]string, error) { warnings := []string{} // cpu subsystem checks and adjustments if resources.CPUPercent < 0 || resources.CPUPercent > 100 { return warnings, fmt.Errorf("Range of CPU percent is from 1 to 100") } if resources.CPUPercent > 0 && resources.CPUShares > 0 { return warnings, fmt.Errorf("Conflicting options: CPU Shares and CPU Percent cannot both be set") } // TODO Windows: Add more validation of resource settings not supported on Windows if resources.BlkioWeight > 0 { warnings = append(warnings, "Windows does not support Block I/O weight. Block I/O weight discarded.") logrus.Warn("Windows does not support Block I/O weight. Block I/O weight discarded.") resources.BlkioWeight = 0 } if len(resources.BlkioWeightDevice) > 0 { warnings = append(warnings, "Windows does not support Block I/O weight-device. Weight-device discarded.") logrus.Warn("Windows does not support Block I/O weight-device. Weight-device discarded.") resources.BlkioWeightDevice = []*pblkiodev.WeightDevice{} } if len(resources.BlkioDeviceReadBps) > 0 { warnings = append(warnings, "Windows does not support Block read limit in bytes per second. Device read bps discarded.") logrus.Warn("Windows does not support Block I/O read limit in bytes per second. Device read bps discarded.") resources.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{} } if len(resources.BlkioDeviceWriteBps) > 0 { warnings = append(warnings, "Windows does not support Block write limit in bytes per second. Device write bps discarded.") logrus.Warn("Windows does not support Block I/O write limit in bytes per second. Device write bps discarded.") resources.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{} } if len(resources.BlkioDeviceReadIOps) > 0 { warnings = append(warnings, "Windows does not support Block read limit in IO per second. Device read iops discarded.") logrus.Warn("Windows does not support Block I/O read limit in IO per second. Device read iops discarded.") resources.BlkioDeviceReadIOps = []*pblkiodev.ThrottleDevice{} } if len(resources.BlkioDeviceWriteIOps) > 0 { warnings = append(warnings, "Windows does not support Block write limit in IO per second. Device write iops discarded.") logrus.Warn("Windows does not support Block I/O write limit in IO per second. Device write iops discarded.") resources.BlkioDeviceWriteIOps = []*pblkiodev.ThrottleDevice{} } return warnings, nil } // verifyPlatformContainerSettings performs platform-specific validation of the // hostconfig and config structures. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) ([]string, error) { warnings := []string{} w, err := verifyContainerResources(&hostConfig.Resources, nil) warnings = append(warnings, w...) if err != nil { return warnings, err } return warnings, nil } // platformReload update configuration with platform specific options func (daemon *Daemon) platformReload(config *Config, attributes *map[string]string) { } // verifyDaemonSettings performs validation of daemon config struct func verifyDaemonSettings(config *Config) error { return nil } // checkSystem validates platform-specific requirements func checkSystem() error { // Validate the OS version. Note that docker.exe must be manifested for this // call to return the correct version. osv := system.GetOSVersion() if osv.MajorVersion < 10 { return fmt.Errorf("This version of Windows does not support the docker daemon") } if osv.Build < 14393 { return fmt.Errorf("The docker daemon requires build 14393 or later of Windows Server 2016 or Windows 10") } return nil } // configureKernelSecuritySupport configures and validate security support for the kernel func configureKernelSecuritySupport(config *Config, driverName string) error { return nil } // configureMaxThreads sets the Go runtime max threads threshold func configureMaxThreads(config *Config) error { return nil } func (daemon *Daemon) initNetworkController(config *Config, activeSandboxes map[string]interface{}) (libnetwork.NetworkController, error) { netOptions, err := daemon.networkOptions(config, nil) if err != nil { return nil, err } controller, err := libnetwork.New(netOptions...) if err != nil { return nil, fmt.Errorf("error obtaining controller instance: %v", err) } hnsresponse, err := hcsshim.HNSListNetworkRequest("GET", "", "") if err != nil { return nil, err } // Remove networks not present in HNS for _, v := range controller.Networks() { options := v.Info().DriverOptions() hnsid := options[winlibnetwork.HNSID] found := false for _, v := range hnsresponse { if v.Id == hnsid { found = true break } } if !found { err = v.Delete() if err != nil { return nil, err } } } _, err = controller.NewNetwork("null", "none", "", libnetwork.NetworkOptionPersist(false)) if err != nil { return nil, err } defaultNetworkExists := false if network, err := controller.NetworkByName(runconfig.DefaultDaemonNetworkMode().NetworkName()); err == nil { options := network.Info().DriverOptions() for _, v := range hnsresponse { if options[winlibnetwork.HNSID] == v.Id { defaultNetworkExists = true break } } } // discover and add HNS networks to windows // network that exist are removed and added again for _, v := range hnsresponse { var n libnetwork.Network s := func(current libnetwork.Network) bool { options := current.Info().DriverOptions() if options[winlibnetwork.HNSID] == v.Id { n = current return true } return false } controller.WalkNetworks(s) if n != nil { v.Name = n.Name() // This will not cause network delete from HNS as the network // is not yet populated in the libnetwork windows driver n.Delete() } netOption := map[string]string{ winlibnetwork.NetworkName: v.Name, winlibnetwork.HNSID: v.Id, } v4Conf := []*libnetwork.IpamConf{} for _, subnet := range v.Subnets { ipamV4Conf := libnetwork.IpamConf{} ipamV4Conf.PreferredPool = subnet.AddressPrefix ipamV4Conf.Gateway = subnet.GatewayAddress v4Conf = append(v4Conf, &ipamV4Conf) } name := v.Name // If there is no nat network create one from the first NAT network // encountered if !defaultNetworkExists && runconfig.DefaultDaemonNetworkMode() == containertypes.NetworkMode(strings.ToLower(v.Type)) { name = runconfig.DefaultDaemonNetworkMode().NetworkName() defaultNetworkExists = true } v6Conf := []*libnetwork.IpamConf{} _, err := controller.NewNetwork(strings.ToLower(v.Type), name, "", libnetwork.NetworkOptionGeneric(options.Generic{ netlabel.GenericData: netOption, }), libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil), ) if err != nil { logrus.Errorf("Error occurred when creating network %v", err) } } if !config.DisableBridge { // Initialize default driver "bridge" if err := initBridgeDriver(controller, config); err != nil { return nil, err } } return controller, nil } func initBridgeDriver(controller libnetwork.NetworkController, config *Config) error { if _, err := controller.NetworkByName(runconfig.DefaultDaemonNetworkMode().NetworkName()); err == nil { return nil } netOption := map[string]string{ winlibnetwork.NetworkName: runconfig.DefaultDaemonNetworkMode().NetworkName(), } var ipamOption libnetwork.NetworkOption var subnetPrefix string if config.bridgeConfig.FixedCIDR != "" { subnetPrefix = config.bridgeConfig.FixedCIDR } else { // TP5 doesn't support properly detecting subnet osv := system.GetOSVersion() if osv.Build < 14360 { subnetPrefix = defaultNetworkSpace } } if subnetPrefix != "" { ipamV4Conf := libnetwork.IpamConf{} ipamV4Conf.PreferredPool = subnetPrefix v4Conf := []*libnetwork.IpamConf{&ipamV4Conf} v6Conf := []*libnetwork.IpamConf{} ipamOption = libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil) } _, err := controller.NewNetwork(string(runconfig.DefaultDaemonNetworkMode()), runconfig.DefaultDaemonNetworkMode().NetworkName(), "", libnetwork.NetworkOptionGeneric(options.Generic{ netlabel.GenericData: netOption, }), ipamOption, ) if err != nil { return fmt.Errorf("Error creating default network: %v", err) } return nil } // registerLinks sets up links between containers and writes the // configuration out for persistence. As of Windows TP4, links are not supported. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error { return nil } func (daemon *Daemon) cleanupMountsByID(in string) error { return nil } func (daemon *Daemon) cleanupMounts() error { return nil } func setupRemappedRoot(config *Config) ([]idtools.IDMap, []idtools.IDMap, error) { return nil, nil, nil } func setupDaemonRoot(config *Config, rootDir string, rootUID, rootGID int) error { config.Root = rootDir // Create the root directory if it doesn't exists if err := system.MkdirAll(config.Root, 0700); err != nil && !os.IsExist(err) { return err } return nil } // runasHyperVContainer returns true if we are going to run as a Hyper-V container func (daemon *Daemon) runAsHyperVContainer(container *container.Container) bool { if container.HostConfig.Isolation.IsDefault() { // Container is set to use the default, so take the default from the daemon configuration return daemon.defaultIsolation.IsHyperV() } // Container is requesting an isolation mode. Honour it. return container.HostConfig.Isolation.IsHyperV() } // conditionalMountOnStart is a platform specific helper function during the // container start to call mount. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error { // We do not mount if a Hyper-V container if !daemon.runAsHyperVContainer(container) { return daemon.Mount(container) } return nil } // conditionalUnmountOnCleanup is a platform specific helper function called // during the cleanup of a container to unmount. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) error { // We do not unmount if a Hyper-V container if !daemon.runAsHyperVContainer(container) { return daemon.Unmount(container) } return nil } func driverOptions(config *Config) []nwconfig.Option { return []nwconfig.Option{} } func (daemon *Daemon) stats(c *container.Container) (*types.StatsJSON, error) { if !c.IsRunning() { return nil, errNotRunning{c.ID} } // Obtain the stats from HCS via libcontainerd stats, err := daemon.containerd.Stats(c.ID) if err != nil { return nil, err } // Start with an empty structure s := &types.StatsJSON{} // Populate the CPU/processor statistics s.CPUStats = types.CPUStats{ CPUUsage: types.CPUUsage{ TotalUsage: stats.Processor.TotalRuntime100ns, UsageInKernelmode: stats.Processor.RuntimeKernel100ns, UsageInUsermode: stats.Processor.RuntimeKernel100ns, }, } // Populate the memory statistics s.MemoryStats = types.MemoryStats{ Commit: stats.Memory.UsageCommitBytes, CommitPeak: stats.Memory.UsageCommitPeakBytes, PrivateWorkingSet: stats.Memory.UsagePrivateWorkingSetBytes, } // Populate the storage statistics s.StorageStats = types.StorageStats{ ReadCountNormalized: stats.Storage.ReadCountNormalized, ReadSizeBytes: stats.Storage.ReadSizeBytes, WriteCountNormalized: stats.Storage.WriteCountNormalized, WriteSizeBytes: stats.Storage.WriteSizeBytes, } // Populate the network statistics s.Networks = make(map[string]types.NetworkStats) for _, nstats := range stats.Network { s.Networks[nstats.EndpointId] = types.NetworkStats{ RxBytes: nstats.BytesReceived, RxPackets: nstats.PacketsReceived, RxDropped: nstats.DroppedPacketsIncoming, TxBytes: nstats.BytesSent, TxPackets: nstats.PacketsSent, TxDropped: nstats.DroppedPacketsOutgoing, } } // Set the timestamp s.Stats.Read = stats.Timestamp s.Stats.NumProcs = platform.NumProcs() return s, nil } // setDefaultIsolation determine the default isolation mode for the // daemon to run in. This is only applicable on Windows func (daemon *Daemon) setDefaultIsolation() error { daemon.defaultIsolation = containertypes.Isolation("process") // On client SKUs, default to Hyper-V if system.IsWindowsClient() { daemon.defaultIsolation = containertypes.Isolation("hyperv") } for _, option := range daemon.configStore.ExecOptions { key, val, err := parsers.ParseKeyValueOpt(option) if err != nil { return err } key = strings.ToLower(key) switch key { case "isolation": if !containertypes.Isolation(val).IsValid() { return fmt.Errorf("Invalid exec-opt value for 'isolation':'%s'", val) } if containertypes.Isolation(val).IsHyperV() { daemon.defaultIsolation = containertypes.Isolation("hyperv") } if containertypes.Isolation(val).IsProcess() { if system.IsWindowsClient() { return fmt.Errorf("Windows client operating systems only support Hyper-V containers") } daemon.defaultIsolation = containertypes.Isolation("process") } default: return fmt.Errorf("Unrecognised exec-opt '%s'\n", key) } } logrus.Infof("Windows default isolation mode: %s", daemon.defaultIsolation) return nil } func rootFSToAPIType(rootfs *image.RootFS) types.RootFS
func setupDaemonProcess(config *Config) error { return nil } // verifyVolumesInfo is a no-op on windows. // This is called during daemon initialization to migrate volumes from pre-1.7. // volumes were not supported on windows pre-1.7 func (daemon *Daemon) verifyVolumesInfo(container *container.Container) error { return nil }
{ var layers []string for _, l := range rootfs.DiffIDs { layers = append(layers, l.String()) } return types.RootFS{ Type: rootfs.Type, Layers: layers, } }
debug.rs
pub mod axes; use sokol_bindings::{ sg::{ Action, PassAction, DepthAttachmentAction, DEFAULT_CLEAR_DEPTH, }, }; /// This pass action clears the depth buffer so that the debug visualizations /// are drawn over everything. pub fn
() -> PassAction { let mut pass_action = PassAction::load(); pass_action.depth = DepthAttachmentAction { action: Action::Clear, value: DEFAULT_CLEAR_DEPTH, }; pass_action }
pass_action
machineset_controller.go
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package machineset import ( "context" "fmt" bmh "github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1" actuator "github.com/openshift/cluster-api-provider-baremetal/pkg/cloud/baremetal/actuators/machine" machinev1beta1 "github.com/openshift/machine-api-operator/pkg/apis/machine/v1beta1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller" "sigs.k8s.io/controller-runtime/pkg/handler" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/predicate" "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" ) var log = logf.Log.WithName("machineset-controller") // errConsumerNotFound indicates that the Machine referenced in a BareMetalHost's // Spec.ConsumerRef cannot be found. That's an unexpected state, so we don't // want to do any scaling until it gets resolved. var errConsumerNotFound = fmt.Errorf("consuming Machine not found") // Add creates a new MachineSet Controller and adds it to the Manager with default RBAC. The Manager will set fields on the Controller // and Start it when the Manager is Started. func Add(mgr manager.Manager) error { return add(mgr, newReconciler(mgr)) } // newReconciler returns a new reconcile.Reconciler func newReconciler(mgr manager.Manager) reconcile.Reconciler { return &ReconcileMachineSet{Client: mgr.GetClient(), scheme: mgr.GetScheme()} } // add adds a new Controller to mgr with r as the reconcile.Reconciler func add(mgr manager.Manager, r reconcile.Reconciler) error { // Create a new controller c, err := controller.New("machineset-controller", mgr, controller.Options{Reconciler: r}) if err != nil { return err } // Watch for changes to MachineSet err = c.Watch(&source.Kind{Type: &machinev1beta1.MachineSet{}}, &handler.EnqueueRequestForObject{}, predicate.ResourceVersionChangedPredicate{}) if err != nil { return err } mapper := msmapper{client: mgr.GetClient()} err = c.Watch(&source.Kind{Type: &bmh.BareMetalHost{}}, handler.EnqueueRequestsFromMapFunc(mapper.Map), predicate.ResourceVersionChangedPredicate{}) if err != nil { return err } return nil } var _ reconcile.Reconciler = &ReconcileMachineSet{} // ReconcileMachineSet reconciles a MachineSet object type ReconcileMachineSet struct { client.Client scheme *runtime.Scheme } // Reconcile reads that state of the cluster for a MachineSet object and makes changes based on the state read // and what is in the MachineSet.Spec // Automatically generate RBAC rules to allow the Controller to read and write Deployments // +kubebuilder:rbac:groups=cluster.k8s.io,resources=machinesets,verbs=get;list;watch;update;patch func (r *ReconcileMachineSet) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { log := log.WithValues("MachineSet", request.NamespacedName.String()) // Fetch the MachineSet instance instance := &machinev1beta1.MachineSet{} err := r.Get(ctx, request.NamespacedName, instance) if err != nil { if errors.IsNotFound(err) { // Object not found, return. Created objects are automatically garbage collected. // For additional cleanup logic use finalizers. return reconcile.Result{}, nil } // Error reading the object - requeue the request. return reconcile.Result{}, err } // Don't take action if the annotation is not present annotations := instance.ObjectMeta.GetAnnotations() if annotations == nil { return reconcile.Result{}, nil } _, present := annotations[AutoScaleAnnotation] if !present { return reconcile.Result{}, nil } // Make sure the MachineSet has a non-empty selector. msselector, err := metav1.LabelSelectorAsSelector(&instance.Spec.Selector) if err != nil { return reconcile.Result{}, err } if msselector.Empty()
hostselector, err := actuator.SelectorFromProviderSpec(&instance.Spec.Template.Spec.ProviderSpec) if err != nil { return reconcile.Result{}, err } hosts := &bmh.BareMetalHostList{} opts := &client.ListOptions{ Namespace: instance.Namespace, } err = r.List(ctx, hosts, opts) if err != nil { return reconcile.Result{}, err } var count int32 for i := range hosts.Items { matches, err := r.hostMatches(ctx, hostselector, msselector, &hosts.Items[i]) switch { case err == errConsumerNotFound: log.Info("Will not scale while BareMetalHost's consuming Machine is not found", "BareMetalHost.Name", &hosts.Items[i].Name) return reconcile.Result{}, nil case err != nil: return reconcile.Result{}, err case matches == true: count++ } } if instance.Spec.Replicas == nil || count != *instance.Spec.Replicas { log.Info("Scaling MachineSet", "new_replicas", count, "old_replicas", instance.Spec.Replicas) new := instance.DeepCopy() new.Spec.Replicas = &count err = r.Update(ctx, new) if err != nil { return reconcile.Result{}, err } } return reconcile.Result{}, nil } // hostMatches returns true if the BareMetalHost matches the MachineSet. func (r *ReconcileMachineSet) hostMatches(ctx context.Context, hostselector labels.Selector, msselector labels.Selector, host *bmh.BareMetalHost) (bool, error) { consumer := host.Spec.ConsumerRef if consumer == nil { // BMH is not consumed, so just see if it matches the host selector return hostselector.Matches(labels.Set(host.ObjectMeta.Labels)), nil } // We will only count this host if it is consumed by a Machine that // is part of the current MachineSet. machine := &machinev1beta1.Machine{} if consumer.Kind != "Machine" || consumer.APIVersion != machinev1beta1.SchemeGroupVersion.String() { // this host is being consumed by something else; don't count it return false, nil } // host is being consumed. Let's get the Machine and see if it // matches the current MachineSet. nn := types.NamespacedName{ Name: consumer.Name, Namespace: consumer.Namespace, } err := r.Get(ctx, nn, machine) if err != nil { if errors.IsNotFound(err) { return false, errConsumerNotFound } return false, err } return msselector.Matches(labels.Set(machine.ObjectMeta.Labels)), nil }
{ // The cluster-api machinesetcontroller expects every MachineSet to have // its Selector set. log.Info("MachineSet has empty selector, which is unexpected. Will not attempt scaling.") return reconcile.Result{}, nil }
test_lazy_loader.py
import sys import types import pytest import lazy_loader as lazy def test_lazy_import_basics():
def test_lazy_import_impact_on_sys_modules(): math = lazy.load("math") anything_not_real = lazy.load("anything_not_real") assert isinstance(math, types.ModuleType) assert "math" in sys.modules assert isinstance(anything_not_real, lazy.DelayedImportErrorModule) assert "anything_not_real" not in sys.modules # only do this if numpy is installed pytest.importorskip("numpy") np = lazy.load("numpy") assert isinstance(np, types.ModuleType) assert "numpy" in sys.modules np.pi # trigger load of numpy assert isinstance(np, types.ModuleType) assert "numpy" in sys.modules def test_lazy_import_nonbuiltins(): sp = lazy.load("scipy") np = lazy.load("numpy") if isinstance(sp, lazy.DelayedImportErrorModule): try: sp.pi assert False except ModuleNotFoundError: pass elif isinstance(np, lazy.DelayedImportErrorModule): try: np.sin(np.pi) assert False except ModuleNotFoundError: pass else: assert np.sin(sp.pi) == pytest.approx(0, 1e-6) def test_lazy_attach(): name = "mymod" submods = ["mysubmodule", "anothersubmodule"] myall = {"not_real_submod": ["some_var_or_func"]} locls = { "attach": lazy.attach, "name": name, "submods": submods, "myall": myall, } s = "__getattr__, __lazy_dir__, __all__ = attach(name, submods, myall)" exec(s, {}, locls) expected = { "attach": lazy.attach, "name": name, "submods": submods, "myall": myall, "__getattr__": None, "__lazy_dir__": None, "__all__": None, } assert locls.keys() == expected.keys() for k, v in expected.items(): if v is not None: assert locls[k] == v
math = lazy.load("math") anything_not_real = lazy.load("anything_not_real") # Now test that accessing attributes does what it should assert math.sin(math.pi) == pytest.approx(0, 1e-6) # poor-mans pytest.raises for testing errors on attribute access try: anything_not_real.pi assert False # Should not get here except ModuleNotFoundError: pass assert isinstance(anything_not_real, lazy.DelayedImportErrorModule) # see if it changes for second access try: anything_not_real.pi assert False # Should not get here except ModuleNotFoundError: pass
mining_test.go
// Copyright (c) 2016 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package mining import ( "container/heap" "math/rand" "testing" "github.com/firobridge/btcutil" ) // TestTxFeePrioHeap ensures the priority queue for transaction fees and // priorities works as expected. func TestTxFeePrioHeap(t *testing.T) { // Create some fake priority items that exercise the expected sort // edge conditions. testItems := []*txPrioItem{ {feePerKB: 5678, priority: 3}, {feePerKB: 5678, priority: 1}, {feePerKB: 5678, priority: 1}, // Duplicate fee and prio {feePerKB: 5678, priority: 5}, {feePerKB: 5678, priority: 2}, {feePerKB: 1234, priority: 3}, {feePerKB: 1234, priority: 1}, {feePerKB: 1234, priority: 5}, {feePerKB: 1234, priority: 5}, // Duplicate fee and prio {feePerKB: 1234, priority: 2}, {feePerKB: 10000, priority: 0}, // Higher fee, smaller prio {feePerKB: 0, priority: 10000}, // Higher prio, lower fee } // Add random data in addition to the edge conditions already manually // specified. randSeed := rand.Int63() defer func() { if t.Failed()
}() prng := rand.New(rand.NewSource(randSeed)) for i := 0; i < 1000; i++ { testItems = append(testItems, &txPrioItem{ feePerKB: int64(prng.Float64() * btcutil.SatoshiPerBitcoin), priority: prng.Float64() * 100, }) } // Test sorting by fee per KB then priority. var highest *txPrioItem priorityQueue := newTxPriorityQueue(len(testItems), true) for i := 0; i < len(testItems); i++ { prioItem := testItems[i] if highest == nil { highest = prioItem } if prioItem.feePerKB >= highest.feePerKB && prioItem.priority > highest.priority { highest = prioItem } heap.Push(priorityQueue, prioItem) } for i := 0; i < len(testItems); i++ { prioItem := heap.Pop(priorityQueue).(*txPrioItem) if prioItem.feePerKB >= highest.feePerKB && prioItem.priority > highest.priority { t.Fatalf("fee sort: item (fee per KB: %v, "+ "priority: %v) higher than than prev "+ "(fee per KB: %v, priority %v)", prioItem.feePerKB, prioItem.priority, highest.feePerKB, highest.priority) } highest = prioItem } // Test sorting by priority then fee per KB. highest = nil priorityQueue = newTxPriorityQueue(len(testItems), false) for i := 0; i < len(testItems); i++ { prioItem := testItems[i] if highest == nil { highest = prioItem } if prioItem.priority >= highest.priority && prioItem.feePerKB > highest.feePerKB { highest = prioItem } heap.Push(priorityQueue, prioItem) } for i := 0; i < len(testItems); i++ { prioItem := heap.Pop(priorityQueue).(*txPrioItem) if prioItem.priority >= highest.priority && prioItem.feePerKB > highest.feePerKB { t.Fatalf("priority sort: item (fee per KB: %v, "+ "priority: %v) higher than than prev "+ "(fee per KB: %v, priority %v)", prioItem.feePerKB, prioItem.priority, highest.feePerKB, highest.priority) } highest = prioItem } }
{ t.Logf("Random numbers using seed: %v", randSeed) }
api_op_CreateIPSet.go
// Code generated by smithy-go-codegen DO NOT EDIT. package waf import ( "context" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "github.com/aws/aws-sdk-go-v2/service/waf/types" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // This is AWS WAF Classic documentation. For more information, see AWS WAF Classic // (https://docs.aws.amazon.com/waf/latest/developerguide/classic-waf-chapter.html) // in the developer guide. For the latest version of AWS WAF, use the AWS WAFV2 API // and see the AWS WAF Developer Guide // (https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html). With // the latest version, AWS WAF has a single set of endpoints for regional and // global use. Creates an IPSet, which you use to specify which web requests that
// individual IP addresses or one or more ranges of IP addresses and you want to // block the requests, you can create an IPSet that contains those IP addresses and // then configure AWS WAF to block the requests. To create and configure an IPSet, // perform the following steps: // // * Use GetChangeToken to get the change token that // you provide in the ChangeToken parameter of a CreateIPSet request. // // * Submit a // CreateIPSet request. // // * Use GetChangeToken to get the change token that you // provide in the ChangeToken parameter of an UpdateIPSet request. // // * Submit an // UpdateIPSet request to specify the IP addresses that you want AWS WAF to watch // for. // // For more information about how to use the AWS WAF API to allow or block // HTTP requests, see the AWS WAF Developer Guide // (https://docs.aws.amazon.com/waf/latest/developerguide/). func (c *Client) CreateIPSet(ctx context.Context, params *CreateIPSetInput, optFns ...func(*Options)) (*CreateIPSetOutput, error) { if params == nil { params = &CreateIPSetInput{} } result, metadata, err := c.invokeOperation(ctx, "CreateIPSet", params, optFns, c.addOperationCreateIPSetMiddlewares) if err != nil { return nil, err } out := result.(*CreateIPSetOutput) out.ResultMetadata = metadata return out, nil } type CreateIPSetInput struct { // The value returned by the most recent call to GetChangeToken. // // This member is required. ChangeToken *string // A friendly name or description of the IPSet. You can't change Name after you // create the IPSet. // // This member is required. Name *string } type CreateIPSetOutput struct { // The ChangeToken that you used to submit the CreateIPSet request. You can also // use this value to query the status of the request. For more information, see // GetChangeTokenStatus. ChangeToken *string // The IPSet returned in the CreateIPSet response. IPSet *types.IPSet // Metadata pertaining to the operation's result. ResultMetadata middleware.Metadata } func (c *Client) addOperationCreateIPSetMiddlewares(stack *middleware.Stack, options Options) (err error) { err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateIPSet{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateIPSet{}, middleware.After) if err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { return err } if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { return err } if err = addRetryMiddlewares(stack, options); err != nil { return err } if err = addHTTPSignerV4Middleware(stack, options); err != nil { return err } if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { return err } if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { return err } if err = addClientUserAgent(stack); err != nil { return err } if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { return err } if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } if err = addOpCreateIPSetValidationMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateIPSet(options.Region), middleware.Before); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { return err } if err = addResponseErrorMiddleware(stack); err != nil { return err } if err = addRequestResponseLogging(stack, options); err != nil { return err } return nil } func newServiceMetadataMiddleware_opCreateIPSet(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "waf", OperationName: "CreateIPSet", } }
// you want to allow or block based on the IP addresses that the requests originate // from. For example, if you're receiving a lot of requests from one or more
client.rs
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[derive(Debug)] pub(crate) struct Handle< C = aws_smithy_client::erase::DynConnector, M = crate::middleware::DefaultMiddleware, R = aws_smithy_client::retry::Standard, > { pub(crate) client: aws_smithy_client::Client<C, M, R>, pub(crate) conf: crate::Config, } /// Client for Amazon Managed Grafana /// /// Client for invoking operations on Amazon Managed Grafana. Each operation on Amazon Managed Grafana is a method on this /// this struct. `.send()` MUST be invoked on the generated operations to dispatch the request to the service. /// /// # Examples /// **Constructing a client and invoking an operation** /// ```rust,no_run /// # async fn docs() { /// // create a shared configuration. This can be used & shared between multiple service clients. /// let shared_config = aws_config::load_from_env().await; /// let client = aws_sdk_grafana::Client::new(&shared_config); /// // invoke an operation /// /* let rsp = client /// .<operation_name>(). /// .<param>("some value") /// .send().await; */ /// # } /// ``` /// **Constructing a client with custom configuration** /// ```rust,no_run /// use aws_config::RetryConfig; /// # async fn docs() { /// let shared_config = aws_config::load_from_env().await; /// let config = aws_sdk_grafana::config::Builder::from(&shared_config) /// .retry_config(RetryConfig::disabled()) /// .build(); /// let client = aws_sdk_grafana::Client::from_conf(config); /// # } #[derive(std::fmt::Debug)] pub struct Client< C = aws_smithy_client::erase::DynConnector, M = crate::middleware::DefaultMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<Handle<C, M, R>>, } impl<C, M, R> std::clone::Clone for Client<C, M, R> { fn clone(&self) -> Self { Self { handle: self.handle.clone(), } } } #[doc(inline)] pub use aws_smithy_client::Builder; impl<C, M, R> From<aws_smithy_client::Client<C, M, R>> for Client<C, M, R> { fn from(client: aws_smithy_client::Client<C, M, R>) -> Self { Self::with_config(client, crate::Config::builder().build()) } } impl<C, M, R> Client<C, M, R> { /// Creates a client with the given service configuration. pub fn with_config(client: aws_smithy_client::Client<C, M, R>, conf: crate::Config) -> Self { Self { handle: std::sync::Arc::new(Handle { client, conf }), } } /// Returns the client's configuration. pub fn conf(&self) -> &crate::Config { &self.handle.conf } } impl<C, M, R> Client<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Constructs a fluent builder for the [`AssociateLicense`](crate::client::fluent_builders::AssociateLicense) operation. /// /// - The fluent builder is configurable: /// - [`workspace_id(impl Into<String>)`](crate::client::fluent_builders::AssociateLicense::workspace_id) / [`set_workspace_id(Option<String>)`](crate::client::fluent_builders::AssociateLicense::set_workspace_id): <p>The ID of the workspace to associate the license with.</p> /// - [`license_type(LicenseType)`](crate::client::fluent_builders::AssociateLicense::license_type) / [`set_license_type(Option<LicenseType>)`](crate::client::fluent_builders::AssociateLicense::set_license_type): <p>The type of license to associate with the workspace.</p> /// - On success, responds with [`AssociateLicenseOutput`](crate::output::AssociateLicenseOutput) with field(s): /// - [`workspace(Option<WorkspaceDescription>)`](crate::output::AssociateLicenseOutput::workspace): <p>A structure containing data about the workspace.</p> /// - On failure, responds with [`SdkError<AssociateLicenseError>`](crate::error::AssociateLicenseError) pub fn associate_license(&self) -> fluent_builders::AssociateLicense<C, M, R> { fluent_builders::AssociateLicense::new(self.handle.clone()) } /// Constructs a fluent builder for the [`CreateWorkspace`](crate::client::fluent_builders::CreateWorkspace) operation. /// /// - The fluent builder is configurable: /// - [`account_access_type(AccountAccessType)`](crate::client::fluent_builders::CreateWorkspace::account_access_type) / [`set_account_access_type(Option<AccountAccessType>)`](crate::client::fluent_builders::CreateWorkspace::set_account_access_type): <p>Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in other accounts in the same organization. If you specify <code>ORGANIZATION</code>, you must specify which organizational units the workspace can access in the <code>workspaceOrganizationalUnits</code> parameter.</p> /// - [`client_token(impl Into<String>)`](crate::client::fluent_builders::CreateWorkspace::client_token) / [`set_client_token(Option<String>)`](crate::client::fluent_builders::CreateWorkspace::set_client_token): <p>A unique, case-sensitive, user-provided identifier to ensure the idempotency of the request.</p> /// - [`organization_role_name(impl Into<String>)`](crate::client::fluent_builders::CreateWorkspace::organization_role_name) / [`set_organization_role_name(Option<String>)`](crate::client::fluent_builders::CreateWorkspace::set_organization_role_name): <p>The name of an IAM role that already exists to use with Organizations to access Amazon Web Services data sources and notification channels in other accounts in an organization.</p> /// - [`permission_type(PermissionType)`](crate::client::fluent_builders::CreateWorkspace::permission_type) / [`set_permission_type(Option<PermissionType>)`](crate::client::fluent_builders::CreateWorkspace::set_permission_type): <p>If you specify <code>Service Managed</code>, Amazon Managed Grafana automatically creates the IAM roles and provisions the permissions that the workspace needs to use Amazon Web Services data sources and notification channels.</p> <p>If you specify <code>CUSTOMER_MANAGED</code>, you will manage those roles and permissions yourself. If you are creating this workspace in a member account of an organization that is not a delegated administrator account, and you want the workspace to access data sources in other Amazon Web Services accounts in the organization, you must choose <code>CUSTOMER_MANAGED</code>.</p> <p>For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/AMG-manage-permissions.html">Amazon Managed Grafana permissions and policies for Amazon Web Services data sources and notification channels</a> </p> /// - [`stack_set_name(impl Into<String>)`](crate::client::fluent_builders::CreateWorkspace::stack_set_name) / [`set_stack_set_name(Option<String>)`](crate::client::fluent_builders::CreateWorkspace::set_stack_set_name): <p>The name of the CloudFormation stack set to use to generate IAM roles to be used for this workspace.</p> /// - [`workspace_data_sources(Vec<DataSourceType>)`](crate::client::fluent_builders::CreateWorkspace::workspace_data_sources) / [`set_workspace_data_sources(Option<Vec<DataSourceType>>)`](crate::client::fluent_builders::CreateWorkspace::set_workspace_data_sources): <p>Specify the Amazon Web Services data sources that you want to be queried in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to read data from these sources. You must still add them as data sources in the Grafana console in the workspace.</p> <p>If you don't specify a data source here, you can still add it as a data source in the workspace console later. However, you will then have to manually configure permissions for it.</p> /// - [`workspace_description(impl Into<String>)`](crate::client::fluent_builders::CreateWorkspace::workspace_description) / [`set_workspace_description(Option<String>)`](crate::client::fluent_builders::CreateWorkspace::set_workspace_description): <p>A description for the workspace. This is used only to help you identify this workspace.</p> /// - [`workspace_name(impl Into<String>)`](crate::client::fluent_builders::CreateWorkspace::workspace_name) / [`set_workspace_name(Option<String>)`](crate::client::fluent_builders::CreateWorkspace::set_workspace_name): <p>The name for the workspace. It does not have to be unique.</p> /// - [`workspace_notification_destinations(Vec<NotificationDestinationType>)`](crate::client::fluent_builders::CreateWorkspace::workspace_notification_destinations) / [`set_workspace_notification_destinations(Option<Vec<NotificationDestinationType>>)`](crate::client::fluent_builders::CreateWorkspace::set_workspace_notification_destinations): <p>Specify the Amazon Web Services notification channels that you plan to use in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to use these channels.</p> /// - [`workspace_organizational_units(Vec<String>)`](crate::client::fluent_builders::CreateWorkspace::workspace_organizational_units) / [`set_workspace_organizational_units(Option<Vec<String>>)`](crate::client::fluent_builders::CreateWorkspace::set_workspace_organizational_units): <p>Specifies the organizational units that this workspace is allowed to use data sources from, if this workspace is in an account that is part of an organization.</p> /// - [`workspace_role_arn(impl Into<String>)`](crate::client::fluent_builders::CreateWorkspace::workspace_role_arn) / [`set_workspace_role_arn(Option<String>)`](crate::client::fluent_builders::CreateWorkspace::set_workspace_role_arn): <p>The workspace needs an IAM role that grants permissions to the Amazon Web Services resources that the workspace will view data from. If you already have a role that you want to use, specify it here. If you omit this field and you specify some Amazon Web Services resources in <code>workspaceDataSources</code> or <code>workspaceNotificationDestinations</code>, a new IAM role with the necessary permissions is automatically created.</p> /// - [`authentication_providers(Vec<AuthenticationProviderTypes>)`](crate::client::fluent_builders::CreateWorkspace::authentication_providers) / [`set_authentication_providers(Option<Vec<AuthenticationProviderTypes>>)`](crate::client::fluent_builders::CreateWorkspace::set_authentication_providers): <p>Specifies whether this workspace uses SAML 2.0, Amazon Web Services Single Sign On, or both to authenticate users for using the Grafana console within a workspace. For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/authentication-in-AMG.html">User authentication in Amazon Managed Grafana</a>.</p> /// - On success, responds with [`CreateWorkspaceOutput`](crate::output::CreateWorkspaceOutput) with field(s): /// - [`workspace(Option<WorkspaceDescription>)`](crate::output::CreateWorkspaceOutput::workspace): <p>A structure containing data about the workspace that was created.</p> /// - On failure, responds with [`SdkError<CreateWorkspaceError>`](crate::error::CreateWorkspaceError) pub fn create_workspace(&self) -> fluent_builders::CreateWorkspace<C, M, R> { fluent_builders::CreateWorkspace::new(self.handle.clone()) } /// Constructs a fluent builder for the [`DeleteWorkspace`](crate::client::fluent_builders::DeleteWorkspace) operation. /// /// - The fluent builder is configurable: /// - [`workspace_id(impl Into<String>)`](crate::client::fluent_builders::DeleteWorkspace::workspace_id) / [`set_workspace_id(Option<String>)`](crate::client::fluent_builders::DeleteWorkspace::set_workspace_id): <p>The ID of the workspace to delete.</p> /// - On success, responds with [`DeleteWorkspaceOutput`](crate::output::DeleteWorkspaceOutput) with field(s): /// - [`workspace(Option<WorkspaceDescription>)`](crate::output::DeleteWorkspaceOutput::workspace): <p>A structure containing information about the workspace that was deleted.</p> /// - On failure, responds with [`SdkError<DeleteWorkspaceError>`](crate::error::DeleteWorkspaceError) pub fn delete_workspace(&self) -> fluent_builders::DeleteWorkspace<C, M, R> { fluent_builders::DeleteWorkspace::new(self.handle.clone()) } /// Constructs a fluent builder for the [`DescribeWorkspace`](crate::client::fluent_builders::DescribeWorkspace) operation. /// /// - The fluent builder is configurable: /// - [`workspace_id(impl Into<String>)`](crate::client::fluent_builders::DescribeWorkspace::workspace_id) / [`set_workspace_id(Option<String>)`](crate::client::fluent_builders::DescribeWorkspace::set_workspace_id): <p>The ID of the workspace to display information about.</p> /// - On success, responds with [`DescribeWorkspaceOutput`](crate::output::DescribeWorkspaceOutput) with field(s): /// - [`workspace(Option<WorkspaceDescription>)`](crate::output::DescribeWorkspaceOutput::workspace): <p>A structure containing information about the workspace.</p> /// - On failure, responds with [`SdkError<DescribeWorkspaceError>`](crate::error::DescribeWorkspaceError) pub fn describe_workspace(&self) -> fluent_builders::DescribeWorkspace<C, M, R> { fluent_builders::DescribeWorkspace::new(self.handle.clone()) } /// Constructs a fluent builder for the [`DescribeWorkspaceAuthentication`](crate::client::fluent_builders::DescribeWorkspaceAuthentication) operation. /// /// - The fluent builder is configurable: /// - [`workspace_id(impl Into<String>)`](crate::client::fluent_builders::DescribeWorkspaceAuthentication::workspace_id) / [`set_workspace_id(Option<String>)`](crate::client::fluent_builders::DescribeWorkspaceAuthentication::set_workspace_id): <p>The ID of the workspace to return authentication information about.</p> /// - On success, responds with [`DescribeWorkspaceAuthenticationOutput`](crate::output::DescribeWorkspaceAuthenticationOutput) with field(s): /// - [`authentication(Option<AuthenticationDescription>)`](crate::output::DescribeWorkspaceAuthenticationOutput::authentication): <p>A structure containing information about the authentication methods used in the workspace.</p> /// - On failure, responds with [`SdkError<DescribeWorkspaceAuthenticationError>`](crate::error::DescribeWorkspaceAuthenticationError) pub fn describe_workspace_authentication( &self, ) -> fluent_builders::DescribeWorkspaceAuthentication<C, M, R> { fluent_builders::DescribeWorkspaceAuthentication::new(self.handle.clone()) } /// Constructs a fluent builder for the [`DisassociateLicense`](crate::client::fluent_builders::DisassociateLicense) operation. /// /// - The fluent builder is configurable: /// - [`workspace_id(impl Into<String>)`](crate::client::fluent_builders::DisassociateLicense::workspace_id) / [`set_workspace_id(Option<String>)`](crate::client::fluent_builders::DisassociateLicense::set_workspace_id): <p>The ID of the workspace to remove the Grafana Enterprise license from.</p> /// - [`license_type(LicenseType)`](crate::client::fluent_builders::DisassociateLicense::license_type) / [`set_license_type(Option<LicenseType>)`](crate::client::fluent_builders::DisassociateLicense::set_license_type): <p>The type of license to remove from the workspace.</p> /// - On success, responds with [`DisassociateLicenseOutput`](crate::output::DisassociateLicenseOutput) with field(s): /// - [`workspace(Option<WorkspaceDescription>)`](crate::output::DisassociateLicenseOutput::workspace): <p>A structure containing information about the workspace.</p> /// - On failure, responds with [`SdkError<DisassociateLicenseError>`](crate::error::DisassociateLicenseError) pub fn disassociate_license(&self) -> fluent_builders::DisassociateLicense<C, M, R> { fluent_builders::DisassociateLicense::new(self.handle.clone()) } /// Constructs a fluent builder for the [`ListPermissions`](crate::client::fluent_builders::ListPermissions) operation. /// This operation supports pagination; See [`into_paginator()`](crate::client::fluent_builders::ListPermissions::into_paginator). /// /// - The fluent builder is configurable: /// - [`max_results(i32)`](crate::client::fluent_builders::ListPermissions::max_results) / [`set_max_results(Option<i32>)`](crate::client::fluent_builders::ListPermissions::set_max_results): <p>The maximum number of results to include in the response.</p> /// - [`next_token(impl Into<String>)`](crate::client::fluent_builders::ListPermissions::next_token) / [`set_next_token(Option<String>)`](crate::client::fluent_builders::ListPermissions::set_next_token): <p>The token to use when requesting the next set of results. You received this token from a previous <code>ListPermissions</code> operation.</p> /// - [`user_type(UserType)`](crate::client::fluent_builders::ListPermissions::user_type) / [`set_user_type(Option<UserType>)`](crate::client::fluent_builders::ListPermissions::set_user_type): <p>(Optional) If you specify <code>SSO_USER</code>, then only the permissions of Amazon Web Services SSO users are returned. If you specify <code>SSO_GROUP</code>, only the permissions of Amazon Web Services SSO groups are returned.</p> /// - [`user_id(impl Into<String>)`](crate::client::fluent_builders::ListPermissions::user_id) / [`set_user_id(Option<String>)`](crate::client::fluent_builders::ListPermissions::set_user_id): <p>(Optional) Limits the results to only the user that matches this ID.</p> /// - [`group_id(impl Into<String>)`](crate::client::fluent_builders::ListPermissions::group_id) / [`set_group_id(Option<String>)`](crate::client::fluent_builders::ListPermissions::set_group_id): <p>(Optional) Limits the results to only the group that matches this ID.</p> /// - [`workspace_id(impl Into<String>)`](crate::client::fluent_builders::ListPermissions::workspace_id) / [`set_workspace_id(Option<String>)`](crate::client::fluent_builders::ListPermissions::set_workspace_id): <p>The ID of the workspace to list permissions for. This parameter is required.</p> /// - On success, responds with [`ListPermissionsOutput`](crate::output::ListPermissionsOutput) with field(s): /// - [`next_token(Option<String>)`](crate::output::ListPermissionsOutput::next_token): <p>The token to use in a subsequent <code>ListPermissions</code> operation to return the next set of results.</p> /// - [`permissions(Option<Vec<PermissionEntry>>)`](crate::output::ListPermissionsOutput::permissions): <p>The permissions returned by the operation.</p> /// - On failure, responds with [`SdkError<ListPermissionsError>`](crate::error::ListPermissionsError) pub fn list_permissions(&self) -> fluent_builders::ListPermissions<C, M, R> { fluent_builders::ListPermissions::new(self.handle.clone()) } /// Constructs a fluent builder for the [`ListWorkspaces`](crate::client::fluent_builders::ListWorkspaces) operation. /// This operation supports pagination; See [`into_paginator()`](crate::client::fluent_builders::ListWorkspaces::into_paginator). /// /// - The fluent builder is configurable: /// - [`max_results(i32)`](crate::client::fluent_builders::ListWorkspaces::max_results) / [`set_max_results(Option<i32>)`](crate::client::fluent_builders::ListWorkspaces::set_max_results): <p>The maximum number of workspaces to include in the results.</p> /// - [`next_token(impl Into<String>)`](crate::client::fluent_builders::ListWorkspaces::next_token) / [`set_next_token(Option<String>)`](crate::client::fluent_builders::ListWorkspaces::set_next_token): <p>The token for the next set of workspaces to return. (You receive this token from a previous <code>ListWorkspaces</code> operation.)</p> /// - On success, responds with [`ListWorkspacesOutput`](crate::output::ListWorkspacesOutput) with field(s): /// - [`workspaces(Option<Vec<WorkspaceSummary>>)`](crate::output::ListWorkspacesOutput::workspaces): <p>An array of structures that contain some information about the workspaces in the account.</p> /// - [`next_token(Option<String>)`](crate::output::ListWorkspacesOutput::next_token): <p>The token to use when requesting the next set of workspaces.</p> /// - On failure, responds with [`SdkError<ListWorkspacesError>`](crate::error::ListWorkspacesError) pub fn list_workspaces(&self) -> fluent_builders::ListWorkspaces<C, M, R> { fluent_builders::ListWorkspaces::new(self.handle.clone()) } /// Constructs a fluent builder for the [`UpdatePermissions`](crate::client::fluent_builders::UpdatePermissions) operation. /// /// - The fluent builder is configurable: /// - [`update_instruction_batch(Vec<UpdateInstruction>)`](crate::client::fluent_builders::UpdatePermissions::update_instruction_batch) / [`set_update_instruction_batch(Option<Vec<UpdateInstruction>>)`](crate::client::fluent_builders::UpdatePermissions::set_update_instruction_batch): <p>An array of structures that contain the permission updates to make.</p> /// - [`workspace_id(impl Into<String>)`](crate::client::fluent_builders::UpdatePermissions::workspace_id) / [`set_workspace_id(Option<String>)`](crate::client::fluent_builders::UpdatePermissions::set_workspace_id): <p>The ID of the workspace to update.</p> /// - On success, responds with [`UpdatePermissionsOutput`](crate::output::UpdatePermissionsOutput) with field(s): /// - [`errors(Option<Vec<UpdateError>>)`](crate::output::UpdatePermissionsOutput::errors): <p>An array of structures that contain the errors from the operation, if any.</p> /// - On failure, responds with [`SdkError<UpdatePermissionsError>`](crate::error::UpdatePermissionsError) pub fn update_permissions(&self) -> fluent_builders::UpdatePermissions<C, M, R> { fluent_builders::UpdatePermissions::new(self.handle.clone()) } /// Constructs a fluent builder for the [`UpdateWorkspace`](crate::client::fluent_builders::UpdateWorkspace) operation. /// /// - The fluent builder is configurable: /// - [`account_access_type(AccountAccessType)`](crate::client::fluent_builders::UpdateWorkspace::account_access_type) / [`set_account_access_type(Option<AccountAccessType>)`](crate::client::fluent_builders::UpdateWorkspace::set_account_access_type): <p>Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in other accounts in the same organization. If you specify <code>ORGANIZATION</code>, you must specify which organizational units the workspace can access in the <code>workspaceOrganizationalUnits</code> parameter.</p> /// - [`organization_role_name(impl Into<String>)`](crate::client::fluent_builders::UpdateWorkspace::organization_role_name) / [`set_organization_role_name(Option<String>)`](crate::client::fluent_builders::UpdateWorkspace::set_organization_role_name): <p>The name of an IAM role that already exists to use to access resources through Organizations.</p> /// - [`permission_type(PermissionType)`](crate::client::fluent_builders::UpdateWorkspace::permission_type) / [`set_permission_type(Option<PermissionType>)`](crate::client::fluent_builders::UpdateWorkspace::set_permission_type): <p>If you specify <code>Service Managed</code>, Amazon Managed Grafana automatically creates the IAM roles and provisions the permissions that the workspace needs to use Amazon Web Services data sources and notification channels.</p> <p>If you specify <code>CUSTOMER_MANAGED</code>, you will manage those roles and permissions yourself. If you are creating this workspace in a member account of an organization and that account is not a delegated administrator account, and you want the workspace to access data sources in other Amazon Web Services accounts in the organization, you must choose <code>CUSTOMER_MANAGED</code>.</p> <p>For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/AMG-manage-permissions.html">Amazon Managed Grafana permissions and policies for Amazon Web Services data sources and notification channels</a> </p> /// - [`stack_set_name(impl Into<String>)`](crate::client::fluent_builders::UpdateWorkspace::stack_set_name) / [`set_stack_set_name(Option<String>)`](crate::client::fluent_builders::UpdateWorkspace::set_stack_set_name): <p>The name of the CloudFormation stack set to use to generate IAM roles to be used for this workspace.</p> /// - [`workspace_data_sources(Vec<DataSourceType>)`](crate::client::fluent_builders::UpdateWorkspace::workspace_data_sources) / [`set_workspace_data_sources(Option<Vec<DataSourceType>>)`](crate::client::fluent_builders::UpdateWorkspace::set_workspace_data_sources): <p>Specify the Amazon Web Services data sources that you want to be queried in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to read data from these sources. You must still add them as data sources in the Grafana console in the workspace.</p> <p>If you don't specify a data source here, you can still add it as a data source later in the workspace console. However, you will then have to manually configure permissions for it.</p> /// - [`workspace_description(impl Into<String>)`](crate::client::fluent_builders::UpdateWorkspace::workspace_description) / [`set_workspace_description(Option<String>)`](crate::client::fluent_builders::UpdateWorkspace::set_workspace_description): <p>A description for the workspace. This is used only to help you identify this workspace.</p> /// - [`workspace_id(impl Into<String>)`](crate::client::fluent_builders::UpdateWorkspace::workspace_id) / [`set_workspace_id(Option<String>)`](crate::client::fluent_builders::UpdateWorkspace::set_workspace_id): <p>The ID of the workspace to update.</p> /// - [`workspace_name(impl Into<String>)`](crate::client::fluent_builders::UpdateWorkspace::workspace_name) / [`set_workspace_name(Option<String>)`](crate::client::fluent_builders::UpdateWorkspace::set_workspace_name): <p>A new name for the workspace to update.</p> /// - [`workspace_notification_destinations(Vec<NotificationDestinationType>)`](crate::client::fluent_builders::UpdateWorkspace::workspace_notification_destinations) / [`set_workspace_notification_destinations(Option<Vec<NotificationDestinationType>>)`](crate::client::fluent_builders::UpdateWorkspace::set_workspace_notification_destinations): <p>Specify the Amazon Web Services notification channels that you plan to use in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to use these channels.</p> /// - [`workspace_organizational_units(Vec<String>)`](crate::client::fluent_builders::UpdateWorkspace::workspace_organizational_units) / [`set_workspace_organizational_units(Option<Vec<String>>)`](crate::client::fluent_builders::UpdateWorkspace::set_workspace_organizational_units): <p>Specifies the organizational units that this workspace is allowed to use data sources from, if this workspace is in an account that is part of an organization.</p> /// - [`workspace_role_arn(impl Into<String>)`](crate::client::fluent_builders::UpdateWorkspace::workspace_role_arn) / [`set_workspace_role_arn(Option<String>)`](crate::client::fluent_builders::UpdateWorkspace::set_workspace_role_arn): <p>The workspace needs an IAM role that grants permissions to the Amazon Web Services resources that the workspace will view data from. If you already have a role that you want to use, specify it here. If you omit this field and you specify some Amazon Web Services resources in <code>workspaceDataSources</code> or <code>workspaceNotificationDestinations</code>, a new IAM role with the necessary permissions is automatically created.</p> /// - On success, responds with [`UpdateWorkspaceOutput`](crate::output::UpdateWorkspaceOutput) with field(s): /// - [`workspace(Option<WorkspaceDescription>)`](crate::output::UpdateWorkspaceOutput::workspace): <p>A structure containing data about the workspace that was created.</p> /// - On failure, responds with [`SdkError<UpdateWorkspaceError>`](crate::error::UpdateWorkspaceError) pub fn update_workspace(&self) -> fluent_builders::UpdateWorkspace<C, M, R> { fluent_builders::UpdateWorkspace::new(self.handle.clone()) } /// Constructs a fluent builder for the [`UpdateWorkspaceAuthentication`](crate::client::fluent_builders::UpdateWorkspaceAuthentication) operation. /// /// - The fluent builder is configurable: /// - [`workspace_id(impl Into<String>)`](crate::client::fluent_builders::UpdateWorkspaceAuthentication::workspace_id) / [`set_workspace_id(Option<String>)`](crate::client::fluent_builders::UpdateWorkspaceAuthentication::set_workspace_id): <p>The ID of the workspace to update the authentication for.</p> /// - [`authentication_providers(Vec<AuthenticationProviderTypes>)`](crate::client::fluent_builders::UpdateWorkspaceAuthentication::authentication_providers) / [`set_authentication_providers(Option<Vec<AuthenticationProviderTypes>>)`](crate::client::fluent_builders::UpdateWorkspaceAuthentication::set_authentication_providers): <p>Specifies whether this workspace uses SAML 2.0, Amazon Web Services Single Sign On, or both to authenticate users for using the Grafana console within a workspace. For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/authentication-in-AMG.html">User authentication in Amazon Managed Grafana</a>.</p> /// - [`saml_configuration(SamlConfiguration)`](crate::client::fluent_builders::UpdateWorkspaceAuthentication::saml_configuration) / [`set_saml_configuration(Option<SamlConfiguration>)`](crate::client::fluent_builders::UpdateWorkspaceAuthentication::set_saml_configuration): <p>If the workspace uses SAML, use this structure to map SAML assertion attributes to workspace user information and define which groups in the assertion attribute are to have the <code>Admin</code> and <code>Editor</code> roles in the workspace.</p> /// - On success, responds with [`UpdateWorkspaceAuthenticationOutput`](crate::output::UpdateWorkspaceAuthenticationOutput) with field(s): /// - [`authentication(Option<AuthenticationDescription>)`](crate::output::UpdateWorkspaceAuthenticationOutput::authentication): <p>A structure that describes the user authentication for this workspace after the update is made.</p> /// - On failure, responds with [`SdkError<UpdateWorkspaceAuthenticationError>`](crate::error::UpdateWorkspaceAuthenticationError) pub fn update_workspace_authentication( &self, ) -> fluent_builders::UpdateWorkspaceAuthentication<C, M, R> { fluent_builders::UpdateWorkspaceAuthentication::new(self.handle.clone()) } } pub mod fluent_builders { //! //! Utilities to ergonomically construct a request to the service. //! //! Fluent builders are created through the [`Client`](crate::client::Client) by calling //! one if its operation methods. After parameters are set using the builder methods, //! the `send` method can be called to initiate the request. //! /// Fluent builder constructing a request to `AssociateLicense`. /// /// <p>Assigns a Grafana Enterprise license to a workspace. Upgrading to Grafana Enterprise incurs additional fees. For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/upgrade-to-Grafana-Enterprise.html">Upgrade a workspace to Grafana Enterprise</a>.</p> #[derive(std::clone::Clone, std::fmt::Debug)] pub struct AssociateLicense< C = aws_smithy_client::erase::DynConnector, M = crate::middleware::DefaultMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::associate_license_input::Builder, } impl<C, M, R> AssociateLicense<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `AssociateLicense`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::AssociateLicenseOutput, aws_smithy_http::result::SdkError<crate::error::AssociateLicenseError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::AssociateLicenseInputOperationOutputAlias, crate::output::AssociateLicenseOutput, crate::error::AssociateLicenseError, crate::input::AssociateLicenseInputOperationRetryAlias, >, { let op = self .inner .build() .map_err(|err| aws_smithy_http::result::SdkError::ConstructionFailure(err.into()))? .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p>The ID of the workspace to associate the license with.</p> pub fn workspace_id(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.workspace_id(input.into()); self } /// <p>The ID of the workspace to associate the license with.</p> pub fn set_workspace_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_workspace_id(input); self } /// <p>The type of license to associate with the workspace.</p> pub fn license_type(mut self, input: crate::model::LicenseType) -> Self { self.inner = self.inner.license_type(input); self } /// <p>The type of license to associate with the workspace.</p> pub fn set_license_type( mut self, input: std::option::Option<crate::model::LicenseType>, ) -> Self { self.inner = self.inner.set_license_type(input); self } } /// Fluent builder constructing a request to `CreateWorkspace`. /// /// <p>Creates a <i>workspace</i>. In a workspace, you can create Grafana dashboards and visualizations to analyze your metrics, logs, and traces. You don't have to build, package, or deploy any hardware to run the Grafana server.</p> /// <p>Don't use <code>CreateWorkspace</code> to modify an existing workspace. Instead, use <a href="https://docs.aws.amazon.com/grafana/latest/APIReference/API_UpdateWorkspace.html">UpdateWorkspace</a>.</p> #[derive(std::clone::Clone, std::fmt::Debug)] pub struct CreateWorkspace< C = aws_smithy_client::erase::DynConnector, M = crate::middleware::DefaultMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::create_workspace_input::Builder, } impl<C, M, R> CreateWorkspace<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `CreateWorkspace`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::CreateWorkspaceOutput, aws_smithy_http::result::SdkError<crate::error::CreateWorkspaceError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::CreateWorkspaceInputOperationOutputAlias, crate::output::CreateWorkspaceOutput, crate::error::CreateWorkspaceError, crate::input::CreateWorkspaceInputOperationRetryAlias, >, { let op = self .inner .build() .map_err(|err| aws_smithy_http::result::SdkError::ConstructionFailure(err.into()))? .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p>Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in other accounts in the same organization. If you specify <code>ORGANIZATION</code>, you must specify which organizational units the workspace can access in the <code>workspaceOrganizationalUnits</code> parameter.</p> pub fn account_access_type(mut self, input: crate::model::AccountAccessType) -> Self { self.inner = self.inner.account_access_type(input); self } /// <p>Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in other accounts in the same organization. If you specify <code>ORGANIZATION</code>, you must specify which organizational units the workspace can access in the <code>workspaceOrganizationalUnits</code> parameter.</p> pub fn set_account_access_type( mut self, input: std::option::Option<crate::model::AccountAccessType>, ) -> Self { self.inner = self.inner.set_account_access_type(input); self } /// <p>A unique, case-sensitive, user-provided identifier to ensure the idempotency of the request.</p> pub fn client_token(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.client_token(input.into()); self } /// <p>A unique, case-sensitive, user-provided identifier to ensure the idempotency of the request.</p> pub fn set_client_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_client_token(input); self } /// <p>The name of an IAM role that already exists to use with Organizations to access Amazon Web Services data sources and notification channels in other accounts in an organization.</p> pub fn organization_role_name(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.organization_role_name(input.into()); self } /// <p>The name of an IAM role that already exists to use with Organizations to access Amazon Web Services data sources and notification channels in other accounts in an organization.</p> pub fn set_organization_role_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_organization_role_name(input); self } /// <p>If you specify <code>Service Managed</code>, Amazon Managed Grafana automatically creates the IAM roles and provisions the permissions that the workspace needs to use Amazon Web Services data sources and notification channels.</p> /// <p>If you specify <code>CUSTOMER_MANAGED</code>, you will manage those roles and permissions yourself. If you are creating this workspace in a member account of an organization that is not a delegated administrator account, and you want the workspace to access data sources in other Amazon Web Services accounts in the organization, you must choose <code>CUSTOMER_MANAGED</code>.</p> /// <p>For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/AMG-manage-permissions.html">Amazon Managed Grafana permissions and policies for Amazon Web Services data sources and notification channels</a> </p> pub fn permission_type(mut self, input: crate::model::PermissionType) -> Self { self.inner = self.inner.permission_type(input); self } /// <p>If you specify <code>Service Managed</code>, Amazon Managed Grafana automatically creates the IAM roles and provisions the permissions that the workspace needs to use Amazon Web Services data sources and notification channels.</p> /// <p>If you specify <code>CUSTOMER_MANAGED</code>, you will manage those roles and permissions yourself. If you are creating this workspace in a member account of an organization that is not a delegated administrator account, and you want the workspace to access data sources in other Amazon Web Services accounts in the organization, you must choose <code>CUSTOMER_MANAGED</code>.</p> /// <p>For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/AMG-manage-permissions.html">Amazon Managed Grafana permissions and policies for Amazon Web Services data sources and notification channels</a> </p> pub fn set_permission_type( mut self, input: std::option::Option<crate::model::PermissionType>, ) -> Self { self.inner = self.inner.set_permission_type(input); self } /// <p>The name of the CloudFormation stack set to use to generate IAM roles to be used for this workspace.</p> pub fn stack_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.stack_set_name(input.into()); self } /// <p>The name of the CloudFormation stack set to use to generate IAM roles to be used for this workspace.</p> pub fn set_stack_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_stack_set_name(input); self } /// Appends an item to `workspaceDataSources`. /// /// To override the contents of this collection use [`set_workspace_data_sources`](Self::set_workspace_data_sources). /// /// <p>Specify the Amazon Web Services data sources that you want to be queried in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to read data from these sources. You must still add them as data sources in the Grafana console in the workspace.</p> /// <p>If you don't specify a data source here, you can still add it as a data source in the workspace console later. However, you will then have to manually configure permissions for it.</p> pub fn workspace_data_sources(mut self, input: crate::model::DataSourceType) -> Self { self.inner = self.inner.workspace_data_sources(input); self } /// <p>Specify the Amazon Web Services data sources that you want to be queried in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to read data from these sources. You must still add them as data sources in the Grafana console in the workspace.</p> /// <p>If you don't specify a data source here, you can still add it as a data source in the workspace console later. However, you will then have to manually configure permissions for it.</p> pub fn set_workspace_data_sources( mut self, input: std::option::Option<std::vec::Vec<crate::model::DataSourceType>>, ) -> Self { self.inner = self.inner.set_workspace_data_sources(input); self } /// <p>A description for the workspace. This is used only to help you identify this workspace.</p> pub fn workspace_description(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.workspace_description(input.into()); self } /// <p>A description for the workspace. This is used only to help you identify this workspace.</p> pub fn set_workspace_description( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_workspace_description(input); self } /// <p>The name for the workspace. It does not have to be unique.</p> pub fn workspace_name(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.workspace_name(input.into()); self } /// <p>The name for the workspace. It does not have to be unique.</p> pub fn set_workspace_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_workspace_name(input); self } /// Appends an item to `workspaceNotificationDestinations`. /// /// To override the contents of this collection use [`set_workspace_notification_destinations`](Self::set_workspace_notification_destinations). /// /// <p>Specify the Amazon Web Services notification channels that you plan to use in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to use these channels.</p> pub fn workspace_notification_destinations( mut self, input: crate::model::NotificationDestinationType, ) -> Self { self.inner = self.inner.workspace_notification_destinations(input); self } /// <p>Specify the Amazon Web Services notification channels that you plan to use in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to use these channels.</p> pub fn set_workspace_notification_destinations( mut self, input: std::option::Option<std::vec::Vec<crate::model::NotificationDestinationType>>, ) -> Self { self.inner = self.inner.set_workspace_notification_destinations(input); self } /// Appends an item to `workspaceOrganizationalUnits`. /// /// To override the contents of this collection use [`set_workspace_organizational_units`](Self::set_workspace_organizational_units). /// /// <p>Specifies the organizational units that this workspace is allowed to use data sources from, if this workspace is in an account that is part of an organization.</p> pub fn workspace_organizational_units( mut self, input: impl Into<std::string::String>, ) -> Self { self.inner = self.inner.workspace_organizational_units(input.into()); self } /// <p>Specifies the organizational units that this workspace is allowed to use data sources from, if this workspace is in an account that is part of an organization.</p> pub fn set_workspace_organizational_units( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.inner = self.inner.set_workspace_organizational_units(input); self } /// <p>The workspace needs an IAM role that grants permissions to the Amazon Web Services resources that the workspace will view data from. If you already have a role that you want to use, specify it here. If you omit this field and you specify some Amazon Web Services resources in <code>workspaceDataSources</code> or <code>workspaceNotificationDestinations</code>, a new IAM role with the necessary permissions is automatically created.</p> pub fn workspace_role_arn(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.workspace_role_arn(input.into()); self } /// <p>The workspace needs an IAM role that grants permissions to the Amazon Web Services resources that the workspace will view data from. If you already have a role that you want to use, specify it here. If you omit this field and you specify some Amazon Web Services resources in <code>workspaceDataSources</code> or <code>workspaceNotificationDestinations</code>, a new IAM role with the necessary permissions is automatically created.</p> pub fn set_workspace_role_arn( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_workspace_role_arn(input); self } /// Appends an item to `authenticationProviders`. /// /// To override the contents of this collection use [`set_authentication_providers`](Self::set_authentication_providers). /// /// <p>Specifies whether this workspace uses SAML 2.0, Amazon Web Services Single Sign On, or both to authenticate users for using the Grafana console within a workspace. For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/authentication-in-AMG.html">User authentication in Amazon Managed Grafana</a>.</p> pub fn authentication_providers( mut self, input: crate::model::AuthenticationProviderTypes, ) -> Self { self.inner = self.inner.authentication_providers(input); self } /// <p>Specifies whether this workspace uses SAML 2.0, Amazon Web Services Single Sign On, or both to authenticate users for using the Grafana console within a workspace. For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/authentication-in-AMG.html">User authentication in Amazon Managed Grafana</a>.</p> pub fn set_authentication_providers( mut self, input: std::option::Option<std::vec::Vec<crate::model::AuthenticationProviderTypes>>, ) -> Self { self.inner = self.inner.set_authentication_providers(input); self } } /// Fluent builder constructing a request to `DeleteWorkspace`. /// /// <p>Deletes an Amazon Managed Grafana workspace.</p> #[derive(std::clone::Clone, std::fmt::Debug)] pub struct DeleteWorkspace< C = aws_smithy_client::erase::DynConnector, M = crate::middleware::DefaultMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::delete_workspace_input::Builder, } impl<C, M, R> DeleteWorkspace<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `DeleteWorkspace`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::DeleteWorkspaceOutput, aws_smithy_http::result::SdkError<crate::error::DeleteWorkspaceError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::DeleteWorkspaceInputOperationOutputAlias, crate::output::DeleteWorkspaceOutput, crate::error::DeleteWorkspaceError, crate::input::DeleteWorkspaceInputOperationRetryAlias, >, { let op = self .inner .build() .map_err(|err| aws_smithy_http::result::SdkError::ConstructionFailure(err.into()))? .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p>The ID of the workspace to delete.</p> pub fn workspace_id(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.workspace_id(input.into()); self } /// <p>The ID of the workspace to delete.</p> pub fn set_workspace_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_workspace_id(input); self } } /// Fluent builder constructing a request to `DescribeWorkspace`. /// /// <p>Displays information about one Amazon Managed Grafana workspace.</p> #[derive(std::clone::Clone, std::fmt::Debug)] pub struct DescribeWorkspace< C = aws_smithy_client::erase::DynConnector, M = crate::middleware::DefaultMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::describe_workspace_input::Builder, } impl<C, M, R> DescribeWorkspace<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `DescribeWorkspace`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::DescribeWorkspaceOutput, aws_smithy_http::result::SdkError<crate::error::DescribeWorkspaceError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::DescribeWorkspaceInputOperationOutputAlias, crate::output::DescribeWorkspaceOutput, crate::error::DescribeWorkspaceError, crate::input::DescribeWorkspaceInputOperationRetryAlias, >, { let op = self .inner .build() .map_err(|err| aws_smithy_http::result::SdkError::ConstructionFailure(err.into()))? .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p>The ID of the workspace to display information about.</p> pub fn workspace_id(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.workspace_id(input.into()); self } /// <p>The ID of the workspace to display information about.</p> pub fn set_workspace_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_workspace_id(input); self } } /// Fluent builder constructing a request to `DescribeWorkspaceAuthentication`. /// /// <p>Displays information about the authentication methods used in one Amazon Managed Grafana workspace.</p> #[derive(std::clone::Clone, std::fmt::Debug)] pub struct DescribeWorkspaceAuthentication< C = aws_smithy_client::erase::DynConnector, M = crate::middleware::DefaultMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::describe_workspace_authentication_input::Builder, } impl<C, M, R> DescribeWorkspaceAuthentication<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `DescribeWorkspaceAuthentication`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::DescribeWorkspaceAuthenticationOutput, aws_smithy_http::result::SdkError<crate::error::DescribeWorkspaceAuthenticationError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::DescribeWorkspaceAuthenticationInputOperationOutputAlias, crate::output::DescribeWorkspaceAuthenticationOutput, crate::error::DescribeWorkspaceAuthenticationError, crate::input::DescribeWorkspaceAuthenticationInputOperationRetryAlias, >, { let op = self .inner .build() .map_err(|err| aws_smithy_http::result::SdkError::ConstructionFailure(err.into()))? .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p>The ID of the workspace to return authentication information about.</p> pub fn workspace_id(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.workspace_id(input.into()); self } /// <p>The ID of the workspace to return authentication information about.</p> pub fn set_workspace_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_workspace_id(input); self } } /// Fluent builder constructing a request to `DisassociateLicense`. /// /// <p>Removes the Grafana Enterprise license from a workspace.</p> #[derive(std::clone::Clone, std::fmt::Debug)] pub struct DisassociateLicense< C = aws_smithy_client::erase::DynConnector, M = crate::middleware::DefaultMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::disassociate_license_input::Builder, } impl<C, M, R> DisassociateLicense<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `DisassociateLicense`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::DisassociateLicenseOutput, aws_smithy_http::result::SdkError<crate::error::DisassociateLicenseError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::DisassociateLicenseInputOperationOutputAlias, crate::output::DisassociateLicenseOutput, crate::error::DisassociateLicenseError, crate::input::DisassociateLicenseInputOperationRetryAlias, >, { let op = self .inner .build() .map_err(|err| aws_smithy_http::result::SdkError::ConstructionFailure(err.into()))? .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p>The ID of the workspace to remove the Grafana Enterprise license from.</p> pub fn workspace_id(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.workspace_id(input.into()); self } /// <p>The ID of the workspace to remove the Grafana Enterprise license from.</p> pub fn set_workspace_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_workspace_id(input); self } /// <p>The type of license to remove from the workspace.</p> pub fn license_type(mut self, input: crate::model::LicenseType) -> Self { self.inner = self.inner.license_type(input); self } /// <p>The type of license to remove from the workspace.</p> pub fn set_license_type( mut self, input: std::option::Option<crate::model::LicenseType>, ) -> Self { self.inner = self.inner.set_license_type(input); self } } /// Fluent builder constructing a request to `ListPermissions`. /// /// <p>Lists the users and groups who have the Grafana <code>Admin</code> and <code>Editor</code> roles in this workspace. If you use this operation without specifying <code>userId</code> or <code>groupId</code>, the operation returns the roles of all users and groups. If you specify a <code>userId</code> or a <code>groupId</code>, only the roles for that user or group are returned. If you do this, you can specify only one <code>userId</code> or one <code>groupId</code>.</p> #[derive(std::clone::Clone, std::fmt::Debug)] pub struct ListPermissions< C = aws_smithy_client::erase::DynConnector, M = crate::middleware::DefaultMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::list_permissions_input::Builder, } impl<C, M, R> ListPermissions<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `ListPermissions`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::ListPermissionsOutput, aws_smithy_http::result::SdkError<crate::error::ListPermissionsError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::ListPermissionsInputOperationOutputAlias, crate::output::ListPermissionsOutput, crate::error::ListPermissionsError, crate::input::ListPermissionsInputOperationRetryAlias, >, { let op = self .inner .build() .map_err(|err| aws_smithy_http::result::SdkError::ConstructionFailure(err.into()))? .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// Create a paginator for this request /// /// Paginators are used by calling [`send().await`](crate::paginator::ListPermissionsPaginator::send) which returns a [`Stream`](tokio_stream::Stream). pub fn into_paginator(self) -> crate::paginator::ListPermissionsPaginator<C, M, R> { crate::paginator::ListPermissionsPaginator::new(self.handle, self.inner) } /// <p>The maximum number of results to include in the response.</p> pub fn max_results(mut self, input: i32) -> Self { self.inner = self.inner.max_results(input); self } /// <p>The maximum number of results to include in the response.</p> pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.inner = self.inner.set_max_results(input); self } /// <p>The token to use when requesting the next set of results. You received this token from a previous <code>ListPermissions</code> operation.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.next_token(input.into()); self } /// <p>The token to use when requesting the next set of results. You received this token from a previous <code>ListPermissions</code> operation.</p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_next_token(input); self } /// <p>(Optional) If you specify <code>SSO_USER</code>, then only the permissions of Amazon Web Services SSO users are returned. If you specify <code>SSO_GROUP</code>, only the permissions of Amazon Web Services SSO groups are returned.</p> pub fn user_type(mut self, input: crate::model::UserType) -> Self { self.inner = self.inner.user_type(input); self } /// <p>(Optional) If you specify <code>SSO_USER</code>, then only the permissions of Amazon Web Services SSO users are returned. If you specify <code>SSO_GROUP</code>, only the permissions of Amazon Web Services SSO groups are returned.</p> pub fn set_user_type(mut self, input: std::option::Option<crate::model::UserType>) -> Self { self.inner = self.inner.set_user_type(input); self } /// <p>(Optional) Limits the results to only the user that matches this ID.</p> pub fn user_id(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.user_id(input.into()); self } /// <p>(Optional) Limits the results to only the user that matches this ID.</p> pub fn set_user_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_user_id(input); self } /// <p>(Optional) Limits the results to only the group that matches this ID.</p> pub fn group_id(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.group_id(input.into()); self } /// <p>(Optional) Limits the results to only the group that matches this ID.</p> pub fn set_group_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_group_id(input); self } /// <p>The ID of the workspace to list permissions for. This parameter is required.</p> pub fn workspace_id(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.workspace_id(input.into()); self } /// <p>The ID of the workspace to list permissions for. This parameter is required.</p> pub fn set_workspace_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_workspace_id(input); self } } /// Fluent builder constructing a request to `ListWorkspaces`. /// /// <p>Returns a list of Amazon Managed Grafana workspaces in the account, with some information about each workspace. For more complete information about one workspace, use <a href="https://docs.aws.amazon.com/AAMG/latest/APIReference/API_DescribeWorkspace.html">DescribeWorkspace</a>.</p> #[derive(std::clone::Clone, std::fmt::Debug)] pub struct ListWorkspaces< C = aws_smithy_client::erase::DynConnector, M = crate::middleware::DefaultMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::list_workspaces_input::Builder, } impl<C, M, R> ListWorkspaces<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `ListWorkspaces`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::ListWorkspacesOutput, aws_smithy_http::result::SdkError<crate::error::ListWorkspacesError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::ListWorkspacesInputOperationOutputAlias, crate::output::ListWorkspacesOutput, crate::error::ListWorkspacesError, crate::input::ListWorkspacesInputOperationRetryAlias, >, { let op = self .inner .build() .map_err(|err| aws_smithy_http::result::SdkError::ConstructionFailure(err.into()))? .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// Create a paginator for this request /// /// Paginators are used by calling [`send().await`](crate::paginator::ListWorkspacesPaginator::send) which returns a [`Stream`](tokio_stream::Stream). pub fn into_paginator(self) -> crate::paginator::ListWorkspacesPaginator<C, M, R> { crate::paginator::ListWorkspacesPaginator::new(self.handle, self.inner) } /// <p>The maximum number of workspaces to include in the results.</p> pub fn max_results(mut self, input: i32) -> Self { self.inner = self.inner.max_results(input); self } /// <p>The maximum number of workspaces to include in the results.</p> pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.inner = self.inner.set_max_results(input); self } /// <p>The token for the next set of workspaces to return. (You receive this token from a previous <code>ListWorkspaces</code> operation.)</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.next_token(input.into()); self } /// <p>The token for the next set of workspaces to return. (You receive this token from a previous <code>ListWorkspaces</code> operation.)</p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_next_token(input); self } } /// Fluent builder constructing a request to `UpdatePermissions`. /// /// <p>Updates which users in a workspace have the Grafana <code>Admin</code> or <code>Editor</code> roles.</p> #[derive(std::clone::Clone, std::fmt::Debug)] pub struct UpdatePermissions< C = aws_smithy_client::erase::DynConnector, M = crate::middleware::DefaultMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::update_permissions_input::Builder, } impl<C, M, R> UpdatePermissions<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `UpdatePermissions`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::UpdatePermissionsOutput, aws_smithy_http::result::SdkError<crate::error::UpdatePermissionsError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::UpdatePermissionsInputOperationOutputAlias, crate::output::UpdatePermissionsOutput, crate::error::UpdatePermissionsError, crate::input::UpdatePermissionsInputOperationRetryAlias, >, { let op = self .inner .build() .map_err(|err| aws_smithy_http::result::SdkError::ConstructionFailure(err.into()))? .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// Appends an item to `updateInstructionBatch`. /// /// To override the contents of this collection use [`set_update_instruction_batch`](Self::set_update_instruction_batch). /// /// <p>An array of structures that contain the permission updates to make.</p> pub fn update_instruction_batch(mut self, input: crate::model::UpdateInstruction) -> Self { self.inner = self.inner.update_instruction_batch(input); self } /// <p>An array of structures that contain the permission updates to make.</p> pub fn set_update_instruction_batch( mut self, input: std::option::Option<std::vec::Vec<crate::model::UpdateInstruction>>, ) -> Self { self.inner = self.inner.set_update_instruction_batch(input); self } /// <p>The ID of the workspace to update.</p> pub fn workspace_id(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.workspace_id(input.into()); self } /// <p>The ID of the workspace to update.</p> pub fn set_workspace_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_workspace_id(input); self } } /// Fluent builder constructing a request to `UpdateWorkspace`. /// /// <p>Modifies an existing Amazon Managed Grafana workspace. If you use this operation and omit any optional parameters, the existing values of those parameters are not changed.</p> /// <p>To modify the user authentication methods that the workspace uses, such as SAML or Amazon Web Services SSO, use <a href="https://docs.aws.amazon.com/grafana/latest/APIReference/API_UpdateWorkspaceAuthentication.html">UpdateWorkspaceAuthentication</a>.</p> /// <p>To modify which users in the workspace have the <code>Admin</code> and <code>Editor</code> Grafana roles, use <a href="https://docs.aws.amazon.com/grafana/latest/APIReference/API_UpdatePermissions.html">UpdatePermissions</a>.</p> #[derive(std::clone::Clone, std::fmt::Debug)] pub struct UpdateWorkspace< C = aws_smithy_client::erase::DynConnector, M = crate::middleware::DefaultMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::update_workspace_input::Builder, } impl<C, M, R> UpdateWorkspace<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `UpdateWorkspace`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::UpdateWorkspaceOutput, aws_smithy_http::result::SdkError<crate::error::UpdateWorkspaceError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::UpdateWorkspaceInputOperationOutputAlias, crate::output::UpdateWorkspaceOutput, crate::error::UpdateWorkspaceError, crate::input::UpdateWorkspaceInputOperationRetryAlias, >, { let op = self .inner .build() .map_err(|err| aws_smithy_http::result::SdkError::ConstructionFailure(err.into()))? .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p>Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in other accounts in the same organization. If you specify <code>ORGANIZATION</code>, you must specify which organizational units the workspace can access in the <code>workspaceOrganizationalUnits</code> parameter.</p> pub fn account_access_type(mut self, input: crate::model::AccountAccessType) -> Self { self.inner = self.inner.account_access_type(input); self } /// <p>Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in other accounts in the same organization. If you specify <code>ORGANIZATION</code>, you must specify which organizational units the workspace can access in the <code>workspaceOrganizationalUnits</code> parameter.</p> pub fn set_account_access_type( mut self, input: std::option::Option<crate::model::AccountAccessType>, ) -> Self { self.inner = self.inner.set_account_access_type(input); self } /// <p>The name of an IAM role that already exists to use to access resources through Organizations.</p> pub fn organization_role_name(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.organization_role_name(input.into()); self } /// <p>The name of an IAM role that already exists to use to access resources through Organizations.</p> pub fn set_organization_role_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_organization_role_name(input); self } /// <p>If you specify <code>Service Managed</code>, Amazon Managed Grafana automatically creates the IAM roles and provisions the permissions that the workspace needs to use Amazon Web Services data sources and notification channels.</p> /// <p>If you specify <code>CUSTOMER_MANAGED</code>, you will manage those roles and permissions yourself. If you are creating this workspace in a member account of an organization and that account is not a delegated administrator account, and you want the workspace to access data sources in other Amazon Web Services accounts in the organization, you must choose <code>CUSTOMER_MANAGED</code>.</p> /// <p>For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/AMG-manage-permissions.html">Amazon Managed Grafana permissions and policies for Amazon Web Services data sources and notification channels</a> </p> pub fn permission_type(mut self, input: crate::model::PermissionType) -> Self { self.inner = self.inner.permission_type(input); self } /// <p>If you specify <code>Service Managed</code>, Amazon Managed Grafana automatically creates the IAM roles and provisions the permissions that the workspace needs to use Amazon Web Services data sources and notification channels.</p> /// <p>If you specify <code>CUSTOMER_MANAGED</code>, you will manage those roles and permissions yourself. If you are creating this workspace in a member account of an organization and that account is not a delegated administrator account, and you want the workspace to access data sources in other Amazon Web Services accounts in the organization, you must choose <code>CUSTOMER_MANAGED</code>.</p> /// <p>For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/AMG-manage-permissions.html">Amazon Managed Grafana permissions and policies for Amazon Web Services data sources and notification channels</a> </p> pub fn set_permission_type( mut self, input: std::option::Option<crate::model::PermissionType>, ) -> Self { self.inner = self.inner.set_permission_type(input); self } /// <p>The name of the CloudFormation stack set to use to generate IAM roles to be used for this workspace.</p> pub fn stack_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.stack_set_name(input.into()); self } /// <p>The name of the CloudFormation stack set to use to generate IAM roles to be used for this workspace.</p> pub fn set_stack_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_stack_set_name(input); self } /// Appends an item to `workspaceDataSources`. /// /// To override the contents of this collection use [`set_workspace_data_sources`](Self::set_workspace_data_sources). /// /// <p>Specify the Amazon Web Services data sources that you want to be queried in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to read data from these sources. You must still add them as data sources in the Grafana console in the workspace.</p> /// <p>If you don't specify a data source here, you can still add it as a data source later in the workspace console. However, you will then have to manually configure permissions for it.</p> pub fn workspace_data_sources(mut self, input: crate::model::DataSourceType) -> Self { self.inner = self.inner.workspace_data_sources(input); self } /// <p>Specify the Amazon Web Services data sources that you want to be queried in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to read data from these sources. You must still add them as data sources in the Grafana console in the workspace.</p> /// <p>If you don't specify a data source here, you can still add it as a data source later in the workspace console. However, you will then have to manually configure permissions for it.</p> pub fn set_workspace_data_sources( mut self, input: std::option::Option<std::vec::Vec<crate::model::DataSourceType>>, ) -> Self { self.inner = self.inner.set_workspace_data_sources(input); self } /// <p>A description for the workspace. This is used only to help you identify this workspace.</p> pub fn workspace_description(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.workspace_description(input.into()); self } /// <p>A description for the workspace. This is used only to help you identify this workspace.</p> pub fn set_workspace_description( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_workspace_description(input); self } /// <p>The ID of the workspace to update.</p> pub fn workspace_id(mut self, input: impl Into<std::string::String>) -> Self
/// <p>The ID of the workspace to update.</p> pub fn set_workspace_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_workspace_id(input); self } /// <p>A new name for the workspace to update.</p> pub fn workspace_name(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.workspace_name(input.into()); self } /// <p>A new name for the workspace to update.</p> pub fn set_workspace_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_workspace_name(input); self } /// Appends an item to `workspaceNotificationDestinations`. /// /// To override the contents of this collection use [`set_workspace_notification_destinations`](Self::set_workspace_notification_destinations). /// /// <p>Specify the Amazon Web Services notification channels that you plan to use in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to use these channels.</p> pub fn workspace_notification_destinations( mut self, input: crate::model::NotificationDestinationType, ) -> Self { self.inner = self.inner.workspace_notification_destinations(input); self } /// <p>Specify the Amazon Web Services notification channels that you plan to use in this workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to use these channels.</p> pub fn set_workspace_notification_destinations( mut self, input: std::option::Option<std::vec::Vec<crate::model::NotificationDestinationType>>, ) -> Self { self.inner = self.inner.set_workspace_notification_destinations(input); self } /// Appends an item to `workspaceOrganizationalUnits`. /// /// To override the contents of this collection use [`set_workspace_organizational_units`](Self::set_workspace_organizational_units). /// /// <p>Specifies the organizational units that this workspace is allowed to use data sources from, if this workspace is in an account that is part of an organization.</p> pub fn workspace_organizational_units( mut self, input: impl Into<std::string::String>, ) -> Self { self.inner = self.inner.workspace_organizational_units(input.into()); self } /// <p>Specifies the organizational units that this workspace is allowed to use data sources from, if this workspace is in an account that is part of an organization.</p> pub fn set_workspace_organizational_units( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.inner = self.inner.set_workspace_organizational_units(input); self } /// <p>The workspace needs an IAM role that grants permissions to the Amazon Web Services resources that the workspace will view data from. If you already have a role that you want to use, specify it here. If you omit this field and you specify some Amazon Web Services resources in <code>workspaceDataSources</code> or <code>workspaceNotificationDestinations</code>, a new IAM role with the necessary permissions is automatically created.</p> pub fn workspace_role_arn(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.workspace_role_arn(input.into()); self } /// <p>The workspace needs an IAM role that grants permissions to the Amazon Web Services resources that the workspace will view data from. If you already have a role that you want to use, specify it here. If you omit this field and you specify some Amazon Web Services resources in <code>workspaceDataSources</code> or <code>workspaceNotificationDestinations</code>, a new IAM role with the necessary permissions is automatically created.</p> pub fn set_workspace_role_arn( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_workspace_role_arn(input); self } } /// Fluent builder constructing a request to `UpdateWorkspaceAuthentication`. /// /// <p>Use this operation to define the identity provider (IdP) that this workspace authenticates users from, using SAML. You can also map SAML assertion attributes to workspace user information and define which groups in the assertion attribute are to have the <code>Admin</code> and <code>Editor</code> roles in the workspace.</p> #[derive(std::clone::Clone, std::fmt::Debug)] pub struct UpdateWorkspaceAuthentication< C = aws_smithy_client::erase::DynConnector, M = crate::middleware::DefaultMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::update_workspace_authentication_input::Builder, } impl<C, M, R> UpdateWorkspaceAuthentication<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `UpdateWorkspaceAuthentication`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::UpdateWorkspaceAuthenticationOutput, aws_smithy_http::result::SdkError<crate::error::UpdateWorkspaceAuthenticationError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::UpdateWorkspaceAuthenticationInputOperationOutputAlias, crate::output::UpdateWorkspaceAuthenticationOutput, crate::error::UpdateWorkspaceAuthenticationError, crate::input::UpdateWorkspaceAuthenticationInputOperationRetryAlias, >, { let op = self .inner .build() .map_err(|err| aws_smithy_http::result::SdkError::ConstructionFailure(err.into()))? .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p>The ID of the workspace to update the authentication for.</p> pub fn workspace_id(mut self, input: impl Into<std::string::String>) -> Self { self.inner = self.inner.workspace_id(input.into()); self } /// <p>The ID of the workspace to update the authentication for.</p> pub fn set_workspace_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_workspace_id(input); self } /// Appends an item to `authenticationProviders`. /// /// To override the contents of this collection use [`set_authentication_providers`](Self::set_authentication_providers). /// /// <p>Specifies whether this workspace uses SAML 2.0, Amazon Web Services Single Sign On, or both to authenticate users for using the Grafana console within a workspace. For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/authentication-in-AMG.html">User authentication in Amazon Managed Grafana</a>.</p> pub fn authentication_providers( mut self, input: crate::model::AuthenticationProviderTypes, ) -> Self { self.inner = self.inner.authentication_providers(input); self } /// <p>Specifies whether this workspace uses SAML 2.0, Amazon Web Services Single Sign On, or both to authenticate users for using the Grafana console within a workspace. For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/authentication-in-AMG.html">User authentication in Amazon Managed Grafana</a>.</p> pub fn set_authentication_providers( mut self, input: std::option::Option<std::vec::Vec<crate::model::AuthenticationProviderTypes>>, ) -> Self { self.inner = self.inner.set_authentication_providers(input); self } /// <p>If the workspace uses SAML, use this structure to map SAML assertion attributes to workspace user information and define which groups in the assertion attribute are to have the <code>Admin</code> and <code>Editor</code> roles in the workspace.</p> pub fn saml_configuration(mut self, input: crate::model::SamlConfiguration) -> Self { self.inner = self.inner.saml_configuration(input); self } /// <p>If the workspace uses SAML, use this structure to map SAML assertion attributes to workspace user information and define which groups in the assertion attribute are to have the <code>Admin</code> and <code>Editor</code> roles in the workspace.</p> pub fn set_saml_configuration( mut self, input: std::option::Option<crate::model::SamlConfiguration>, ) -> Self { self.inner = self.inner.set_saml_configuration(input); self } } } impl<C> Client<C, crate::middleware::DefaultMiddleware, aws_smithy_client::retry::Standard> { /// Creates a client with the given service config and connector override. pub fn from_conf_conn(conf: crate::Config, conn: C) -> Self { let retry_config = conf.retry_config.as_ref().cloned().unwrap_or_default(); let timeout_config = conf.timeout_config.as_ref().cloned().unwrap_or_default(); let sleep_impl = conf.sleep_impl.clone(); let mut builder = aws_smithy_client::Builder::new() .connector(conn) .middleware(crate::middleware::DefaultMiddleware::new()); builder.set_retry_config(retry_config.into()); builder.set_timeout_config(timeout_config); if let Some(sleep_impl) = sleep_impl { builder.set_sleep_impl(Some(sleep_impl)); } let client = builder.build(); Self { handle: std::sync::Arc::new(Handle { client, conf }), } } } impl Client< aws_smithy_client::erase::DynConnector, crate::middleware::DefaultMiddleware, aws_smithy_client::retry::Standard, > { /// Creates a new client from a shared config. #[cfg(any(feature = "rustls", feature = "native-tls"))] pub fn new(config: &aws_types::config::Config) -> Self { Self::from_conf(config.into()) } /// Creates a new client from the service [`Config`](crate::Config). #[cfg(any(feature = "rustls", feature = "native-tls"))] pub fn from_conf(conf: crate::Config) -> Self { let retry_config = conf.retry_config.as_ref().cloned().unwrap_or_default(); let timeout_config = conf.timeout_config.as_ref().cloned().unwrap_or_default(); let sleep_impl = conf.sleep_impl.clone(); let mut builder = aws_smithy_client::Builder::dyn_https() .middleware(crate::middleware::DefaultMiddleware::new()); builder.set_retry_config(retry_config.into()); builder.set_timeout_config(timeout_config); // the builder maintains a try-state. To avoid suppressing the warning when sleep is unset, // only set it if we actually have a sleep impl. if let Some(sleep_impl) = sleep_impl { builder.set_sleep_impl(Some(sleep_impl)); } let client = builder.build(); Self { handle: std::sync::Arc::new(Handle { client, conf }), } } }
{ self.inner = self.inner.workspace_id(input.into()); self }
orbital_utilities.py
#!/usr/bin/env python """ Functions and objects to deal with meteoroids orbits """ __author__ = "Hadrien A.R. Devillepoix, Trent Jansen-Sturgeon " __copyright__ = "Copyright 2016-2017, Desert Fireball Network" __license__ = "MIT" __version__ = "1.0" import numpy as np from numpy.linalg import norm import matplotlib.pyplot as plt from astropy import units as u from astropy.time import Time from astropy.coordinates import HCRS, ITRS, GCRS from astropy.utils.iers import IERS_A, IERS_A_URL, IERS from astropy.utils.data import download_file from trajectory_utilities import ECEF2LLH, \ EarthPosition, HCRS2HCI, HCI2ECI_pos, \ OrbitalElements2PosVel, ECI2ECEF_pos try: iers_a_file = download_file(IERS_A_URL, cache=True) iers_a = IERS_A.open(iers_a_file) IERS.iers_table = iers_a except: print('IERS_A_URL is temporarily unavailable') pass AU = 1*u.au.to(u.m) SMA_JUPITER = 5.20336301 * u.au def tisserand_wrt_jupiter(a, e, i): ''' Calculate the Tisserrand criterion with respect to Jupiter ''' T_j = (SMA_JUPITER / a + 2 * np.cos(i) * np.sqrt(a / SMA_JUPITER * (1 - e**2))) return T_j # Conversion vector AU_Deg2m_Rad = np.vstack((AU, 1, np.pi / 180 * np.ones((4, 1)))) Planets = {'Mercury': np.vstack((0.387099, 0.205636, 7.004979, 29.127030, 48.330766, 252.250324)), 'Venus': np.vstack((0.723336, 0.006777, 3.394676, 54.922625, 76.679843, 181.979100)), 'Earth': np.vstack((1.000003, 0.016711, -0.000015, 102.937682, 0.000000, 100.464572)), 'Mars': np.vstack((1.523710, 0.093394, 1.849691, -73.503169, 49.559539, -4.553432)), 'Jupiter': np.vstack((5.202887, 0.048386, 1.304397, -85.745429, 100.473909, 34.396441)), 'Saturn': np.vstack((9.536676,0.053862,2.485992,-21.063546,113.662424,49.954244)), 'Uranus': np.vstack((19.189165,0.047257,0.772638,96.937351,74.016925,313.238105)), 'Neptune': np.vstack((30.069923,0.008590,1.770043,-86.819463,131.784226,-55.120030))} class OrbitObject(object): """ Solar system object osculating orbit """ def __init__(self, orbit_type, a, e, i, omega, Omega, theta, ra_corr=np.nan*u.rad, dec_corr=np.nan*u.rad, v_g=np.nan*u.m/u.second): self.semi_major_axis = a.to(u.au) self.eccentricity = e self.inclination = i.to(u.deg) self.argument_periapsis = omega.to(u.deg) self.longitude_ascending_node = Omega.to(u.deg) self.longitude_perihelion = (self.longitude_ascending_node + self.argument_periapsis) % (360 * u.deg) self.true_anomaly = theta.to(u.deg) self.orbit_type = orbit_type self.perihelion = (1 - self.eccentricity) * self.semi_major_axis self.aphelion = (1 + self.eccentricity) * self.semi_major_axis self.corr_radiant_ra = (ra_corr.to(u.deg)) % (360 * u.deg) self.corr_radiant_dec = dec_corr.to(u.deg) radiant = HCRS(ra=self.corr_radiant_ra, dec=self.corr_radiant_dec, distance=1.0*u.au) ecpliptic_radiant = HCRS2HCI(np.vstack(radiant.cartesian.xyz.value)) self.ecliptic_latitude = np.rad2deg(np.arcsin(ecpliptic_radiant[2] / norm(ecpliptic_radiant)))*u.deg self.velocity_g = v_g.to(u.m / u.second) self.T_j = self.tisserand_criterion_wrt_jupiter() def tisserand_criterion_wrt_jupiter(self): ''' Calculate the Tisserrand criterion with respect to Jupiter ''' return tisserand_wrt_jupiter(self.semi_major_axis, self.eccentricity, self.inclination) def __str__(self): return str("Semi-major axis: " + str(self.semi_major_axis) + "\n" + "Eccentricity: " + str(self.eccentricity) + "\n" + "Inclination: " + str(self.inclination) + "\n" + "Argument of Periapsis: " + str(self.argument_periapsis) + "\n" + "Longitude of Ascending Node: " + str(self.longitude_ascending_node) + "\n" + "True Anomaly: " + str(self.true_anomaly) + "\n\n" + "Ra_corrected: " + str(self.corr_radiant_ra) + "\n" + "Dec_corrected: " + str(self.corr_radiant_dec) + "\n" + "Vel_g: " + str(self.velocity_g)) ''' Function delibaretely outside of native StateVector class to allow multithreaded call ''' def random_compute_orbit_ceplecha(sv): sv.randomize_velocity_vector() sv.computeOrbit(orbit_computation_method='Ceplecha') return sv def random_compute_orbit_integration_EOE(sv): sv.randomize_velocity_vector() sv.computeOrbit(orbit_computation_method='integrate_EOE') return sv def random_compute_orbit_integration_posvel(sv): sv.randomize_velocity_vector() sv.computeOrbit(orbit_computation_method='integrate_posvel') return sv def PlotOrbitalElements(COE, t_jd, t_soi, Sol): Colour = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] i = 2 #FIXME error plt.figure() plt.subplot(321) plt.plot(t_jd, COE[0] / AU, Colour[i]) plt.axvline(x=t_soi[0], color='b'); plt.grid() plt.xlabel("Time (JD)"); plt.ylabel("Semi-major Axis (AU)") # plt.axvline(x=t_soi[1], color='k') # plt.axvline(x=t_soi[2], color='c') plt.subplot(322) plt.plot(t_jd, COE[1], Colour[i]) plt.axvline(x=t_soi[0], color='b'); plt.grid() plt.xlabel("Time (JD)"); plt.ylabel("Eccentricity") # plt.axvline(x=t_soi[1], color='k') # plt.axvline(x=t_soi[2], color='c') plt.subplot(323) plt.plot(t_jd, COE[2] * 180 / np.pi, Colour[i]) plt.axvline(x=t_soi[0], color='b'); plt.grid() plt.xlabel("Time (JD)"); plt.ylabel("Inclination (deg)") # plt.axvline(x=t_soi[1], color='k') # plt.axvline(x=t_soi[2], color='c') plt.subplot(324) plt.plot(t_jd, COE[3] * 180 / np.pi, Colour[i]) plt.axvline(x=t_soi[0], color='b'); plt.grid() plt.xlabel("Time (JD)"); plt.ylabel("Argument of Periapsis (deg)") # plt.axvline(x=t_soi[1], color='k') # plt.axvline(x=t_soi[2], color='c') plt.subplot(325) plt.plot(t_jd, COE[4] * 180 / np.pi, Colour[i]) plt.axvline(x=t_soi[0], color='b'); plt.grid() plt.xlabel("Time (JD)"); plt.ylabel("Longitude of the Ascending Node (deg)") # plt.axvline(x=t_soi[1], color='k') # plt.axvline(x=t_soi[2], color='c') plt.subplot(326) plt.plot(t_jd, COE[5] * 180 / np.pi, Colour[i]) plt.axvline(x=t_soi[0], color='b'); plt.grid() plt.xlabel("Time (JD)"); plt.ylabel("True Anomaly (deg)") # plt.axvline(x=t_soi[1], color='k') # plt.axvline(x=t_soi[2], color='c') if Sol != 'NoSol': plt.subplot(321) plt.axhline(Sol.semi_major_axis.value, color='g') plt.subplot(322) plt.axhline(Sol.eccentricity, color='g') plt.subplot(323) plt.axhline(Sol.inclination.value, color='g') plt.subplot(324) plt.axhline(Sol.argument_periapsis.value, color='g') plt.subplot(325) plt.axhline(Sol.longitude_ascending_node.value, color='g') plt.subplot(326) plt.axhline(Sol.true_anomaly.value, color='g') plt.show() def PlotOrbit3D(OrbObjList, t0=2457535.0, Sol='NoSol'): from mpl_toolkits.mplot3d import Axes3D ''' 3D Orbit Plot''' fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for OrbObj in OrbObjList: COE = np.vstack((OrbObj.semi_major_axis.value, OrbObj.eccentricity, OrbObj.inclination.value, OrbObj.argument_periapsis.value, OrbObj.longitude_ascending_node.value, OrbObj.true_anomaly.value)) * AU_Deg2m_Rad COE = COE + np.vstack((np.zeros((5, 100)), np.linspace(0, 2 * np.pi, 100))) [Pos_HCI, Vel_HCI] = OrbitalElements2PosVel(COE, 'Sun', 'Classical') ax.plot(Pos_HCI[0]/AU, Pos_HCI[1]/AU, Pos_HCI[2]/AU, color='r', label='Determined Orbit') ''' Plot the planets''' for Planet in Planets: COE = Planets[Planet] * AU_Deg2m_Rad COEs = COE + np.vstack((np.zeros((5, 200)), np.linspace(0, 2 * np.pi, 200))) [pos, vel] = OrbitalElements2PosVel(COEs, 'Sun', 'Classical') ax.plot(pos[0]/AU, pos[1]/AU, pos[2]/AU, color='b') # t_yr = t0 + np.linspace(0, 365.25, 100) # pos_earth = EarthPosition(t_yr) # ax.plot(pos_earth[0]/AU, pos_earth[1]/AU, pos_earth[2]/AU, # color='b', linewidth=2.0, label='Earth') ''' Plot the solution (if given) ''' if Sol != 'NoSol': Sol_oe = np.vstack((Sol.semi_major_axis.value, Sol.eccentricity, Sol.inclination.value, Sol.argument_periapsis.value, Sol.longitude_ascending_node.value, Sol.true_anomaly.value)) * AU_Deg2m_Rad Sol_oe = Sol_oe + np.vstack((np.zeros((5, 100)), np.linspace(0, 2 * np.pi, 100))) [pos, vel] = OrbitalElements2PosVel(Sol_oe, 'Sun', 'Classical') ax.plot(pos[0]/AU, pos[1]/AU, pos[2]/AU, color='g', label='Published Orbit') plt.legend() ax.set_xlim([-5, 5]) ax.set_ylim([-5, 5]) ax.set_zlim([-5, 5]) plt.show() def PlotPerts(Pert): PPert = np.vstack(Pert).T; t = PPert[0] plt.figure(figsize=(16,9)) t_rel = t - np.max(t) # Days plt.plot(t_rel, PPert[1], '-b', linewidth=3.0, label='Earth') plt.plot(t_rel, PPert[2], '--k', linewidth=3.0, label='Moon') plt.plot(t_rel, PPert[3], '-.r', linewidth=3.0, label='Sun') PertJ2 = PPert[4][~np.isnan(PPert[4])] plt.plot(t_rel[~np.isnan(PPert[4])], PertJ2, ':g', linewidth=3.0, label='J2') PertDrag = PPert[5][~np.isnan(PPert[5])] plt.plot(t_rel[~np.isnan(PPert[5])], PertDrag, '-.c', linewidth=3.0, label='Drag') plt.yscale('log'); plt.grid(True); plt.legend(loc='best') plt.xlabel('Relative Time [days]'); plt.ylabel('Perturbation Acceleration [m/s^2]') plt.show() def PlotIntStep(t): dt=[] for k in range(len(t)-1): dt.append((t[k+1] - t[k]) * 24*60*60) plt.figure(figsize=(16,9)) t_rel = t - np.max(t) # Days plt.plot(t_rel[1:], abs(np.array(dt))) plt.yscale('log'); plt.grid(True)#; plt.legend() plt.xlabel('Relative Time [days]'); plt.ylabel('Timestep [sec]') plt.show() def ThirdBodyPerturbation(Pos, rho, mu): ''' Pos is the position of the meteoroid (m) rho is the position of the third body (m) mu is the standard gravitational parameter of the third body (m3/s2) ''' # Battin's scalar formula for vector difference q = np.dot(Pos.T, (Pos - 2 * rho) / (np.dot(rho.T, rho))) f = (3 * q + 3 * q**2 + q**3) / (1 + (1 + q)**1.5) # Third body perturbation acceleration (with indirect term) u = -mu * (Pos + f * rho) / ((norm(Pos - rho))**3) return u def NRLMSISE_00(pos, time, pos_type='eci'): ''' Courtesy of Ellie Sansom ''' """ Inputs: inertial position and time Outputs: [altitude, temp, atm_pres, atm density, sos, dyn_vis] """ from nrlmsise_00_header import nrlmsise_input, nrlmsise_output, nrlmsise_flags from nrlmsise_00 import gtd7 time = Time(time, format='jd', scale='utc') # Convert ECI to LLH coordinates if pos_type == 'eci': Pos_LLH = ECEF2LLH(ECI2ECEF_pos(pos, time)) elif pos_type == 'ecef': Pos_LLH = ECEF2LLH(pos) elif pos_type == 'llh': Pos_LLH = pos else: print('NRLMSISE_00 error: Invalid pos_type') exit() g_lat = np.rad2deg(Pos_LLH[0][0]) g_long = np.rad2deg(Pos_LLH[1][0]) alt = Pos_LLH[2][0] # Break up time into year, day of year, and seconds of the day yDay = time.yday.split(':'); yr = float(yDay[0]); doy = float(yDay[1]) sec = float(yDay[2]) * 60*60 + float(yDay[3]) * 60 + float(yDay[4]) # Assign our variables into the nrmsise inputs Input = nrlmsise_input(yr, doy, sec, alt/1000, g_lat, g_long) Output = nrlmsise_output(); Flags = nrlmsise_flags() # Switches for i in range(1, 24): Flags.switches[i]=1 # GTD7 atmospheric model subroutine gtd7(Input, Flags, Output) # Temperature at alt [deg K] T = Output.t[1] # Molecular number densities [m-3] He = Output.d[0] # He O = Output.d[1] # O N2 = Output.d[2] # N2 O2 = Output.d[3] # O2 Ar = Output.d[4] # Ar H = Output.d[6] # H N = Output.d[7] # N # ano_O = Output.d[8] # Anomalous oxygen sum_mass = He + O + N2 + O2 + Ar + H + N # Molar mass He_mass = 4.0026 # g/mol O_mass = 15.9994 # g/mol N2_mass = 28.013 # g/mol O2_mass = 31.998 # g/mol Ar_mass = 39.948 # g/mol H_mass = 1.0079 # g/mol N_mass = 14.0067 # g/mol # Molecular weight of air [kg/mol] mol_mass_air = (He_mass * He + O_mass * O + N2_mass * N2 + O2_mass * O2 + Ar_mass * Ar + H_mass * H + N_mass * N) / (1000 * sum_mass) # Total mass density [kg*m-3] po = Output.d[5] * 1000 Ru = 8.3144621 # Universal gas constant [J/(K*mol)] R = Ru / mol_mass_air # Individual gas constant [J/(kg*K)] #287.058 # Ideal gas law atm_pres = po * T * R # Speed of sound in atm sos = 331.3 * np.sqrt(1 + T / 273.15) # Dynamic viscosity (http://en.wikipedia.org/wiki/Viscosity) C = 120 #Sutherland's constant for air [deg K] mu_ref = 18.27e-6 # Reference viscosity [[mu_Pa s] * e-6] T_ref = 291.15 # Reference temperature [deg K] dyn_vis = mu_ref * (T_ref + C) / (T + C) * (T / T_ref)**1.5 return T, atm_pres, po, sos, dyn_vis # def compute_infinity_radiant(stateVec): # ''' This method computing the apparent radiant, it doesn't consider the zenith attraction ''' # Pos_geo = stateVec.position # Vel_geo = stateVec.vel_xyz # t0 = stateVec.epoch # # Compute radiant (apparent ORIGIN of meteoroid) # Vel_eci = ECEF2ECI(Pos_geo, Vel_geo, t0)[1] # ra_eci = np.arctan2(-Vel_eci[1], -Vel_eci[0]) # dec_eci = np.arcsin(-Vel_eci[2] / norm(Vel_eci)) # # ^-- redundant information. Already have it in metadata # return ra_eci, dec_eci def compute_cartesian_velocities_from_radiant(stateVec): ''' Turn apparent ecef radiant and velocity into cartesian velocity component ''' vel_geo = -(stateVec.velocity_inf * np.vstack((np.cos(np.deg2rad(stateVec.ra_ecef_inf)) * np.cos(np.deg2rad(stateVec.dec_ecef_inf)), np.sin(np.deg2rad(stateVec.ra_ecef_inf)) * np.cos(np.deg2rad(stateVec.dec_ecef_inf)), np.sin(np.deg2rad(stateVec.dec_ecef_inf))))) return vel_geo def SimilarityCriterion(COE1, COE2, method='SH'): ''' Southworth & Hawkins similarity criterion (1963); or Drummond's similarity criterion (1981); or Jopek's similarity criterion (1993). ''' if type(COE1) == np.ndarray: a1 = COE1[0]/AU; a2 = COE2[0]/AU # [AU] e1 = COE1[1]; e2 = COE2[1] # [] i1 = COE1[2]; i2 = COE2[2] # [rad] w1 = COE1[3]; w2 = COE2[3] # [rad] W1 = COE1[4]; W2 = COE2[4] # [rad] else: a1 = COE1.semi_major_axis.value; a2 = COE2.semi_major_axis.value # [AU] e1 = COE1.eccentricity; e2 = COE2.eccentricity # [] i1 = COE1.inclination.to(u.rad).value; i2 = COE2.inclination.to(u.rad).value # [rad] w1 = COE1.argument_periapsis.to(u.rad).value; w2 = COE2.argument_periapsis.to(u.rad).value # [rad] W1 = COE1.longitude_ascending_node.to(u.rad).value; W2 = COE2.longitude_ascending_node.to(u.rad).value # [rad] q1 = a1 * (1 - e1) # [AU] q2 = a2 * (1 - e2) # [AU] # Angle between the orbital planes (I21) var = (2 * np.sin((i2 - i1) / 2))**2 + np.sin(i1) * np.sin(i2) * (2 * np.sin((W2 - W1) / 2))**2 I21 = 2 * np.arcsin(np.sqrt(var) / 2) if method == 'SH': # Difference between orbits longitude of perihelion (pi21) pi21 = w2 - w1 + 2 * np.arcsin(np.cos((i2 + i1) / 2) * np.sin((W2 - W1) / 2) / np.cos(I21 / 2)) Similarity2 = (e2 - e1)**2 + (q2 - q1)**2 + var + (((e2 + e1) / 2) * (2 * np.sin(pi21 / 2)))**2 Similarity = np.sqrt(Similarity2) elif method == 'D': # Angle between the orbital lines of apsides (theta21) # l1 = W1 + np.arcsin(np.cos(i1) * np.tan(w1)); b1 = np.arcsin(np.sin(i1) * np.sin(w1)) # l2 = W2 + np.arcsin(np.cos(i2) * np.tan(w2)); b2 = np.arcsin(np.sin(i2) * np.sin(w2)) l1 = W1 + np.arctan(np.cos(i1) * np.tan(w1)); b1 = np.arcsin(np.sin(i1) * np.sin(w1)) l2 = W2 + np.arctan(np.cos(i2) * np.tan(w2)); b2 = np.arcsin(np.sin(i2) * np.sin(w2)) theta21 = np.arccos(np.sin(b1) * np.sin(b2) + np.cos(b1) * np.cos(b2) * np.cos(l2 - l1)) Similarity2 = ((e2 - e1) / (e2 + e1))**2 + ((q2 - q1) / (q2 + q1))**2 + \ (I21 / np.pi)**2 + ((e2 + e1) / 2)**2 * (theta21 / np.pi)**2 Similarity = np.sqrt(Similarity2) elif method == 'H': # Difference between orbits longitude of perihelion (pi21) pi21 = w2 - w1 + 2 * np.arcsin(np.cos((i2 + i1) / 2) * np.sin((W2 - W1) / 2) / np.cos(I21 / 2)) Similarity2 = (e2 - e1)**2 + ((q2 - q1) / (q2 + q1))**2 + var + \ (((e2 + e1) / 2) * (2 * np.sin(pi21 / 2)))**2 Similarity = np.sqrt(Similarity2) return Similarity def generate_ephemeris(pos_hci, t_jd): # Save the datetime ephem_dict = {'datetime': Time(t_jd, format='jd', scale='utc').isot} ephem_dict['MJD'] = Time(t_jd, format='jd', scale='utc').mjd # distance to sun ephem_dict['distance_to_sun'] = norm(pos_hci, axis=0) / 1000 #km # Convert to eci coordinates pos_eci = HCI2ECI_pos(pos_hci, t_jd) ephem_dict['pos_eci_x'] = pos_eci[0] ephem_dict['pos_eci_y'] = pos_eci[1] ephem_dict['pos_eci_z'] = pos_eci[2] pos_hcrs = HCI2HCRS(pos_hci)
# Calculate elongation angle pos_sun = pos_eci - pos_hcrs ephem_dict['elongation_angle'] = np.rad2deg(np.arccos(np.sum(pos_sun * pos_eci, axis=0) / (norm(pos_sun, axis=0) * norm(pos_eci, axis=0)))) # Calculate ephemeris dist = norm(pos_eci, axis=0) #m ephem_dict['ra'] = np.rad2deg(np.arctan2(pos_eci[1], pos_eci[0]))%360 #deg ephem_dict['dec'] = np.rad2deg(np.arcsin(pos_eci[2] / dist)) #deg ephem_dict['distance_to_earth'] = norm(pos_eci, axis=0) / 1000 #km return ephem_dict
# Calculate phase angle ephem_dict['phase_angle'] = np.rad2deg(np.arccos(np.sum(pos_hcrs * pos_eci, axis=0) / (norm(pos_hcrs, axis=0) * norm(pos_eci, axis=0))))
Event.py
# coding=utf-8 # *** WARNING: this file was generated by pulumigen. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs from ... import meta as _meta from ._inputs import * __all__ = ['EventInitArgs', 'Event'] @pulumi.input_type class EventInitArgs: def __init__(__self__, *, involved_object: pulumi.Input['ObjectReferenceArgs'], metadata: pulumi.Input['_meta.v1.ObjectMetaArgs'], action: Optional[pulumi.Input[str]] = None, api_version: Optional[pulumi.Input[str]] = None, count: Optional[pulumi.Input[int]] = None, event_time: Optional[pulumi.Input[str]] = None, first_timestamp: Optional[pulumi.Input[str]] = None, kind: Optional[pulumi.Input[str]] = None, last_timestamp: Optional[pulumi.Input[str]] = None, message: Optional[pulumi.Input[str]] = None, reason: Optional[pulumi.Input[str]] = None, related: Optional[pulumi.Input['ObjectReferenceArgs']] = None, reporting_component: Optional[pulumi.Input[str]] = None, reporting_instance: Optional[pulumi.Input[str]] = None, series: Optional[pulumi.Input['EventSeriesArgs']] = None, source: Optional[pulumi.Input['EventSourceArgs']] = None, type: Optional[pulumi.Input[str]] = None): """ The set of arguments for constructing a Event resource. :param pulumi.Input['ObjectReferenceArgs'] involved_object: The object that this event is about. :param pulumi.Input['_meta.v1.ObjectMetaArgs'] metadata: Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata :param pulumi.Input[str] action: What action was taken/failed regarding to the Regarding object. :param pulumi.Input[str] api_version: APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources :param pulumi.Input[int] count: The number of times this event has occurred. :param pulumi.Input[str] event_time: Time when this Event was first observed. :param pulumi.Input[str] first_timestamp: The time at which the event was first recorded. (Time of server receipt is in TypeMeta.) :param pulumi.Input[str] kind: Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds :param pulumi.Input[str] last_timestamp: The time at which the most recent occurrence of this event was recorded. :param pulumi.Input[str] message: A human-readable description of the status of this operation. :param pulumi.Input[str] reason: This should be a short, machine understandable string that gives the reason for the transition into the object's current status. :param pulumi.Input['ObjectReferenceArgs'] related: Optional secondary object for more complex actions. :param pulumi.Input[str] reporting_component: Name of the controller that emitted this Event, e.g. `kubernetes.io/kubelet`. :param pulumi.Input[str] reporting_instance: ID of the controller instance, e.g. `kubelet-xyzf`. :param pulumi.Input['EventSeriesArgs'] series: Data about the Event series this event represents or nil if it's a singleton Event. :param pulumi.Input['EventSourceArgs'] source: The component reporting this event. Should be a short machine understandable string. :param pulumi.Input[str] type: Type of this event (Normal, Warning), new types could be added in the future """ pulumi.set(__self__, "involved_object", involved_object) pulumi.set(__self__, "metadata", metadata) if action is not None: pulumi.set(__self__, "action", action) if api_version is not None: pulumi.set(__self__, "api_version", 'v1') if count is not None: pulumi.set(__self__, "count", count) if event_time is not None: pulumi.set(__self__, "event_time", event_time) if first_timestamp is not None: pulumi.set(__self__, "first_timestamp", first_timestamp) if kind is not None: pulumi.set(__self__, "kind", 'Event') if last_timestamp is not None: pulumi.set(__self__, "last_timestamp", last_timestamp) if message is not None: pulumi.set(__self__, "message", message) if reason is not None: pulumi.set(__self__, "reason", reason) if related is not None: pulumi.set(__self__, "related", related) if reporting_component is not None: pulumi.set(__self__, "reporting_component", reporting_component) if reporting_instance is not None: pulumi.set(__self__, "reporting_instance", reporting_instance) if series is not None: pulumi.set(__self__, "series", series) if source is not None: pulumi.set(__self__, "source", source) if type is not None: pulumi.set(__self__, "type", type) @property @pulumi.getter(name="involvedObject") def involved_object(self) -> pulumi.Input['ObjectReferenceArgs']: """ The object that this event is about. """ return pulumi.get(self, "involved_object") @involved_object.setter def involved_object(self, value: pulumi.Input['ObjectReferenceArgs']): pulumi.set(self, "involved_object", value) @property @pulumi.getter def metadata(self) -> pulumi.Input['_meta.v1.ObjectMetaArgs']: """ Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata """ return pulumi.get(self, "metadata") @metadata.setter def metadata(self, value: pulumi.Input['_meta.v1.ObjectMetaArgs']): pulumi.set(self, "metadata", value) @property @pulumi.getter def action(self) -> Optional[pulumi.Input[str]]: """ What action was taken/failed regarding to the Regarding object. """ return pulumi.get(self, "action") @action.setter def action(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "action", value) @property @pulumi.getter(name="apiVersion") def api_version(self) -> Optional[pulumi.Input[str]]: """ APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources """ return pulumi.get(self, "api_version") @api_version.setter def api_version(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "api_version", value) @property @pulumi.getter def count(self) -> Optional[pulumi.Input[int]]: """ The number of times this event has occurred. """ return pulumi.get(self, "count") @count.setter def count(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "count", value) @property @pulumi.getter(name="eventTime") def event_time(self) -> Optional[pulumi.Input[str]]: """ Time when this Event was first observed. """ return pulumi.get(self, "event_time") @event_time.setter def event_time(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "event_time", value) @property @pulumi.getter(name="firstTimestamp") def first_timestamp(self) -> Optional[pulumi.Input[str]]: """ The time at which the event was first recorded. (Time of server receipt is in TypeMeta.) """ return pulumi.get(self, "first_timestamp") @first_timestamp.setter def first_timestamp(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "first_timestamp", value) @property @pulumi.getter def kind(self) -> Optional[pulumi.Input[str]]: """ Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds """ return pulumi.get(self, "kind") @kind.setter def kind(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "kind", value) @property @pulumi.getter(name="lastTimestamp") def last_timestamp(self) -> Optional[pulumi.Input[str]]: """ The time at which the most recent occurrence of this event was recorded. """ return pulumi.get(self, "last_timestamp") @last_timestamp.setter def last_timestamp(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "last_timestamp", value) @property @pulumi.getter def message(self) -> Optional[pulumi.Input[str]]: """ A human-readable description of the status of this operation. """ return pulumi.get(self, "message") @message.setter def message(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "message", value) @property @pulumi.getter def reason(self) -> Optional[pulumi.Input[str]]: """ This should be a short, machine understandable string that gives the reason for the transition into the object's current status. """ return pulumi.get(self, "reason") @reason.setter def reason(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "reason", value) @property @pulumi.getter def related(self) -> Optional[pulumi.Input['ObjectReferenceArgs']]: """ Optional secondary object for more complex actions. """ return pulumi.get(self, "related") @related.setter def related(self, value: Optional[pulumi.Input['ObjectReferenceArgs']]): pulumi.set(self, "related", value) @property @pulumi.getter(name="reportingComponent") def reporting_component(self) -> Optional[pulumi.Input[str]]: """ Name of the controller that emitted this Event, e.g. `kubernetes.io/kubelet`. """ return pulumi.get(self, "reporting_component") @reporting_component.setter def reporting_component(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "reporting_component", value) @property @pulumi.getter(name="reportingInstance") def reporting_instance(self) -> Optional[pulumi.Input[str]]: """ ID of the controller instance, e.g. `kubelet-xyzf`. """ return pulumi.get(self, "reporting_instance") @reporting_instance.setter def reporting_instance(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "reporting_instance", value) @property @pulumi.getter def series(self) -> Optional[pulumi.Input['EventSeriesArgs']]: """ Data about the Event series this event represents or nil if it's a singleton Event. """ return pulumi.get(self, "series") @series.setter def series(self, value: Optional[pulumi.Input['EventSeriesArgs']]): pulumi.set(self, "series", value) @property @pulumi.getter def source(self) -> Optional[pulumi.Input['EventSourceArgs']]: """ The component reporting this event. Should be a short machine understandable string. """ return pulumi.get(self, "source") @source.setter def source(self, value: Optional[pulumi.Input['EventSourceArgs']]): pulumi.set(self, "source", value) @property @pulumi.getter def type(self) -> Optional[pulumi.Input[str]]: """ Type of this event (Normal, Warning), new types could be added in the future """ return pulumi.get(self, "type") @type.setter def type(self, value: Optional[pulumi.Input[str]]):
class Event(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, action: Optional[pulumi.Input[str]] = None, api_version: Optional[pulumi.Input[str]] = None, count: Optional[pulumi.Input[int]] = None, event_time: Optional[pulumi.Input[str]] = None, first_timestamp: Optional[pulumi.Input[str]] = None, involved_object: Optional[pulumi.Input[pulumi.InputType['ObjectReferenceArgs']]] = None, kind: Optional[pulumi.Input[str]] = None, last_timestamp: Optional[pulumi.Input[str]] = None, message: Optional[pulumi.Input[str]] = None, metadata: Optional[pulumi.Input[pulumi.InputType['_meta.v1.ObjectMetaArgs']]] = None, reason: Optional[pulumi.Input[str]] = None, related: Optional[pulumi.Input[pulumi.InputType['ObjectReferenceArgs']]] = None, reporting_component: Optional[pulumi.Input[str]] = None, reporting_instance: Optional[pulumi.Input[str]] = None, series: Optional[pulumi.Input[pulumi.InputType['EventSeriesArgs']]] = None, source: Optional[pulumi.Input[pulumi.InputType['EventSourceArgs']]] = None, type: Optional[pulumi.Input[str]] = None, __props__=None): """ Event is a report of an event somewhere in the cluster. Events have a limited retention time and triggers and messages may evolve with time. Event consumers should not rely on the timing of an event with a given Reason reflecting a consistent underlying trigger, or the continued existence of events with that Reason. Events should be treated as informative, best-effort, supplemental data. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] action: What action was taken/failed regarding to the Regarding object. :param pulumi.Input[str] api_version: APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources :param pulumi.Input[int] count: The number of times this event has occurred. :param pulumi.Input[str] event_time: Time when this Event was first observed. :param pulumi.Input[str] first_timestamp: The time at which the event was first recorded. (Time of server receipt is in TypeMeta.) :param pulumi.Input[pulumi.InputType['ObjectReferenceArgs']] involved_object: The object that this event is about. :param pulumi.Input[str] kind: Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds :param pulumi.Input[str] last_timestamp: The time at which the most recent occurrence of this event was recorded. :param pulumi.Input[str] message: A human-readable description of the status of this operation. :param pulumi.Input[pulumi.InputType['_meta.v1.ObjectMetaArgs']] metadata: Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata :param pulumi.Input[str] reason: This should be a short, machine understandable string that gives the reason for the transition into the object's current status. :param pulumi.Input[pulumi.InputType['ObjectReferenceArgs']] related: Optional secondary object for more complex actions. :param pulumi.Input[str] reporting_component: Name of the controller that emitted this Event, e.g. `kubernetes.io/kubelet`. :param pulumi.Input[str] reporting_instance: ID of the controller instance, e.g. `kubelet-xyzf`. :param pulumi.Input[pulumi.InputType['EventSeriesArgs']] series: Data about the Event series this event represents or nil if it's a singleton Event. :param pulumi.Input[pulumi.InputType['EventSourceArgs']] source: The component reporting this event. Should be a short machine understandable string. :param pulumi.Input[str] type: Type of this event (Normal, Warning), new types could be added in the future """ ... @overload def __init__(__self__, resource_name: str, args: EventInitArgs, opts: Optional[pulumi.ResourceOptions] = None): """ Event is a report of an event somewhere in the cluster. Events have a limited retention time and triggers and messages may evolve with time. Event consumers should not rely on the timing of an event with a given Reason reflecting a consistent underlying trigger, or the continued existence of events with that Reason. Events should be treated as informative, best-effort, supplemental data. :param str resource_name: The name of the resource. :param EventInitArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(EventInitArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, action: Optional[pulumi.Input[str]] = None, api_version: Optional[pulumi.Input[str]] = None, count: Optional[pulumi.Input[int]] = None, event_time: Optional[pulumi.Input[str]] = None, first_timestamp: Optional[pulumi.Input[str]] = None, involved_object: Optional[pulumi.Input[pulumi.InputType['ObjectReferenceArgs']]] = None, kind: Optional[pulumi.Input[str]] = None, last_timestamp: Optional[pulumi.Input[str]] = None, message: Optional[pulumi.Input[str]] = None, metadata: Optional[pulumi.Input[pulumi.InputType['_meta.v1.ObjectMetaArgs']]] = None, reason: Optional[pulumi.Input[str]] = None, related: Optional[pulumi.Input[pulumi.InputType['ObjectReferenceArgs']]] = None, reporting_component: Optional[pulumi.Input[str]] = None, reporting_instance: Optional[pulumi.Input[str]] = None, series: Optional[pulumi.Input[pulumi.InputType['EventSeriesArgs']]] = None, source: Optional[pulumi.Input[pulumi.InputType['EventSourceArgs']]] = None, type: Optional[pulumi.Input[str]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = EventInitArgs.__new__(EventInitArgs) __props__.__dict__["action"] = action __props__.__dict__["api_version"] = 'v1' __props__.__dict__["count"] = count __props__.__dict__["event_time"] = event_time __props__.__dict__["first_timestamp"] = first_timestamp if involved_object is None and not opts.urn: raise TypeError("Missing required property 'involved_object'") __props__.__dict__["involved_object"] = involved_object __props__.__dict__["kind"] = 'Event' __props__.__dict__["last_timestamp"] = last_timestamp __props__.__dict__["message"] = message if metadata is None and not opts.urn: raise TypeError("Missing required property 'metadata'") __props__.__dict__["metadata"] = metadata __props__.__dict__["reason"] = reason __props__.__dict__["related"] = related __props__.__dict__["reporting_component"] = reporting_component __props__.__dict__["reporting_instance"] = reporting_instance __props__.__dict__["series"] = series __props__.__dict__["source"] = source __props__.__dict__["type"] = type alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="kubernetes:events.k8s.io/v1:Event"), pulumi.Alias(type_="kubernetes:events.k8s.io/v1beta1:Event")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(Event, __self__).__init__( 'kubernetes:core/v1:Event', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'Event': """ Get an existing Event resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = EventInitArgs.__new__(EventInitArgs) __props__.__dict__["action"] = None __props__.__dict__["api_version"] = None __props__.__dict__["count"] = None __props__.__dict__["event_time"] = None __props__.__dict__["first_timestamp"] = None __props__.__dict__["involved_object"] = None __props__.__dict__["kind"] = None __props__.__dict__["last_timestamp"] = None __props__.__dict__["message"] = None __props__.__dict__["metadata"] = None __props__.__dict__["reason"] = None __props__.__dict__["related"] = None __props__.__dict__["reporting_component"] = None __props__.__dict__["reporting_instance"] = None __props__.__dict__["series"] = None __props__.__dict__["source"] = None __props__.__dict__["type"] = None return Event(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter def action(self) -> pulumi.Output[Optional[str]]: """ What action was taken/failed regarding to the Regarding object. """ return pulumi.get(self, "action") @property @pulumi.getter(name="apiVersion") def api_version(self) -> pulumi.Output[Optional[str]]: """ APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources """ return pulumi.get(self, "api_version") @property @pulumi.getter def count(self) -> pulumi.Output[Optional[int]]: """ The number of times this event has occurred. """ return pulumi.get(self, "count") @property @pulumi.getter(name="eventTime") def event_time(self) -> pulumi.Output[Optional[str]]: """ Time when this Event was first observed. """ return pulumi.get(self, "event_time") @property @pulumi.getter(name="firstTimestamp") def first_timestamp(self) -> pulumi.Output[Optional[str]]: """ The time at which the event was first recorded. (Time of server receipt is in TypeMeta.) """ return pulumi.get(self, "first_timestamp") @property @pulumi.getter(name="involvedObject") def involved_object(self) -> pulumi.Output['outputs.ObjectReference']: """ The object that this event is about. """ return pulumi.get(self, "involved_object") @property @pulumi.getter def kind(self) -> pulumi.Output[Optional[str]]: """ Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds """ return pulumi.get(self, "kind") @property @pulumi.getter(name="lastTimestamp") def last_timestamp(self) -> pulumi.Output[Optional[str]]: """ The time at which the most recent occurrence of this event was recorded. """ return pulumi.get(self, "last_timestamp") @property @pulumi.getter def message(self) -> pulumi.Output[Optional[str]]: """ A human-readable description of the status of this operation. """ return pulumi.get(self, "message") @property @pulumi.getter def metadata(self) -> pulumi.Output['_meta.v1.outputs.ObjectMeta']: """ Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata """ return pulumi.get(self, "metadata") @property @pulumi.getter def reason(self) -> pulumi.Output[Optional[str]]: """ This should be a short, machine understandable string that gives the reason for the transition into the object's current status. """ return pulumi.get(self, "reason") @property @pulumi.getter def related(self) -> pulumi.Output[Optional['outputs.ObjectReference']]: """ Optional secondary object for more complex actions. """ return pulumi.get(self, "related") @property @pulumi.getter(name="reportingComponent") def reporting_component(self) -> pulumi.Output[Optional[str]]: """ Name of the controller that emitted this Event, e.g. `kubernetes.io/kubelet`. """ return pulumi.get(self, "reporting_component") @property @pulumi.getter(name="reportingInstance") def reporting_instance(self) -> pulumi.Output[Optional[str]]: """ ID of the controller instance, e.g. `kubelet-xyzf`. """ return pulumi.get(self, "reporting_instance") @property @pulumi.getter def series(self) -> pulumi.Output[Optional['outputs.EventSeries']]: """ Data about the Event series this event represents or nil if it's a singleton Event. """ return pulumi.get(self, "series") @property @pulumi.getter def source(self) -> pulumi.Output[Optional['outputs.EventSource']]: """ The component reporting this event. Should be a short machine understandable string. """ return pulumi.get(self, "source") @property @pulumi.getter def type(self) -> pulumi.Output[Optional[str]]: """ Type of this event (Normal, Warning), new types could be added in the future """ return pulumi.get(self, "type")
pulumi.set(self, "type", value)
pushbullet_report.go
package data_report import ( "bytes" "fmt" "io/ioutil" "log" "net/http" "regexp" "strconv" "strings" ) func
(function string, object_config map[string]map[string]interface{}, title_message string, result interface{}) { warning := object_config[function]["warning"].(int) critical := object_config[function]["critical"].(int) email := object_config["email"]["email"].(string) // convert result value to int var notification string var check bool var result_int int var result_string string var re = regexp.MustCompile(`[\n%a-zA-Z ]+`) switch result.(type) { case int8: result_string = strconv.Itoa(result.(int)) result_int = result.(int) case int16: result_string = strconv.Itoa(result.(int)) result_int = result.(int) case int32: result_string = strconv.Itoa(result.(int)) result_int = result.(int) case int64: result_string = strconv.Itoa(result.(int)) result_int = result.(int) case string: result_string = result.(string) result_int, _ = strconv.Atoi(re.ReplaceAllString(result.(string), "")) case float64: result_string = strconv.FormatFloat(result.(float64), 'f', -1, 64) result_int = int(result.(float64)) case float32: result_string = strconv.FormatFloat(result.(float64), 'f', -1, 32) result_int = int(result.(float32)) default: fmt.Println("unknown") } fmt.Println(title_message) fmt.Println(result_int) if result_int > critical { // critical case, send notification fmt.Println("critical") notification = "[CRITICAL] " + title_message + " " + strings.Replace(result_string, "\n", "", -1) + " greater than " + strconv.Itoa(critical) check = true } else if result_int > warning { fmt.Println("warning") // warning case, send notification notification = "[WARNING] " + title_message + " " + strings.Replace(result_string, "\n", "", -1) + " greater than " + strconv.Itoa(warning) check = true } if check { list_email := strings.Split(email, ",") for _, reciever := range list_email { uri_path := "https://api.pushbullet.com/v2/pushes" email_reciever := reciever message := "{'type': 'note', 'title':'" + title_message + "', 'body':'" + notification + "', 'email':'" + email_reciever + "'}" message_format := strings.Replace(message, "'", "\"", -1) req, err := http.NewRequest("POST", uri_path, bytes.NewBuffer([]byte(message_format))) req.Header.Set("Access-Token", "xxx") req.Header.Set("Content-Type", "application/json") if err != nil { log.Fatal(err) } client := &http.Client{} resp, err := client.Do(req) response, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(response)) } } }
Pushbullet_report
BaseView.js
/** * Copyright (c) 2015-present, Facebook, Inc. * 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. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ /** * Defines RTCBaseView which maintains an array of children, style, and properties. * Provides methods to manage children and do layout, including presentLayout, * which essentially assigns position/rotation/frame). * @class RCTBaseView */ const INTERACTION_CALLBACKS = [ 'onEnter', 'onExit', 'onInput', 'onGazeEnter',
'onChange', 'onHeadPose', 'onGazeInput', 'onGazeHeadPose', 'onMouseInput', 'onMouseHeadPose', 'onChangeCaptured', 'onInputCaptured', 'onHeadPoseCaptured', 'onGazeInputCaptured', 'onGazeHeadPoseCaptured', 'onMouseInputCaptured', 'onMouseHeadPoseCaptured']; const IS_MOUSE_INTERACTION_CALLBACKS = { 'onEnter': true, 'onExit': true, 'onInput': true, 'onMouseEnter': true, 'onMouseExit': true, 'onChange': true, 'onHeadPose': true, 'onMouseInput': true, 'onMouseHeadPose': true, 'onChangeCaptured': true, 'onInputCaptured': true, 'onHeadPoseCaptured': true, 'onMouseInputCaptured': true, 'onMouseHeadPoseCaptured': true}; export default class RCTBaseView { /** * constructor: sets defaults for all views */ constructor() { this.UIManager = null; this.tag = 0; this.rootTag = 0; this.children = []; this.parent = null; this.props = {}; this.layout = {}; this.style = { layoutOrigin: [0, 0], }; this.interactableCount = 0; this.mouseInteractableCount = 0; this.isDirty = true; // renderGroup style property mapping to three.js view Object.defineProperty(this.style, "renderGroup", { set: (value) => { this.view && (this.view.renderGroup = value); } }); let self = this; INTERACTION_CALLBACKS.forEach((element) => { Object.defineProperty(self.props, element.toString(), { set: (value) => { if (self.props['_'+element] != value) { self.interactableCount += (value) ? 1 : -1; if (IS_MOUSE_INTERACTION_CALLBACKS[element]) { self.mouseInteractableCount += (value) ? 1 : -1; self.view && self.view.setIsMouseInteractable(self.mouseInteractableCount>0); } self.view && self.view.setIsInteractable(self.interactableCount>0); self.view && self.view.forceRaycastTest(self.interactableCount>0); self.props['_'+element] = value; } } }); }); this.view = null; } /** * Returns react tag that this view is associated with */ getTag() { return this.tag; } /** * Returns the index of child * @param child - child to find return -1 for not present */ getIndexOf(child) { return this.children.indexOf(child); } /** * Returns the parent view */ getParent() { return this.parent; } /** * Add a child view at a specific index * @param index - index to add at * @param child - view to add */ addChild(index, child) { this.children.splice(index, 0, child); this.view.add(child.view); } /** * Sets the parent view * @param parent - view to set */ setParent(parent) { this.parent = parent; } /** * Remove a child a specfic index * @param index - index within child to remove, will also child view * from three.js scene */ removeChild(index) { this.view.remove( this.children[index].view ); this.children.splice(index,1); } /** * Returns the child at index * @param index - index within children Array to return */ getChild(index) { return this.children[index]; } /** * Returns the number of children attached to this view */ getChildCount() { return this.children.length; } /** * Mark this view as dirty as well as parents, this will cause this view * to be relayed out */ makeDirty() { let view = this; while (view) { view.isDirty = true; view = view.getParent(); } } /** * dispose of any associated resource */ dispose() { RCTBaseView.disposeThreeJSObject(this.view); this.view = null; } /** * Per Frame update for view */ frame() { // TODO query why this isn't a setter if (this.style.opacity !== undefined) { this.view.setOpacity(this.style.opacity); } } /** * Given a layout object, calculate the associate transforms for three.js */ presentLayout() { var x = this.layout.width ? -this.style.layoutOrigin[0] * this.layout.width : 0; var y = this.layout.height ? -this.style.layoutOrigin[1] * this.layout.height : 0; if (this.props.onLayout) { // send an event to the interested view which details // the layout location in the frame of the parent view // takes into account he layoutOrigin this.UIManager._rnctx.callFunction( 'RCTEventEmitter', 'receiveEvent', [this.getTag(), 'topLayout', { x: x+this.layout.left, y: y+this.layout.top, width: this.layout.width, height: this.layout.height, }]); } // it transform is set apply to UIView if (this.style.transform) { this.view.setLocalTransform && this.view.setLocalTransform(this.style.transform); } this.view.setFrame && this.view.setFrame( x+this.layout.left, -(y+this.layout.top), this.layout.width, this.layout.height, this.UIManager._layoutAnimation ); this.view.owner = this; } /** * Helper to dispose of the internal memory allocations for three js object */ static disposeThreeJSObject(node) { if (!node) { return; } if (node.geometry) { node.geometry.dispose(); node.geometry = null; } if (node.material) { if (node.material.type === 'MultiMaterial') { for (let i in node.material.materials) { let mtr = node.material.materials[i]; if (mtr.map) { mtr.map.dispose(); mtr.map = null; } mtr.dispose(); } node.material.materials = null; } else { if (node.material.map) { node.material.map.dispose(); node.material.map = null; } node.material.dispose(); } } for (let i in node.children) { RCTBaseView.disposeThreeJSObject(node.children[i]); } node.parent = null; node.children = null; } /** * Describe the props that are available for React to change */ static describe() { return { NativeProps : { onLayout: 'function', onEnter: 'function', onExit: 'function', onInput: 'function', onGazeEnter: 'function', onGazeExit: 'function', onMouseEnter: 'function', onMouseExit: 'function', onChange: 'function', onInput: 'function', onHeadPose: 'function', onGazeInput: 'function', onGazeHeadPose: 'function', onMouseInput: 'function', onMouseHeadPose: 'function', onChangeCaptured: 'function', onInputCaptured: 'function', onHeadPoseCaptured: 'function', onGazeInputCaptured: 'function', onGazeHeadPoseCaptured: 'function', onMouseInputCaptured: 'function', onMouseHeadPoseCaptured: 'function', }, }; } }
'onGazeExit', 'onMouseEnter', 'onMouseExit',
handshake.rs
#![cfg(any(target_os = "macos", target_os = "ios"))] use security_framework::secure_transport::ClientHandshakeError; use security_framework::secure_transport::HandshakeError; use security_framework::secure_transport::MidHandshakeClientBuilder; use security_framework::secure_transport::MidHandshakeSslStream; use security_framework::secure_transport::SslConnectionType; use security_framework::secure_transport::SslContext; use security_framework::secure_transport::SslProtocolSide; use security_framework::secure_transport::SslStream; use std::future::Future; use std::mem; use std::pin::Pin; use std::task::Context; use std::task::Poll; use tls_api::async_as_sync::AsyncIoAsSyncIo; use tls_api::AsyncSocket; use tls_api::BoxFuture; use crate::TlsAcceptor; use tls_api::spi::save_context; enum ClientHandshakeFuture<F, S: Unpin> { Initial(F, AsyncIoAsSyncIo<S>), MidHandshake(MidHandshakeClientBuilder<AsyncIoAsSyncIo<S>>), Done, } pub(crate) fn new_slient_handshake<'a, S>( connector: &'a crate::TlsConnector, domain: &'a str, stream: S, ) -> impl Future<Output = tls_api::Result<crate::TlsStream<S>>> + 'a where S: AsyncSocket, { ClientHandshakeFuture::Initial( move |stream| connector.0.handshake(domain, stream), AsyncIoAsSyncIo::new(stream), ) } impl<F, S> Future for ClientHandshakeFuture<F, S> where S: AsyncSocket, F: FnOnce( AsyncIoAsSyncIo<S>, ) -> Result<SslStream<AsyncIoAsSyncIo<S>>, ClientHandshakeError<AsyncIoAsSyncIo<S>>>, Self: Unpin, { type Output = tls_api::Result<crate::TlsStream<S>>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { save_context(cx, || { let self_mut = self.get_mut(); match mem::replace(self_mut, ClientHandshakeFuture::Done) { ClientHandshakeFuture::Initial(f, stream) => match f(stream) { Ok(stream) => { return Poll::Ready(Ok(crate::TlsStream::new(stream))); } Err(ClientHandshakeError::Interrupted(mid)) => { *self_mut = ClientHandshakeFuture::MidHandshake(mid); return Poll::Pending; } Err(ClientHandshakeError::Failure(e)) => { return Poll::Ready(Err(tls_api::Error::new(e))) } }, ClientHandshakeFuture::MidHandshake(stream) => match stream.handshake() { Ok(stream) => { return Poll::Ready(Ok(crate::TlsStream::new(stream))); } Err(ClientHandshakeError::Interrupted(mid)) => { *self_mut = ClientHandshakeFuture::MidHandshake(mid); return Poll::Pending; } Err(ClientHandshakeError::Failure(e)) => { return Poll::Ready(Err(tls_api::Error::new(e))) } }, ClientHandshakeFuture::Done => panic!("Future must not be polled after ready"), } }) } } enum ServerHandshakeFuture<F, S: Unpin> { Initial(F, AsyncIoAsSyncIo<S>), MidHandshake(MidHandshakeSslStream<AsyncIoAsSyncIo<S>>), Done, } pub(crate) fn new_server_handshake<'a, S>( acceptor: &'a TlsAcceptor, stream: S, ) -> impl Future<Output = tls_api::Result<crate::TlsStream<S>>> + 'a where S: AsyncSocket, { BoxFuture::new(async move { let mut ctx = SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM) .map_err(tls_api::Error::new)?; ctx.set_certificate(&acceptor.0.identity, &acceptor.0.certs) .map_err(tls_api::Error::new)?; ServerHandshakeFuture::Initial(move |s| ctx.handshake(s), AsyncIoAsSyncIo::new(stream)) .await }) } impl<F, S> Future for ServerHandshakeFuture<F, S> where S: AsyncSocket, F: FnOnce( AsyncIoAsSyncIo<S>, ) -> Result<SslStream<AsyncIoAsSyncIo<S>>, HandshakeError<AsyncIoAsSyncIo<S>>>, Self: Unpin, { type Output = tls_api::Result<crate::TlsStream<S>>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>
}
{ save_context(cx, || { let self_mut = self.get_mut(); match mem::replace(self_mut, ServerHandshakeFuture::Done) { ServerHandshakeFuture::Initial(f, stream) => match f(stream) { Ok(stream) => { return Poll::Ready(Ok(crate::TlsStream::new(stream))); } Err(HandshakeError::Interrupted(mid)) => { *self_mut = ServerHandshakeFuture::MidHandshake(mid); return Poll::Pending; } Err(HandshakeError::Failure(e)) => { return Poll::Ready(Err(tls_api::Error::new(e))) } }, ServerHandshakeFuture::MidHandshake(stream) => match stream.handshake() { Ok(stream) => { return Poll::Ready(Ok(crate::TlsStream::new(stream))); } Err(HandshakeError::Interrupted(mid)) => { *self_mut = ServerHandshakeFuture::MidHandshake(mid); return Poll::Pending; } Err(HandshakeError::Failure(e)) => { return Poll::Ready(Err(tls_api::Error::new(e))) } }, ServerHandshakeFuture::Done => panic!("Future must not be polled after ready"), } }) }
engine.io.esm.min.js
/*! * Engine.IO v6.1.1 * (c) 2014-2022 Guillermo Rauch * Released under the MIT License. */ const t=Object.create(null);t.open="0",t.close="1",t.ping="2",t.pong="3",t.message="4",t.upgrade="5",t.noop="6";const e=Object.create(null);Object.keys(t).forEach((s=>{e[t[s]]=s}));const s={type:"error",data:"parser error"},r="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),o="function"==typeof ArrayBuffer,i=({type:e,data:s},i,a)=>{return r&&s instanceof Blob?i?a(s):n(s,a):o&&(s instanceof ArrayBuffer||(h=s,"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(h):h&&h.buffer instanceof ArrayBuffer))?i?a(s):n(new Blob([s]),a):a(t[e]+(s||""));var h},n=(t,e)=>{const s=new FileReader;return s.onload=function(){const t=s.result.split(",")[1];e("b"+t)},s.readAsDataURL(t)};for(var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h="undefined"==typeof Uint8Array?[]:new Uint8Array(256),p=0;p<a.length;p++)h[a.charCodeAt(p)]=p;const c="function"==typeof ArrayBuffer,l=(t,e)=>{if(c){const s=function(t){var e,s,r,o,i,n=.75*t.length,a=t.length,p=0;"="===t[t.length-1]&&(n--,"="===t[t.length-2]&&n--);var c=new ArrayBuffer(n),l=new Uint8Array(c);for(e=0;e<a;e+=4)s=h[t.charCodeAt(e)],r=h[t.charCodeAt(e+1)],o=h[t.charCodeAt(e+2)],i=h[t.charCodeAt(e+3)],l[p++]=s<<2|r>>4,l[p++]=(15&r)<<4|o>>2,l[p++]=(3&o)<<6|63&i;return c}(t);return u(s,e)}return{base64:!0,data:t}},u=(t,e)=>"blob"===e&&t instanceof ArrayBuffer?new Blob([t]):t;var d=f;function
(t){if(t)return function(t){for(var e in f.prototype)t[e]=f.prototype[e];return t}(t)}f.prototype.on=f.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},f.prototype.once=function(t,e){function s(){this.off(t,s),e.apply(this,arguments)}return s.fn=e,this.on(t,s),this},f.prototype.off=f.prototype.removeListener=f.prototype.removeAllListeners=f.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var o=0;o<r.length;o++)if((s=r[o])===e||s.fn===e){r.splice(o,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},f.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),s=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(s){r=0;for(var o=(s=s.slice(0)).length;r<o;++r)s[r].apply(this,e)}return this},f.prototype.emitReserved=f.prototype.emit,f.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},f.prototype.hasListeners=function(t){return!!this.listeners(t).length};var g="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();const y=setTimeout,m=clearTimeout;function b(t,e){e.useNativeTimers?(t.setTimeoutFn=y.bind(g),t.clearTimeoutFn=m.bind(g)):(t.setTimeoutFn=setTimeout.bind(g),t.clearTimeoutFn=clearTimeout.bind(g))}class v extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class w extends d{constructor(t){super(),this.writable=!1,b(this,t),this.opts=t,this.query=t.query,this.readyState="",this.socket=t.socket}onError(t,e,s){return super.emitReserved("error",new v(t,e,s)),this}open(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const r=((t,r)=>{if("string"!=typeof t)return{type:"message",data:u(t,r)};const o=t.charAt(0);return"b"===o?{type:"message",data:l(t.substring(1),r)}:e[o]?t.length>1?{type:e[o],data:t.substring(1)}:{type:e[o]}:s})(t,this.socket.binaryType);this.onPacket(r)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}}const k="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),T={};let B,S=0,R=0;function L(t){let e="";do{e=k[t%64]+e,t=Math.floor(t/64)}while(t>0);return e}for(;R<64;R++)T[k[R]]=R;const E="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),A=g.WebSocket||g.MozWebSocket,O="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class P extends w{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),e=this.opts.protocols,s=O?{}:function(t,...e){return e.reduce(((e,s)=>(t.hasOwnProperty(s)&&(e[s]=t[s]),e)),{})}(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=O?new A(t,e,s):e?new A(t,e):new A(t)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType||"arraybuffer",this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1;i(s,this.supportsBinary,(t=>{try{this.ws.send(t)}catch(t){}r&&E((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){let t=this.query||{};const e=this.opts.secure?"wss":"ws";let s="";this.opts.port&&("wss"===e&&443!==Number(this.opts.port)||"ws"===e&&80!==Number(this.opts.port))&&(s=":"+this.opts.port),this.opts.timestampRequests&&(t[this.opts.timestampParam]=function(){const t=L(+new Date);return t!==B?(S=0,B=t):t+"."+L(S++)}()),this.supportsBinary||(t.b64=1);const r=function(t){let e="";for(let s in t)t.hasOwnProperty(s)&&(e.length&&(e+="&"),e+=encodeURIComponent(s)+"="+encodeURIComponent(t[s]));return e}(t);return e+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+s+this.opts.path+(r.length?"?"+r:"")}check(){return!(!A||"__initialize"in A&&this.name===P.prototype.name)}}const C={websocket:P},x=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,_=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function q(t){const e=t,s=t.indexOf("["),r=t.indexOf("]");-1!=s&&-1!=r&&(t=t.substring(0,s)+t.substring(s,r).replace(/:/g,";")+t.substring(r,t.length));let o=x.exec(t||""),i={},n=14;for(;n--;)i[_[n]]=o[n]||"";return-1!=s&&-1!=r&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(t,e){const s=/\/{2,9}/g,r=e.replace(s,"/").split("/");"/"!=e.substr(0,1)&&0!==e.length||r.splice(0,1);"/"==e.substr(e.length-1,1)&&r.splice(r.length-1,1);return r}(0,i.path),i.queryKey=function(t,e){const s={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,r){e&&(s[e]=r)})),s}(0,i.query),i}class U extends d{constructor(t,e={}){super(),t&&"object"==typeof t&&(e=t,t=null),t?(t=q(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=q(e.host).host),b(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=e.transports||["websocket"],this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},e),this.opts.path=this.opts.path.replace(/\/$/,"")+"/","string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},s=t.split("&");for(let t=0,r=s.length;t<r;t++){let r=s[t].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&addEventListener("beforeunload",(()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())}),!1),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const e=function(t){const e={};for(let s in t)t.hasOwnProperty(s)&&(e[s]=t[s]);return e}(this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts.transportOptions[t],this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new C[t](s)}open(){let t;if(this.opts.rememberUpgrade&&U.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(t=>this.onClose("transport close",t)))}probe(t){let e=this.createTransport(t),s=!1;U.priorWebsocketSuccess=!1;const r=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",(t=>{if(!s)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;U.priorWebsocketSuccess="websocket"===e.name,this.transport.pause((()=>{s||"closed"!==this.readyState&&(p(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())}))}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}})))};function o(){s||(s=!0,p(),e.close(),e=null)}const i=t=>{const s=new Error("probe error: "+t);s.transport=e.name,o(),this.emitReserved("upgradeError",s)};function n(){i("transport closed")}function a(){i("socket closed")}function h(t){e&&t.name!==e.name&&o()}const p=()=>{e.removeListener("open",r),e.removeListener("error",i),e.removeListener("close",n),this.off("close",a),this.off("upgrading",h)};e.once("open",r),e.once("error",i),e.once("close",n),this.once("close",a),this.once("upgrading",h),e.open()}onOpen(){if(this.readyState="open",U.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade&&this.transport.pause){let t=0;const e=this.upgrades.length;for(;t<e;t++)this.probe(this.upgrades[t])}}onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this.resetPingTimeout(),this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const e=new Error("server error");e.code=t.data,this.onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.upgrades=this.filterUpgrades(t.upgrades),this.pingInterval=t.pingInterval,this.pingTimeout=t.pingTimeout,this.maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s<this.writeBuffer.length;s++){const r=this.writeBuffer[s].data;if(r&&(t+="string"==typeof(e=r)?function(t){let e=0,s=0;for(let r=0,o=t.length;r<o;r++)e=t.charCodeAt(r),e<128?s+=1:e<2048?s+=2:e<55296||e>=57344?s+=3:(r++,s+=4);return s}(e):Math.ceil(1.33*(e.byteLength||e.size))),s>0&&t>this.maxPayload)return this.writeBuffer.slice(0,s);t+=2}var e;return this.writeBuffer}write(t,e,s){return this.sendPacket("message",t,e,s),this}send(t,e,s){return this.sendPacket("message",t,e,s),this}sendPacket(t,e,s,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof s&&(r=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const o={type:t,data:e,options:s};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?s():t()})):this.upgrading?s():t()),this}onError(t){U.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,e){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&removeEventListener("offline",this.offlineEventListener,!1),this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const e=[];let s=0;const r=t.length;for(;s<r;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}U.protocol=4;const F=U.protocol;export{U as Socket,w as Transport,b as installTimerFunctions,q as parse,F as protocol,C as transports}; //# sourceMappingURL=engine.io.esm.min.js.map
f
tuples.rs
//! Mutators for tuple-like types //! //! This module contains the following traits and types: //! - [`RefTypes`] is a trait which essentially holds the types of a destructured tuple or structure. //! //! - `TupleN` is a marker type which implements [`RefTypes`] for tuples and structures of N elements. //! //! In this module, `Tuple0` to `Tuple10` are defined. //! //! - [`TupleStructure`] is a trait that can actually perform the destructuring for tuples and structures. //! For example, the code below shows how to implement `TupleStructure<Tuple2<A, B>>` for a struct `S`. //! ``` //! use fuzzcheck::mutators::tuples::*; //! struct S<A, B> { //! x: A, //! y: B //! } //! impl<A: 'static, B: 'static> TupleStructure<Tuple2<A, B>> for S<A, B> { //! fn get_ref<'a>(&'a self) -> <Tuple2<A, B> as RefTypes>::Ref<'a> { // Ref is (&'a A, &'a B) //! (&self.x, &self.y) //! } //! fn get_mut<'a>(&'a mut self) -> <Tuple2<A, B> as RefTypes>::Mut<'a> { // Mut is (&'a mut A, &'a mut B) //! (&mut self.x, &mut self.y) //! } //! fn new(t: <Tuple2<A, B> as RefTypes>::Owned) -> Self { // Owned is (A, B) //! S { x: t.0, y: t.1 } //! } //! } //! let mut s = S { x: true, y: true }; //! let (x, y) = s.get_ref(); // : (&bool, &bool) //! let (x, y) = s.get_mut(); // : (&mut bool, &mut bool) //! let s = S::new((true, false)); //! ``` //! //! - [`TupleMutator`] is a trait that is exactly the same as [`Mutator`] except that it works on //! the destructured form of types implementing [`TupleStructure`] instead. //! //! - [`TupleMutatorWrapper`] creates a [`Mutator`] from a [`TupleMutator`] //! //! - `TupleNMutator` is a [`TupleMutator`] for types that implememt `TupleStructure<TupleN<..>>`. //! //! In this module, `Tuple1Mutator` to `Tuple10Mutator` are defined. //! //! ### It seems convoluted, why does all of this exist?” //! //! To make the the [`#[derive(DefaultMutator)]`](derive@crate::DefaultMutator) procedural macro much simpler. //! //! First, it allows me to reuse a limited number of [`TupleMutator`](TupleMutator) implementations, //! paired with [`TupleMutatorWrapper`], to create mutators for any struct that implements `TupleStructure`. This makes the //! derive macro easier to write because now its job is mostly to implement `TupleStructure` for the struct, which is easy to do. //! //! Second, it also allows me to reuse the same tuple mutators to mutate the content of enum variants. For example, //! ``` //! enum S { //! A { x: u8, y: bool }, //! B(u8, bool), //! C, //! D //! } //! ``` //! Here, the enum `S` is essentially a sum type of `(u8, bool)`, `(u8, bool)`, `()`, `()`. //! So I'd like to reuse the mutators I already have for `(u8, bool)` and `()` to mutate `S`. If `TupleMutator` didn't //! exist, then I would have to defer to a `Mutator<(u8, bool)>`. But that wouldn't be efficient, because when the enum //! is destructured through `match`, we get access to `(&u8, &bool)` or `(&mut u8, &mut bool)`, which cannot be handled //! by a `Mutator<(u8, bool)>`: //! ``` //! # enum S { //! # A { x: u8, y: bool }, //! # B(u8, bool), //! # C, //! # D { } //! # } //! let mut s = S::A { x: 7, y: true }; //! match &mut s { //! S::A { x, y } => { //! // here we have access to (x, y): (&mut u8, &mut bool) //! // but a Mutator<(u8, bool)> would ask for a &mut (u8, bool) //! // there is no efficient way to convert between the two. //! // By contrast, if I have a `Tuple2Mutator<U8Mutator, BoolMutator>` //! // then I can write: //! // mutator.random_mutate((x, y), ...) //! } //! _ => {} //! } //! ``` //! None of it is *strictly* necessary since I could always write a brand new mutator for each type from scratch instead //! of trying to reuse mutators. But it would be a much larger amount of work, would probably increase compile times, and //! it would be more difficult to refactor and keep the implementations correct. use crate::Mutator; use std::marker::PhantomData; /// A trait which essentially holds the types of a destructured tuple or structure. /// /// Read the [module documentation](crate::mutators::tuples) for more information about it. pub trait RefTypes { type Owned; type Ref<'a>: Copy; type Mut<'a>; fn get_ref_from_mut<'a>(v: &'a Self::Mut<'a>) -> Self::Ref<'a>; } /// Trait for types that have the same shape as tuples, such as tuples and structs. /// /// For example, the tuple `(A, B)` implements `TupleStructure<Tuple2<A, B>>` since it is /// a 2-tuple with fields of type `A` and `B`. The struct `S { a: A, b: B }` /// also implements `TupleStructure<Tuple2<A, B>>`. /// /// We can then write generic functions over both `(A, B)` and `S` using this trait. /// /// * [`self.get_ref()`](TupleStructure::get_ref) returns immutable references to each of their fields (e.g. `(&A, &B)`) /// * [`self.get_mut()`](TupleStructure::get_mut) returns mutable references to each of their fields (e.g. `(&mut A, &mut B)`) /// * [`Self::new(..)`](TupleStructure::new) creates a new `Self` from a list of its fields (e.g. `Self::new((a, b))`) pub trait TupleStructure<TupleKind: RefTypes> { fn get_ref(&self) -> TupleKind::Ref<'_>; fn get_mut(&mut self) -> TupleKind::Mut<'_>; fn new(t: TupleKind::Owned) -> Self; } /// A trait equivalent in every way to [`Mutator`] except that it operates /// on the destructured form of types implementing [`TupleStructure`]. /// /// Defer to the documentation of [`Mutator`] to understand the purpose of each method. pub trait TupleMutator<T, TupleKind>: Sized + 'static where TupleKind: RefTypes, T: TupleStructure<TupleKind>, { type Cache: Clone; type MutationStep: Clone; type ArbitraryStep: Clone; type UnmutateToken; fn default_arbitrary_step(&self) -> Self::ArbitraryStep; fn complexity<'a>(&self, value: TupleKind::Ref<'a>, cache: &'a Self::Cache) -> f64; fn validate_value<'a>(&self, value: TupleKind::Ref<'a>) -> Option<Self::Cache>; fn default_mutation_step<'a>(&self, value: TupleKind::Ref<'a>, cache: &'a Self::Cache) -> Self::MutationStep; fn max_complexity(&self) -> f64; fn min_complexity(&self) -> f64; fn ordered_arbitrary(&self, step: &mut Self::ArbitraryStep, max_cplx: f64) -> Option<(T, f64)>; fn random_arbitrary(&self, max_cplx: f64) -> (T, f64); fn ordered_mutate<'a>( &self, value: TupleKind::Mut<'a>, cache: &'a mut Self::Cache, step: &'a mut Self::MutationStep, max_cplx: f64, ) -> Option<(Self::UnmutateToken, f64)>; fn random_mutate<'a>( &self, value: TupleKind::Mut<'a>, cache: &'a mut Self::Cache, max_cplx: f64, ) -> (Self::UnmutateToken, f64); fn unmutate<'a>(&self, value: TupleKind::Mut<'a>, cache: &'a mut Self::Cache, t: Self::UnmutateToken); type RecursingPartIndex: Clone; fn default_recursing_part_index<'a>( &self, value: TupleKind::Ref<'a>, cache: &Self::Cache, ) -> Self::RecursingPartIndex; fn recursing_part<'a, V, N>( &self, parent: &N, value: TupleKind::Ref<'a>, index: &mut Self::RecursingPartIndex, ) -> Option<&'a V> where V: Clone + 'static, N: Mutator<V>; } /// A wrapper that transforms a [`TupleMutator`] into a [`Mutator`] of values [with a tuple structure](TupleStructure). pub struct TupleMutatorWrapper<M, TupleKind> where TupleKind: RefTypes, { pub mutator: M, _phantom: PhantomData<TupleKind>, } impl<M, TupleKind> TupleMutatorWrapper<M, TupleKind> where TupleKind: RefTypes, { #[no_coverage] pub fn new(mutator: M) -> Self { Self { mutator, _phantom: PhantomData, } } } impl<M, TupleKind> Default for TupleMutatorWrapper<M, TupleKind> where TupleKind: RefTypes, M: Default, { #[no_coverage] fn default() -> Self { Self { mutator: <_>::default(), _phantom: PhantomData, } } } impl<T, M, TupleKind> Mutator<T> for TupleMutatorWrapper<M, TupleKind> where T: Clone + 'static, TupleKind: RefTypes + 'static, T: TupleStructure<TupleKind>, M: TupleMutator<T, TupleKind>, { #[doc(hidden)] type Cache = M::Cache; #[doc(hidden)] type MutationStep = M::MutationStep; #[doc(hidden)] type ArbitraryStep = M::ArbitraryStep; #[doc(hidden)] type UnmutateToken = M::UnmutateToken; #[doc(hidden)] #[no_coverage] fn default_arbitrary_step(&self) -> Self::ArbitraryStep { self.mutator.default_arbitrary_step() } #[doc(hidden)] #[no_coverage] fn complexity(&self, value: &T, cache: &Self::Cache) -> f64 { self.mutator.complexity(value.get_ref(), cache) } #[doc(hidden)] #[no_coverage] fn va
self, value: &T) -> Option<Self::Cache> { self.mutator.validate_value(value.get_ref()) } #[doc(hidden)] #[no_coverage] fn default_mutation_step(&self, value: &T, cache: &Self::Cache) -> Self::MutationStep { self.mutator.default_mutation_step(value.get_ref(), cache) } #[doc(hidden)] #[no_coverage] fn max_complexity(&self) -> f64 { self.mutator.max_complexity() } #[doc(hidden)] #[no_coverage] fn min_complexity(&self) -> f64 { self.mutator.min_complexity() } #[doc(hidden)] #[no_coverage] fn ordered_arbitrary(&self, step: &mut Self::ArbitraryStep, max_cplx: f64) -> Option<(T, f64)> { self.mutator.ordered_arbitrary(step, max_cplx) } #[doc(hidden)] #[no_coverage] fn random_arbitrary(&self, max_cplx: f64) -> (T, f64) { self.mutator.random_arbitrary(max_cplx) } #[doc(hidden)] #[no_coverage] fn ordered_mutate( &self, value: &mut T, cache: &mut Self::Cache, step: &mut Self::MutationStep, max_cplx: f64, ) -> Option<(Self::UnmutateToken, f64)> { self.mutator.ordered_mutate(value.get_mut(), cache, step, max_cplx) } #[doc(hidden)] #[no_coverage] fn random_mutate(&self, value: &mut T, cache: &mut Self::Cache, max_cplx: f64) -> (Self::UnmutateToken, f64) { self.mutator.random_mutate(value.get_mut(), cache, max_cplx) } #[doc(hidden)] #[no_coverage] fn unmutate(&self, value: &mut T, cache: &mut Self::Cache, t: Self::UnmutateToken) { self.mutator.unmutate(value.get_mut(), cache, t) } #[doc(hidden)] type RecursingPartIndex = M::RecursingPartIndex; #[doc(hidden)] #[no_coverage] fn default_recursing_part_index(&self, value: &T, cache: &Self::Cache) -> Self::RecursingPartIndex { self.mutator.default_recursing_part_index(value.get_ref(), cache) } #[doc(hidden)] #[no_coverage] fn recursing_part<'a, V, N>(&self, parent: &N, value: &'a T, index: &mut Self::RecursingPartIndex) -> Option<&'a V> where V: Clone + 'static, N: Mutator<V>, { self.mutator.recursing_part::<V, N>(parent, value.get_ref(), index) } } pub use tuple0::{Tuple0, Tuple0Mutator}; mod tuple0 { use super::TupleMutator; use crate::mutators::tuples::RefTypes; use crate::mutators::tuples::TupleStructure; use crate::Mutator; /// A marker type implementing [`RefTypes`] indicating that a type is equivalent to the unit type `()` pub struct Tuple0; impl RefTypes for Tuple0 { type Owned = (); type Ref<'a> = (); type Mut<'a> = (); fn get_ref_from_mut<'a>(_v: &'a Self::Mut<'a>) -> Self::Ref<'a> {} } impl TupleStructure<Tuple0> for () { fn get_ref(&self) -> <Tuple0 as RefTypes>::Ref<'_> {} fn get_mut(&mut self) -> <Tuple0 as RefTypes>::Mut<'_> {} fn new(_t: <Tuple0 as RefTypes>::Owned) -> Self {} } /// A `TupleMutator` for types equivalent to the unit type `()` pub struct Tuple0Mutator; impl TupleMutator<(), Tuple0> for Tuple0Mutator { #[doc(hidden)] type Cache = (); #[doc(hidden)] type MutationStep = bool; #[doc(hidden)] type ArbitraryStep = bool; #[doc(hidden)] type UnmutateToken = (); #[doc(hidden)] #[no_coverage] fn default_arbitrary_step(&self) -> Self::ArbitraryStep { false } #[doc(hidden)] #[no_coverage] fn complexity(&self, _value: (), _cache: &Self::Cache) -> f64 { 0.0 } #[doc(hidden)] #[no_coverage] fn validate_value(&self, _value: ()) -> Option<Self::Cache> { Some(()) } #[doc(hidden)] #[no_coverage] fn default_mutation_step<'a>(&self, _value: (), _cache: &'a Self::Cache) -> Self::MutationStep { false } #[doc(hidden)] #[no_coverage] fn max_complexity(&self) -> f64 { 0.0 } #[doc(hidden)] #[no_coverage] fn min_complexity(&self) -> f64 { 0.0 } #[doc(hidden)] #[no_coverage] fn ordered_arbitrary(&self, step: &mut Self::ArbitraryStep, _max_cplx: f64) -> Option<((), f64)> { if !*step { *step = true; Some(((), 0.0)) } else { None } } #[doc(hidden)] #[no_coverage] fn random_arbitrary(&self, _max_cplx: f64) -> ((), f64) { ((), 0.0) } #[doc(hidden)] #[no_coverage] fn ordered_mutate( &self, _value: (), _cache: &mut Self::Cache, step: &mut Self::MutationStep, _max_cplx: f64, ) -> Option<(Self::UnmutateToken, f64)> { if !*step { *step = true; Some(((), 0.0)) } else { None } } #[doc(hidden)] #[no_coverage] fn random_mutate(&self, _value: (), _cache: &mut Self::Cache, _max_cplx: f64) -> (Self::UnmutateToken, f64) { ((), 0.0) } #[doc(hidden)] #[no_coverage] fn unmutate(&self, _value: (), _cache: &mut Self::Cache, _t: Self::UnmutateToken) {} #[doc(hidden)] type RecursingPartIndex = (); #[doc(hidden)] #[no_coverage] fn default_recursing_part_index(&self, _value: (), _cache: &Self::Cache) -> Self::RecursingPartIndex {} #[doc(hidden)] #[no_coverage] fn recursing_part<'a, V, N>( &self, _parent: &N, _value: (), _index: &mut Self::RecursingPartIndex, ) -> Option<&'a V> where V: Clone + 'static, N: Mutator<V>, { None } } } pub use tuple1::{Tuple1, Tuple1Mutator}; mod tuple1 { use super::{TupleMutator, TupleMutatorWrapper}; use crate::mutators::tuples::RefTypes; #[doc = "A marker type implementing [`RefTypes`](crate::mutators::tuples::RefTypes) indicating that a type has the [structure](crate::mutators::tuples::TupleStructure) of a 1-tuple."] pub struct Tuple1<T0: 'static> { _phantom: ::std::marker::PhantomData<(T0,)>, } impl<T0: 'static> RefTypes for Tuple1<T0> { type Owned = (T0,); type Ref<'a> = (&'a T0,); type Mut<'a> = (&'a mut T0,); #[no_coverage] fn get_ref_from_mut<'a>(v: &'a Self::Mut<'a>) -> Self::Ref<'a> { (v.0,) } } impl<T0: 'static> crate::mutators::tuples::TupleStructure<Tuple1<T0>> for (T0,) { #[no_coverage] fn get_ref<'a>(&'a self) -> (&'a T0,) { (&self.0,) } #[no_coverage] fn get_mut<'a>(&'a mut self) -> (&'a mut T0,) { (&mut self.0,) } #[no_coverage] fn new(t: (T0,)) -> Self { t } } #[doc = " A `TupleMutator` for types that have a 1-tuple structure"] #[derive(::std::default::Default)] pub struct Tuple1Mutator<M0> { mutator_0: M0, } impl<M0> Tuple1Mutator<M0> { #[no_coverage] pub fn new(mutator_0: M0) -> Self { Self { mutator_0 } } } impl<T, T0, M0> TupleMutator<T, Tuple1<T0>> for Tuple1Mutator<M0> where T: ::std::clone::Clone + 'static, T0: ::std::clone::Clone + 'static, M0: crate::Mutator<T0>, T: crate::mutators::tuples::TupleStructure<Tuple1<T0>>, { #[doc(hidden)] type Cache = <M0 as crate::Mutator<T0>>::Cache; #[doc(hidden)] type MutationStep = <M0 as crate::Mutator<T0>>::MutationStep; #[doc(hidden)] type RecursingPartIndex = <M0 as crate::Mutator<T0>>::RecursingPartIndex; #[doc(hidden)] type ArbitraryStep = <M0 as crate::Mutator<T0>>::ArbitraryStep; #[doc(hidden)] type UnmutateToken = <M0 as crate::Mutator<T0>>::UnmutateToken; #[doc(hidden)] #[no_coverage] fn default_arbitrary_step(&self) -> Self::ArbitraryStep { self.mutator_0.default_arbitrary_step() } #[doc(hidden)] #[no_coverage] fn max_complexity(&self) -> f64 { self.mutator_0.max_complexity() } #[doc(hidden)] #[no_coverage] fn min_complexity(&self) -> f64 { self.mutator_0.min_complexity() } #[doc(hidden)] #[no_coverage] fn complexity<'a>(&self, value: <Tuple1<T0> as RefTypes>::Ref<'a>, cache: &'a Self::Cache) -> f64 { self.mutator_0.complexity(value.0, cache) } #[doc(hidden)] #[no_coverage] fn validate_value<'a>(&self, value: <Tuple1<T0> as RefTypes>::Ref<'a>) -> Option<Self::Cache> { self.mutator_0.validate_value(value.0) } #[doc(hidden)] #[no_coverage] fn default_mutation_step<'a>( &self, value: <Tuple1<T0> as RefTypes>::Ref<'a>, cache: &'a Self::Cache, ) -> Self::MutationStep { self.mutator_0.default_mutation_step(value.0, cache) } #[doc(hidden)] #[no_coverage] fn ordered_arbitrary(&self, step: &mut Self::ArbitraryStep, max_cplx: f64) -> Option<(T, f64)> { self.mutator_0 .ordered_arbitrary(step, max_cplx) .map(|(value, cplx)| (T::new((value,)), cplx)) } #[doc(hidden)] #[no_coverage] fn random_arbitrary(&self, max_cplx: f64) -> (T, f64) { let (value, cplx) = self.mutator_0.random_arbitrary(max_cplx); (T::new((value,)), cplx) } #[doc(hidden)] #[no_coverage] fn ordered_mutate<'a>( &self, value: <Tuple1<T0> as RefTypes>::Mut<'a>, cache: &'a mut Self::Cache, step: &'a mut Self::MutationStep, max_cplx: f64, ) -> Option<(Self::UnmutateToken, f64)> { self.mutator_0.ordered_mutate(value.0, cache, step, max_cplx) } #[doc(hidden)] #[no_coverage] fn random_mutate<'a>( &self, value: <Tuple1<T0> as RefTypes>::Mut<'a>, cache: &'a mut Self::Cache, max_cplx: f64, ) -> (Self::UnmutateToken, f64) { self.mutator_0.random_mutate(value.0, cache, max_cplx) } #[doc(hidden)] #[no_coverage] fn unmutate<'a>( &'a self, value: <Tuple1<T0> as RefTypes>::Mut<'a>, cache: &'a mut Self::Cache, t: Self::UnmutateToken, ) { self.mutator_0.unmutate(value.0, cache, t); } #[doc(hidden)] #[no_coverage] fn default_recursing_part_index<'a>( &self, value: <Tuple1<T0> as RefTypes>::Ref<'a>, cache: &'a Self::Cache, ) -> Self::RecursingPartIndex { self.mutator_0.default_recursing_part_index(value.0, cache) } #[doc(hidden)] #[no_coverage] fn recursing_part<'a, ___V, ___N>( &self, parent: &___N, value: <Tuple1<T0> as RefTypes>::Ref<'a>, index: &mut Self::RecursingPartIndex, ) -> Option<&'a ___V> where ___V: ::std::clone::Clone + 'static, ___N: crate::Mutator<___V>, { self.mutator_0.recursing_part::<___V, ___N>(parent, value.0, index) } } impl<T0> crate::mutators::DefaultMutator for (T0,) where T0: crate::mutators::DefaultMutator + 'static, { type Mutator = TupleMutatorWrapper<Tuple1Mutator<<T0 as crate::mutators::DefaultMutator>::Mutator>, Tuple1<T0>>; #[no_coverage] fn default_mutator() -> Self::Mutator { Self::Mutator::new(Tuple1Mutator::new( <T0 as crate::mutators::DefaultMutator>::default_mutator(), )) } } } pub use tuple2::{Tuple2, Tuple2Mutator}; mod tuple2 { extern crate self as fuzzcheck; fuzzcheck_mutators_derive::make_basic_tuple_mutator!(2); } pub use tuple3::{Tuple3, Tuple3Mutator}; mod tuple3 { extern crate self as fuzzcheck; fuzzcheck_mutators_derive::make_basic_tuple_mutator!(3); } pub use tuple4::{Tuple4, Tuple4Mutator}; mod tuple4 { extern crate self as fuzzcheck; fuzzcheck_mutators_derive::make_basic_tuple_mutator!(4); } pub use tuple5::{Tuple5, Tuple5Mutator}; mod tuple5 { extern crate self as fuzzcheck; fuzzcheck_mutators_derive::make_basic_tuple_mutator!(5); } pub use tuple6::{Tuple6, Tuple6Mutator}; mod tuple6 { extern crate self as fuzzcheck; fuzzcheck_mutators_derive::make_basic_tuple_mutator!(6); } pub use tuple7::{Tuple7, Tuple7Mutator}; mod tuple7 { extern crate self as fuzzcheck; fuzzcheck_mutators_derive::make_basic_tuple_mutator!(7); } pub use tuple8::{Tuple8, Tuple8Mutator}; mod tuple8 { extern crate self as fuzzcheck; fuzzcheck_mutators_derive::make_basic_tuple_mutator!(8); } pub use tuple9::{Tuple9, Tuple9Mutator}; mod tuple9 { extern crate self as fuzzcheck; fuzzcheck_mutators_derive::make_basic_tuple_mutator!(9); } pub use tuple10::{Tuple10, Tuple10Mutator}; mod tuple10 { extern crate self as fuzzcheck; fuzzcheck_mutators_derive::make_basic_tuple_mutator!(10); }
lidate_value(&
Checkbox.test.tsx
import React, {AllHTMLAttributes} from 'react'; import {mountWithApp} from 'test-utilities'; import {Key} from '../../../types'; import {Choice} from '../../Choice'; import {Checkbox} from '../Checkbox'; describe('<Checkbox />', () => { it('sets pass through properties on the input', () => { const input = mountWithApp( <Checkbox label="Checkbox" checked name="Checkbox" value="Some value" />, ); expect(input).toContainReactComponent('input', { checked: true, name: 'Checkbox', value: 'Some value', }); }); it('does not change checked states when onChange is not provided', () => { const element = mountWithApp( <Checkbox id="MyCheckbox" label="Checkbox" checked />, ); element.find('input')!.trigger('onClick', { stopPropagation: () => {}, }); expect(element).toContainReactComponent('input', { checked: true, }); }); it('does not propagate click events from input element', () => { const spy = jest.fn(); const element = mountWithApp( <Checkbox id="MyCheckbox" label="Checkbox" onChange={spy} />, ); element.find('input')!.trigger('onClick', { stopPropagation: () => {}, }); expect(spy).not.toHaveBeenCalled(); }); describe('onChange()', () => { it('is called with the updated checked value of the input on click', () => { const spy = jest.fn(); const element = mountWithApp( <Checkbox id="MyCheckbox" label="Checkbox" onChange={spy} />, ); (element.find('input')!.domNode as HTMLInputElement).checked = true; element.find(Choice)?.trigger('onClick'); expect(spy).toHaveBeenCalledWith(false, 'MyCheckbox'); }); it('is called when space is pressed', () => { const spy = jest.fn(); const element = mountWithApp( <Checkbox id="MyCheckbox" label="Checkbox" onChange={spy} />, ); element.find('input')!.trigger('onKeyUp', { keyCode: Key.Space, }); expect(spy).toHaveBeenCalledTimes(1); }); it('is not from keys other than space', () => { const spy = jest.fn(); const element = mountWithApp( <Checkbox id="MyCheckbox" label="Checkbox" onChange={spy} />, ); element.find('input')!.trigger('onKeyUp', { keyCode: Key.Enter, }); expect(spy).not.toHaveBeenCalled(); }); it('sets focus on the input when checkbox is toggled off', () => { const checkbox = mountWithApp( <Checkbox checked id="checkboxId" label="Checkbox" onChange={noop} />, ); checkbox.find(Choice)!.trigger('onClick'); expect(document.activeElement).toBe(checkbox.find('input')!.domNode); }); it('is not called from keyboard events when disabled', () => { const spy = jest.fn(); const checkbox = mountWithApp( <Checkbox label="label" disabled onChange={spy} />, ); checkbox.find('input')!.trigger('onKeyUp', { keyCode: Key.Enter, }); expect(spy).not.toHaveBeenCalled(); }); it('is not called from click events when disabled', () => { const spy = jest.fn(); const checkbox = mountWithApp( <Checkbox label="label" disabled onChange={spy} />, ); checkbox.find('input')!.trigger('onClick', { stopPropagation: () => {}, }); expect(spy).not.toHaveBeenCalled(); }); }); describe('onFocus()', () => { it('is called when the input is focused', () => { const spy = jest.fn(); const element = mountWithApp(<Checkbox label="Checkbox" onFocus={spy} />); element.find('input')!.trigger('onFocus'); expect(spy).toHaveBeenCalled(); }); }); describe('onBlur()', () => { it('is called when the input is focused', () => { const spy = jest.fn(); const element = mountWithApp(<Checkbox label="Checkbox" onBlur={spy} />); element.find('input')!.trigger('onBlur'); expect(spy).toHaveBeenCalled(); }); }); describe('id', () => { it('sets the id on the input', () => { const element = mountWithApp( <Checkbox id="MyCheckbox" label="Checkbox" />, ); expect(element).toContainReactComponent('input', { id: 'MyCheckbox', }); }); it('sets a random id on the input when none is passed', () => { const element = mountWithApp(<Checkbox label="Checkbox" />); expect(element).toContainReactComponent('input', { id: 'PolarisCheckbox1', }); }); }); describe('disabled', () => { it('sets the disabled attribute on the input', () => { const element = mountWithApp(<Checkbox label="Checkbox" disabled />); expect(element).toContainReactComponent('input', { disabled: true, }); }); it('is only disabled when disabled is explicitly set to true', () => { let element = mountWithApp(<Checkbox label="Checkbox" />); expect(element).toContainReactComponent('input', { disabled: undefined, }); element = mountWithApp(<Checkbox label="Checkbox" disabled={false} />); expect(element).toContainReactComponent('input', { disabled: false, }); }); it('can change values when disabled', () => { const spy = jest.fn(); const checkbox = mountWithApp( <Checkbox label="label" disabled onChange={spy} />, ); checkbox.find('input')!.trigger('onKeyUp', { keyCode: Key.Enter, }); checkbox.setProps({checked: true}); expect(checkbox).toContainReactComponent('input', { checked: true, }); }); }); describe('helpText', () => { it('connects the input to the help text', () => { const checkbox = mountWithApp( <Checkbox label="Checkbox" helpText="Some help" />, ); expect(checkbox).toContainReactComponent('input', { 'aria-describedby': 'PolarisCheckbox1HelpText', }); expect(checkbox.find('div')).toContainReactText('Some help'); }); }); describe('error', () => { it('marks the input as invalid', () => { const checkbox = mountWithApp( <Checkbox error={<span>Error</span>} label="Checkbox" />, ); expect(checkbox).toContainReactComponent('input', { 'aria-invalid': true, }); checkbox.setProps({error: 'Some error'}); expect(checkbox).toContainReactComponent('input', { 'aria-invalid': true, }); }); it('connects the input to the error if the error is not boolean', () => { const checkbox = mountWithApp( <Checkbox label="Checkbox" error="Some error" />, ); expect(checkbox).toContainReactComponent('input', { 'aria-describedby': 'PolarisCheckbox1Error', }); expect(checkbox.find('div')).toContainReactText('Some error'); }); it('does not connect the input to the error if the error is boolean', () => { const checkbox = mountWithApp(<Checkbox label="Checkbox" error />); expect(checkbox).toContainReactComponent('input', { 'aria-describedby': undefined, }); }); it('connects the input to both an error and help text', () => { const checkbox = mountWithApp( <Checkbox label="Checkbox" error="Some error" helpText="Some help" />, ); expect(checkbox).toContainReactComponent('input', { 'aria-describedby': 'PolarisCheckbox1Error PolarisCheckbox1HelpText', }); expect(checkbox.find('div')).toContainReactText('Some error'); expect(checkbox.find('div')).toContainReactText('Some help'); }); }); describe('indeterminate', () => { it('sets the indeterminate attribute to be true on the input when checked is "indeterminate"', () => { const checkbox = mountWithApp( <Checkbox label="Checkbox" checked="indeterminate" />, ); expect(checkbox).toContainReactComponent('input', { indeterminate: 'true', } as AllHTMLAttributes<HTMLInputElement>); }); it('sets the aria-checked attribute on the input as mixed when checked is "indeterminate"', () => { const checkbox = mountWithApp( <Checkbox label="Checkbox" checked="indeterminate" />, ); expect(checkbox).toContainReactComponent('input', { 'aria-checked': 'mixed', }); }); it('sets the checked attribute on the input to false when checked is "indeterminate"', () => { const checkbox = mountWithApp( <Checkbox label="Checkbox" checked="indeterminate" />, ); expect(checkbox).toContainReactComponent('input', { checked: false, }); }); }); describe('ariaDescribedBy', () => { it('sets the aria-describedBy attribute on the input', () => { const checkBox = mountWithApp( <Checkbox label="checkbox" ariaDescribedBy="SomeId" />, ); expect(checkBox).toContainReactComponent('input', { 'aria-describedby': 'SomeId', }); }); }); describe('Hovering the label', () => { it('adds the hover class to the Backdrop onMouseOver the label', () => { const checkBox = mountWithApp(<Checkbox label="checkbox" />); const label = checkBox.find('label'); label!.trigger('onMouseOver'); expect(checkBox).toContainReactComponent('span', { className: 'Backdrop hover', }); }); it('removes the hover class from the Backdrop onMouseOut the label', () => { const checkBox = mountWithApp(<Checkbox label="checkbox" />); const label = checkBox.find('label'); label!.trigger('onMouseOver'); label!.trigger('onMouseOut'); expect(checkBox).toContainReactComponent('span', { className: 'Backdrop', }); }); }); describe('Focus className', () => { it('on keyUp adds a keyFocused class to the input', () => { const checkbox = mountWithApp(<Checkbox label="Checkbox" />); checkbox.find('input')!.trigger('onKeyUp', { keyCode: Key.Space, }); expect(checkbox).toContainReactComponent('input', { className: 'Input keyFocused', }); }); it('on change does not add a keyFocused class to the input', () => { const checkbox = mountWithApp(<Checkbox label="Checkbox" />); const checkboxInput = checkbox.find('input'); checkboxInput!.trigger('onChange', { currentTarget: checkboxInput!.domNode as HTMLInputElement, }); expect(checkbox).not.toContainReactComponent('input', { className: 'Input keyFocused', }); }); }); }); function
() {}
noop
ranndom_m.py
#there are many ways we can do random numbers #1. import random #used to produce pseudo-random numbers. # They are called pseudo-random because they are not truly random and can be reproduced. import random a = random.random() #random float between 0 and 1 b = random.uniform(1,10) #random float between 1 and 10 c = random.randrange(1,10) #random integer between 1 and 10 (not including 10) d = random.randint(1,10) #random integer between 1 and 10 (including 10) e = random.choice(['a','b','c']) #random element from a list #sample picks one element one time and choices may pick one element multiple times f = random.sample(range(1,10),3) #3 random elements from a list g = random.choices(range(1,10),k=3) #3 random elements from a list h = random.normalvariate(0,1) #random float from normal distribution with mean 0 and standard deviation 1 random.shuffle(['a','b','c']) #shuffle a list in place random.seed(10) #set the seed for the random number generator to 10 (so that the same sequence of numbers will be generated) import secrets #secrets — Generate secure random numbers for managing secrets (True randomness) # https://docs.python.org/3/library/secrets.html #But this is slower than random module as more complex algorithms are used. a = secrets.randbelow(10) #random integer between 0 and 9 b = secrets.randbits(10) #random integer between 0 and 2**10-1 c = secrets.choice(['a','b','c']) #random element from a list d = secrets.sample(range(1,10),3) #3 random elements from a list #2. import numpy import numpy as np #numpy random generator uses a different generator than random module and also has a different seed np.random.seed(10) #set the seed for the random number generator to 10 (so that the same sequence of numbers will be generated) a = np.random.random() #random float between 0 and 1 b = np.random.uniform(1,10) #random float between 1 and 10 c = np.random.randrange(1,10) #random integer between 1 and 10 (not including 10) d = np.random.randint(1,10) #random integer between 1 and 10 (including 10)
e = np.random.choice(['a','b','c']) #random element from a list f = np.random.randn(3) #list of 3 random elements
implementInterface.js
import { GraphQLObjectType } from "graphql/type";
/** * Creates a trivial implementation resource object type for given Interfaces and a singular * interfaceFields. */ export default function implementInterface (ObjectName, objectDescription, Interfaces, interfaceFields) { return new GraphQLObjectType({ name: ObjectName, interfaces: Interfaces, fields: () => ({ ...interfaceFields(objectDescription).fields(), }), }); }
test_number.rs
use microserde::json; use std::f64; #[test] fn test_ser()
{ let cases = &[ (1.0, "1"), (1.42, "1.42"), (f64::NAN, "null"), (f64::INFINITY, "null"), (f64::NEG_INFINITY, "null"), ]; for (number, expected) in cases { let actual = json::to_string(number); assert_eq!(actual, *expected); } }
vector_object.rs
//! Vector storage object use crate::avm2::activation::Activation; use crate::avm2::names::Multiname; use crate::avm2::object::script_object::ScriptObjectData; use crate::avm2::object::{ClassObject, Object, ObjectPtr, TObject}; use crate::avm2::value::Value; use crate::avm2::vector::VectorStorage; use crate::avm2::Error; use crate::string::AvmString; use gc_arena::{Collect, GcCell, MutationContext}; use std::cell::{Ref, RefMut}; /// A class instance allocator that allocates Vector objects. pub fn vector_allocator<'gc>( class: ClassObject<'gc>, proto: Object<'gc>, activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Object<'gc>, Error> { let base = ScriptObjectData::base_new(Some(proto), Some(class)); //Because allocators are still called to build prototypes, especially for //the unspecialized Vector class, we have to fall back to Object when //getting the parameter type for our storage. let param_type = class .as_class_params() .flatten() .unwrap_or_else(|| activation.avm2().classes().object); Ok(VectorObject(GcCell::allocate( activation.context.gc_context, VectorObjectData { base, vector: VectorStorage::new(0, false, param_type, activation), }, )) .into()) } /// An Object which stores typed properties in vector storage #[derive(Collect, Debug, Clone, Copy)] #[collect(no_drop)] pub struct VectorObject<'gc>(GcCell<'gc, VectorObjectData<'gc>>); #[derive(Collect, Debug, Clone)] #[collect(no_drop)] pub struct VectorObjectData<'gc> { /// Base script object base: ScriptObjectData<'gc>, /// Vector-structured properties vector: VectorStorage<'gc>, } impl<'gc> VectorObject<'gc> { /// Wrap an existing vector in an object. pub fn from_vector( vector: VectorStorage<'gc>, activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Object<'gc>, Error> { let value_type = vector.value_type(); let vector_class = activation.avm2().classes().vector; let applied_class = vector_class.apply(activation, &[value_type.into()])?; let applied_proto = applied_class.prototype(); let mut object: Object<'gc> = VectorObject(GcCell::allocate( activation.context.gc_context, VectorObjectData { base: ScriptObjectData::base_new(Some(applied_proto), Some(applied_class)), vector, }, )) .into(); object.install_instance_slots(activation); Ok(object) } } impl<'gc> TObject<'gc> for VectorObject<'gc> { fn base(&self) -> Ref<ScriptObjectData<'gc>> { Ref::map(self.0.read(), |read| &read.base) } fn base_mut(&self, mc: MutationContext<'gc, '_>) -> RefMut<ScriptObjectData<'gc>> { RefMut::map(self.0.write(mc), |write| &mut write.base) } fn as_ptr(&self) -> *const ObjectPtr { self.0.as_ptr() as *const ObjectPtr } fn get_property_local( self, name: &Multiname<'gc>, activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Value<'gc>, Error> { let read = self.0.read(); if name.contains_public_namespace() { if let Some(name) = name.local_name() { if let Ok(index) = name.parse::<usize>() { return Ok(read.vector.get(index).unwrap_or(Value::Undefined)); } } } read.base.get_property_local(name, activation) } fn set_property_local( self, name: &Multiname<'gc>, value: Value<'gc>, activation: &mut Activation<'_, 'gc, '_>, ) -> Result<(), Error> { if name.contains_public_namespace() { if let Some(name) = name.local_name() { if let Ok(index) = name.parse::<usize>() { let type_of = self.0.read().vector.value_type(); let value = match value.coerce_to_type(activation, type_of)? { Value::Undefined => self.0.read().vector.default(activation), Value::Null => self.0.read().vector.default(activation), v => v, }; self.0 .write(activation.context.gc_context) .vector .set(index, value, activation)?; return Ok(()); } } } let mut write = self.0.write(activation.context.gc_context); write.base.set_property_local(name, value, activation) } fn init_property_local( self, name: &Multiname<'gc>, value: Value<'gc>, activation: &mut Activation<'_, 'gc, '_>, ) -> Result<(), Error> { if name.contains_public_namespace() { if let Some(name) = name.local_name() { if let Ok(index) = name.parse::<usize>() { let type_of = self.0.read().vector.value_type(); let value = match value.coerce_to_type(activation, type_of)? { Value::Undefined => self.0.read().vector.default(activation), Value::Null => self.0.read().vector.default(activation), v => v, }; self.0 .write(activation.context.gc_context) .vector .set(index, value, activation)?; return Ok(()); } } } let mut write = self.0.write(activation.context.gc_context); write.base.init_property_local(name, value, activation) } fn delete_property_local( self, activation: &mut Activation<'_, 'gc, '_>, name: &Multiname<'gc>, ) -> Result<bool, Error> { if name.contains_public_namespace() && name.local_name().is_some() && name.local_name().unwrap().parse::<usize>().is_ok() { return Ok(true); } Ok(self .0 .write(activation.context.gc_context) .base .delete_property_local(name)) } fn has_own_property(self, name: &Multiname<'gc>) -> bool { if name.contains_public_namespace() { if let Some(name) = name.local_name() { if let Ok(index) = name.parse::<usize>() { return self.0.read().vector.is_in_range(index); } } } self.0.read().base.has_own_property(name) } fn get_next_enumerant( self, last_index: u32, _activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Option<u32>, Error> { if last_index < self.0.read().vector.length() as u32 { Ok(Some(last_index.saturating_add(1)))
} fn get_enumerant_name( self, index: u32, _activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Value<'gc>, Error> { if self.0.read().vector.length() as u32 >= index { Ok(index .checked_sub(1) .map(|index| index.into()) .unwrap_or(Value::Undefined)) } else { Ok("".into()) } } fn property_is_enumerable(&self, name: AvmString<'gc>) -> bool { name.parse::<u32>() .map(|index| self.0.read().vector.length() as u32 >= index) .unwrap_or(false) } fn to_string(&self, _mc: MutationContext<'gc, '_>) -> Result<Value<'gc>, Error> { Ok(Value::Object(Object::from(*self))) } fn value_of(&self, _mc: MutationContext<'gc, '_>) -> Result<Value<'gc>, Error> { Ok(Value::Object(Object::from(*self))) } fn as_vector_storage(&self) -> Option<Ref<VectorStorage<'gc>>> { Some(Ref::map(self.0.read(), |vod| &vod.vector)) } fn as_vector_storage_mut( &self, mc: MutationContext<'gc, '_>, ) -> Option<RefMut<VectorStorage<'gc>>> { Some(RefMut::map(self.0.write(mc), |vod| &mut vod.vector)) } }
} else { Ok(None) }
binary_sensor.py
""" A sensor platform which detects underruns and capped status from the official Raspberry Pi Kernel. Minimal Kernel needed is 4.14+ """ import logging from rpi_bad_power import UnderVoltage, new_under_voltage from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback _LOGGER = logging.getLogger(__name__) DESCRIPTION_NORMALIZED = "Voltage normalized. Everything is working as intended." DESCRIPTION_UNDER_VOLTAGE = "Under-voltage was detected. Consider getting a uninterruptible power supply for your Raspberry Pi." async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up rpi_power binary sensor.""" under_voltage = await hass.async_add_executor_job(new_under_voltage) async_add_entities([RaspberryChargerBinarySensor(under_voltage)], True) class RaspberryChargerBinarySensor(BinarySensorEntity): """Binary sensor representing the rpi power status.""" _attr_device_class = BinarySensorDeviceClass.PROBLEM _attr_icon = "mdi:raspberry-pi" _attr_name = "RPi Power status"
def __init__(self, under_voltage: UnderVoltage) -> None: """Initialize the binary sensor.""" self._under_voltage = under_voltage def update(self) -> None: """Update the state.""" value = self._under_voltage.get() if self._attr_is_on != value: if value: _LOGGER.warning(DESCRIPTION_UNDER_VOLTAGE) else: _LOGGER.info(DESCRIPTION_NORMALIZED) self._attr_is_on = value
_attr_unique_id = "rpi_power" # only one sensor possible
config.py
import time import hashlib import torch from torch_geometric.data import DataLoader from cgl.utils.params import ParamDict from cgl.data.graph_data import CircuitInMemDataset, CircuitGraphDataset # from cgl.models.gnn import DeepGENNet s = time.time() print('Loading the dataset ...') root = '/store/nosnap/results/ngspice_biased_pmos_gain/two_stage_biased_pmos' cir_dset = CircuitGraphDataset(root=root, mode='train', circuit_type='opamp_biased_pmos') node_output_idx = next(iter(cir_dset.graph_nodes.values()))['V_net6'] vout_idx = torch.where((torch.where(cir_dset[0].output_node_mask)[0] == node_output_idx))[0].item() # gain mean and variance gmean, gstd = -1.1057, 0.6559 def
(data): data.gain = (data.vac_mag[vout_idx, 0].float() - gmean) / gstd return data dset = CircuitInMemDataset(root=root, mode='train', transform=transform_fn) print(f'Dataset was loaded in {time.time() - s:.6f} seconds.') sample_data = dset[0] fract = 0.05 splits = dset.splits train_idx = int(fract * len(splits['train'])) train_dset = dset[splits['train'][:train_idx]] valid_dset = dset[splits['valid']] test_dset = dset[splits['test']] backbone_config = 'configs/opamp/dc/deep_gen_net/15-layer/config.py' bb_id = hashlib.sha256(backbone_config.encode('utf-8')).hexdigest()[:6] lr = 1e-3 activation = 'relu' hidden_channels = 128 num_layers = 15 train_batch_size = min(256, len(train_dset)) valid_batch_size = min(256, len(valid_dset)) test_batch_size = min(256, len(test_dset)) exp_name = f'GAIN_PMOS_FT_Pool_{fract*10:.1f}_DeepGEN_h{hidden_channels}_nl{num_layers}_bs{train_batch_size}_lr{lr:.0e}_{activation}' mdl_config = ParamDict( exp_name=exp_name, num_nodes=sample_data.vdc.shape[0], in_channels=sample_data.x.shape[-1] + sample_data.type_tens.shape[-1], hidden_channels=hidden_channels, num_layers=num_layers, dropout=0, activation=activation, bins=50, lr=lr, freeze_backbone=False, use_pooling=True, output_label='gain', output_sigmoid=False, lr_warmup={'peak_lr': lr, 'weight_decay': 0, 'warmup_updates': 50, 'tot_updates': 20000, 'end_lr': 5e-5}, ) train_dloader = DataLoader(train_dset, batch_size=train_batch_size, shuffle=True, num_workers=0) valid_dloader = DataLoader(valid_dset, batch_size=valid_batch_size, num_workers=0) test_dloader = DataLoader(test_dset, batch_size=test_batch_size, num_workers=0) # .to converts the weight dtype to match input # model = DeepGENNet(mdl_config).to(sample_data.x.dtype)
transform_fn
max_test.go
package funk import ( "github.com/stretchr/testify/assert" "testing" ) func TestMaxWithArrayNumericInput(t *testing.T) { //Test Data d1 := []int{8, 3, 4, 44, 0} n1 := []int{} d2 := []int8{3, 3, 5, 9, 1} n2 := []int8{} d3 := []int16{4, 5, 4, 33, 2} n3 := []int16{} d4 := []int32{5, 3, 21, 15, 3} n4 := []int32{} d5 := []int64{9, 3, 9, 1, 2} n5 := []int64{} //Calls r1 := MaxInt(d1) c1 := MaxInt(n1) r2 := MaxInt8(d2) c2 := MaxInt8(n2) r3 := MaxInt16(d3) c3 := MaxInt16(n3) r4 := MaxInt32(d4) c4 := MaxInt32(n4) r5 := MaxInt64(d5) c5 := MaxInt64(n5) // Assertions assert.Equal(t, int(44), r1, "It should return the max value in array") assert.Equal(t, nil, c1, "It should return nil") assert.Equal(t, int8(9), r2, "It should return the max value in array") assert.Equal(t, nil, c2, "It should return nil") assert.Equal(t, int16(33), r3, "It should return the max value in array") assert.Equal(t, nil, c3, "It should return nil") assert.Equal(t, int32(21), r4, "It should return the max value in array") assert.Equal(t, nil, c4, "It should return nil") assert.Equal(t, int64(9), r5, "It should return the max value in array") assert.Equal(t, nil, c5, "It should return nil") } func TestMaxWithArrayFloatInput(t *testing.T) { //Test Data d1 := []float64{2, 38.3, 4, 4.4, 4} n1 := []float64{} d2 := []float32{2.9, 1.3, 4.23, 4.4, 7.7} n2 := []float32{} //Calls r1 := MaxFloat64(d1) c1 := MaxFloat64(n1) r2 := MaxFloat32(d2) c2 := MaxFloat32(n2) // Assertions assert.Equal(t, float64(38.3), r1, "It should return the max value in array") assert.Equal(t, nil, c1, "It should return nil") assert.Equal(t, float32(7.7), r2, "It should return the max value in array") assert.Equal(t, nil, c2, "It should return nil") }
d1 := []string{"abc", "abd", "cbd"} d2 := []string{"abc", "abd", "abe"} d3 := []string{"abc", "foo", " "} d4 := []string{"abc", "abc", "aaa"} n1 := []string{} //Calls r1 := MaxString(d1) r2 := MaxString(d2) r3 := MaxString(d3) r4 := MaxString(d4) c1 := MaxString(n1) // Assertions assert.Equal(t, "cbd", r1, "It should print cbd because its first char is max in the list") assert.Equal(t, "abe", r2, "It should print abe because its first different char is max in the list") assert.Equal(t, "foo", r3, "It should print foo because its first different char is max in the list") assert.Equal(t, "abc", r4, "It should print abc because its first different char is max in the list") assert.Equal(t, nil, c1, "It should return nil") }
func TestMaxWithArrayInputWithStrings(t *testing.T) { //Test Data
trainUtils.ts
/** * @module botbuilder-ai */ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { QnAMakerEndpoint } from '../qnamaker-interfaces/qnamakerEndpoint'; import { FeedbackRecords } from '../qnamaker-interfaces/feedbackRecords'; import { HttpRequestUtils } from './httpRequestUtils'; /** * Generate Answer api utils class. * * @remarks * This class is helper class for generate answer api, which is used to make queries to a single QnA Maker knowledge base and return the result. */ export class
{ httpRequestUtils: HttpRequestUtils; /** * Creates new instance for active learning train utils. * @param endpoint The endpoint of the knowledge base to query. */ constructor (private readonly endpoint: QnAMakerEndpoint) { this.httpRequestUtils = new HttpRequestUtils(); } /** * Train API to provide feedback. * @param feedbackRecords Feedback record list. */ public async callTrain(feedbackRecords: FeedbackRecords) { if (!feedbackRecords) { throw new TypeError('Feedback records can not be null.'); } if (!feedbackRecords.feedbackRecords || feedbackRecords.feedbackRecords.length == 0) { return; } await this.queryTrain(feedbackRecords); } private async queryTrain(feedbackRecords: FeedbackRecords) { const url: string = `${ this.endpoint.host }/knowledgebases/${ this.endpoint.knowledgeBaseId }/train`; var payloadBody = JSON.stringify({ feedbackRecords: feedbackRecords.feedbackRecords }); await this.httpRequestUtils.executeHttpRequest(url, payloadBody, this.endpoint); } }
TrainUtils
test_special_actors.py
from __future__ import absolute_import, division, print_function, unicode_literals from wowp.actors.special import Splitter, Chain from wowp.schedulers import NaiveScheduler from wowp.actors import FuncActor from wowp.util import ConstructorWrapper def test_splitter(): splitter = Splitter(multiplicity=2, inport_name="x") assert len(splitter.outports) == 2 scheduler = NaiveScheduler() for i in range(0, 10): scheduler.put_value(splitter.inports.x, i) scheduler.execute() x1_all = list(splitter.outports["x_1"].pop_all()) x2_all = list(splitter.outports["x_2"].pop_all()) print("x1:", x1_all) print("x2:", x2_all) assert [0, 2, 4, 6, 8] == x1_all assert [1, 3, 5, 7, 9] == x2_all def double_me(x):
def test_chain(): func_generator = ConstructorWrapper(FuncActor, double_me) chain = Chain("func_chain", [func_generator, func_generator]) wf = chain.get_workflow() res = wf(inp=4) assert res["out"].pop() == 16 res = wf(inp=2) assert res["out"].pop() == 8 res = wf(inp="a") assert res["out"].pop() == "aaaa"
return x * 2
interactions.py
from view_common import * class DashboardSliceInteractions(View): def get(self, request, name="users", **kwargs): colors = ["#005586", "#6ebe49", "orange", "#707170", "#00c4b3", "#077767", "dodgerblue", "#a79b94", "#c4e76a", "red"] groups = [] matrix = [] slices = list(Slice.objects.all()) ids_by_slice = self.build_id_list(slices, name) slices = [x for x in slices if (len(ids_by_slice[x])>0)] for i,slice in enumerate(slices): groups.append({"name": slice.name, "color": colors[i%len(colors)]}) row=self.buildMatrix(slice, slices, name, ids_by_slice) matrix.append(row) result = {"groups": groups, "matrix": matrix} if name=="users": result["title"] = "Slice interactions by user privilege" result["objectName"] = "users" elif name=="networks": result["title"] = "Slice interactions by network membership" result["objectName"] = "networks" elif name=="sites": result["title"] = "Slice interactions by site ownership" result["objectName"] = "sites" elif name=="instance_sites": result["title"] = "Slice interactions by instance sites" result["objectName"] = "sites" elif name=="instance_nodes": result["title"] = "Slice interactions by instance nodes" result["objectName"] = "nodes" return HttpResponse(json.dumps(result), content_type='application/javascript') def build_id_list(self, slices, name): ids_by_slice = {} for slice in slices: # build up a list of object ids that are used by each slice ids_by_slice[slice] = self.getIds(slice, name) return ids_by_slice def buildMatrix(self, slice, slices, name, ids_by_slice): not_only_my_ids = []
if not id in not_only_my_ids: not_only_my_ids.append(id) # build up a list of ids that are used only by the slice, and not # shared with any other slice only_my_ids = [] for id in ids_by_slice[slice]: if id not in not_only_my_ids: only_my_ids.append(id) row = [] for otherSlice in ids_by_slice.keys(): if (otherSlice == slice): row.append(len(only_my_ids)) else: row.append(self.inCommonIds(ids_by_slice[slice], ids_by_slice[otherSlice])) return row def getIds(self, slice, name): ids=[] if name=="users": for sp in slice.slice_privileges.all(): if sp.user.id not in ids: ids.append(sp.user.id) elif name=="networks": for sp in slice.networkslices.all(): if sp.network.id not in ids: ids.append(sp.network.id) elif name=="sites": ids = [slice.site.id] elif name=="instance_sites": for sp in slice.instances.all(): if sp.node.site.id not in ids: ids.append(sp.node.site.id) elif name=="instance_nodes": for sp in slice.instances.all(): if sp.node.id not in ids: ids.append(sp.node.id) return ids def inCommonIds(self, ids1, ids2): count = 0 for id in ids1: if id in ids2: count+=1 return count
# build up a list of object ids that are used by other slices for otherSlice in ids_by_slice.keys(): if (slice != otherSlice): for id in ids_by_slice[otherSlice]:
sort.go
package bed import ( "sort" "strings" ) type BedSlice []Bed func HeapSort(a BedSlice) { a = buildHeap(a) size := len(a) for i := size - 1; i >= 1; i-- { a[0], a[i] = a[i], a[0] size-- heapify(a[:size], 0) } } func QuickSort(beds []Bed) { sort.Slice(beds, func(i, j int) bool { return Compare(beds[i], beds[j]) == -1 }) } func heapify(beds []Bed, i int) []Bed { var l int = 2*i + 1 var r int = 2*i + 2 var max int if l < len(beds) && l >= 0 && Compare(beds[l], beds[i]) < 0 { max = l } else { max = i } if r < len(beds) && r >= 0 && Compare(beds[r], beds[max]) < 0 { max = r } if max != i { beds[i], beds[max] = beds[max], beds[i] beds = heapify(beds, max) } return beds } func buildHeap(a []Bed) []Bed { for i := len(a)/2 - 1; i >= 0; i-- { a = heapify(a, i) } return a } func Compare(a Bed, b Bed) int { if chrName := strings.Compare(a.Chrom(), b.Chrom()); chrName != 0 { return chrName }
if a.ChrStart() > b.ChrStart() { return 1 } if a.ChrEnd() < b.ChrEnd() { return -1 } if a.ChrEnd() > b.ChrEnd() { return 1 } return 0 } func Len(b Bed) int { return b.ChrEnd() - b.ChrStart() }
if a.ChrStart() < b.ChrStart() { return -1 }
TreeTableHeader.tsx
/* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable @typescript-eslint/ban-types */ import React from 'react'; import styles from './treeTableHeader.css'; import { Column } from '../types'; export interface TreeTableHeaderProps<R> { columns: Array<Column<R>>, scrollPadding: number, } function
<R extends object = {}>({ columns, scrollPadding, }: TreeTableHeaderProps<R>): React.ReactElement<TreeTableHeaderProps<R>> { return ( <div className={styles.treeTableHeader} style={{ paddingRight: scrollPadding }}> {columns.map((column) => { // Do not display hidden columns if (column.hidden) { return null; } const header = column.headerName ? column.headerName : column.accessor; const colWidth = typeof column.width !== 'undefined' || column.width !== 0 ? column.width : null; const styling = { width: colWidth, flex: colWidth ? `${colWidth} 0 auto` : null, }; return ( // @ts-ignore <div style={{ ...styling, ...column.headerStyle }} className={styles.treeTableHeaderCell} key={header}> {header} </div> ); })} </div> ); } export default TreeTableHeader;
TreeTableHeader
geo_operations.py
# # Copyright (c) 2018 Via Technology Ltd. All Rights Reserved. # Consult your license regarding permissions and restrictions. # """ operations related to airspaces and intersections. """ from psycopg2 import Error, InternalError from psycopg2.extensions import AsIs from psycopg2.extras import DictCursor from itertools import filterfalse from functools import reduce from shapely.wkt import loads import pru.db.context as ctx from pru.logger import logger log = logger(__name__) def make_point(lon, lat, connection): """ Makes a geo point """ cursor = connection.cursor() query = "SELECT ST_MakePoint(%s, %s)" params = (float(lon), float(lat)) cursor.execute(query, params) return cursor.fetchone() def make_augmented_point_from_position(position, flight_id, connection): """ Takes a position tuple and makes a augmented point. """ point = make_point(position[1], position[0], connection) return {'flight_id': flight_id, 'lon': position[1], 'lat': position[0], 'geoPoint': point} def make_augmented_points_from_positions(latitudes, longitudes, flight_id, connection): """ Takes a list of latitudes and a list of longitudes and a flight_id. Makes a list of augmented points. """ return [make_augmented_point_from_position(position, flight_id, connection) for position in zip(latitudes, longitudes)] def extract_point_list_from_augmented_points(augmented_points): """ Given a list or generator of augmented points extract the geo point representation as a list. """ return list(map(lambda augmented_points: augmented_points['geoPoint'], augmented_points)) def make_line_from_augmented_points(augmented_points, flight_id, connection): """ Given a list of augmented points create a geographic line. """ if (len(augmented_points) == 0): log.warning(f"Creating a line from a list of points but the list " "was empty for flight id {flight_id}.") return [[]] cursor = connection.cursor() query = "SELECT ST_AsEWKT(ST_MakeLine(ARRAY[%s]));" params = [augmented_points] cursor.execute(query, params) return cursor.fetchone() def find_sectors_intersected_by(line_string, flight_id, min_altitude, max_altitude, context, connection): """ Lists the airspace ids and details of those airspaces where the given line string intersects excluding those that are outside of the range of altitudes of the trajectory. """ log.debug(f"Finding trajectory intersection with airspaces for flight id: {flight_id}") schema_name = context[ctx.SCHEMA_NAME] try: with connection.cursor() as cursor: query = "SELECT id, av_airspace_id, min_altitude, max_altitude " \ "from %s.sectors where " \ "NOT (max_altitude < %s OR min_altitude > %s) AND " \ "ST_Intersects(wkt, ST_GeographyFromText('SRID=4326;%s'));" params = [AsIs(schema_name), min_altitude, max_altitude, AsIs(line_string)] cursor.execute(query, params) return cursor.fetchall() except InternalError: log.exception(f"Failed whist trying to find the intersection between " "a route with flight id {flight_id} and the airspace model.") return [] def find_user_sectors_intersected_by(line_string, flight_id, min_altitude, max_altitude, context, connection): """ Lists the user defined airspace uids and details of those airspaces where the given line string intersects. """ log.debug(f"Finding trajectory intersection with user defined airspaces for flight id: {flight_id}") schema_name = context[ctx.SCHEMA_NAME] try: with connection.cursor() as cursor: query = "SELECT id, org_id, min_altitude, max_altitude, user_id, " \ "sector_name from %s.user_defined_sectors where " \ "NOT (max_altitude < %s OR min_altitude > %s) AND " \ "ST_Intersects(wkt, ST_GeographyFromText('SRID=4326;%s'));" params = [AsIs(schema_name), min_altitude, max_altitude, AsIs(line_string)] cursor.execute(query, params) return cursor.fetchall() except InternalError: log.exception(f"Failed whist trying to find the intersection between " "a route with flight id {flight_id} and the airspace model.") return [] def make_geographic_trajectory(augmented_points, flight_id, connection): """ Given a list of augmented points create a geographic line segment. """ log.debug(f"Making geo trajectory for flight id: {flight_id}") return make_line_from_augmented_points( extract_point_list_from_augmented_points(augmented_points), flight_id, connection)[0] def make_augmented_trajectory(augmented_points, geographic_trajectory, flight_id, min_altitude, max_altitude, connection, is_user_defined=False): """ Makes a trajectory augmented with geographic positions and a list of sectors intersected by the trajectory excluding those that do not meet the altitude range of the trajectory. """ log.debug(f"Creating an augmented trajectory for flight id: {flight_id}") if not is_user_defined: sectors = find_sectors_intersected_by(geographic_trajectory, flight_id, min_altitude, max_altitude, ctx.CONTEXT, connection) else: sectors = find_user_sectors_intersected_by(geographic_trajectory, flight_id, min_altitude, max_altitude, ctx.CONTEXT, connection) return {'extendedPoints': augmented_points, 'line': geographic_trajectory, 'sectors': sectors, 'is_user_defined': is_user_defined} def find_sector(db_ID, connection): schemaName = ctx.CONTEXT[ctx.SCHEMA_NAME] with connection.cursor(cursor_factory=DictCursor) as cursor: cursor.execute("SELECT id, av_airspace_id, av_icao_state_id, av_name, min_altitude, max_altitude FROM %s.sectors WHERE " "id = %s", [AsIs(schemaName), db_ID]) return cursor.fetchone() def find_sector_identifiers(db_ID, context, connection): """ Finds the identifiers for a sector given the db id of the sector. """ schemaName = context[ctx.SCHEMA_NAME] with connection.cursor(cursor_factory=DictCursor) as cursor: cursor.execute("SELECT av_airspace_id, av_icao_state_id, av_name FROM %s.sectors WHERE " "id = %s", [AsIs(schemaName), db_ID]) return cursor.fetchmany() def find_airspace_by_database_ID(db_ID, context, connection, is_user_defined=False): """ Finds an aairspace with the given database id Returns a list, list may be empty. """ schemaName = context[ctx.SCHEMA_NAME] with connection.cursor(cursor_factory=DictCursor) as cursor: if is_user_defined: cursor.execute("SELECT * FROM %s.user_defined_sectors WHERE " "id = %s", [AsIs(schemaName), db_ID]) return cursor.fetchmany() else: cursor.execute("SELECT * FROM %s.sectors WHERE " "id = %s", [AsIs(schemaName), db_ID]) return cursor.fetchmany() def
(first_point, polygon_string, flight_id, sector_id, connection): """ If the first point is inside the given sector we determine that the trajectory originates in the sector. first_point wkb for the first point of the trajectory returns True => originates in sectors """ cursor = connection.cursor() query = "SELECT ST_Intersects(%s::geography, %s::geography);" params = [first_point, polygon_string] cursor.execute(query, params) originates = cursor.fetchone()[0] if originates: log.debug(f"Flight with id {flight_id} originates in sector {sector_id}") return originates def find_line_poly_intersection_without_boundary(lineString, polygonString, connection): """ Use the geo db to find the intersections between the linestring and the unbounded polygon string. The polygon is assumed to _NOT_ have a boundary around it. """ query = "SELECT ST_AsText(ST_Intersection(%s::geography, ST_Force2D(ST_Boundary(%s))::geography));" params = [lineString, polygonString] try: with connection.cursor() as cursor: cursor.execute(query, params) res = cursor.fetchall() return {'segmentStrings': res, 'ploygonString': polygonString} except Error: log.exception("Failed to find intersection : Error") return [] def find_line_poly_intersection_with_boundary(lineString, polygonString, connection): """ Use the geo db to find the intersections between the linestring and the bounded polygon string. The polygon is assumed to already have a boundary around it. """ query = "SELECT unit.find_intersections(%s, %s)" params = [lineString, polygonString] try: with connection.cursor() as cursor: cursor.execute(query, params) res = cursor.fetchall() return {'segmentStrings': res, 'ploygonString': polygonString} except Error: log.exception("Failed to find intersection : Error") return [] def find_intersections(augmented_trajectory, min_altitude, max_altitude, flight_id, connection): """ Finds the points on the trajectory that intersect with the sectors of the the augmented trajectory. """ log.debug(f"Finding intersection for flight id {flight_id}") first_point = augmented_trajectory['extendedPoints'][0]['geoPoint'] first_point_lon = augmented_trajectory['extendedPoints'][0]['lon'] first_point_lat = augmented_trajectory['extendedPoints'][0]['lat'] is_user_defined = augmented_trajectory['is_user_defined'] # Find each sector sector_IDs = [sector[0] for sector in augmented_trajectory['sectors']] log.debug("Found sector ids %s", str(sector_IDs)) sectors = [find_airspace_by_database_ID(str(sector_id), ctx.CONTEXT, connection, is_user_defined)[0] for sector_id in sector_IDs] # Find the points of the trajectory where the trajectory intersects # with each sector if is_user_defined: segments = [{'flight_id': flight_id, 'intersections': find_line_poly_intersection_with_boundary(augmented_trajectory['line'], sector['bounded_sector'], connection), 'origin': {'is_origin': originates(first_point, sector['wkt'], flight_id, sector['id'], connection), 'origin_lat': first_point_lat, 'origin_lon': first_point_lon}, 'id': sector['id'], 'org_id': sector['org_id'], 'user_id': sector['user_id'], 'sector_name': sector['sector_name'], 'min_altitude': sector['min_altitude'], 'max_altitude': sector['max_altitude'], 'is_cylinder': sector['is_cylinder'], 'is_user_defined': is_user_defined} for sector in sectors] else: segments = [{'flight_id': flight_id, 'intersections': find_line_poly_intersection_with_boundary(augmented_trajectory['line'], sector['bounded_sector'], connection), 'origin': {'is_origin': originates(first_point, sector['wkt'], flight_id, sector['id'], connection), 'origin_lat': first_point_lat, 'origin_lon': first_point_lon}, 'id': sector['id'], 'av_icao_state_id': sector['av_icao_state_id'], 'av_name': sector['av_name'], 'av_airspace_id': sector['av_airspace_id'], 'min_altitude': sector['min_altitude'], 'max_altitude': sector['max_altitude'], 'is_user_defined': is_user_defined} for sector in sectors] return segments def extract(sector_id, shape, flight_id): """ Given a shapley shape find if we have a point or a multipoint. For a point extract the y, x pair as a list of one tuple of sector_id, latitude and longitude. For a multipoint return a list of multiple tuples. """ if shape.geom_type == 'MultiPoint': return [(sector_id, p.y, p.x) for p in shape] elif shape.geom_type == 'Point': return [(sector_id, shape.y, shape.x)] else: log.debug("Unknown geom type : %s in flight id %s and sector_id %s, was %s, skipping", shape.geom_type, flight_id, sector_id, str(shape)) return [] def extract_details_from_intersection(sector_id, wkt, origin, flight_id): """ Given an intersection wkt use shapley to create the point or multipoint object. Then extract the latitude and longitudes from the (multi)point. Returns a list of tuples of sector_id, latiitude and longitude """ intersection_tuples = extract(sector_id, loads(wkt), flight_id) if origin['is_origin']: # If this sector is an origin sector, add in the lat lons at the start. intersection_tuples = [(sector_id, origin['origin_lat'], origin['origin_lon'])] + intersection_tuples return intersection_tuples def make_sector_description(intersection, is_user_defined=False): """ Makes a text description of the sector from the intersection description """ if is_user_defined: return f'{intersection["org_id"]}/{intersection["user_id"]}/{intersection["sector_name"]}' else: return f'{intersection["av_icao_state_id"]}/{intersection["av_name"]}/{intersection["id"]}/{intersection["av_airspace_id"]}' def make_sector_identifier(intersection): """ Makes a text version of the database id in the given intersection """ return f'{intersection["id"]}' def extract_intersection_wkts(intersections): """ Given a list of intersection dicts return a list of wkts with sector descriptive text and the origin details as a tuple. ie ("some-text-made-from-sector-ids", wkt, {is_origin:False, origin_lat:lat, origin_lon: lon}) """ return [(make_sector_identifier(intersection), intersection['intersections']['segmentStrings'][0][0], intersection['origin']) for intersection in intersections] def merge_l_t(l, lt): """ Merge a list of tuples lt, each of three values into three lists l. For example: [('a', 'b', 'c'), ('a', 'd', 'e')] -> [['a', 'a'], ['b', 'd'], ['c', 'e']] """ for t in lt: l[0].append(t[1]) l[1].append(t[2]) l[2].append(t[0]) return l def create_intersection_data_structure(intersections, flight_id): """ Given the intersection data structures create a response tuple. """ # The intersection wkts are tuples of the sector_id, the wkt and the origin # status for the intersection. intersection_wkts = extract_intersection_wkts(intersections) intersection_details = [extract_details_from_intersection(*intersection_wkt, flight_id) for intersection_wkt in intersection_wkts] x_y_sector_ids = reduce(merge_l_t, intersection_details, [[], [], []]) return x_y_sector_ids[0], x_y_sector_ids[1], x_y_sector_ids[2]
originates
offset_table.rs
use std::prelude::v1::*; use dataview::Pod; use std::convert::TryFrom; use std::str; /// Describes an offset file. /// At compile time this crate will create a binary blob of all /// TOML files contained in the memflow-win32/offsets/ folder /// and merge the byte buffer directly into the build. /// /// This byte buffer is then transmuted back into a slice of /// Win32OffsetFile structs and parsed as a backup in case /// no symbol store is available. /// /// To get loaded properly this struct guarantees a certain alignment and no padding. /// This is enforced due to a compile time assert as well as the Pod derive itself. /// Especially in the case of cross-compilation where the target architecture /// is different from the architecture memflow is built with this could give potential issues. /// // # Safety // This struct guarantees that it does not contain any padding. #[repr(C, align(4))] #[derive(Clone, Pod)] #[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))] pub struct Win32OffsetFile { // Win32GUID #[cfg_attr(feature = "serde", serde(default))] pub pdb_file_name: BinaryString, #[cfg_attr(feature = "serde", serde(default))] pub pdb_guid: BinaryString, // Win32Version pub nt_major_version: u32, pub nt_minor_version: u32, pub nt_build_number: u32, // Architecture pub arch: Win32OffsetsArchitecture, pub offsets: Win32OffsetTable, } const _: [(); std::mem::size_of::<[Win32OffsetFile; 16]>()] = [(); 16 * std::mem::size_of::<Win32OffsetFile>()]; #[repr(u32)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))] pub enum Win32OffsetsArchitecture { X86 = 0, X64 = 1, AArch64 = 2, } impl std::fmt::Display for Win32OffsetsArchitecture { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self) } } unsafe impl Pod for Win32OffsetsArchitecture {} // TODO: use const-generics here once they are fully stabilized #[derive(Clone)] pub struct BinaryString(pub [u8; 128]); impl Default for BinaryString { fn default() -> Self { (&[][..]).into() } } impl<'a> From<&'a [u8]> for BinaryString { fn from(other: &'a [u8]) -> Self { let mut arr = [0; 128]; arr[..other.len()].copy_from_slice(other); Self { 0: arr } } } impl<'a> TryFrom<&'a BinaryString> for &'a str { type Error = std::str::Utf8Error; fn try_from(other: &'a BinaryString) -> Result<Self, Self::Error> { Ok(str::from_utf8(&other.0)? .split_terminator('\0') .next() .unwrap()) } } impl<'a> From<&'a str> for BinaryString { fn
(other: &'a str) -> Self { let mut arr = [0; 128]; arr[..other.len()].copy_from_slice(other.as_bytes()); Self { 0: arr } } } impl From<String> for BinaryString { fn from(other: String) -> Self { Self::from(other.as_str()) } } unsafe impl Pod for BinaryString {} #[cfg(feature = "serde")] impl ::serde::Serialize for BinaryString { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ::serde::Serializer, { serializer.serialize_str( <&str>::try_from(self) .map_err(|_| ::serde::ser::Error::custom("invalid UTF-8 characters"))?, ) } } #[cfg(feature = "serde")] impl<'de> ::serde::de::Deserialize<'de> for BinaryString { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: ::serde::de::Deserializer<'de>, { struct BinaryStringVisitor; impl<'de> ::serde::de::Visitor<'de> for BinaryStringVisitor { type Value = [u8; 128]; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("a string containing json data") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: ::serde::de::Error, { // unfortunately we lose some typed information // from errors deserializing the json string let mut result = [0u8; 128]; result[..v.len()].copy_from_slice(v.as_bytes()); Ok(result) } } // use our visitor to deserialize an `ActualValue` let inner: [u8; 128] = deserializer.deserialize_any(BinaryStringVisitor)?; Ok(Self { 0: inner }) } } #[repr(C, align(4))] #[derive(Debug, Clone, Pod)] #[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))] pub struct Win32OffsetTable { pub list_blink: u32, pub eproc_link: u32, /// Since version 3.10 pub kproc_dtb: u32, /// Since version 3.10 pub eproc_pid: u32, /// Since version 3.10 pub eproc_name: u32, /// Since version 5.10 pub eproc_peb: u32, /// Since version 3.10 pub eproc_section_base: u32, /// Since version 3.10 pub eproc_exit_status: u32, /// Since version 5.10 pub eproc_thread_list: u32, /// Since version 5.0 pub eproc_wow64: u32, /// Since version 6.2 pub kthread_teb: u32, /// Since version 6.2 pub ethread_list_entry: u32, /// Since version x.x pub teb_peb: u32, /// Since version x.x pub teb_peb_x86: u32, }
from
index.ts
/* tslint:disable */ export { ApiResponse } from './api-response.model'; export { Category } from './category.model'; export { Order } from './order.model'; export { Pet } from './pet.model'; export { Tag } from './tag.model';
export { User } from './user.model';
util.go
package proxy import ( "github.com/coyove/goflyway/pkg/bitsop" "github.com/coyove/goflyway/pkg/logg" "github.com/coyove/goflyway/pkg/lookup" "github.com/coyove/goflyway/pkg/tlds" "crypto/tls" "encoding/base32" "encoding/base64" "io" "io/ioutil" "net" "net/http" "net/url" "regexp" "strings" ) const ( SOCKS5_VERSION = byte(0x05) SOCKS_TYPE_IPv4 = 1 SOCKS_TYPE_Dm = 3 SOCKS_TYPE_IPv6 = 4 DO_HTTP = 0 DO_SOCKS5 = 1 HOST_HTTP_CONNECT = byte(0x00) HOST_HTTP_FORWARD = byte(0x01) HOST_SOCKS_CONNECT = byte(0x02) HOST_IPV6 = byte(0x04) AUTH_HEADER = "X-Authorization" CANNOT_READ_BUF = "socks server: cannot read buffer: " NOT_SOCKS5 = "invalid socks version (socks5 only)" UDP_TIMEOUT = 30 TCP_TIMEOUT = 60 ) var ( OK_HTTP = []byte("HTTP/1.0 200 OK\r\n\r\n") // version, granted = 0, 0, ipv4, 0, 0, 0, 0, (port) 0, 0 OK_SOCKS = []byte{SOCKS5_VERSION, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01} // RSV | FRAG | ATYP | DST.ADDR | DST.PORT | UDP_REQUEST_HEADER = []byte{0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} UDP_REQUEST_HEADER6 = []byte{0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} DUMMY_FIELDS = []string{"Accept-Language", "User-Agent", "Referer", "Cache-Control", "Accept-Encoding", "Connection"} tlsSkip = &tls.Config{InsecureSkipVerify: true} hostHeadExtract = regexp.MustCompile(`(\S+)\.com`) urlExtract = regexp.MustCompile(`\?q=(\S+)$`) hasPort = regexp.MustCompile(`:\d+$`) base32Encoding = base32.NewEncoding("0123456789abcdefghiklmnoprstuwxy") ) func SafeAddHeader(req *http.Request, k, v string) { if orig := req.Header.Get(k); orig != "" { req.Header.Set(k, v+" "+orig) } else { req.Header.Add(k, v) } } func SafeGetHeader(req *http.Request, k string) string { v := req.Header.Get(k) if s := strings.Index(v, " "); s > 0 { req.Header.Set(k, v[s+1:]) v = v[:s] } return v } func (proxy *ProxyClient) addToDummies(req *http.Request) { for _, field := range DUMMY_FIELDS { if x := req.Header.Get(field); x != "" { proxy.dummies.Add(field, x) } } } func (proxy *ProxyClient) encryptRequest(req *http.Request) []byte { req.Host = EncryptHost(proxy.GCipher, req.Host, HOST_HTTP_FORWARD) req.URL, _ = url.Parse("http://" + req.Host + "/?q=" + proxy.GCipher.EncryptString(req.URL.String())) rkey, rkeybuf := proxy.GCipher.RandomIV() SafeAddHeader(req, proxy.rkeyHeader, rkey) for _, c := range req.Cookies() { c.Value = proxy.GCipher.EncryptString(c.Value) } req.Body = ioutil.NopCloser((&IOReaderCipher{ Src: req.Body, Key: rkeybuf, Cipher: proxy.GCipher, }).Init()) return rkeybuf } func (proxy *ProxyUpstream) decryptRequest(req *http.Request, rkeybuf []byte) { req.Host = DecryptHost(proxy.GCipher, req.Host, HOST_HTTP_FORWARD) if p := urlExtract.FindStringSubmatch(req.URL.String()); len(p) > 1 { req.URL, _ = url.Parse(proxy.GCipher.DecryptString(p[1])) req.RequestURI = req.URL.String() } for _, c := range req.Cookies() { c.Value = proxy.GCipher.DecryptString(c.Value) } req.Body = ioutil.NopCloser((&IOReaderCipher{ Src: req.Body, Key: rkeybuf, Cipher: proxy.GCipher, }).Init()) } func copyHeaders(dst, src http.Header) { for k := range dst { dst.Del(k) } for k, vs := range src { for _, v := range vs { dst.Add(k, v) } } } func (proxy *ProxyClient) basicAuth(token string) string { parts := strings.Split(token, " ") if len(parts) != 2 { return "" } pa, err := base64.StdEncoding.DecodeString(strings.TrimSpace(parts[1])) if err != nil { return "" } if s := string(pa); s == proxy.UserAuth { return s } else { return "" } } func getAuth(r *http.Request) string { pa := r.Header.Get("Proxy-Authorization") if pa == "" { pa = r.Header.Get(AUTH_HEADER) } return pa } func tryClose(b io.ReadCloser) { if err := b.Close(); err != nil { logg.W("can't close: ", err) } } func splitHostPort(host string) (string, string) { if idx := strings.LastIndex(host, ":"); idx > 0 { idx2 := strings.LastIndex(host, "]") if idx2 < idx { return strings.ToLower(host[:idx]), host[idx:] } // ipv6 without port } return strings.ToLower(host), "" } func EncryptHost(c *GCipher, text string, mark byte) string
func DecryptHost(c *GCipher, text string, mark byte) string { host, m := TryDecryptHost(c, text) if m != mark { return "" } else { return host } } func TryDecryptHost(c *GCipher, text string) (h string, m byte) { host, port := splitHostPort(text) parts := strings.Split(host, ".") for i := len(parts) - 1; i >= 0; i-- { if !tlds.TLDs[parts[i]] { buf := c.Decrypt(Base32Decode(parts[i])) if len(buf) == 0 { return text, 0 } mark := buf[0] >> 5 if (mark & HOST_IPV6) != 0 { if ipv6 := net.IP(buf[1:]).To16(); ipv6 != nil { return "[" + ipv6.String() + "]" + port, mark - HOST_IPV6 } else { return "", 0 } } m, parts[i] = bitsop.Decompress(buf) if len(parts[i]) == 0 { return text, 0 } break } } return strings.Join(parts, ".") + port, m } func isTrustedToken(mark string, rkeybuf []byte) bool { if string(rkeybuf[:len(mark)]) != mark { return false } b := rkeybuf[len(mark)] for i := len(mark) + 1; i < IV_LENGTH; i++ { if rkeybuf[i] >= b { return false } } return true } func genTrustedToken(mark string, gc *GCipher) []byte { ret := make([]byte, IV_LENGTH) copy(ret, []byte(mark)) n := gc.Rand.Intn(128) ret[len(mark)] = byte(n) for i := len(mark) + 1; i < IV_LENGTH; i++ { ret[i] = byte(gc.Rand.Intn(n)) } return ret } func Base32Encode(buf []byte) string { str := base32Encoding.EncodeToString(buf) idx := strings.Index(str, "=") if idx == -1 { return str } return str[:idx] //+ base32Replace[len(str)-idx-1] } func Base32Decode(text string) []byte { const paddings = "======" if m := len(text) % 8; m > 1 { text = text + paddings[:8-m] } buf, err := base32Encoding.DecodeString(text) if err != nil { return []byte{} } return buf } func genWord(gc *GCipher) string { const ( vowels = "aeiou" cons = "bcdfghlmnprst" ) ret := make([]byte, 16) gc.Block.Encrypt(ret, gc.Key) ret[0] = (vowels + cons)[ret[0]/15] i, ln := 1, int(ret[15]/85)+6 link := func(prev string, this string, thisidx byte) { if strings.ContainsRune(prev, rune(ret[i-1])) { ret[i] = this[ret[i]/thisidx] i++ } } for i < ln { link(vowels, cons, 20) link(cons, vowels, 52) link(vowels, cons, 20) link(cons, vowels+"tr", 37) } ret[0] -= 32 return string(ret[:ln]) }
{ host, port := splitHostPort(text) enc := func(in string) string { return Base32Encode(c.Encrypt(bitsop.Compress(mark, in))) } if lookup.IPAddressToInteger(host) != 0 { return enc(host) + port } if len(host) > 2 && host[0] == '[' && host[len(host)-1] == ']' { ip := net.ParseIP(host[1 : len(host)-1]) if ip != nil { buf := append([]byte{(mark | HOST_IPV6) << 5}, ip...) return Base32Encode(c.Encrypt(buf)) + port } } parts := strings.Split(host, ".") flag := false for i := len(parts) - 1; i >= 0; i-- { if !tlds.TLDs[parts[i]] { parts[i] = enc(parts[i]) flag = true break } } if flag { return strings.Join(parts, ".") + port } return enc(host) + port }
models.py
from vlasisku.utils import compound2affixes class Entry(object): """Container for jbovlaste entry data.""" #: The word (or compound) this entry describes. word = None #: The type of the word, such as ``'gismu'``.
affixes = None #: A list of affixes including four and five-letter versions. searchaffixes = None #: The grammatical class if the word is a particle. grammarclass = None #: The grammatical class of this words terminator, if any. terminator = None #: A list of grammatical classes this word terminates, for terminators. terminates = None #: A list of two-tuples such as ``('<chapter>.<section>', 'http://...')``. cll = None #: HTML for the entry definition, such as a place structure. definition = None #: HTML for notes about the entry. notes = None #: Plain text definition. textdefinition = None #: Plain text notes. textnotes = None #: The :class:`~vlasisku.database.Root` instance this entry is in. db = None # We need new lists for every instance. def __init__(self, db): self.affixes = [] self.searchaffixes = [] self.terminates = [] self.cll = [] self.db = db def __str__(self): return self.word def __repr__(self): return '<Entry %s>' % self.word def components(self): """Build HTML that links the affixes in a compound to their corresponding words, with definitions in the link tooltips. """ if self.type == 'lujvo': components = '' for a in compound2affixes(self.word): if len(a) == 1: components += a else: word = [e for e in self.db.entries.values() if a in e.searchaffixes] if word: components += '<a href="%s" ' % word[0] components += 'title="<strong>%s:</strong> ' % word[0] components += '%s">%s</a>' % (word[0].definition, a) else: components += a return components class Gloss(object): """Container for jbovlaste gloss data.""" #: The actual gloss word. gloss = None #: The :class:`Entry` this glosses to. entry = None #: The sense in which this gloss word relates to the entry, or ``None``. sense = None #: The specific place of the entry this glosses to, if any. place = None def __str__(self): return self.entry.word
type = None #: A list of three-letter affix forms for the word.
display-during-signup.py
#!/usr/bin/python import participantCollection import string import re import datetime import pyperclip #TODO: need to figure out how to get total days in current month... # Remember, this is during signup, so current month is not July, it's June. currentMonthTotalDays = 30 #TODO: fill in the current month url... currentMonthURL = "https://www.reddit.com/r/pornfree/comments/381nyz/stay_clean_june_this_thread_updated_daily_check/" currentMonthIndex = datetime.date.today().month currentMonthPenultimateDayIndex = currentMonthTotalDays - 1 currentMonthName = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'}[currentMonthIndex] nextMonthIndex = currentMonthIndex % 12 + 1 nextMonthName = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'}[nextMonthIndex] uppercaseMonth = string.upper(nextMonthName) currentDayOfMonthIndex = datetime.date.today().day currentDayOfMonthName = {1:'first', 2:'second', 3:'third', 4:'fourth', 5:'fifth', 6:'sixth', 7:'seventh', 8:'eighth', 9:'ninth', 10:'tenth', 11:'eleventh', 12:'twelfth', 13:'thirteenth', 14:'fourteenth', 15:'fifteenth', 16:'sixteenth', 17:'seventeenth', 18:'eighteenth', 19:'nineteenth', 20:'twentieth', 21:'twenty-first', 22:'twenty-second', 23:'twenty-third', 24:'twenty-fourth', 25:'twenty-fifth', 26:'twenty-sixth', 27:'twenty-seventh', 28:'twenty-eighth', 29:'twenty-ninth', 30:'thirtieth', 31:'thirty-first'}[currentDayOfMonthIndex] currentDayOfWeekName = {0:'Monday', 1:'Tuesday', 2:'Wednesday', 3:'Thursday', 4:'Friday', 5:'Saturday', 6:'Sunday'}[datetime.date.today().weekday()] #TODO: testing #currentDayOfMonthIndex = 28 participantCollection = participantCollection.ParticipantCollection() initialNumber = participantCollection.size() def templateForParticipants(): answer = "" answer += "Here are the **INITIAL_NUMBER participants** who have already signed up:\n\n" for participant in participantCollection.participants: answer += "/u/" + participant.name answer += "\n\n" return answer def templateForTooEarly(): answer = "" answer += "(Too early. Come back on CURRENT_MONTH_NAME " + str(currentMonthTotalDays - 6) + ")\n" return answer def templateForFirstSignupDay(): answer = "" answer += "STAY CLEAN: UPPERCASE_MONTH! Sign up here! (CURRENT_MONTH_NAME CURRENT_DAY_OF_MONTH_INDEX)\n" answer += "Hey everybody, we had a great turnout for [Stay Clean: CURRENT_MONTH_NAME](CURRENT_MONTH_URL) - let's see if we can knock it out of the park for NEXT_MONTH_NAME. Have you been clean for the month of CURRENT_MONTH_NAME? Great! Join us here, and let's keep our streak going. Did you slip in CURRENT_MONTH_NAME? Then NEXT_MONTH_NAME is your month to shine, and we will gladly fight the good fight along with you. Did you miss out on the CURRENT_MONTH_NAME challenge? Well then here is your opportunity to join us.\n" answer += "\n" answer += "If you would like to be included in this challenge, please post a brief comment to this thread, and I will include you. After midnight, NEXT_MONTH_NAME 1, the sign up window will close, and the challenge will begin." return answer def templateForMiddleSignupDays(): answer = "" answer += "STAY CLEAN: UPPERCASE_MONTH! Sign up here! (CURRENT_MONTH_NAME CURRENT_DAY_OF_MONTH_INDEX)\n" answer += "Hey everybody, so far **INITIAL_NUMBER participants** have signed up. Have you been clean for **[the month of CURRENT_MONTH_NAME](CURRENT_MONTH_URL)**? Great! Join us here, and let's keep our streak going. Did you slip in CURRENT_MONTH_NAME? Then NEXT_MONTH_NAME is your month to shine, and we will gladly fight the good fight along with you. Did you miss out on the CURRENT_MONTH_NAME challenge? Well then here is your opportunity to join us.\n" answer += "\n" answer += "If you would like to be included in this challenge, please post a brief comment to this thread (if you haven't already done so on an earlier signup thread), and I will include you. After midnight, NEXT_MONTH_NAME 1, the sign up window will close, and the challenge will begin.\n" answer += "\n" answer += templateForParticipants() return answer def templateForLastSignupDay(): answer = "" answer += "LAST CHANCE TO SIGN UP FOR STAY CLEAN: UPPERCASE_MONTH! Sign up here!\n" answer += "The Stay Clean: NEXT_MONTH_NAME challenge **begins tomorrow**! So far, we have **INITIAL_NUMBER participants** signed up. If you would like to be included in the challenge, please post a brief comment to this thread (if you haven't already done so on an earlier signup thread), and we will include you. After midnight tonight, we will not be accepting any more participants. I will create the official update post tomorrow.\n" answer += "\n" answer += templateForParticipants() return answer def templateToUse(): if currentDayOfMonthIndex <= (currentMonthTotalDays - 7): return templateForTooEarly() elif currentDayOfMonthIndex == (currentMonthTotalDays - 6): return templateForFirstSignupDay() elif ( (currentMonthTotalDays - 5) <= currentDayOfMonthIndex <= (currentMonthTotalDays - 1) ): return templateForMiddleSignupDays() elif ( currentMonthTotalDays == currentDayOfMonthIndex ): return templateForLastSignupDay() def stringToPrint():
outputString = stringToPrint() print "=============================================================" print outputString print "=============================================================" pyperclip.copy(outputString)
answer = templateToUse() answer = re.sub( 'INITIAL_NUMBER', str(initialNumber), answer ) answer = re.sub( 'CURRENT_MONTH_INDEX', str(currentMonthIndex), answer ) answer = re.sub( 'CURRENT_MONTH_TOTAL_DAYS', str(currentMonthTotalDays), answer ) answer = re.sub( 'CURRENT_MONTH_PENULTIMATE_DAY_INDEX', str(currentMonthPenultimateDayIndex), answer ) answer = re.sub( 'CURRENT_MONTH_NAME', currentMonthName, answer ) answer = re.sub( 'CURRENT_MONTH_URL', currentMonthURL, answer ) answer = re.sub( 'NEXT_MONTH_INDEX', str(nextMonthIndex), answer ) answer = re.sub( 'NEXT_MONTH_NAME', nextMonthName, answer ) answer = re.sub( 'CURRENT_DAY_OF_MONTH_INDEX', str(currentDayOfMonthIndex), answer ) answer = re.sub( 'CURRENT_DAY_OF_MONTH_NAME', currentDayOfMonthName, answer ) answer = re.sub( 'CURRENT_DAY_OF_WEEK_NAME', currentDayOfWeekName, answer ) answer = re.sub( 'UPPERCASE_MONTH', uppercaseMonth, answer ) return answer
text-input.tsx
import React from 'react'; import { Text, View } from 'react-native'; import { withTheme, IThemeProps } from '../../core/theme/with-theme'; import stylesProvider from './styles'; import { smartConnect } from '../../core/utils/smart-connect'; export interface IExternalProps { word: string; style?: any; styleInputText?: any; onFocus?: any; onBlur?: any; obRef?: any; isFocus?: boolean; isValid?: boolean; placeholder?: string; showBorderBottom: boolean; testID?: string; } interface IState { cursorWidth: number; } export class
extends React.Component< IExternalProps & IThemeProps<ReturnType<typeof stylesProvider>>, IState > { public static renderedTextInputComponents = new Set(); public static focus(ref: any) { if (TextInputComponent.renderedTextInputComponents.has(ref)) { TextInputComponent.renderedTextInputComponents.forEach((r: any) => r === ref ? r.focus() : r.blur() ); } } public cursorInterval = null; constructor(props: IExternalProps & IThemeProps<ReturnType<typeof stylesProvider>>) { super(props); this.state = { cursorWidth: 0 }; props.obRef && props.obRef(this); this.cursorInterval = null; TextInputComponent.renderedTextInputComponents.add(this); } public componentWillUnmount() { TextInputComponent.renderedTextInputComponents.delete(this); } public focus() { if (!this.cursorInterval) { this.cursorInterval = setInterval( () => this.setState({ cursorWidth: (this.state.cursorWidth + 2) % 4 }), 500 ); } } public blur() { clearInterval(this.cursorInterval); this.setState({ cursorWidth: 0 }); this.cursorInterval = null; this.props.onBlur && this.props.onBlur(); } public render() { const { styles, theme } = this.props; let containerBorderBottomColor = theme.colors.textTertiary; if (this.props.isFocus) { containerBorderBottomColor = theme.colors.accent; } else if (this.props.isValid) { containerBorderBottomColor = theme.colors.text; } return ( <View style={[ styles.container, { borderBottomColor: this.props.showBorderBottom && containerBorderBottomColor, borderBottomWidth: this.props.showBorderBottom ? 1 : 0 }, this.props.style ]} onStartShouldSetResponderCapture={() => { TextInputComponent.focus(this); this.props.onFocus(); return true; }} > <Text testID={this.props?.testID || 'textinput'} numberOfLines={1} ellipsizeMode="head" style={[ styles.text, { color: this.props.isFocus ? theme.colors.accent : theme.colors.text }, this.props.styleInputText ]} > {this.props.placeholder && this.props.word === '' && !this.props.isFocus ? this.props.placeholder : this.props.word} </Text> <View style={[styles.cursor, { width: this.state.cursorWidth }]} /> </View> ); } } export const TextInput = smartConnect<IExternalProps>(TextInputComponent, [ withTheme(stylesProvider) ]);
TextInputComponent
server.go
package gopenapi
// Server : https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#fixed-fields-4 type Server struct { URL string `json:"url,omitempty"` Description string `json:"description,omitempty"` Variables map[string]*ServerVariable `json:"variables,omitempty"` }
// Servers type Servers []*Server
_models.py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import msrest.serialization from .._generated.models import ( LexicalAnalyzer, LexicalTokenizer, AnalyzeRequest, CustomAnalyzer as _CustomAnalyzer, PatternAnalyzer as _PatternAnalyzer, PatternTokenizer as _PatternTokenizer, SearchResourceEncryptionKey as _SearchResourceEncryptionKey, SearchIndexerDataSource as _SearchIndexerDataSource, SynonymMap as _SynonymMap, DataSourceCredentials, AzureActiveDirectoryApplicationCredentials ) DELIMITER = "|" class AnalyzeTextOptions(msrest.serialization.Model): """Specifies some text and analysis components used to break that text into tokens. All required parameters must be populated in order to send to Azure. :param text: Required. The text to break into tokens. :type text: str :param analyzer_name: The name of the analyzer to use to break the given text. If this parameter is not specified, you must specify a tokenizer instead. The tokenizer and analyzer parameters are mutually exclusive. Possible values include: "ar.microsoft", "ar.lucene", "hy.lucene", "bn.microsoft", "eu.lucene", "bg.microsoft", "bg.lucene", "ca.microsoft", "ca.lucene", "zh- Hans.microsoft", "zh-Hans.lucene", "zh-Hant.microsoft", "zh-Hant.lucene", "hr.microsoft", "cs.microsoft", "cs.lucene", "da.microsoft", "da.lucene", "nl.microsoft", "nl.lucene", "en.microsoft", "en.lucene", "et.microsoft", "fi.microsoft", "fi.lucene", "fr.microsoft", "fr.lucene", "gl.lucene", "de.microsoft", "de.lucene", "el.microsoft", "el.lucene", "gu.microsoft", "he.microsoft", "hi.microsoft", "hi.lucene", "hu.microsoft", "hu.lucene", "is.microsoft", "id.microsoft", "id.lucene", "ga.lucene", "it.microsoft", "it.lucene", "ja.microsoft", "ja.lucene", "kn.microsoft", "ko.microsoft", "ko.lucene", "lv.microsoft", "lv.lucene", "lt.microsoft", "ml.microsoft", "ms.microsoft", "mr.microsoft", "nb.microsoft", "no.lucene", "fa.lucene", "pl.microsoft", "pl.lucene", "pt-BR.microsoft", "pt-BR.lucene", "pt- PT.microsoft", "pt-PT.lucene", "pa.microsoft", "ro.microsoft", "ro.lucene", "ru.microsoft", "ru.lucene", "sr-cyrillic.microsoft", "sr-latin.microsoft", "sk.microsoft", "sl.microsoft", "es.microsoft", "es.lucene", "sv.microsoft", "sv.lucene", "ta.microsoft", "te.microsoft", "th.microsoft", "th.lucene", "tr.microsoft", "tr.lucene", "uk.microsoft", "ur.microsoft", "vi.microsoft", "standard.lucene", "standardasciifolding.lucene", "keyword", "pattern", "simple", "stop", "whitespace". :type analyzer_name: str or ~azure.search.documents.indexes.models.LexicalAnalyzerName :param tokenizer_name: The name of the tokenizer to use to break the given text. If this parameter is not specified, you must specify an analyzer instead. The tokenizer and analyzer parameters are mutually exclusive. Possible values include: "classic", "edgeNGram", "keyword_v2", "letter", "lowercase", "microsoft_language_tokenizer", "microsoft_language_stemming_tokenizer", "nGram", "path_hierarchy_v2", "pattern", "standard_v2", "uax_url_email", "whitespace". :type tokenizer_name: str or ~azure.search.documents.indexes.models.LexicalTokenizerName :param token_filters: An optional list of token filters to use when breaking the given text. This parameter can only be set when using the tokenizer parameter. :type token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] :param char_filters: An optional list of character filters to use when breaking the given text. This parameter can only be set when using the tokenizer parameter. :type char_filters: list[str] """ _validation = { 'text': {'required': True}, } _attribute_map = { 'text': {'key': 'text', 'type': 'str'}, 'analyzer_name': {'key': 'analyzerName', 'type': 'str'}, 'tokenizer_name': {'key': 'tokenizerName', 'type': 'str'}, 'token_filters': {'key': 'tokenFilters', 'type': '[str]'}, 'char_filters': {'key': 'charFilters', 'type': '[str]'}, } def __init__( self, **kwargs ): super(AnalyzeTextOptions, self).__init__(**kwargs) self.text = kwargs['text'] self.analyzer_name = kwargs.get('analyzer_name', None) self.tokenizer_name = kwargs.get('tokenizer_name', None) self.token_filters = kwargs.get('token_filters', None) self.char_filters = kwargs.get('char_filters', None) def _to_analyze_request(self): return AnalyzeRequest( text=self.text, analyzer=self.analyzer_name, tokenizer=self.tokenizer_name, token_filters=self.token_filters, char_filters=self.char_filters ) class CustomAnalyzer(LexicalAnalyzer): """Allows you to take control over the process of converting text into indexable/searchable tokens. It's a user-defined configuration consisting of a single predefined tokenizer and one or more filters. The tokenizer is responsible for breaking text into tokens, and the filters for modifying tokens emitted by the tokenizer. All required parameters must be populated in order to send to Azure. :param odata_type: Required. Identifies the concrete type of the analyzer.Constant filled by server. :type odata_type: str :param name: Required. The name of the analyzer. It must only contain letters, digits, spaces, dashes or underscores, can only start and end with alphanumeric characters, and is limited to 128 characters. :type name: str :param tokenizer_name: Required. The name of the tokenizer to use to divide continuous text into a sequence of tokens, such as breaking a sentence into words. Possible values include: "classic", "edgeNGram", "keyword_v2", "letter", "lowercase", "microsoft_language_tokenizer", "microsoft_language_stemming_tokenizer", "nGram", "path_hierarchy_v2", "pattern", "standard_v2", "uax_url_email", "whitespace". :type tokenizer_name: str or ~azure.search.documents.indexes.models.LexicalTokenizerName :param token_filters: A list of token filters used to filter out or modify the tokens generated by a tokenizer. For example, you can specify a lowercase filter that converts all characters to lowercase. The filters are run in the order in which they are listed. :type token_filters: list[str or ~azure.search.documents.indexes.models.TokenFilterName] :param char_filters: A list of character filters used to prepare input text before it is processed by the tokenizer. For instance, they can replace certain characters or symbols. The filters are run in the order in which they are listed. :type char_filters: list[str] """ _validation = { 'odata_type': {'required': True}, 'name': {'required': True}, 'tokenizer_name': {'required': True}, } _attribute_map = { 'odata_type': {'key': '@odata\\.type', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'tokenizer_name': {'key': 'tokenizerName', 'type': 'str'}, 'token_filters': {'key': 'tokenFilters', 'type': '[str]'}, 'char_filters': {'key': 'charFilters', 'type': '[str]'}, } def __init__( self, **kwargs ): super(CustomAnalyzer, self).__init__(**kwargs) self.odata_type = '#Microsoft.Azure.Search.CustomAnalyzer' self.tokenizer_name = kwargs['tokenizer_name'] self.token_filters = kwargs.get('token_filters', None) self.char_filters = kwargs.get('char_filters', None) def _to_generated(self): return _CustomAnalyzer( name=self.name, odata_type=self.odata_type, tokenizer=self.tokenizer_name, token_filters=self.token_filters, char_filters=self.char_filters ) @classmethod def _from_generated(cls, custom_analyzer): if not custom_analyzer: return None return cls( name=custom_analyzer.name, odata_type=custom_analyzer.odata_type, tokenizer_name=custom_analyzer.tokenizer, token_filters=custom_analyzer.token_filters, char_filters=custom_analyzer.char_filters ) class PatternAnalyzer(LexicalAnalyzer): """Flexibly separates text into terms via a regular expression. This analyzer is implemented using Apache Lucene. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the analyzer. It must only contain letters, digits, spaces, dashes or underscores, can only start and end with alphanumeric characters, and is limited to 128 characters. :type name: str :param lower_case_terms: A value indicating whether terms should be lower-cased. Default is true. :type lower_case_terms: bool :param pattern: A regular expression to match token separators. Default is an expression that matches one or more white space characters. :type pattern: str :param flags: List of regular expression flags. Possible values of each flag include: 'CANON_EQ', 'CASE_INSENSITIVE', 'COMMENTS', 'DOTALL', 'LITERAL', 'MULTILINE', 'UNICODE_CASE', 'UNIX_LINES'. :type flags: list[str] or list[~search_service_client.models.RegexFlags] :param stopwords: A list of stopwords. :type stopwords: list[str] """ _validation = {"odata_type": {"required": True}, "name": {"required": True}} _attribute_map = { "odata_type": {"key": "@odata\\.type", "type": "str"}, "name": {"key": "name", "type": "str"}, "lower_case_terms": {"key": "lowercase", "type": "bool"}, "pattern": {"key": "pattern", "type": "str"}, "flags": {"key": "flags", "type": "[str]"}, "stopwords": {"key": "stopwords", "type": "[str]"}, } def __init__(self, **kwargs): super(PatternAnalyzer, self).__init__(**kwargs) self.odata_type = "#Microsoft.Azure.Search.PatternAnalyzer" self.lower_case_terms = kwargs.get("lower_case_terms", True) self.pattern = kwargs.get("pattern", r"\W+") self.flags = kwargs.get("flags", None) self.stopwords = kwargs.get("stopwords", None) def _to_generated(self): if not self.flags: flags = None else: flags = DELIMITER.join(self.flags) return _PatternAnalyzer( name=self.name, lower_case_terms=self.lower_case_terms, pattern=self.pattern, flags=flags, stopwords=self.stopwords, ) @classmethod def _from_generated(cls, pattern_analyzer): if not pattern_analyzer: return None if not pattern_analyzer.flags: flags = None else: flags = pattern_analyzer.flags.split(DELIMITER) return cls( name=pattern_analyzer.name, lower_case_terms=pattern_analyzer.lower_case_terms, pattern=pattern_analyzer.pattern, flags=flags, stopwords=pattern_analyzer.stopwords, ) class PatternTokenizer(LexicalTokenizer): """Tokenizer that uses regex pattern matching to construct distinct tokens. This tokenizer is implemented using Apache Lucene. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the tokenizer. It must only contain letters, digits, spaces, dashes or underscores, can only start and end with alphanumeric characters, and is limited to 128 characters. :type name: str :param pattern: A regular expression to match token separators. Default is an expression that matches one or more white space characters. :type pattern: str :param flags: List of regular expression flags. Possible values of each flag include: 'CANON_EQ', 'CASE_INSENSITIVE', 'COMMENTS', 'DOTALL', 'LITERAL', 'MULTILINE', 'UNICODE_CASE', 'UNIX_LINES'. :type flags: list[str] or list[~search_service_client.models.RegexFlags] :param group: The zero-based ordinal of the matching group in the regular expression to extract into tokens. Use -1 if you want to use the entire pattern to split the input into tokens, irrespective of matching groups. Default is -1. :type group: int """ _validation = {"odata_type": {"required": True}, "name": {"required": True}} _attribute_map = { "odata_type": {"key": "@odata\\.type", "type": "str"}, "name": {"key": "name", "type": "str"}, "pattern": {"key": "pattern", "type": "str"}, "flags": {"key": "flags", "type": "[str]"}, "group": {"key": "group", "type": "int"}, } def __init__(self, **kwargs): super(PatternTokenizer, self).__init__(**kwargs) self.odata_type = "#Microsoft.Azure.Search.PatternTokenizer" self.pattern = kwargs.get("pattern", r"\W+") self.flags = kwargs.get("flags", None) self.group = kwargs.get("group", -1) def _to_generated(self): if not self.flags: flags = None else: flags = DELIMITER.join(self.flags) return _PatternTokenizer( name=self.name, pattern=self.pattern, flags=flags, group=self.group, ) @classmethod def _from_generated(cls, pattern_tokenizer): if not pattern_tokenizer: return None if not pattern_tokenizer.flags: flags = None else: flags = pattern_tokenizer.flags.split(DELIMITER) return cls( name=pattern_tokenizer.name, pattern=pattern_tokenizer.pattern, flags=flags, group=pattern_tokenizer.group, ) class SearchResourceEncryptionKey(msrest.serialization.Model): """A customer-managed encryption key in Azure Key Vault. Keys that you create and manage can be used to encrypt or decrypt data-at-rest in Azure Cognitive Search, such as indexes and synonym maps. All required parameters must be populated in order to send to Azure. :param key_name: Required. The name of your Azure Key Vault key to be used to encrypt your data at rest. :type key_name: str :param key_version: Required. The version of your Azure Key Vault key to be used to encrypt your data at rest. :type key_version: str :param vault_uri: Required. The URI of your Azure Key Vault, also referred to as DNS name, that contains the key to be used to encrypt your data at rest. An example URI might be https://my- keyvault-name.vault.azure.net. :type vault_uri: str :param application_id: Required. An AAD Application ID that was granted the required access permissions to the Azure Key Vault that is to be used when encrypting your data at rest. The Application ID should not be confused with the Object ID for your AAD Application. :type application_id: str :param application_secret: The authentication key of the specified AAD application. :type application_secret: str """ _validation = { 'key_name': {'required': True}, 'key_version': {'required': True}, 'vault_uri': {'required': True}, } _attribute_map = { 'key_name': {'key': 'keyVaultKeyName', 'type': 'str'}, 'key_version': {'key': 'keyVaultKeyVersion', 'type': 'str'}, 'vault_uri': {'key': 'keyVaultUri', 'type': 'str'}, 'application_id': {'key': 'applicationId', 'type': 'str'}, 'application_secret': {'key': 'applicationSecret', 'type': 'str'}, } def __init__( self, **kwargs ): super(SearchResourceEncryptionKey, self).__init__(**kwargs) self.key_name = kwargs['key_name'] self.key_version = kwargs['key_version'] self.vault_uri = kwargs['vault_uri'] self.application_id = kwargs.get('application_id', None) self.application_secret = kwargs.get('application_secret', None) def _to_generated(self): if self.application_id and self.application_secret: access_credentials = AzureActiveDirectoryApplicationCredentials( application_id=self.application_id, application_secret=self.application_secret ) else: access_credentials = None return _SearchResourceEncryptionKey( key_name=self.key_name, key_version=self.key_version, vault_uri=self.vault_uri, access_credentials=access_credentials ) @classmethod def _from_generated(cls, search_resource_encryption_key): if not search_resource_encryption_key: return None if search_resource_encryption_key.access_credentials: application_id = search_resource_encryption_key.access_credentials.application_id application_secret = search_resource_encryption_key.access_credentials.application_secret else: application_id = None application_secret = None return cls( key_name=search_resource_encryption_key.key_name, key_version=search_resource_encryption_key.key_version, vault_uri=search_resource_encryption_key.vault_uri, application_id=application_id, application_secret=application_secret ) class SynonymMap(msrest.serialization.Model): """Represents a synonym map definition. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the synonym map. :type name: str :ivar format: Required. The format of the synonym map. Only the 'solr' format is currently supported. Default value: "solr". :vartype format: str :param synonyms: Required. A series of synonym rules in the specified synonym map format. The rules must be separated by newlines. :type synonyms: list[str] :param encryption_key: A description of an encryption key that you create in Azure Key Vault. This key is used to provide an additional level of encryption-at-rest for your data when you want full assurance that no one, not even Microsoft, can decrypt your data in Azure Cognitive Search. Once you have encrypted your data, it will always remain encrypted. Azure Cognitive Search will ignore attempts to set this property to null. You can change this property as needed if you want to rotate your encryption key; Your data will be unaffected. Encryption with customer-managed keys is not available for free search services, and is only available for paid services created on or after January 1, 2019. :type encryption_key: ~azure.search.documents.indexes.models.SearchResourceEncryptionKey :param e_tag: The ETag of the synonym map. :type e_tag: str """ _validation = { 'name': {'required': True}, 'format': {'required': True, 'constant': True}, 'synonyms': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'format': {'key': 'format', 'type': 'str'}, 'synonyms': {'key': 'synonyms', 'type': '[str]'}, 'encryption_key': {'key': 'encryptionKey', 'type': 'SearchResourceEncryptionKey'}, 'e_tag': {'key': '@odata\\.etag', 'type': 'str'}, } format = "solr" def __init__( self, **kwargs ): super(SynonymMap, self).__init__(**kwargs) self.name = kwargs['name'] self.synonyms = kwargs['synonyms'] self.encryption_key = kwargs.get('encryption_key', None) self.e_tag = kwargs.get('e_tag', None) def _to_generated(self): return _SynonymMap( name=self.name, synonyms="\n".join(self.synonyms), encryption_key=self.encryption_key._to_generated() if self.encryption_key else None, # pylint:disable=protected-access e_tag=self.e_tag ) @classmethod def _from_generated(cls, synonym_map): if not synonym_map: return None return cls( name=synonym_map.name, synonyms=synonym_map.synonyms.split("\n"), # pylint:disable=protected-access encryption_key=SearchResourceEncryptionKey._from_generated(synonym_map.encryption_key), e_tag=synonym_map.e_tag ) @classmethod def create_from_file(cls, name, file_path): with open(file_path, "r") as f: solr_format_synonyms = f.read() synonyms = solr_format_synonyms.split("\n") return cls( name=name, synonyms=synonyms ) class SearchIndexerDataSourceConnection(msrest.serialization.Model): """Represents a datasource connection definition, which can be used to configure an indexer. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the datasource connection. :type name: str :param description: The description of the datasource connection. :type description: str :param type: Required. The type of the datasource connection. Possible values include: "azuresql", "cosmosdb", "azureblob", "azuretable", "mysql", "adlsgen2". :type type: str or ~azure.search.documents.indexes.models.SearchIndexerDataSourceType :param connection_string: The connection string for the datasource connection. :type connection_string: str :param container: Required. The data container for the datasource connection. :type container: ~azure.search.documents.indexes.models.SearchIndexerDataContainer :param data_change_detection_policy: The data change detection policy for the datasource connection. :type data_change_detection_policy: ~azure.search.documents.models.DataChangeDetectionPolicy :param data_deletion_detection_policy: The data deletion detection policy for the datasource connection. :type data_deletion_detection_policy: ~azure.search.documents.models.DataDeletionDetectionPolicy
:type e_tag: str """ _validation = { 'name': {'required': True}, 'type': {'required': True}, 'connection_string': {'required': True}, 'container': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'connection_string': {'key': 'connectionString', 'type': 'str'}, 'container': {'key': 'container', 'type': 'SearchIndexerDataContainer'}, 'data_change_detection_policy': {'key': 'dataChangeDetectionPolicy', 'type': 'DataChangeDetectionPolicy'}, 'data_deletion_detection_policy': {'key': 'dataDeletionDetectionPolicy', 'type': 'DataDeletionDetectionPolicy'}, 'e_tag': {'key': '@odata\\.etag', 'type': 'str'}, } def __init__( self, **kwargs ): super(SearchIndexerDataSourceConnection, self).__init__(**kwargs) self.name = kwargs['name'] self.description = kwargs.get('description', None) self.type = kwargs['type'] self.connection_string = kwargs['connection_string'] self.container = kwargs['container'] self.data_change_detection_policy = kwargs.get('data_change_detection_policy', None) self.data_deletion_detection_policy = kwargs.get('data_deletion_detection_policy', None) self.e_tag = kwargs.get('e_tag', None) def _to_generated(self): if self.connection_string is None or self.connection_string == "": connection_string = "<unchanged>" else: connection_string = self.connection_string credentials = DataSourceCredentials( connection_string=connection_string ) return _SearchIndexerDataSource( name=self.name, description=self.description, type=self.type, credentials=credentials, container=self.container, data_change_detection_policy=self.data_change_detection_policy, data_deletion_detection_policy=self.data_deletion_detection_policy, e_tag=self.e_tag ) @classmethod def _from_generated(cls, search_indexer_data_source): if not search_indexer_data_source: return None connection_string = search_indexer_data_source.credentials.connection_string \ if search_indexer_data_source.credentials else None return cls( name=search_indexer_data_source.name, description=search_indexer_data_source.description, type=search_indexer_data_source.type, connection_string=connection_string, container=search_indexer_data_source.container, data_change_detection_policy=search_indexer_data_source.data_change_detection_policy, data_deletion_detection_policy=search_indexer_data_source.data_deletion_detection_policy, e_tag=search_indexer_data_source.e_tag ) def pack_analyzer(analyzer): if not analyzer: return None if isinstance(analyzer, (PatternAnalyzer, CustomAnalyzer)): return analyzer._to_generated() # pylint:disable=protected-access return analyzer def unpack_analyzer(analyzer): if not analyzer: return None if isinstance(analyzer, _PatternAnalyzer): return PatternAnalyzer._from_generated(analyzer) # pylint:disable=protected-access if isinstance(analyzer, _CustomAnalyzer): return CustomAnalyzer._from_generated(analyzer) # pylint:disable=protected-access return analyzer
:param e_tag: The ETag of the data source.
pud_ctrl_hw.rs
#[doc = "Register `pud_ctrl_hw` reader"] pub struct R(crate::R<PUD_CTRL_HW_SPEC>); impl core::ops::Deref for R { type Target = crate::R<PUD_CTRL_HW_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::convert::From<crate::R<PUD_CTRL_HW_SPEC>> for R { fn from(reader: crate::R<PUD_CTRL_HW_SPEC>) -> Self { R(reader) } } #[doc = "Register `pud_ctrl_hw` writer"] pub struct W(crate::W<PUD_CTRL_HW_SPEC>); impl core::ops::Deref for W { type Target = crate::W<PUD_CTRL_HW_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 core::convert::From<crate::W<PUD_CTRL_HW_SPEC>> for W { fn from(writer: crate::W<PUD_CTRL_HW_SPEC>) -> Self { W(writer) } } #[doc = "Field `pud_vco_hw` reader - "] pub struct PUD_VCO_HW_R(crate::FieldReader<bool, bool>); impl PUD_VCO_HW_R { pub(crate) fn new(bits: bool) -> Self { PUD_VCO_HW_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PUD_VCO_HW_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `pud_vco_hw` writer - "] pub struct PUD_VCO_HW_W<'a> { w: &'a mut W, } impl<'a> PUD_VCO_HW_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | ((value as u32 & 0x01) << 20); self.w } } impl R { #[doc = "Bit 20"] #[inline(always)] pub fn pud_vco_hw(&self) -> PUD_VCO_HW_R { PUD_VCO_HW_R::new(((self.bits >> 20) & 0x01) != 0) } } impl W { #[doc = "Bit 20"] #[inline(always)] pub fn pud_vco_hw(&mut self) -> PUD_VCO_HW_W { PUD_VCO_HW_W { w: self } } #[doc = "Writes raw bits to the register."] pub unsafe fn
(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "pud_ctrl_hw.\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 [pud_ctrl_hw](index.html) module"] pub struct PUD_CTRL_HW_SPEC; impl crate::RegisterSpec for PUD_CTRL_HW_SPEC { type Ux = u32; } #[doc = "`read()` method returns [pud_ctrl_hw::R](R) reader structure"] impl crate::Readable for PUD_CTRL_HW_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [pud_ctrl_hw::W](W) writer structure"] impl crate::Writable for PUD_CTRL_HW_SPEC { type Writer = W; } #[doc = "`reset()` method sets pud_ctrl_hw to value 0"] impl crate::Resettable for PUD_CTRL_HW_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
bits
user_truncated.py
# coding: utf-8 """ Sunshine Conversations API The version of the OpenAPI document: 9.4.5 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from sunshine_conversations_client.configuration import Configuration from sunshine_conversations_client.undefined import Undefined class UserTruncated(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 = { 'id': 'str', 'external_id': 'str' } attribute_map = { 'id': 'id', 'external_id': 'externalId' } nulls = set() def __init__(self, id=None, external_id=Undefined(), local_vars_configuration=None): # noqa: E501 """UserTruncated - 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._id = None self._external_id = None self.discriminator = None if id is not None: self.id = id self.external_id = external_id @property def id(self): """Gets the id of this UserTruncated. # noqa: E501 The unique ID of the user. # noqa: E501 :return: The id of this UserTruncated. # noqa: E501 :rtype: str """ return self._id @id.setter def id(self, id): """Sets the id of this UserTruncated. The unique ID of the user. # noqa: E501 :param id: The id of this UserTruncated. # noqa: E501 :type: str """ self._id = id @property def external_id(self): """Gets the external_id of this UserTruncated. # noqa: E501 An optional ID that can also be used to retrieve the user. # noqa: E501 :return: The external_id of this UserTruncated. # noqa: E501 :rtype: str """ return self._external_id @external_id.setter def
(self, external_id): """Sets the external_id of this UserTruncated. An optional ID that can also be used to retrieve the user. # noqa: E501 :param external_id: The external_id of this UserTruncated. # noqa: E501 :type: str """ if type(external_id) is Undefined: external_id = None self.nulls.discard("external_id") elif external_id is None: self.nulls.add("external_id") else: self.nulls.discard("external_id") self._external_id = external_id 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): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) 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, UserTruncated): 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, UserTruncated): return True return self.to_dict() != other.to_dict()
external_id
main.py
from telegram.ext import MessageHandler, Filters, CommandHandler, Updater from mastodon import MastodonIllegalArgumentError, MastodonUnauthorizedError import DataHandler import threading import os import sys import logging import certifi import urllib3 import re bot_token = '<your bot token here>' # secretfile = open('secretbot', 'r') # secret = secretfile.readline().rstrip('\n') # bot_token = secret logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) test_visibility = 'public' group_media_queue = {} lookup_dict = {} tootObject = DataHandler.mastodonapi.TootObject def geturl(url_string):
def load_account(chat_id, force_reload=False): try: if force_reload: raise KeyError return lookup_dict[chat_id] except KeyError: account = DataHandler.account_object(chat_id) lookup_dict[chat_id] = account return account def download(file_id, telegram_file_object): file_url = telegram_file_object.file_path file_ext = re.search(r'\.[0-9a-z]+$', file_url).group() media_name = 'media-' + str(file_id) + file_ext telegram_file_object.download(media_name) return media_name def process_group_media(chat_id, key): files = group_media_queue.pop(key) toot_object = tootObject() for file_tuple in files: file_id = file_tuple[0] telegram_file_object = file_tuple[1] caption = file_tuple[2] media_name = download(file_id, telegram_file_object) toot_object.append(text=caption, media=media_name) tooting(chat_id, toot_object, test_visibility) for media in toot_object.medias: os.remove(media) def add_to_group_media_queue(chat_id, group_id, file_id, telegram_file_object, caption): key = str(chat_id) + str(group_id) try: media_container = group_media_queue[key] except KeyError: threading.Timer(20, process_group_media, [chat_id, key]).start() media_container = [] group_media_queue[key] = media_container finally: media_container.append( (file_id, telegram_file_object, caption) ) def tooting(chat_id, tootobject, visibility): load_account(chat_id).toot(tootobject, visibility) def reply(context, chat_id, text): context.bot.send_message(chat_id=chat_id, text=text, parse_mode='markdown') def start(update, context): context.bot.send_message(chat_id=update.message.chat_id, text="Toot to Mastodon using this bot. See /help") def add(update, context): chat_id = update.message.chat_id try: assert len(context.args) == 3 except AssertionError: reply(context, chat_id, 'usage:`\n/add <user_email> <password> <full_instance_url>`\nexample: `/add [email protected] cyberpunk277 https://mastodon.social/`') return else: username = context.args[0] instance = geturl(context.args[2]) password = context.args[1] try: new_account = DataHandler.insert_account( chat_id, username, instance, password) reply(context, chat_id, 'Account added successfully') except MastodonIllegalArgumentError: reply(context, chat_id, 'Authentication failed') reply(context, chat_id, 'usage:`\n/add <user_email> <password> <full_instance_url>`\nexample: `\add [email protected] cyberpunk277 https://mastodon.social/`') except MastodonUnauthorizedError: reply(context, chat_id, 'Authentication failed') except DataHandler.InsertError: reply(context, chat_id, 'Account already registered') except: reply(context, chat_id, 'Oops!, Something gone wrong. Check and try again') else: if isinstance(new_account, DataHandler.mastodonapi.MastodonAccount) and (DataHandler.number_of_accounts(chat_id) == 1): lookup_dict[chat_id] = new_account DataHandler.upsert_user(chat_id, 1) reply(context, chat_id, 'Great!, You can use /listall to list your currently registered accounts') def setdefault(update, context): chat_id = update.message.chat_id number_of_accounts = DataHandler.number_of_accounts(chat_id) if number_of_accounts == 0: reply(context, chat_id, 'You have not registered any mastodon account yet') return if number_of_accounts == 1: acc = DataHandler.account_info(chat_id) reply(context, chat_id, "Your only registered account is `{}` at `{}`".format(acc[0], acc[1])) return try: newDefault = int(context.args[0]) if newDefault <= number_of_accounts: DataHandler.upsert_user(chat_id, newDefault) accountObj = load_account(chat_id, force_reload=True) reply(context, chat_id, "Now you can toot to your account `{}` at `{}`".format( accountObj.user, accountObj.instance)) else: reply(context, chat_id, "You need to specify right account number as given in /listall") except: reply(context, chat_id, "`/setdefault` <number>") def delete(update, context): chat_id = update.message.chat_id number_of_accounts = DataHandler.number_of_accounts(chat_id) if number_of_accounts == 0: reply(context, chat_id, 'You don\'t have any registered account(s) to delete') elif number_of_accounts == 1: DataHandler.delete_user(chat_id) lookup_dict.pop(chat_id) else: try: acc_num = int(context.args[0]) if acc_num > number_of_accounts: reply(context, chat_id, "You need to specify right account number as given in /listall") return current_default = DataHandler.get_default_acc(chat_id) id_to_delete = DataHandler.account_id(chat_id, acc_num) DataHandler.delete_account(id_to_delete) if id_to_delete == current_default: DataHandler.upsert_user(chat_id, 1) load_account(chat_id, force_reload=True) account_info_tuple = DataHandler.account_info(chat_id) reply(context, chat_id, 'Your current default account is now set to {username} @ {instance}'.format( username=account_info_tuple[0], instance=account_info_tuple[1])) except: reply(context, chat_id, '`usage:`\n`/delete <number>`') def deleteall(update, context): chat_id = update.message.chat_id try: assert (context.args[0] == 'yes') except: reply(context, chat_id, '`NOTE: delete all registered accounts \nusage:\n/deleteall yes`') else: DataHandler.delete_user(chat_id) try: lookup_dict.pop(chat_id) except KeyError: pass def listall(update, context): chat_id = update.message.chat_id text = DataHandler.all_accounts(chat_id) reply(context, chat_id, "currenly registered accounts\n" + text) def media(update, context): chat_id = update.message.chat_id file_id = update.message.photo[-1].file_id new_file = context.bot.get_file(file_id) if update.message.media_group_id: add_to_group_media_queue(chat_id, update.message.media_group_id, file_id, new_file, update.message.caption) else: try: media_name = download(file_id, new_file) tooting(chat_id, tootObject(update.message.caption, media_name), test_visibility) except DataHandler.NoDataError: reply(context, chat_id, 'Please add an account first using /add') def text(update, context): chat_id = update.message.chat_id try: tooting(chat_id, tootObject(update.message.text), test_visibility) except DataHandler.NoDataError: reply(context, chat_id, 'Please add an account first using /add') def helpcommand(update, context): chat_id = update.message.chat_id reply(context, chat_id, "With TeleToot Bot you can to post on any Mastodon account's public timeline. Currently you can only post on one account at a time although you can authenticate various accounts and switch between them\n`availible commands:\n`/add\n/listall\n/setdefault\n/delete\n/deleteall") reply(context, chat_id, "To start tooting using your mastodon account send `/add <registered email> <password> <instance_url>`. See /add for more detail") updater = Updater(bot_token, use_context=True) dispatcher = updater.dispatcher list_of_commands = [start, add, listall, setdefault, delete, deleteall] def load_commands(commands): for command in commands: dispatcher.add_handler(CommandHandler(command.__name__, command)) load_commands(list_of_commands) media_handler = MessageHandler(Filters.photo | (Filters.text & Filters.photo), media, pass_job_queue=True) text_handler = MessageHandler(Filters.text, text) dispatcher.add_handler(media_handler) dispatcher.add_handler(text_handler) dispatcher.add_handler(CommandHandler('help', helpcommand)) updater.start_polling(poll_interval=1.0, timeout=60) updater.idle()
man = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where() ,num_pools=1) response = man.urlopen('GET', url_string) rurl = response.geturl() return re.search(r'([://a-z.0-9]+/)', rurl, re.I).group(0)
mod.rs
// 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 in the LICENSE-APACHE file or at: // https://www.apache.org/licenses/LICENSE-2.0 //! Drawing APIs //! //! Multiple drawing APIs are available. Each has a slightly different purpose. //! //! ### High-level themeable interface //! //! The [`DrawHandle`] trait and companion [`SizeHandle`] trait provide the //! highest-level API over themeable widget components. These traits are //! implemented by a theme defined in `kas-theme` or another crate. //! //! ### Medium-level drawing interfaces //! //! The [`Draw`] trait and its extensions are provided as the building-blocks //! used to implement themes, but may also be used directly (as in the `clock` //! example). These traits allow drawing of simple shapes, mostly in the form of //! an axis-aligned box or frame with several shading options. //! //! The [`Draw`] trait itself contains very little; extension traits //! [`DrawRounded`] and [`DrawShaded`] provide additional draw //! routines. Shells are only required to implement the base [`Draw`] trait, //! and may also provide their own extension traits. Themes may specify their //! own requirements, e.g. `D: Draw + DrawRounded + DrawText`. //! //! The medium-level API will be extended in the future to support texturing //! (not yet supported) and potentially a more comprehensive path-based API //! (e.g. Lyon). //! //! ### Low-level interface //! //! There is no universal graphics API, hence none is provided by this crate. //! Instead, shells may provide their own extensions allowing direct access //! to the host graphics API, for example //! [`kas-wgpu::draw::CustomPipe`](https://docs.rs/kas-wgpu/*/kas_wgpu/draw/trait.CustomPipe.html). pub mod color; mod handle; mod theme; use std::any::Any; use std::num::NonZeroU32; use std::path::Path; use crate::cast::Cast; use crate::geom::{Quad, Rect, Size, Vec2}; use crate::text::{Effect, TextDisplay}; use color::Rgba; pub use handle::*; pub use theme::*; /// Pass identifier /// /// Users normally need only pass this value. /// /// Custom render pipes should extract the pass number. #[derive(Copy, Clone)] pub struct Pass(u32); impl Pass { /// Construct a new pass from a `u32` identifier #[cfg_attr(not(feature = "internal_doc"), doc(hidden))] #[cfg_attr(doc_cfg, doc(cfg(internal_doc)))] #[inline] pub const fn
(n: u32) -> Self { Pass(n) } /// The pass number /// /// This value is returned as `usize` but is always safe to store `as u32`. #[inline] pub fn pass(self) -> usize { self.0.cast() } /// The depth value /// /// This is a historical left-over and always returns 0.0. #[inline] pub fn depth(self) -> f32 { 0.0 } } #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct ImageId(NonZeroU32); impl ImageId { /// Construct a new identifier from `u32` value not equal to 0 #[cfg_attr(not(feature = "internal_doc"), doc(hidden))] #[cfg_attr(doc_cfg, doc(cfg(internal_doc)))] #[inline] pub const fn try_new(n: u32) -> Option<Self> { // We can't use ? or .map in a const fn so do it the tedious way: if let Some(nz) = NonZeroU32::new(n) { Some(ImageId(nz)) } else { None } } } /// Bounds on type shared across [`Draw`] implementations pub trait DrawShared: 'static { type Draw: Draw; /// Load an image from a path, autodetecting file type /// /// TODO: revise error handling? fn load_image(&mut self, path: &Path) -> Result<ImageId, Box<dyn std::error::Error + 'static>>; /// Free an image fn remove_image(&mut self, id: ImageId); /// Get size of image fn image_size(&self, id: ImageId) -> Option<Size>; /// Draw the image in the given `rect` fn draw_image(&self, window: &mut Self::Draw, pass: Pass, id: ImageId, rect: Quad); /// Draw text with a colour fn draw_text( &mut self, window: &mut Self::Draw, pass: Pass, pos: Vec2, text: &TextDisplay, col: Rgba, ); /// Draw text with a colour and effects /// /// The effects list does not contain colour information, but may contain /// underlining/strikethrough information. It may be empty. fn draw_text_col_effects( &mut self, window: &mut Self::Draw, pass: Pass, pos: Vec2, text: &TextDisplay, col: Rgba, effects: &[Effect<()>], ); /// Draw text with effects /// /// The `effects` list provides both underlining and colour information. /// If the `effects` list is empty or the first entry has `start > 0`, a /// default entity will be assumed. fn draw_text_effects( &mut self, window: &mut Self::Draw, pass: Pass, pos: Vec2, text: &TextDisplay, effects: &[Effect<Rgba>], ); } /// Base abstraction over drawing /// /// Unlike [`DrawHandle`], coordinates are specified via a [`Vec2`] and /// rectangular regions via [`Quad`]. The same coordinate system is used, hence /// type conversions can be performed with `from` and `into`. Integral /// coordinates align with pixels, non-integral coordinates may also be used. /// /// All draw operations may be batched; when drawn primitives overlap, the /// results are only loosely defined. Draw operations involving transparency /// should be ordered after those without transparency. /// /// Draw operations take place over multiple render passes, identified by a /// handle of type [`Pass`]. In general the user only needs to pass this value /// into methods as required. [`Draw::add_clip_region`] creates a new [`Pass`]. pub trait Draw: Any { /// Cast self to [`std::any::Any`] reference. /// /// A downcast on this value may be used to obtain a reference to a /// shell-specific API. fn as_any_mut(&mut self) -> &mut dyn Any; /// Add a clip region /// /// Clip regions are cleared each frame and so must be recreated on demand. fn add_clip_region(&mut self, pass: Pass, rect: Rect, class: RegionClass) -> Pass; /// Get drawable rect for a clip region /// /// (This may be smaller than the rect passed to [`Draw::add_clip_region`].) fn get_clip_rect(&self, pass: Pass) -> Rect; /// Draw a rectangle of uniform colour fn rect(&mut self, pass: Pass, rect: Quad, col: Rgba); /// Draw a frame of uniform colour /// /// The frame is defined by the area inside `outer` and not inside `inner`. fn frame(&mut self, pass: Pass, outer: Quad, inner: Quad, col: Rgba); } /// Drawing commands for rounded shapes /// /// This trait is an extension over [`Draw`] providing rounded shapes. /// /// The primitives provided by this trait are partially transparent. /// If the implementation buffers draw commands, it should draw these /// primitives after solid primitives. pub trait DrawRounded: Draw { /// Draw a line with rounded ends and uniform colour /// /// This command draws a line segment between the points `p1` and `p2`. /// Pixels within the given `radius` of this segment are drawn, resulting /// in rounded ends and width `2 * radius`. /// /// Note that for rectangular, axis-aligned lines, [`Draw::rect`] should be /// preferred. fn rounded_line(&mut self, pass: Pass, p1: Vec2, p2: Vec2, radius: f32, col: Rgba); /// Draw a circle or oval of uniform colour /// /// More generally, this shape is an axis-aligned oval which may be hollow. /// /// The `inner_radius` parameter gives the inner radius relative to the /// outer radius: a value of `0.0` will result in the whole shape being /// painted, while `1.0` will result in a zero-width line on the outer edge. fn circle(&mut self, pass: Pass, rect: Quad, inner_radius: f32, col: Rgba); /// Draw a frame with rounded corners and uniform colour /// /// All drawing occurs within the `outer` rect and outside of the `inner` /// rect. Corners are circular (or more generally, ovular), centered on the /// inner corners. /// /// The `inner_radius` parameter gives the inner radius relative to the /// outer radius: a value of `0.0` will result in the whole shape being /// painted, while `1.0` will result in a zero-width line on the outer edge. /// When `inner_radius > 0`, the frame will be visually thinner than the /// allocated area. fn rounded_frame(&mut self, pass: Pass, outer: Quad, inner: Quad, inner_radius: f32, col: Rgba); } /// Drawing commands for shaded shapes /// /// This trait is an extension over [`Draw`] providing solid shaded shapes. /// /// Some drawing primitives (the "round" ones) are partially transparent. /// If the implementation buffers draw commands, it should draw these /// primitives after solid primitives. /// /// These are parameterised via a pair of normals, `(inner, outer)`. These may /// have values from the closed range `[-1, 1]`, where -1 points inwards, /// 0 is perpendicular to the screen towards the viewer, and 1 points outwards. pub trait DrawShaded: Draw { /// Add a shaded square to the draw buffer fn shaded_square(&mut self, pass: Pass, rect: Quad, norm: (f32, f32), col: Rgba); /// Add a shaded circle to the draw buffer fn shaded_circle(&mut self, pass: Pass, rect: Quad, norm: (f32, f32), col: Rgba); /// Add a square shaded frame to the draw buffer. fn shaded_square_frame( &mut self, pass: Pass, outer: Quad, inner: Quad, norm: (f32, f32), outer_col: Rgba, inner_col: Rgba, ); /// Add a rounded shaded frame to the draw buffer. fn shaded_round_frame( &mut self, pass: Pass, outer: Quad, inner: Quad, norm: (f32, f32), col: Rgba, ); }
new
utils.py
# Copyright (C) 2020 University of Oxford # # 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 io import requests import pandas as pd from pandas import DataFrame from datetime import date, timedelta from requests.exceptions import ConnectionError def get_recent_apple_mobility_data() -> DataFrame:
baseurl = 'https://covid19-static.cdn-apple.com/covid19-mobility-data/current/v3/en-us/applemobilitytrends-{}.csv' for delta in range(14): dt = date.today() - timedelta(delta) url = baseurl.format(dt.strftime("%Y-%m-%d")) try: request = requests.get(url, timeout=30) if request.status_code != 200: continue request.encoding = 'utf-8' return pd.read_csv(io.StringIO(request.text)) except ConnectionError: continue return None
LSAPlugin.py
import sys import numpy import random class LSAPlugin: def
(self, filename): self.myfile = filename def run(self): filestuff = open(self.myfile, 'r') self.firstline = filestuff.readline() lines = [] for line in filestuff: lines.append(line) self.m = len(lines) self.samples = [] self.bacteria = self.firstline.split(',') if (self.bacteria.count('\"\"') != 0): self.bacteria.remove('\"\"') self.n = len(self.bacteria) self.ADJ = []#numpy.zeros([self.m, self.n]) self.results=[] i = 0 for i in range(self.m): self.ADJ.append([]) contents = lines[i].split(',') self.samples.append(contents[0]) for j in range(self.n): value = float(contents[j+1].strip()) self.ADJ[i].append(value)#[j] = value for i in range(self.n): self.results.append([]) for j in range(self.n): if (i == j): self.results[i].append(1) else: self.results[i].append(0) # From Ruan et al, 2006 for b1 in range(0, self.n): for b2 in range(b1+1, self.n): #if (b1 != b2): self.P = [] self.N = [] for i in range(0, self.m+2): self.P.append([]) self.N.append([]) for j in range(0, self.m+2): self.P[len(self.P)-1].append(0) self.N[len(self.N)-1].append(0) for i in range(1, self.m+1): self.P[0][i] = 0 self.N[0][i] = 0 self.P[i][0] = 0 self.N[i][0] = 0 for i in range(1, self.m+1): for j in range(1, self.m+1): self.P[i+1][j+1] = max(0, self.P[i][j]+self.ADJ[i-1][b1]*self.ADJ[i-1][b2]) self.N[i+1][j+1] = max(0, self.N[i][j]-self.ADJ[i-1][b1]*self.ADJ[i-1][b2]) # Find maxP maxP = 0 maxN = 0 for i in range(1, self.m+1): if (max(self.P[i]) > maxP): maxP = max(self.P[i]) if (max(self.N[i]) > maxN): maxN = max(self.N[i]) maxScore = max(maxP, maxN) if (maxP - maxN < 0): maxScore *= -1 self.results[b1][b2] = maxScore / float(self.m) self.results[b2][b1] = maxScore / float(self.m) def output(self, filename): filestuff2 = open(filename, 'w') filestuff2.write(self.firstline) for i in range(self.n): filestuff2.write(self.bacteria[i]+',') for j in range(self.n): filestuff2.write(str(self.results[i][j])) if (j < self.n-1): filestuff2.write(",") else: filestuff2.write("\n")
input
metrics.go
package costmodel import ( "math" "strconv" "strings" "sync" "time" "github.com/kubecost/cost-model/pkg/cloud" "github.com/kubecost/cost-model/pkg/clustercache" "github.com/kubecost/cost-model/pkg/env" "github.com/kubecost/cost-model/pkg/errors" "github.com/kubecost/cost-model/pkg/log" "github.com/kubecost/cost-model/pkg/metrics" "github.com/kubecost/cost-model/pkg/prom" "github.com/kubecost/cost-model/pkg/util" promclient "github.com/prometheus/client_golang/api" "github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" v1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" "k8s.io/klog" ) //-------------------------------------------------------------------------- // ClusterInfoCollector //-------------------------------------------------------------------------- // ClusterInfoCollector is a prometheus collector that generates ClusterInfoMetrics type ClusterInfoCollector struct { Cloud cloud.Provider KubeClientSet kubernetes.Interface } // Describe sends the super-set of all possible descriptors of metrics // collected by this Collector. func (cic ClusterInfoCollector) Describe(ch chan<- *prometheus.Desc) { ch <- prometheus.NewDesc("kubecost_cluster_info", "Kubecost Cluster Info", []string{}, nil) } // Collect is called by the Prometheus registry when collecting metrics. func (cic ClusterInfoCollector) Collect(ch chan<- prometheus.Metric) { clusterInfo := GetClusterInfo(cic.KubeClientSet, cic.Cloud) labels := prom.MapToLabels(clusterInfo) m := newClusterInfoMetric("kubecost_cluster_info", labels) ch <- m } //-------------------------------------------------------------------------- // ClusterInfoMetric //-------------------------------------------------------------------------- // ClusterInfoMetric is a prometheus.Metric used to encode the local cluster info type ClusterInfoMetric struct { fqName string help string labels map[string]string } // Creates a new ClusterInfoMetric, implementation of prometheus.Metric func newClusterInfoMetric(fqName string, labels map[string]string) ClusterInfoMetric { return ClusterInfoMetric{ fqName: fqName, labels: labels, help: "kubecost_cluster_info ClusterInfo", } } // Desc returns the descriptor for the Metric. This method idempotently // returns the same descriptor throughout the lifetime of the Metric. func (cim ClusterInfoMetric) Desc() *prometheus.Desc { l := prometheus.Labels{} return prometheus.NewDesc(cim.fqName, cim.help, prom.LabelNamesFrom(cim.labels), l) } // Write encodes the Metric into a "Metric" Protocol Buffer data // transmission object. func (cim ClusterInfoMetric) Write(m *dto.Metric) error { h := float64(1) m.Gauge = &dto.Gauge{ Value: &h, } var labels []*dto.LabelPair for k, v := range cim.labels { labels = append(labels, &dto.LabelPair{ Name: toStringPtr(k), Value: toStringPtr(v), }) } m.Label = labels return nil } // returns a pointer to the string provided func toStringPtr(s string) *string { return &s } //-------------------------------------------------------------------------- // Cost Model Metrics Initialization //-------------------------------------------------------------------------- // Only allow the metrics to be instantiated and registered once var metricsInit sync.Once var ( cpuGv *prometheus.GaugeVec ramGv *prometheus.GaugeVec gpuGv *prometheus.GaugeVec gpuCountGv *prometheus.GaugeVec pvGv *prometheus.GaugeVec spotGv *prometheus.GaugeVec totalGv *prometheus.GaugeVec ramAllocGv *prometheus.GaugeVec cpuAllocGv *prometheus.GaugeVec gpuAllocGv *prometheus.GaugeVec pvAllocGv *prometheus.GaugeVec networkZoneEgressCostG prometheus.Gauge networkRegionEgressCostG prometheus.Gauge networkInternetEgressCostG prometheus.Gauge clusterManagementCostGv *prometheus.GaugeVec lbCostGv *prometheus.GaugeVec ) // initCostModelMetrics uses a sync.Once to ensure that these metrics are only created once func initCostModelMetrics(clusterCache clustercache.ClusterCache, provider cloud.Provider) { metricsInit.Do(func() { cpuGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "node_cpu_hourly_cost", Help: "node_cpu_hourly_cost hourly cost for each cpu on this node", }, []string{"instance", "node", "instance_type", "region", "provider_id"}) ramGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "node_ram_hourly_cost", Help: "node_ram_hourly_cost hourly cost for each gb of ram on this node", }, []string{"instance", "node", "instance_type", "region", "provider_id"}) gpuGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "node_gpu_hourly_cost", Help: "node_gpu_hourly_cost hourly cost for each gpu on this node", }, []string{"instance", "node", "instance_type", "region", "provider_id"}) gpuCountGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "node_gpu_count", Help: "node_gpu_count count of gpu on this node", }, []string{"instance", "node", "instance_type", "region", "provider_id"}) pvGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "pv_hourly_cost", Help: "pv_hourly_cost Cost per GB per hour on a persistent disk", }, []string{"volumename", "persistentvolume", "provider_id"}) spotGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "kubecost_node_is_spot", Help: "kubecost_node_is_spot Cloud provider info about node preemptibility", }, []string{"instance", "node", "instance_type", "region", "provider_id"}) totalGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "node_total_hourly_cost", Help: "node_total_hourly_cost Total node cost per hour", }, []string{"instance", "node", "instance_type", "region", "provider_id"}) ramAllocGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "container_memory_allocation_bytes", Help: "container_memory_allocation_bytes Bytes of RAM used", }, []string{"namespace", "pod", "container", "instance", "node"}) cpuAllocGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "container_cpu_allocation", Help: "container_cpu_allocation Percent of a single CPU used in a minute", }, []string{"namespace", "pod", "container", "instance", "node"}) gpuAllocGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "container_gpu_allocation", Help: "container_gpu_allocation GPU used", }, []string{"namespace", "pod", "container", "instance", "node"}) pvAllocGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "pod_pvc_allocation", Help: "pod_pvc_allocation Bytes used by a PVC attached to a pod", }, []string{"namespace", "pod", "persistentvolumeclaim", "persistentvolume"}) networkZoneEgressCostG = prometheus.NewGauge(prometheus.GaugeOpts{ Name: "kubecost_network_zone_egress_cost", Help: "kubecost_network_zone_egress_cost Total cost per GB egress across zones", }) networkRegionEgressCostG = prometheus.NewGauge(prometheus.GaugeOpts{ Name: "kubecost_network_region_egress_cost", Help: "kubecost_network_region_egress_cost Total cost per GB egress across regions", }) networkInternetEgressCostG = prometheus.NewGauge(prometheus.GaugeOpts{ Name: "kubecost_network_internet_egress_cost", Help: "kubecost_network_internet_egress_cost Total cost per GB of internet egress.", }) clusterManagementCostGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "kubecost_cluster_management_cost", Help: "kubecost_cluster_management_cost Hourly cost paid as a cluster management fee.", }, []string{"provisioner_name"}) lbCostGv = prometheus.NewGaugeVec(prometheus.GaugeOpts{ // no differentiation between ELB and ALB right now Name: "kubecost_load_balancer_cost", Help: "kubecost_load_balancer_cost Hourly cost of load balancer", }, []string{"ingress_ip", "namespace", "service_name"}) // assumes one ingress IP per load balancer // Register cost-model metrics for emission prometheus.MustRegister(cpuGv, ramGv, gpuGv, gpuCountGv, totalGv, pvGv, spotGv) prometheus.MustRegister(ramAllocGv, cpuAllocGv, gpuAllocGv, pvAllocGv) prometheus.MustRegister(networkZoneEgressCostG, networkRegionEgressCostG, networkInternetEgressCostG) prometheus.MustRegister(clusterManagementCostGv, lbCostGv) // General Metric Collectors prometheus.MustRegister(ClusterInfoCollector{ KubeClientSet: clusterCache.GetClient(), Cloud: provider, }) }) } //-------------------------------------------------------------------------- // CostModelMetricsEmitter //-------------------------------------------------------------------------- // CostModelMetricsEmitter emits all cost-model specific metrics calculated by // the CostModel.ComputeCostData() method. type CostModelMetricsEmitter struct { PrometheusClient promclient.Client KubeClusterCache clustercache.ClusterCache CloudProvider cloud.Provider Model *CostModel // Metrics CPUPriceRecorder *prometheus.GaugeVec RAMPriceRecorder *prometheus.GaugeVec PersistentVolumePriceRecorder *prometheus.GaugeVec GPUPriceRecorder *prometheus.GaugeVec GPUCountRecorder *prometheus.GaugeVec PVAllocationRecorder *prometheus.GaugeVec NodeSpotRecorder *prometheus.GaugeVec NodeTotalPriceRecorder *prometheus.GaugeVec RAMAllocationRecorder *prometheus.GaugeVec CPUAllocationRecorder *prometheus.GaugeVec GPUAllocationRecorder *prometheus.GaugeVec ClusterManagementCostRecorder *prometheus.GaugeVec LBCostRecorder *prometheus.GaugeVec NetworkZoneEgressRecorder prometheus.Gauge NetworkRegionEgressRecorder prometheus.Gauge NetworkInternetEgressRecorder prometheus.Gauge // Flow Control recordingLock *sync.Mutex recordingStopping bool recordingStop chan bool } // NewCostModelMetricsEmitter creates a new cost-model metrics emitter. Use Start() to begin metric emission. func NewCostModelMetricsEmitter(promClient promclient.Client, clusterCache clustercache.ClusterCache, provider cloud.Provider, model *CostModel) *CostModelMetricsEmitter
// Checks to see if there is a metric recording stop channel. If it exists, a new // channel is not created and false is returned. If it doesn't exist, a new channel // is created and true is returned. func (cmme *CostModelMetricsEmitter) checkOrCreateRecordingChan() bool { cmme.recordingLock.Lock() defer cmme.recordingLock.Unlock() if cmme.recordingStop != nil { return false } cmme.recordingStop = make(chan bool, 1) return true } // IsRunning returns true if metric recording is running. func (cmme *CostModelMetricsEmitter) IsRunning() bool { cmme.recordingLock.Lock() defer cmme.recordingLock.Unlock() return cmme.recordingStop != nil } // StartCostModelMetricRecording starts the go routine that emits metrics used to determine // cluster costs. func (cmme *CostModelMetricsEmitter) Start() bool { // Check to see if we're already recording // This function will create the stop recording channel and return true // if it doesn't exist. if !cmme.checkOrCreateRecordingChan() { log.Errorf("Attempted to start cost model metric recording when it's already running.") return false } go func() { defer errors.HandlePanic() containerSeen := make(map[string]bool) nodeSeen := make(map[string]bool) loadBalancerSeen := make(map[string]bool) pvSeen := make(map[string]bool) pvcSeen := make(map[string]bool) getKeyFromLabelStrings := func(labels ...string) string { return strings.Join(labels, ",") } getLabelStringsFromKey := func(key string) []string { return strings.Split(key, ",") } var defaultRegion string = "" nodeList := cmme.KubeClusterCache.GetAllNodes() if len(nodeList) > 0 { var ok bool defaultRegion, ok = util.GetRegion(nodeList[0].Labels) if !ok { log.DedupedWarningf(5, "Failed to locate default region") } } for { klog.V(4).Info("Recording prices...") podlist := cmme.KubeClusterCache.GetAllPods() podStatus := make(map[string]v1.PodPhase) for _, pod := range podlist { podStatus[pod.Name] = pod.Status.Phase } cfg, _ := cmme.CloudProvider.GetConfig() provisioner, clusterManagementCost, err := cmme.CloudProvider.ClusterManagementPricing() if err != nil { klog.V(1).Infof("Error getting cluster management cost %s", err.Error()) } cmme.ClusterManagementCostRecorder.WithLabelValues(provisioner).Set(clusterManagementCost) // Record network pricing at global scope networkCosts, err := cmme.CloudProvider.NetworkPricing() if err != nil { klog.V(4).Infof("Failed to retrieve network costs: %s", err.Error()) } else { cmme.NetworkZoneEgressRecorder.Set(networkCosts.ZoneNetworkEgressCost) cmme.NetworkRegionEgressRecorder.Set(networkCosts.RegionNetworkEgressCost) cmme.NetworkInternetEgressRecorder.Set(networkCosts.InternetNetworkEgressCost) } // TODO: Pass PrometheusClient and CloudProvider into CostModel on instantiation so this isn't so awkward data, err := cmme.Model.ComputeCostData(cmme.PrometheusClient, cmme.CloudProvider, "2m", "", "") if err != nil { // For an error collection, we'll just log the length of the errors (ComputeCostData already logs the // actual errors) if prom.IsErrorCollection(err) { if ec, ok := err.(prom.QueryErrorCollection); ok { log.Errorf("Error in price recording: %d errors occurred", len(ec.Errors())) } } else { log.Errorf("Error in price recording: " + err.Error()) } // zero the for loop so the time.Sleep will still work data = map[string]*CostData{} } // TODO: Pass CloudProvider into CostModel on instantiation so this isn't so awkward nodes, err := cmme.Model.GetNodeCost(cmme.CloudProvider) for nodeName, node := range nodes { // Emit costs, guarding against NaN inputs for custom pricing. cpuCost, _ := strconv.ParseFloat(node.VCPUCost, 64) if math.IsNaN(cpuCost) || math.IsInf(cpuCost, 0) { cpuCost, _ = strconv.ParseFloat(cfg.CPU, 64) if math.IsNaN(cpuCost) || math.IsInf(cpuCost, 0) { cpuCost = 0 } } cpu, _ := strconv.ParseFloat(node.VCPU, 64) if math.IsNaN(cpu) || math.IsInf(cpu, 0) { cpu = 1 // Assume 1 CPU } ramCost, _ := strconv.ParseFloat(node.RAMCost, 64) if math.IsNaN(ramCost) || math.IsInf(ramCost, 0) { ramCost, _ = strconv.ParseFloat(cfg.RAM, 64) if math.IsNaN(ramCost) || math.IsInf(ramCost, 0) { ramCost = 0 } } ram, _ := strconv.ParseFloat(node.RAMBytes, 64) if math.IsNaN(ram) || math.IsInf(ram, 0) { ram = 0 } gpu, _ := strconv.ParseFloat(node.GPU, 64) if math.IsNaN(gpu) || math.IsInf(gpu, 0) { gpu = 0 } gpuCost, _ := strconv.ParseFloat(node.GPUCost, 64) if math.IsNaN(gpuCost) || math.IsInf(gpuCost, 0) { gpuCost, _ = strconv.ParseFloat(cfg.GPU, 64) if math.IsNaN(gpuCost) || math.IsInf(gpuCost, 0) { gpuCost = 0 } } nodeType := node.InstanceType nodeRegion := node.Region totalCost := cpu*cpuCost + ramCost*(ram/1024/1024/1024) + gpu*gpuCost cmme.CPUPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID).Set(cpuCost) cmme.RAMPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID).Set(ramCost) cmme.GPUPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID).Set(gpuCost) cmme.GPUCountRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID).Set(gpu) cmme.NodeTotalPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID).Set(totalCost) if node.IsSpot() { cmme.NodeSpotRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID).Set(1.0) } else { cmme.NodeSpotRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID).Set(0.0) } labelKey := getKeyFromLabelStrings(nodeName, nodeName, nodeType, nodeRegion, node.ProviderID) nodeSeen[labelKey] = true } // TODO: Pass CloudProvider into CostModel on instantiation so this isn't so awkward loadBalancers, err := cmme.Model.GetLBCost(cmme.CloudProvider) for lbKey, lb := range loadBalancers { // TODO: parse (if necessary) and calculate cost associated with loadBalancer based on dynamic cloud prices fetched into each lb struct on GetLBCost() call keyParts := getLabelStringsFromKey(lbKey) namespace := keyParts[0] serviceName := keyParts[1] ingressIP := "" if len(lb.IngressIPAddresses) > 0 { ingressIP = lb.IngressIPAddresses[0] // assumes one ingress IP per load balancer } cmme.LBCostRecorder.WithLabelValues(ingressIP, namespace, serviceName).Set(lb.Cost) labelKey := getKeyFromLabelStrings(namespace, serviceName) loadBalancerSeen[labelKey] = true } for _, costs := range data { nodeName := costs.NodeName namespace := costs.Namespace podName := costs.PodName containerName := costs.Name if costs.PVCData != nil { for _, pvc := range costs.PVCData { if pvc.Volume != nil { timesClaimed := pvc.TimesClaimed if timesClaimed == 0 { timesClaimed = 1 // unallocated PVs are unclaimed but have a full allocation } cmme.PVAllocationRecorder.WithLabelValues(namespace, podName, pvc.Claim, pvc.VolumeName).Set(pvc.Values[0].Value / float64(timesClaimed)) labelKey := getKeyFromLabelStrings(namespace, podName, pvc.Claim, pvc.VolumeName) pvcSeen[labelKey] = true } } } if len(costs.RAMAllocation) > 0 { cmme.RAMAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName).Set(costs.RAMAllocation[0].Value) } if len(costs.CPUAllocation) > 0 { cmme.CPUAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName).Set(costs.CPUAllocation[0].Value) } if len(costs.GPUReq) > 0 { // allocation here is set to the request because shared GPU usage not yet supported. cmme.GPUAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName).Set(costs.GPUReq[0].Value) } labelKey := getKeyFromLabelStrings(namespace, podName, containerName, nodeName, nodeName) if podStatus[podName] == v1.PodRunning { // Only report data for current pods containerSeen[labelKey] = true } else { containerSeen[labelKey] = false } } storageClasses := cmme.KubeClusterCache.GetAllStorageClasses() storageClassMap := make(map[string]map[string]string) for _, storageClass := range storageClasses { params := storageClass.Parameters storageClassMap[storageClass.ObjectMeta.Name] = params if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" { storageClassMap["default"] = params storageClassMap[""] = params } } pvs := cmme.KubeClusterCache.GetAllPersistentVolumes() for _, pv := range pvs { // Omit pv_hourly_cost if the volume status is failed if pv.Status.Phase == v1.VolumeFailed { continue } parameters, ok := storageClassMap[pv.Spec.StorageClassName] if !ok { klog.V(4).Infof("Unable to find parameters for storage class \"%s\". Does pv \"%s\" have a storageClassName?", pv.Spec.StorageClassName, pv.Name) } var region string if r, ok := util.GetRegion(pv.Labels); ok { region = r } else { region = defaultRegion } cacPv := &cloud.PV{ Class: pv.Spec.StorageClassName, Region: region, Parameters: parameters, } // TODO: GetPVCost should be a method in CostModel? GetPVCost(cacPv, pv, cmme.CloudProvider, region) c, _ := strconv.ParseFloat(cacPv.Cost, 64) cmme.PersistentVolumePriceRecorder.WithLabelValues(pv.Name, pv.Name, cacPv.ProviderID).Set(c) labelKey := getKeyFromLabelStrings(pv.Name, pv.Name) pvSeen[labelKey] = true } for labelString, seen := range nodeSeen { if !seen { klog.V(4).Infof("Removing %s from nodes", labelString) labels := getLabelStringsFromKey(labelString) ok := cmme.NodeTotalPriceRecorder.DeleteLabelValues(labels...) if ok { klog.V(4).Infof("removed %s from totalprice", labelString) } else { klog.Infof("FAILURE TO REMOVE %s from totalprice", labelString) } ok = cmme.NodeSpotRecorder.DeleteLabelValues(labels...) if ok { klog.V(4).Infof("removed %s from spot records", labelString) } else { klog.Infof("FAILURE TO REMOVE %s from spot records", labelString) } ok = cmme.CPUPriceRecorder.DeleteLabelValues(labels...) if ok { klog.V(4).Infof("removed %s from cpuprice", labelString) } else { klog.Infof("FAILURE TO REMOVE %s from cpuprice", labelString) } ok = cmme.GPUPriceRecorder.DeleteLabelValues(labels...) if ok { klog.V(4).Infof("removed %s from gpuprice", labelString) } else { klog.Infof("FAILURE TO REMOVE %s from gpuprice", labelString) } ok = cmme.GPUCountRecorder.DeleteLabelValues(labels...) if ok { klog.V(4).Infof("removed %s from gpucount", labelString) } else { klog.Infof("FAILURE TO REMOVE %s from gpucount", labelString) } ok = cmme.RAMPriceRecorder.DeleteLabelValues(labels...) if ok { klog.V(4).Infof("removed %s from ramprice", labelString) } else { klog.Infof("FAILURE TO REMOVE %s from ramprice", labelString) } delete(nodeSeen, labelString) } else { nodeSeen[labelString] = false } } for labelString, seen := range loadBalancerSeen { if !seen { labels := getLabelStringsFromKey(labelString) cmme.LBCostRecorder.DeleteLabelValues(labels...) } else { loadBalancerSeen[labelString] = false } } for labelString, seen := range containerSeen { if !seen { labels := getLabelStringsFromKey(labelString) cmme.RAMAllocationRecorder.DeleteLabelValues(labels...) cmme.CPUAllocationRecorder.DeleteLabelValues(labels...) cmme.GPUAllocationRecorder.DeleteLabelValues(labels...) delete(containerSeen, labelString) } else { containerSeen[labelString] = false } } for labelString, seen := range pvSeen { if !seen { labels := getLabelStringsFromKey(labelString) cmme.PersistentVolumePriceRecorder.DeleteLabelValues(labels...) delete(pvSeen, labelString) } else { pvSeen[labelString] = false } } for labelString, seen := range pvcSeen { if !seen { labels := getLabelStringsFromKey(labelString) cmme.PVAllocationRecorder.DeleteLabelValues(labels...) delete(pvcSeen, labelString) } else { pvcSeen[labelString] = false } } select { case <-time.After(time.Minute): case <-cmme.recordingStop: cmme.recordingLock.Lock() cmme.recordingStopping = false cmme.recordingStop = nil cmme.recordingLock.Unlock() return } } }() return true } // Stop halts the metrics emission loop after the current emission is completed // or if the emission is paused. func (cmme *CostModelMetricsEmitter) Stop() { cmme.recordingLock.Lock() defer cmme.recordingLock.Unlock() if !cmme.recordingStopping && cmme.recordingStop != nil { cmme.recordingStopping = true close(cmme.recordingStop) } }
{ // init will only actually execute once to register the custom gauges initCostModelMetrics(clusterCache, provider) // if the metrics pod is not enabled, we want to emit those metrics from this pod. // NOTE: This is not optimal, as we calculate costs based on run times for other containers. // NOTE: The metrics for run times should be emitted separate from cost-model if !env.IsKubecostMetricsPodEnabled() { metrics.InitKubeMetrics(clusterCache, &metrics.KubeMetricsOpts{ EmitKubecostControllerMetrics: true, EmitNamespaceAnnotations: env.IsEmitNamespaceAnnotationsMetric(), EmitPodAnnotations: env.IsEmitPodAnnotationsMetric(), EmitKubeStateMetrics: env.IsEmitKsmV1Metrics(), }) } return &CostModelMetricsEmitter{ PrometheusClient: promClient, KubeClusterCache: clusterCache, CloudProvider: provider, Model: model, CPUPriceRecorder: cpuGv, RAMPriceRecorder: ramGv, GPUPriceRecorder: gpuGv, GPUCountRecorder: gpuCountGv, PersistentVolumePriceRecorder: pvGv, NodeSpotRecorder: spotGv, NodeTotalPriceRecorder: totalGv, RAMAllocationRecorder: ramAllocGv, CPUAllocationRecorder: cpuAllocGv, GPUAllocationRecorder: gpuAllocGv, PVAllocationRecorder: pvAllocGv, NetworkZoneEgressRecorder: networkZoneEgressCostG, NetworkRegionEgressRecorder: networkRegionEgressCostG, NetworkInternetEgressRecorder: networkInternetEgressCostG, ClusterManagementCostRecorder: clusterManagementCostGv, LBCostRecorder: lbCostGv, recordingLock: new(sync.Mutex), recordingStopping: false, recordingStop: nil, } }
reverse.py
def reverse_string(a_string: str): """Take the input a_string and return it reversed (e.g. "hello" becomes
reversed_string += a_string[~i] return reversed_string
"olleh".""" reversed_string = "" for i in range(len(a_string)):
mkgti.py
#!/usr/bin/env python from __future__ import print_function, division import os, sys import matplotlib.pyplot as plt import numpy as np import argparse from astropy import log from os import path from glob import glob from subprocess import check_call import shutil from astropy.table import Table from astropy.io import fits from nicer.values import * from nicer.plotutils import plot_light_curve def runcmd(cmd): # CMD should be a list of strings since it is not processed by a shell
################################################ # Checking the presence of HEASOFT try: check_call('nicerversion',env=os.environ) except: print("You need to initialize FTOOLS/HEASOFT first (e.g., type 'heainit')!", file=sys.stderr) exit() ################################################ # Checking the presence of gti header and columns in data/ gticolumns = path.join(datadir,'gti_columns.txt') gtiheader = path.join(datadir,'gti_header.txt') if not os.path.isfile(gtiheader) or not os.path.isfile(gticolumns): log.error('The files gti_header.txt or gti_columns.txt are missing. Check the {} directory'.format(os.path.abspath(datadir))) exit() desc = """ Create a simple GTI file from a pair of NICER METs. This is handy as an input file to niextract-events timefile=xxx.gti """ parser = argparse.ArgumentParser(description = desc) parser.add_argument("startmet", help="Starting MET for GTI", type=float) parser.add_argument("stopmet", help="Ending MET for GTI", type=float) parser.add_argument("--gtiname", help="Name of output GTI FITS file (default gti.fits)", default="gti.fits") args = parser.parse_args() ################################################ ## STEP 5 - dumping the TSTART and TEND into text file import tempfile fp = tempfile.NamedTemporaryFile() fp.write('{0} {1}\n'.format(args.startmet,args.stopmet)) fp.flush() ################################################ ## STEP 6 - Making the GTI file from the text file log.info("Making the GTI file gti.fits from the GTI data textfile") cmd = ['ftcreate', '{}'.format(gticolumns), fp.name, args.gtiname, 'headfile={}'.format(gtiheader), 'extname="GTI"', 'clobber=yes'] runcmd(cmd) fp.close()
log.info('CMD: '+" ".join(cmd)) os.system(" ".join(cmd)) ## Some ftools calls don't work properly with check_call...not sure why! ## so I am using os.system instead of check_call #check_call(cmd,env=os.environ)
opcode.rs
pub mod Opcode { pub const LoadI: u8 = 0x1; pub const LoadF: u8 = 0x2; pub const LoadL: u8 = 0x3; pub const LoadD: u8 = 0x4; pub const LoadG: u8 = 0xa1;
pub const LoadAt: u8 = 0xa2; pub const StoreAt: u8 = 0xa3; pub const Ret: u8 = 0xa4; pub const Ret0: u8 = 0xa5; pub const Call: u8 = 0xa6; pub const StoreG: u8 = 0xa7; pub const Move: u8 = 0xa8; pub const Label: u8 = 0xa9; pub const Goto: u8 = 0xe1; pub const GotoT: u8 = 0xe2; pub const GotoF: u8 = 0xe3; pub fn to_string<'a>(op: u8) -> &'a str { match op { LoadI => "LoadI", Move => "Move", _ => "", } } } pub mod Size { pub const Float: u32 = ::std::mem::size_of::<f32>() as u32; pub const Double: u32 = ::std::mem::size_of::<f64>() as u32; pub const Int: u32 = ::std::mem::size_of::<i32>() as u32; pub const Long: u32 = ::std::mem::size_of::<i64>() as u32; pub const Bool: u32 = ::std::mem::size_of::<bool>() as u32; }
provider.go
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ /* Notice: This file has been modified for Hyperledger Fabric SDK Go usage. Please review third_party pinning scripts and patches for more details. */ package prometheus import ( "github.com/ChinaArJun/fabric-sdk-go-gm/internal/github.com/hyperledger/fabric/common/metrics" kitmetrics "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/prometheus" prom "github.com/prometheus/client_golang/prometheus" ) type Provider struct{} func (p *Provider) NewCounter(o metrics.CounterOpts) metrics.Counter { return &Counter{ Counter: prometheus.NewCounterFrom( prom.CounterOpts{ Namespace: o.Namespace, Subsystem: o.Subsystem, Name: o.Name, Help: o.Help, }, o.LabelNames, ), } } func (p *Provider) NewGauge(o metrics.GaugeOpts) metrics.Gauge { return &Gauge{ Gauge: prometheus.NewGaugeFrom( prom.GaugeOpts{ Namespace: o.Namespace, Subsystem: o.Subsystem, Name: o.Name, Help: o.Help, }, o.LabelNames, ), } } func (p *Provider) NewHistogram(o metrics.HistogramOpts) metrics.Histogram { return &Histogram{ Histogram: prometheus.NewHistogramFrom( prom.HistogramOpts{ Namespace: o.Namespace, Subsystem: o.Subsystem, Name: o.Name, Help: o.Help, Buckets: o.Buckets, }, o.LabelNames, ), } } type Counter struct{ kitmetrics.Counter } func (c *Counter) With(labelValues ...string) metrics.Counter { return &Counter{Counter: c.Counter.With(labelValues...)} } type Gauge struct{ kitmetrics.Gauge } func (g *Gauge) With(labelValues ...string) metrics.Gauge { return &Gauge{Gauge: g.Gauge.With(labelValues...)}
type Histogram struct{ kitmetrics.Histogram } func (h *Histogram) With(labelValues ...string) metrics.Histogram { return &Histogram{Histogram: h.Histogram.With(labelValues...)} }
}