text
stringlengths
3
1.05M
/* * Vector subtraction */ void dvsub(int n, double *x, int incx, double *y, int incy, double *z, int incz) { while( n-- ) { *z = *x - *y; x += incx; y += incy; z += incz; } return; }
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets 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. """wiki_auto dataset for text simplification.""" import json import tensorflow as tf import tensorflow_datasets.public_api as tfds _CITATION = """\ @inproceedings{acl/JiangMLZX20, author = {Chao Jiang and Mounica Maddela and Wuwei Lan and Yang Zhong and Wei Xu}, editor = {Dan Jurafsky and Joyce Chai and Natalie Schluter and Joel R. Tetreault}, title = {Neural {CRF} Model for Sentence Alignment in Text Simplification}, booktitle = {Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, {ACL} 2020, Online, July 5-10, 2020}, pages = {7943--7960}, publisher = {Association for Computational Linguistics}, year = {2020}, url = {https://www.aclweb.org/anthology/2020.acl-main.709/} } """ _DESCRIPTION = """ WikiAuto provides a set of aligned sentences from English Wikipedia and Simple English Wikipedia as a resource to train sentence simplification systems. The authors first crowd-sourced a set of manual alignments between sentences in a subset of the Simple English Wikipedia and their corresponding versions in English Wikipedia (this corresponds to the `manual` config), then trained a neural CRF system to predict these alignments. The trained model was then applied to the other articles in Simple English Wikipedia with an English counterpart to create a larger corpus of aligned sentences (corresponding to the `auto`, `auto_acl`, `auto_full_no_split`, and `auto_full_with_split` configs here). """ _URLs = { 'manual': { 'dev': 'https://github.com/chaojiang06/wiki-auto/raw/master/wiki-manual/dev.tsv', 'test': 'https://github.com/chaojiang06/wiki-auto/raw/master/wiki-manual/test.tsv', }, 'auto_acl': { 'normal': 'https://github.com/chaojiang06/wiki-auto/raw/master/wiki-auto/ACL2020/train.src', 'simple': 'https://github.com/chaojiang06/wiki-auto/raw/master/wiki-auto/ACL2020/train.dst', }, 'auto_full_no_split': { 'normal': 'https://github.com/chaojiang06/wiki-auto/raw/master/wiki-auto/GEM2021/full_no_split/train.src', 'simple': 'https://github.com/chaojiang06/wiki-auto/raw/master/wiki-auto/GEM2021/full_no_split/train.dst', }, 'auto_full_with_split': { 'normal': 'https://github.com/chaojiang06/wiki-auto/raw/master/wiki-auto/GEM2021/full_with_split/train.src', 'simple': 'https://github.com/chaojiang06/wiki-auto/raw/master/wiki-auto/GEM2021/full_with_split/train.dst', }, 'auto': { 'part_1': 'https://dl.dropboxusercontent.com/sh/ohqaw41v48c7e5p/AAATBDhU1zpdcT5x5WgO8DMaa/wiki-auto-all-data/wiki-auto-part-1-data.json', 'part_2': 'https://dl.dropboxusercontent.com/sh/ohqaw41v48c7e5p/AAATgPkjo_tPt9z12vZxJ3MRa/wiki-auto-all-data/wiki-auto-part-2-data.json', }, } class WikiAuto(tfds.core.GeneratorBasedBuilder): """DatasetBuilder for wiki_auto dataset.""" VERSION = tfds.core.Version('1.0.0') RELEASE_NOTES = { '1.0.0': 'Initial release.', } BUILDER_CONFIGS = [ tfds.core.BuilderConfig( name='manual', description='A set of 10K Wikipedia sentence pairs aligned by crowd workers.' ), tfds.core.BuilderConfig( name='auto_acl', description='Sentence pairs aligned to train the ACL2020 system.'), tfds.core.BuilderConfig( name='auto_full_no_split', description='All automatically aligned sentence pairs without sentence splitting.' ), tfds.core.BuilderConfig( name='auto_full_with_split', description='All automatically aligned sentence pairs with sentence splitting.' ), tfds.core.BuilderConfig( name='auto', description='A large set of automatically aligned sentence pairs.') ] DEFAULT_CONFIG_NAME = 'auto' def _info(self) -> tfds.core.DatasetInfo: """Returns the dataset metadata.""" if self.builder_config.name == 'manual': features = tfds.features.FeaturesDict({ 'alignment_label': tfds.features.ClassLabel( names=['notAligned', 'aligned', 'partialAligned']), 'normal_sentence_id': tfds.features.Text(), 'simple_sentence_id': tfds.features.Text(), 'normal_sentence': tfds.features.Text(), 'simple_sentence': tfds.features.Text(), 'GLEU-score': tf.float64, }) elif (self.builder_config.name == 'auto_acl' or self.builder_config.name == 'auto_full_no_split' or self.builder_config.name == 'auto_full_with_split'): features = tfds.features.FeaturesDict({ 'normal_sentence': tfds.features.Text(), 'simple_sentence': tfds.features.Text(), }) else: features = tfds.features.FeaturesDict({ 'example_id': tfds.features.Text(), 'normal': { 'normal_article_id': tf.int32, 'normal_article_title': tfds.features.Text(), 'normal_article_url': tfds.features.Text(), 'normal_article_content': tfds.features.Sequence({ 'normal_sentence_id': tfds.features.Text(), 'normal_sentence': tfds.features.Text(), }), }, 'simple': { 'simple_article_id': tf.int32, 'simple_article_title': tfds.features.Text(), 'simple_article_url': tfds.features.Text(), 'simple_article_content': tfds.features.Sequence({ 'simple_sentence_id': tfds.features.Text(), 'simple_sentence': tfds.features.Text(), }), }, 'paragraph_alignment': tfds.features.Sequence({ 'normal_paragraph_id': tfds.features.Text(), 'simple_paragraph_id': tfds.features.Text(), }), 'sentence_alignment': tfds.features.Sequence({ 'normal_sentence_id': tfds.features.Text(), 'simple_sentence_id': tfds.features.Text(), }), }) return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=features, supervised_keys=None, homepage='https://github.com/chaojiang06/wiki-auto', citation=_CITATION, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" urls_to_download = _URLs[self.builder_config.name] data_dir = dl_manager.download_and_extract(urls_to_download) if self.builder_config.name in ['manual', 'auto']: return { spl: self._generate_examples(filepaths=data_dir, split=spl) for spl in data_dir } else: return {'full': self._generate_examples(filepaths=data_dir, split='full')} def _generate_examples(self, filepaths, split): """Yields examples.""" if self.builder_config.name == 'manual': keys = [ 'alignment_label', 'simple_sentence_id', 'normal_sentence_id', 'simple_sentence', 'normal_sentence', 'GLEU-score' ] with tf.io.gfile.GFile(filepaths[split]) as f: for id_, line in enumerate(f): values = line.strip().split('\t') dict_ = {} for k, v in zip(keys, values): dict_[k] = v yield id_, dict_ elif (self.builder_config.name == 'auto_acl' or self.builder_config.name == 'auto_full_no_split' or self.builder_config.name == 'auto_full_with_split'): with tf.io.gfile.GFile(filepaths['normal']) as fi: with tf.io.gfile.GFile(filepaths['simple']) as fo: for id_, (norm_se, simp_se) in enumerate(zip(fi, fo)): yield id_, { 'normal_sentence': norm_se, 'simple_sentence': simp_se, } else: dataset_dict = json.load(tf.io.gfile.GFile(filepaths[split])) for id_, (eid, example_dict) in enumerate(dataset_dict.items()): res = { 'example_id': eid, 'normal': { 'normal_article_id': example_dict['normal']['id'], 'normal_article_title': example_dict['normal']['title'], 'normal_article_url': example_dict['normal']['url'], 'normal_article_content': { 'normal_sentence_id': [ sen_id for sen_id, sen_txt in example_dict['normal'] ['content'].items() ], 'normal_sentence': [ sen_txt for sen_id, sen_txt in example_dict['normal'] ['content'].items() ], }, }, 'simple': { 'simple_article_id': example_dict['simple']['id'], 'simple_article_title': example_dict['simple']['title'], 'simple_article_url': example_dict['simple']['url'], 'simple_article_content': { 'simple_sentence_id': [ sen_id for sen_id, sen_txt in example_dict['simple'] ['content'].items() ], 'simple_sentence': [ sen_txt for sen_id, sen_txt in example_dict['simple'] ['content'].items() ], }, }, 'paragraph_alignment': { 'normal_paragraph_id': [ norm_id for simp_id, norm_id in example_dict.get( 'paragraph_alignment', []) ], 'simple_paragraph_id': [ simp_id for simp_id, norm_id in example_dict.get( 'paragraph_alignment', []) ], }, 'sentence_alignment': { 'normal_sentence_id': [ norm_id for simp_id, norm_id in example_dict.get( 'sentence_alignment', []) ], 'simple_sentence_id': [ simp_id for simp_id, norm_id in example_dict.get( 'sentence_alignment', []) ], }, } yield id_, res
const Joi = require('joi'); const { objectId } = require('./custom.validation'); const create = { body: Joi.object().keys({ ten: Joi.string().optional().required(), vungMien: Joi.number().optional().min(1).max(3), }), }; const findByIdAndUpdate = { body: Joi.object().keys({ ten: Joi.string().optional(), vungMien: Joi.number().optional().min(1).max(3), }), }; const findByIdAndDelete = { params: Joi.object().keys({ id: Joi.string().required(), }), }; const paginate = { params: Joi.object().keys({ id: Joi.string().custom(objectId), month: Joi.string().optional(), year: Joi.string().optional(), }), }; const findById = { params: Joi.object().keys({ id: Joi.string().required(), }), }; const updateDeviceToken = { params: Joi.object().keys({ id: Joi.string().custom(objectId).required(), }), body: Joi.object().keys({ deviceToken: Joi.string().required(), }), }; module.exports = { create, findByIdAndUpdate, findByIdAndDelete, paginate, findById, updateDeviceToken, };
"""Handler for fetching outputs from fully qualified stacks. The `output` handler supports fetching outputs from stacks created within a sigle config file. Sometimes it's useful to fetch outputs from stacks created outside of the current config file. `rxref` supports this by not using the :class:`stacker.context.Context` to expand the fqn of the stack. Example: conf_value: ${rxref some-relative-fully-qualified-stack-name::SomeOutputName} """ from .output import deconstruct TYPE_NAME = "rxref" def handler(value, provider=None, context=None, **kwargs): """Fetch an output from the designated stack. Args: value (str): string with the following format: <stack_name>::<output_name>, ie. some-stack::SomeOutput provider (:class:`stacker.provider.base.BaseProvider`): subclass of the base provider context (:class:`stacker.context.Context`): stacker context Returns: str: output from the specified stack """ if provider is None: raise ValueError('Provider is required') if context is None: raise ValueError('Context is required') d = deconstruct(value) stack_fqn = context.get_fqn(d.stack_name) output = provider.get_output(stack_fqn, d.output_name) return output
# importing libraries import pandas as pd # custom libraries import config def cataract_or_not(txt): if "cataract" in txt: return 1 else: return 0 def downsample(df): df = pd.concat([ df.query('cataract==1'), df.query('cataract==0').sample(sum(df['cataract']), random_state=42) ]) return df def preprocess_me(path): """ path: dataframe""" df=pd.read_csv(path) df['left_eye_cataract']=df["Left-Diagnostic Keywords"].apply(lambda x:cataract_or_not(x)) df['right_eye_cataract']=df["Right-Diagnostic Keywords"].apply(lambda x:cataract_or_not(x)) left_df=df.loc[:,['Left-Fundus','left_eye_cataract']].rename(columns={'left_eye_cataract':'cataract'}) left_df['Path']=config.oc_img_path+"/"+left_df['Left-Fundus'] left_df=left_df.drop(['Left-Fundus'],1) right_df=df.loc[:,['Right-Fundus','right_eye_cataract']].rename(columns={'right_eye_cataract':'cataract'}) right_df['Path']=config.oc_img_path+"/"+right_df['Right-Fundus'] right_df=right_df.drop(['Right-Fundus'],1) ## if you have data with little unbalance skip this step left_df = downsample(left_df) right_df = downsample(right_df) train_df = pd.concat([left_df, right_df], ignore_index=True) # shuffle train_df=train_df.sample(frac=1.0) return train_df
// // The MIT License(MIT) // // Copyright(c) 2014 Demonsaw LLC // // 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. #ifndef _EJA_GROUP_CIPHER_ #define _EJA_GROUP_CIPHER_ #include <string> #include "object/cipher.h" #include "system/type.h" namespace eja { class group_cipher : public cipher { protected: std::string m_data; public: using ptr = std::shared_ptr<group_cipher>; public: group_cipher() : cipher() { } group_cipher(const eja::group_cipher& cipher) : eja::cipher(cipher), m_data(cipher.m_data) { } group_cipher(const size_t size) : cipher(size) { } group_cipher(const std::string& id) : cipher(id) { } group_cipher(const char* id) : cipher(id) { } virtual ~group_cipher() override { } // Utility bool has_data() const { return !m_data.empty(); } // Mutator void set_data(const std::string& data) { m_data = data; } void set_data(const char* data) { m_data = data; } void set_data() { m_data.clear(); } // Accessor const std::string& get_data() const { return m_data; } // Static static ptr create() { return std::make_shared<group_cipher>(); } static ptr create(const eja::group_cipher& group_cipher) { return std::make_shared<eja::group_cipher>(group_cipher); } static ptr create(const group_cipher::ptr group_cipher) { return std::make_shared<eja::group_cipher>(*group_cipher); } static ptr create(const std::string& id) { return std::make_shared<group_cipher>(id); } static ptr create(const char* id) { return std::make_shared<group_cipher>(id); } }; } #endif
import { ApolloClient } from 'apollo-client'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { HttpLink } from 'apollo-link-http'; export default new ApolloClient({ link: new HttpLink({ uri: 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2' }), fetchOptions: { mode: 'no-cors' }, cache: new InMemoryCache() });
__all__ = [ "resnet_param_groups", "resnet18", "resnet34", "resnet50", "resnet101", "resnet152", "resnext101_32x8d", ] from icevision.imports import * from icevision.utils import * def _resnet_features(model: nn.Module, out_channels: int): # remove last layer (fully-connected) modules = list(model.named_children())[:-1] features = nn.Sequential(OrderedDict(modules)) features.out_channels = out_channels features.param_groups = MethodType(resnet_param_groups, features) return features def resnet_param_groups(model: nn.Module) -> List[nn.Parameter]: layers = [] layers += [nn.Sequential(model.conv1, model.bn1)] layers += [l for name, l in model.named_children() if name.startswith("layer")] param_groups = [list(layer.parameters()) for layer in layers] check_all_model_params_in_groups2(model, param_groups) return param_groups def resnet18(pretrained: bool = True): model = torchvision.models.resnet18(pretrained=pretrained) return _resnet_features(model, out_channels=512) def resnet34(pretrained: bool = True): model = torchvision.models.resnet34(pretrained=pretrained) return _resnet_features(model, out_channels=512) def resnet50(pretrained: bool = True): model = torchvision.models.resnet50(pretrained=pretrained) return _resnet_features(model, out_channels=2048) def resnet101(pretrained: bool = True): model = torchvision.models.resnet101(pretrained=pretrained) return _resnet_features(model, out_channels=2048) def resnet152(pretrained: bool = True): model = torchvision.models.resnet152(pretrained=pretrained) return _resnet_features(model, out_channels=2048) def resnext101_32x8d(pretrained: bool = True): model = torchvision.models.resnext101_32x8d(pretrained=pretrained) return _resnet_features(model, out_channels=2048)
""" Django settings for animal crossing project. Generated by 'django-admin startproject' using Django 2.2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'wa1aa3p_56hg-y)y6-98t1y#i(wxv#p5wlffx36q4z1egu9z2b' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['ac-fishing.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.sites', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sessions', # My App 'animalcrossing', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ac.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ac.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join('static'), ) SITE_ID = 1
''' Copyright 2018 - LC This file is part of webshscr. webshscr is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. webshscr is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with webshscr. If not, see <http://www.gnu.org/licenses/>. ''' import hashlib import os from flask_login import UserMixin from utils import stripstr USER_FILE = "users.dat" #format: user:sha256(pwd):group_1,...group_n filepath = "" Users = {} class User(UserMixin): def __init__(self, name, hash_pwd, groups = []): self._name = name self._hash_pwd = hash_pwd self._groups = set(groups) self._authenticated = False @property def name(self): return self._name @property def hash_pwd(self): return self._hash_pwd @property def groups(self): return self._groups def add_group(self, name): self._groups.add(name) def has_group(self, name): return name in self._groups def has_groups(self, groups): return len(self._groups.intersection(set(groups))) > 0 def verify_password(self, password): check = (self._hash_pwd == hashlib.sha256(self._name + ":" + password).hexdigest()) self._authenticated = check return check #subsequent override UserMixin methods def get_id(self): return unicode(self._name) @property def is_authenticated(self): return self._authenticated def init_users(config_dir): global USER_FILE global filepath filepath = os.path.join(config_dir, USER_FILE) _read_users() def _read_users(): global filepath global Users Users = {} with open(filepath, 'r') as f: for line in f: line = line.rstrip() #removes trailing whitespace and '\n' chars if line.startswith("#"): continue #skips comments that starts with '#' fields = line.split(':') if len(fields) >= 3: name = fields[0].strip() hash_pwd = fields[1].strip() groups = fields[2].split(',') groups = map(stripstr, groups) user = User(name, hash_pwd, groups) Users[name] = user def _write_users(): global filepath global Users with open(filepath, 'w') as f: for name in Users: user = Users[name] line = user.name + ":" + user.hash_pwd + ":" + ",".join(user.groups) f.write(line+'\n') def get_user_names(): return Users.keys() def get_user(name): global Users if name in Users: return Users[name] else: return None def create_user(name, password): return User(name, hashlib.sha256(name + ":" + password).hexdigest()) def add_or_modify_user(user): global Users Users[user.name] = user _write_users() def del_user(name): if name in Users: del Users[name] _write_users()
import graphene from ...graphql.core.enums import to_enum from ...payment import GATEWAYS_ENUM, ChargeStatus PaymentChargeStatusEnum = to_enum( ChargeStatus, type_name='PaymentChargeStatusEnum') PaymentGatewayEnum = graphene.Enum.from_enum(GATEWAYS_ENUM) class OrderAction(graphene.Enum): CAPTURE = 'CAPTURE' MARK_AS_PAID = 'MARK_AS_PAID' REFUND = 'REFUND' VOID = 'VOID' @property def description(self): if self == OrderAction.CAPTURE: return 'Represents the capture action.' if self == OrderAction.MARK_AS_PAID: return 'Represents a mark-as-paid action.' if self == OrderAction.REFUND: return 'Represents a refund action.' if self == OrderAction.VOID: return 'Represents a void action.' raise ValueError('Unsupported enum value: %s' % self.value)
from __future__ import absolute_import import jinja2 from jinja2.ext import Extension from .templatetags.wagtailuserbar import wagtailuserbar class WagtailUserbarExtension(Extension): def __init__(self, environment): super(WagtailUserbarExtension, self).__init__(environment) self.environment.globals.update({ 'wagtailuserbar': jinja2.contextfunction(wagtailuserbar), }) # Nicer import names userbar = WagtailUserbarExtension
/*! ========================================================= * Argon Design System React - v1.1.0 ========================================================= * Product Page: https://www.creative-tim.com/product/argon-design-system-react * Copyright 2020 Creative Tim (https://www.creative-tim.com) * Licensed under MIT (https://github.com/creativetimofficial/argon-design-system-react/blob/main/LICENSE.md) * Coded by Creative Tim ========================================================= * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ import React from "react"; // reactstrap components import { Button, Card, Container, Row, Col } from "reactstrap"; // core components import DemoNavbar from "components/Navbars/DemoNavbar.js"; import SimpleFooter from "components/Footers/SimpleFooter.js"; import profile from "assets/img/theme/f9307072-48c1-416d-87fb-f9a538466e71.jpg"; class Profile extends React.Component { componentDidMount() { document.documentElement.scrollTop = 0; document.scrollingElement.scrollTop = 0; this.refs.main.scrollTop = 0; } render() { return ( <> <DemoNavbar /> <main className="profile-page" ref="main"> <section className="section-profile-cover section-shaped my-0"> {/* Circles background */} <div className="shape shape-style-1 shape-default alpha-4"> <span /> <span /> <span /> <span /> <span /> <span /> <span /> </div> {/* SVG separator */} <div className="separator separator-bottom separator-skew"> <svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" version="1.1" viewBox="0 0 2560 100" x="0" y="0" > <polygon className="fill-white" points="2560 0 2560 100 0 100" /> </svg> </div> </section> <section className="section"> <Container> <Card className="card-profile shadow mt--300"> <div className="px-4"> <Row className="justify-content-center"> <Col className="order-lg-2" lg="3"> <div className="card-profile-image"> <a href="#pablo" onClick={e => e.preventDefault()}> <img alt="..." className="rounded-circle" src={profile} /> </a> </div> </Col> <Col className="order-lg-3 text-lg-right align-self-lg-center" lg="4" > <div className="card-profile-actions py-4 mt-lg-0"> <Button className="mr-4" color="info" href="#pablo" onClick={e => e.preventDefault()} size="sm" > Connect </Button> <Button className="float-right" color="default" href="#pablo" onClick={e => e.preventDefault()} size="sm" > Message </Button> </div> </Col> <Col className="order-lg-1" lg="4"> <div className="card-profile-stats d-flex justify-content-center"> <div> <span className="heading">0</span> <span className="description">Years of working experience</span> </div> <div> <span className="heading">10</span> <span className="description">Web development projects</span> </div> </div> </Col> </Row> <div className="text-center mt-5"> <h3> Miral Alabdullah{" "} <span className="font-weight-light">, 23</span> </h3> <div className="h6 font-weight-300"> <i className="ni location_pin mr-2" /> Jordan, Irbid </div> <div className="h6 mt-4"> <i className="ni business_briefcase-24 mr-2" /> Computer Science - Software Developer </div> <div> <i className="ni education_hat mr-2" /> University of Computer Science </div> </div> <div className="mt-5 py-5 border-top text-center"> <Row className="justify-content-center"> <Col lg="9"> <p> An Ambitious Front-End Software Developer. </p> <a href="#pablo" onClick={e => e.preventDefault()}> Show more </a> </Col> </Row> </div> </div> </Card> </Container> </section> </main> <SimpleFooter /> </> ); } } export default Profile;
''' Created on 22 Mar 2016 @author: steve ''' import read_file as rf import math def LFC_tracks(in_file_1, in_file_2, chromosome): """ Return a list --> [chr, start, end, LFC] LFC = log2(in_file_1/in_file_2) First and last position in output is LFC=0 """ bin_list=rf.read_bin(in_file_1, chromosome) calc_LFC(in_file_2, bin_list) return bin_list def raw_count_track(WT_24nt, chromosome): """ Raw RPRM for inner track """ bin_list=rf.read_bin(WT_24nt, chromosome) return bin_list def calc_LFC(in_file_2, bin_list): """ Mods the count to L2FC in each bin """ #for itereating through the bin list bin_no=0 header_line = True with open(in_file_2, 'r') as f: for bin_count in f: if header_line: header_line = False else: bin_count = bin_count.strip().split(',') try: FC = bin_list[bin_no][3]/float(bin_count[3]) LFC = math.log(FC, 2) except: LFC = 0 bin_list[bin_no][3] = round(LFC, 2) bin_no+=1 return bin_list
#pragma once #include <Python.h> #include <library/cpp/yson/node/node.h> namespace NYT { PyObject* BuildPyObject(const TNode& val); }
import factory import faker fake = faker.Factory.create() class UserFactory(factory.django.DjangoModelFactory): id = factory.LazyAttribute( lambda x: str(fake.random_int( min=1000000000000000000, max=999999999999999999999)) ) access_token = factory.LazyAttribute( lambda x: fake.sha256() + fake.sha256() ) email = factory.LazyAttribute(lambda x: fake.email()) first_name = factory.LazyAttribute(lambda x: fake.first_name()) last_name = factory.LazyAttribute(lambda x: fake.last_name()) is_staff = factory.LazyAttribute(lambda x: fake.boolean()) class Meta: model = 'todo.User' class TodoFactory(factory.django.DjangoModelFactory): name = factory.LazyAttribute( lambda x: ' '.join(fake.words(fake.random_int(1, 4))) ) completed = factory.LazyAttribute(lambda x: fake.boolean()) user = factory.SubFactory(UserFactory) class Meta: model = 'todo.Todo'
import joblib import uuid class Packager(): def __init__(self, model): self.model = model self.function_map = { "sklearn": self.package_sklearn_model, "keras": self.package_keras_model, "pytorch": self.package_pytorch_model } def package_sklearn_model(self): filename = str(uuid.uuid1()) + ".joblib" joblib.dump(self.model, filename) return filename def package_keras_model(self): filename = str(uuid.uuid1()) + ".h5" self.model.save(filename) return filename def package_pytorch_model(self): import torch filename = str(uuid.uuid1()) + ".pytorch" scripted_model = torch.jit.script(self.model) scripted_model.save(filename) return filename
""" Le premier prgramme en Python * utilisation des arguments de la lignne de commande * les listes et la fonction map * les threads * le logger * Producer Consumer @author Dragos STOICA @version 0.5 @date 16.feb.2014 """ import sys, threading, logging, os, Queue class Producer(threading.Thread): """ Producer class that takes the raw data and performs some work on it. Once this work is complete it puts the resultant data in to the out queue for the Consumer class. """ def __init__(self, in_queue, fichier, lock): threading.Thread.__init__(self) self.in_queue = in_queue self.fichier = fichier self.lock = lock def run(self): self.lock.acquire() with open(self.fichier,'r') as f: #Dites bonjour a chaque personne de fichier for ligne in f: self.in_queue.put(ligne.strip(' \r\n')) logging.info("Producer: %s"%(ligne.strip(' \r\n'))) #signal that the worker task is done self.lock.release() logging.info("Producer stop.") class Consumer(threading.Thread): """ Consumer class that takes the data outputted by the Producer class and consumes the data from the out queue and outputs a meaningful result. """ def __init__(self, in_queue, lock): threading.Thread.__init__(self) self.in_queue = in_queue self.M = [] self.Mme = [] self.lock = lock def run(self): self.lock.acquire() while True: #grab the data from the out queue item = self.in_queue.get() if item[0:2] == "M.": self.M.append(item) else: self.Mme.append(item) logging.info("Consumer : %(personne)s" %{"personne":item}) #signal that the consumer task is done self.in_queue.task_done() self.lock.release() def write_file(self, fichier): f = open(fichier + "pc_resultat.txt",'w') for mme in self.Mme: #Fonction polie - saluer une personne f.write("Bonjour {}!\n".format(mme)) for m in self.M: #Fonction polie - saluer une personne f.write("Bonjour {}!\n".format(m)) f.close() def utilisation(): #Affichage mode d'utilisation print """ Le programme doit etre appelle avec minimum 1 argument: python bonjour_listes.py Nom_de_fichier.txt """ def main(argv=None): working_dir = os.path.dirname(os.path.abspath(__file__)) + "\\" #Configurez le logging pour ecrire dans un fichier texte logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', filename = working_dir + 'pc.log', level=logging.INFO) logging.info("Main start") #La boucle principale if argv is None: argv = sys.argv if len(argv) == 1: utilisation() else: #Argument 1 est le nom de fichier avec un noms per ligne in_queue = Queue.Queue() lock = threading.Lock() p = Producer(in_queue, working_dir + argv[1],lock) p.start() #spawn our consumer threads and start consuming c = Consumer(in_queue,lock) c.daemon = True c.start() #invoke method run #attendez que les donnees soit traitees in_queue.join() c.write_file(working_dir) logging.info("Main stop") return 0 if __name__ == "__main__": #Simplifiez la logique de la fonction principale sys.exit(main())
module.exports = { heroHeader: "Let the Nature Unleash Your Beauty", heroText: "Defend. Repair. Hydrate. Stay gorgeous and enhance your skin care routine with our", fromNatureToSkinDesc: "Formulated with extracts from 7 different species of plants, Miracle Radiance targets to rejuvenate your long-lost youthful, glowing skin without upsetting your complexion.", intenseHealingDesc: "Not only does Miracle Radiance heals the outer layers of your skin, but also repairs the deeper layers and protects your skin from sunlight and pollution, effectively and efficiently.", }
/** @type {import('@docusaurus/types').DocusaurusConfig} */ module.exports = { title: 'Atlas', tagline: 'Manage your data', url: 'https://atlasgo.io', baseUrl: '/', onBrokenLinks: 'throw', onBrokenMarkdownLinks: 'warn', favicon: 'https://atlasgo.io/uploads/favicon.ico', organizationName: 'ariga', projectName: 'atlas', themeConfig: { gtag: { trackingID: 'G-Z88N4TF03R' }, prism: { additionalLanguages: ['hcl'], }, navbar: { title: 'Atlas', logo: { alt: 'Atlas', src: 'https://atlasgo.io/uploads/landing/logo.svg', }, items: [ { href: 'https://github.com/ariga/atlas', className: 'header-github-link', position: 'right', }, { href: 'https://github.com/ariga/atlas', className: 'header-discord-link', position: 'right', },{ href: 'https://twitter.com/ariga_io', className: 'header-twitter-link', position: 'right', }, ], }, // "footer": { "links": [ { "title": "Docs", "items": [ {"label": "Getting Started", "to": "cli/getting-started/setting-up"}, {"label": "Data Definition Language ", "to": "ddl/intro"}, {"label": "CLI Reference", "to": "cli/reference"}, {"label": "About", "to": "about"}, ] }, { "title": "Community", "items": [ {"label": "GitHub", "to": "https://github.com/ariga/atlas"}, {"label": "Discord", "to": "https://discord.com/invite/QhsmBAWzrC"}, ] }, ], copyright: ` Copyright © ${new Date().getFullYear()} The Atlas Authors. The Go gopher was designed by <a href="http://reneefrench.blogspot.com/">Renee French</a>. <br/> The design is licensed under the Creative Commons 3.0 Attributions license. Read this <a href="https://blog.golang.org/gopher">article</a> for more details. <br/> `, }, }, presets: [ [ '@docusaurus/preset-classic', { docs: { routeBasePath: '/', sidebarPath: require.resolve('./sidebars.js'), path: "../md", showLastUpdateAuthor: false, showLastUpdateTime: false, }, blog: { showReadingTime: true, }, theme: { customCss: require.resolve('./src/css/custom.css'), }, }, ], ], };
// Copyright (c) 1991-2018 Roger Allen // // 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. /*********************************************************************** * * the digitType.value field is encoded so that each bit stands for a * segment in a digit. Therefore, for each number the following table * shows how each digit is encoded. * * The digit segments are arranged like so: 0 * 1 2 * 3 * 4 5 * 6 * Displayed Digit * Seg# 0 1 2 3 4 5 6 7 8 9 * ----+---------- * 0 |x x x x x x x x * 1 |x x x x x x * 2 |x x x x x x x x * 3 | x x x x x x x * 4 |x x x x * 5 |x x x x x x x x x * 6 |x x x x x x x * **********************************************************************/ typedef struct { XPoint origin; unsigned int value; /* see preceding table */ } digitType; typedef struct alarm { unsigned int type; char date[10]; char time[10]; char command[255]; } AlarmType; #define DATE_LEN 40 #define TIME_LEN 5 #define SEG_LENGTH 17 #define SEG_WIDTH 4 #define CLOCK_WIDTH 17*SEG_WIDTH + 4*SEG_LENGTH #define CLOCK_HEIGHT 11*SEG_WIDTH/2 + 2*SEG_LENGTH #define DATE_HEIGHT 20 #define ICON_AREA_HEIGHT 0 #define LABEL_HEIGHT 25 #define BUTTON_WIDTH 55 #define DLG_H_SPC 5 #define DLG_V_SPC 5 void xs_wprintf(Widget w, char *format, ...); void InitWidgets(void); void InitDigits(void); void InitGC(void); void DoTime(XtIntervalId id); void PrintTime(char *timeBuf, int reverse); void IMouseUp(Widget w, XEvent *event, String *params, Cardinal *num_params); void IMouseDown(Widget w, XEvent *event, String *params, Cardinal *num_params); void DrawDigit(digitType digit, GC fg); void DrawSegment(XPoint origin, int segNum, GC fg); void Update(void); time_t UpdateTime(int write_date);
dojo.provide("dojox.encoding.tests.compression.splay"); dojo.require("dojox.encoding.compression.splay"); dojo.require("dojox.encoding.bits"); (function(){ var msg1 = "The rain in Spain falls mainly on the plain."; var msg2 = "The rain in Spain falls mainly on the plain.1"; var msg3 = "The rain in Spain falls mainly on the plain.ab"; var msg4 = "The rain in Spain falls mainly on the plain.!@#"; var dc = dojox.encoding.compression, dcb = dojox.encoding.bits; var s2b = function(s){ var b = []; for(var i = 0; i < s.length; ++i){ b.push(s.charCodeAt(i)); } return b; }; var b2s = function(b){ var s = []; dojo.forEach(b, function(c){ s.push(String.fromCharCode(c)); }); return s.join(""); }; var encode = function(msg){ var x = new dcb.OutputStream(), encoder = new dc.Splay(256); dojo.forEach(s2b(msg), function(v){ encoder.encode(v, x); }); console.debug("bits =", x.getWidth()); return x.getBuffer(); }; var decode = function(n, buf){ var x = new dcb.InputStream(buf, buf.length * 8), decoder = new dc.Splay(256), t = []; for(var i = 0; i < n; ++i){ t.push(decoder.decode(x)); } return b2s(t); }; tests.register("dojox.encoding.tests.compression.splay", [ function testSplayMsg1(t){ t.assertEqual(msg1, decode(msg1.length, encode(msg1))); }, function testSplayMsg2(t){ t.assertEqual(msg2, decode(msg2.length, encode(msg2))); }, function testSplayMsg3(t){ t.assertEqual(msg3, decode(msg3.length, encode(msg3))); }, function testSplayMsg4(t){ t.assertEqual(msg4, decode(msg4.length, encode(msg4))); } ]); })();
const CustomAPIError = require('./custom-error') const { StatusCodes } = require('http-status-codes') class BadRequest extends CustomAPIError { constructor (message) { super(message) this.statusCode = StatusCodes.BAD_REQUEST } } module.exports = BadRequest
/** * 全球热卖搜索商品 */ ymtapp.service("searchCategory",function(){ this.isShowDefault=false; this.isShowSearch=false; this.lastY=0; this.currentY=0; this.isSearchOver=false; this.searchKeyword=""; this.searchNumber=0; //还原方法 this.reduction = function(){}; //打开搜索框 this.openSearchBox=function(){ if(!(this.isShowSearch = !this.isShowSearch)){ this.closeSearchBox(); } } this.closeSearchBox = function(){ this.isSearchOver=false; this.reduction && this.reduction() } //搜索关键字 this.searchVal=function(val){ if(!val){ return ; } this.savekeyword(val); this.toSearch(val); } //保存关键字 this.savekeyword = function(val){ //关键字 key var SEARCH_KEY = "keywordHistory", histories=localStorage.getItem(SEARCH_KEY); //判断是否有历史记录 if(!histories){ localStorage.setItem(SEARCH_KEY,[]); histories=[]; }else{ histories=histories.split("|"); } var i = histories.length; while(i--){ if(histories[i]===val){ return; } } histories.unshift(val); localStorage.setItem(SEARCH_KEY,histories.join("|")); this.keywordHistory=histories; } this.toSearch = function(val){} this.initHistory = function(){ var histories=localStorage.getItem("keywordHistory"); if(!histories){ return []; }else{ return histories.split("|"); } } //清理历史记录 this.clear = function(){ localStorage.removeItem("keywordHistory"); this.keywordHistory=[]; } this.keywordHistory = this.initHistory(); })
import moment from 'moment' export const rolesarray = (arr) => { var emptystring = ''; for (let index = 0; index <= arr.length - 1; index++) { emptystring += arr[index] + ','; } emptystring = emptystring.replace(/,\s*$/, ""); return emptystring; } ///////////////////////////AlterModal//////////////////////////////// export const multiRolesInput = (arr) => { var newArray = []; arr.map((element, index) => { newArray.push({ value: element, label: element }); }); return newArray; } export const labeledArray = (arr) => { var newArray = []; arr.map((element, index) => { newArray.push({ value: element.name, label: element.name }); }); return newArray; } ///////////////////////////UserModal//////////////////////////////// export const PrivelegesArray = (arr) => { var newArray = []; arr.map((element, index) => { newArray.push({ value: element._id, label: element.name }); }); return newArray; } export const rolesInput = (obj) => { let newobj = { value: obj._id, label: obj.name } return newobj; } ///////////////////////////RiderModal//////////////////////////////// export const Licensed = (arr) => { var newArray = []; arr.map((element, index) => { newArray.push({ value: element._id, label: element.name }); }); return newArray; } export const licenseInput = (obj) => { let newobj = { value: 'obj', label: 'obj' } if (obj == true) { newobj.value = true newobj.label = 'Yes' } else { newobj.value = false newobj.label = 'No' } return newobj; } export const PartnerTypeInput = (obj) => { let newobj = { value: 'obj', label: 'obj' } newobj.value = obj newobj.label = obj return newobj; } ///////////////////////////DATE Component//////////////////////////////// export const get24hours = (date) => { return { from: moment(date).subtract(24, "h"), to: moment(date) } } export const formatDate = (date, format) => { return moment(new Date(date)).format(format ? format : "MMM Do YY, h:mm a"); } export const dateFormats = { f1: "MMM Do, YY"//Do MMM, YYYY" } function GetLastWeekStart() { var today = moment(); var daystoLastSunday = 0 - (1 - today.isoWeekday()) + 8; var lastSunday = today.subtract('days', daystoLastSunday); return lastSunday; } function GetLastWeekEnd() { var lastSunday = GetLastWeekStart(); var lastSaturday = lastSunday.add('days', 6); return lastSaturday; } export function getThisMonthFilter() { var result = []; var startDate = new Date(); var endDate = new Date(); if (startDate.getDate() > 25) { startDate.setDate(26); } else { startDate.setMonth(startDate.getMonth() - 1); startDate.setDate(26); } if (startDate.getMonth() == 11) { endDate.setMonth(0); endDate.setFullYear(startDate.getFullYear() + 1); } else { endDate.setMonth(startDate.getMonth() + 1); } endDate.setDate(25) result[0] = startDate.setHours(0, 0); // result[1] = new Date(); result[1] = endDate.setHours(23, 59); result[2] = endDate.setHours(23, 59); return result; } export function getLastMonthFilter() { var result = getThisMonthFilter(); var startDate = new Date(result[0]); var endDate = new Date(result[2]); startDate.setMonth(startDate.getMonth() - 1); endDate.setMonth(endDate.getMonth() - 1); endDate.setDate(25) result[0] = startDate.setHours(0, 0); result[1] = endDate.setHours(23, 59); result[2] = endDate.setHours(23, 59); return result; } function compareDate(d1, d2) { return formatDate(d1, dateFormats.f1) == formatDate(d2, dateFormats.f1) } function isLastWeek(startDate, endDate) { return compareDate(startDate, GetLastWeekStart()) && compareDate(endDate, GetLastWeekEnd()) } function isThisMonth(startDate, endDate) { var date = new Date(), y = date.getFullYear(), m = date.getMonth(); var firstDay = new Date(y, m, 1); var lastDay = new Date(y, m + 1, 0); firstDay = moment(firstDay) lastDay = moment(lastDay) return compareDate(startDate, firstDay) && compareDate(endDate, lastDay) } function isLastMonth(startDate, endDate) { let lastMonthStartDate = moment().subtract(1, 'months').startOf('month') let lastMonthEndDate = moment().subtract(1, 'months').endOf('month') return compareDate(startDate, lastMonthStartDate) && compareDate(endDate, lastMonthEndDate) } export const formatDateTimeRange = (startDate, endDate) => { startDate = moment(startDate); endDate = moment(endDate); let dayDifferenceCurrentDate = moment().diff(startDate, 'days'); let dayDiffernce = endDate.diff(startDate, 'days'); // let hourDifferenceCurrentDate = moment().diff(startDate, 'hours'); // let hourDiffernce = moment().diff(endDate, 'hours'); //var mins = moment.utc(moment(endDate, "HH:mm:ss").diff(moment(startDate, "HH:mm:ss"))).format("HH:mm") var ms = Math.abs(moment(startDate, "DD/MM/YYYY HH:mm:ss").diff(moment(endDate, "DD/MM/YYYY HH:mm:ss"))); var d = moment.duration(ms); var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm"); if (isLastWeek(startDate, endDate)) { return 'Last Week'; } if (isThisMonth(startDate, endDate)) { return 'This Month'; } if (isLastMonth(startDate, endDate)) { return 'Last Month'; } if (dayDiffernce == 6 && startDate.weekday() == 0 && endDate.weekday() == 6 && moment().isBetween(startDate, endDate)) { return "This Week"; } if (dayDifferenceCurrentDate == 1 && dayDiffernce == 1 && parseFloat(s) <= 24.00) { return s + ' Hours'; } switch (dayDifferenceCurrentDate) { case 0: return "Today" case 1: return "Yesterday" case 3: return "Last 3 Days" case 7: return "Last 7 Days" case 30: return "Last 30 Days" default: { return `${formatDate(startDate, dateFormats.f1)} - ${formatDate(endDate, dateFormats.f1)}` } } }
/******************************************************************************/ /* view.js -- Deal with integration views * * Copyright Yahoo Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this Software except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; class View { constructor (data) { Object.assign(this, data); } /** * A Cont3xt View object * * Cont3xt Views are used to save lists of integrations to apply to a query. * @typedef Cont3xtView * @type {object} * @param {string} _id - The id of the view * @param {string} name - The name of the view * @param {string} creator - The creator of the view * @param {string[]} integrations - The array of integration names in this view * @param {array} editRoles - The Arkime roles that can edit this view * @param {array} viewRoles - The Arkime roles that can view this view * @param {boolean} _editable - Whether the logged in user is allowed to edit this view * @param {boolean} _viewable - Whether the logged in user is allowed to view this view */ /** * GET - /api/views * * Returns views that the requesting user is allowed to view. * @name /views * @returns {Cont3xtView[]} views - An array of views that the logged in user can view * @returns {boolean} success - True if the request was successful, false otherwise */ static async apiGet (req, res, next) { const roles = await req.user.getRoles(); const views = await Db.getMatchingViews(req.user.userId, [...roles]); // Set editable on any views that the user is allowed to edit for (const view of views) { view._editable = view.creator === req.user.userId || req.user.hasRole(view.editRoles); view._viewable = view.creator === req.user.userId || req.user.hasRole(view.viewRoles); } res.send({ success: true, views: views }); } /** * Verify the view, returns error msg on failure */ static verifyView (view) { // TODO: Check roles if (typeof (view.name) !== 'string') { return 'Missing name'; } if (view.viewRoles !== undefined && !Array.isArray(view.viewRoles)) { return 'viewRoles must be array'; } if (view.editRoles !== undefined && !Array.isArray(view.editRoles)) { return 'viewRoles must be array'; } if (view.integrations !== undefined && !Array.isArray(view.integrations)) { return 'integrations must be array'; } return null; } /** * POST - /api/view * * Creates a new view * @name /view * @param {Cont3xtView} views - The view to create * @returns {boolean} success - True if the request was successful, false otherwise * @returns {string} text - The success/error message to (optionally) display to the user */ static async apiCreate (req, res, next) { const view = req.body; view.creator = req.user.userId; const msg = View.verifyView(view); if (msg) { return res.send({ success: false, text: msg }); } const result = await Db.putView(null, view); if (!result) { return res.send({ success: false, text: 'ES Error' }); } view._id = result; view._editable = true; view._viewable = true; return res.send({ success: true, text: 'Success', view }); } /** * PUT - /api/view/:id * * Updates a view * @name /view/:id * @param {Cont3xtView} views - The view to update * @returns {boolean} success - True if the request was successful, false otherwise * @returns {string} text - The success/error message to (optionally) display to the user */ static async apiUpdate (req, res, next) { const dbView = await Db.getView(req.params.id); if (!dbView) { return res.send({ success: false, text: 'View not found' }); } if (dbView.creator !== req.user.userId && !(req.user.hasRole(dbView.editRoles))) { return res.send({ success: false, text: 'Permission denied' }); } const view = req.body; view.creator = dbView.creator; // Make sure the creator doesn't get changed const msg = View.verifyView(view); if (msg) { return res.send({ success: false, text: msg }); } try { const results = await Db.putView(req.params.id, view); if (!results) { return res.send({ success: false, text: 'ES Error' }); } return res.send({ success: true, text: 'Success' }); } catch (err) { return res.send({ success: false, text: err.toString() }); } } /** * DELETE - /api/view/:id * * Deletes a view * @name /view/:id * @param {Cont3xtView} views - The view to delete * @returns {boolean} success - True if the request was successful, false otherwise * @returns {string} text - The success/error message to (optionally) display to the user */ static async apiDelete (req, res, next) { const view = await Db.getView(req.params.id); if (!view) { return res.send({ success: false, text: 'View not found' }); } if (view.creator !== req.user.userId && !(req.user.hasRole(view.editRoles))) { return res.send({ success: false, text: 'Permission denied' }); } const results = await Db.deleteView(req.params.id, req.body); if (!results) { return res.send({ success: false, text: 'ES Error' }); } return res.send({ success: true, text: 'Success' }); } } module.exports = View; // Must be at bottom to avoid circular dependency const Db = require('./db.js');
module.exports = { onInput: function(input) { this.state = { size: input.size || "normal", label: input.label || "(no label)" }; } };
import React from 'react'; import { useGlobal } from 'reactn'; import styled from 'styled-components'; import _ from 'lodash'; import { Card, Value, FlexRow, FlexColumn, Devices } from '../../Common'; import BlockChart from './BlockChart'; import { Link } from 'react-router-dom'; import { timeAgo, getShortHash, formatValue } from '../../../utils'; import { getBlockTimeRange, getBlockHeight } from '../../../services/api/tz-stats'; function calcAgo(last) { return timeAgo.format(new Date(last)); } function convertRemToPixels(rem) { return rem * parseFloat(getComputedStyle(document.documentElement).fontSize); } const BlockHistory = () => { const [config] = useGlobal('config'); const [chain] = useGlobal('chain'); // model const [data, setData] = React.useState({ isLoaded: false, blocks: [], last: {} }); const [lastFullLoad, setLastFullLoad] = React.useState(0); // chart size handling const [chartConfig, setChartConfig] = React.useState({size: 60, width: 11, margin: 1}); const ref = React.useRef(null); const rootElement = document.documentElement; // ago update handling const [countInTimeout, setCountInTimeout] = React.useState(0); const [ago, setAgo] = React.useState(calcAgo(chain.timestamp)); // manage dynamic size React.useEffect(() => { function adjustSize() { const chart = ref.current ? ref.current.offsetWidth : 720; // Note: values are aligned with the CSS configuration in BlockChart const elem = convertRemToPixels(0.88); const margin = Math.max(parseInt(convertRemToPixels(0.05)), 1); setChartConfig({ size: parseInt(chart / (elem + margin)), width: elem, margin: margin, }); // console.log("Resize",elem,margin,parseInt(chart / (elem+margin) )) } const resize = _.debounce(() => { adjustSize(); }, 200); adjustSize(); window.addEventListener('resize', resize); return () => window.removeEventListener('resize', resize); }, [setChartConfig, rootElement.style.fontSize]); // update displayed time each 10 sec React.useEffect(() => { const diff = (60 - new Date().getSeconds())%10; let timer = setTimeout(() => { setCountInTimeout(c => c + 1); }, diff*1000); setAgo(calcAgo(chain.timestamp)); return () => clearTimeout(timer); }, [countInTimeout, chain.timestamp, setAgo]); // run full reload React.useEffect(() => { const fetchFull = async () => { let now = parseInt(new Date().getTime() / 1000) * 1000; // round to seconds now += now % 60000; // round up now to the next full minute const last = lastFullLoad; // const last = new Date(chain.timestamp).getTime(); const blockspan = chartConfig.size * config.time_between_blocks[0] * 1000; if (now - last > blockspan) { now = last; } let blocks = await getBlockTimeRange(last - blockspan, now); setData({ isLoaded: true, blocks, last: blocks.slice(-1)[0], }); }; if (config.version && lastFullLoad) { // console.log("Running full reload",lastFullLoad, config.time_between_blocks, config.version); fetchFull(); } }, [config, lastFullLoad, chartConfig.size]); React.useEffect(() => { const fetchSingle = async () => { // console.log("Single block load",chain.height); let newblock = await getBlockHeight(chain.height); let now = parseInt(new Date().getTime() / 1000) * 1000; now += now % 60000; // round up now to the next full minute const blockspan = chartConfig.size * config.time_between_blocks[0] * 1000; // this may or may not be needed when the chain made no progress for blockspan // time slots // const last = new Date(chain.timestamp).getTime(); // if (now - last > blockspan) { // now = last; // } let blocks = data.blocks.filter(b => now - new Date(b.time).getTime() <= blockspan); blocks.push(newblock[0]); setData(d => { return { isLoaded: true, blocks: blocks, last: newblock[0], }; }); }; // nothing to do without a new block if (!chain.height || (data.last && data.last.height === chain.height)) { // console.log("No new block", chain.height, data); return; } // we reload all state when // - on init // - older than 10 minutes // - detecing a gap // - detecting a reorg let full = !data.last||!data.blocks.length; // if (full) { console.log("Need full load on init", chain.height, chain.timestamp); } if (!full) { full = full || chain.height > data.last.height + 1; // if (chain.height>data.last.height+1) { console.log("Need full reload after gap", chain.height,data.last.height);} full = full || new Date(chain.timestamp) - lastFullLoad > 10 * 60000; // if (new Date(chain.timestamp).getTime() - lastFullLoad > 10*60000) { console.log("Need full reload after 10min");} full = full || data.last.parent_id !== data.blocks.slice(-2)[0].row_id; // if (data.last.parent_id!==data.blocks.slice(-2)[0].row_id) { console.log("Need full reload after reorg", data.last, data.blocks.slice(-2));} } switch (chain.status.status) { case 'synced': if (full) { setLastFullLoad(new Date(chain.timestamp).getTime()); } else { fetchSingle(); } break; default: // skip on init and when syncing (will be triggered by sidebar) break; } }, [config.time_between_blocks, chain, lastFullLoad, chartConfig.size, data]); return ( <Wrapper> <Card> <DataRow> <DataItem> <DataTitle>Latest Block</DataTitle> <Value type="plain" value={<Link to={`/${chain.block_hash}`}>{formatValue(chain.height)}</Link>} /> </DataItem> <DataItem> <DataTitle>Hash</DataTitle> <Value type="plain" value={<Link to={`/${chain.block_hash}`}>{getShortHash(chain.block_hash)}</Link>} /> </DataItem> <DataItem> <DataTitle>Time</DataTitle> <Value type="text" value={ago}/> </DataItem> <DataItem> <DataTitle>Ops</DataTitle> <Value value={data.last.n_ops}/> </DataItem> <DataItem> <DataTitle>Volume</DataTitle> <Value type="currency" round={1} digits={0} value={data.last.volume} /> </DataItem> </DataRow> <FlexRow> <BlockHistoryWrapper ref={ref}> <BlockChart blocks={data.blocks} config={chartConfig} /> </BlockHistoryWrapper> </FlexRow> </Card> </Wrapper> ); }; const DataRow = styled.div` display: flex; flex-direction: row; justify-content: space-around; align-items: center; position: relative; flex-wrap: wrap; `; const DataItem = styled.div` font-size: 14px; margin-left: 0px; margin-right: 20px; white-space: nowrap; display: flex; flex-grow: 1; align-items: center; max-width: 120px; &:last-child { margin-right: 0; } @media ${Devices.mobileL} { max-width: unset; width: 100%; margin-right: 0; line-height: 1.4; } `; const DataTitle = styled.div` color: rgba(255,255,255,0.52); font-size: 12px; margin-right: 15px; width: 100%; text-align: right; @media ${Devices.mobileL} { text-align: left; } `; const Wrapper = styled.div` min-width: 300px; `; const BlockHistoryWrapper = styled(FlexColumn)` margin-top: 25px; margin-bottom: 10px; flex: 1; `; export default BlockHistory;
"""LessonsLearningStylesResources provides an interface of subroutines for the management of LessonsLearningStylesResources models (and thus the entities in the database). Operations in this module refer to operations which are performable on LessonsLearningStylesResources entities or are within reason to do with the domain of LessonsLearningStylesResources management. """ from collections import Iterable from django.db.models import QuerySet from courses.models import Lessons from courses.models import LessonsLearningStylesResources __version__ = '1.0' __author__ = 'Callum Dempsey Leach' def get_lessonslearningstyleresource_from_id(id: int) -> LessonsLearningStylesResources: """ Gets the lessonslearningstyleresource with a corresponding an id. :param id: The id of the LessonsLearningStylesResources object to obtain. :return: Returns the resource at the id. :raises: Raises an ObjectDoesNotExist exception if the object does not exist. """ return LessonsLearningStylesResources.objects.get(id=id) def remove_lessonlearningstyleresources_ids_from_lesson(lesson: Lessons, ids: Iterable) -> None: """ Given an iterable list of primary keys safely removes the corresponding LessonsLearningStylesResources from a Lessons object (will have a null effect if the id is not for that lesson). :param lesson: The Lessons object. :param ids: Iterable of ids """ assert all([str(i).isdigit() and int(i) > 0 for i in ids]) LessonsLearningStylesResources.objects.filter(lesson=lesson, pk__in=ids).delete() def get_all_learning_styles_lesson_resources(learning_styles: Iterable, lesson: Lessons) -> QuerySet: """ Given an iterable of LearningStyles objects returns associated lesson resources. :param learning_styles: The list of LearningStyles objects. :param lesson: The Lessons object. :return: returns all associable LessonsResources objects. """ resources = LessonsLearningStylesResources.objects.filter(learning_style__in=learning_styles, lesson=lesson) return resources def has_lesson_resource(lesson: Lessons, resource: LessonsLearningStylesResources) -> bool: """ Identifies if a Lessons object has a Resources object. :param lesson: The Lessons object. :param resource: The Resources object. :return: Returns true if true otherwise returns false. """ has_resource = LessonsLearningStylesResources.objects.filter(lesson=lesson, id=resource.id).exists() return has_resource def get_excluded_learning_styles_lesson_resources(learning_styles: Iterable, lesson: Lessons) -> QuerySet: """ Passed a collection of LearningStyles objects and a Lessons object, get all the resources for that lesson that are *not* for that learning style. :param learning_styles: The LearningStyles objects. :param lesson: The Lessons Object :return: Returns a Queryset of requested resources. """ resources = LessonsLearningStylesResources.objects.filter(lesson=lesson).exclude(learning_style__in=learning_styles) return resources
//// [parserExportAssignment3.ts] export = //// [parserExportAssignment3.js]
from django.apps import AppConfig class FavoriteConfig(AppConfig): name = 'Favorite'
/*------------------------------------------------------------------------- * * reorderbuffer.c * PostgreSQL logical replay/reorder buffer management * * * Copyright (c) 2012-2019, PostgreSQL Global Development Group * * * IDENTIFICATION * src/backend/replication/reorderbuffer.c * * NOTES * This module gets handed individual pieces of transactions in the order * they are written to the WAL and is responsible to reassemble them into * toplevel transaction sized pieces. When a transaction is completely * reassembled - signalled by reading the transaction commit record - it * will then call the output plugin (cf. ReorderBufferCommit()) with the * individual changes. The output plugins rely on snapshots built by * snapbuild.c which hands them to us. * * Transactions and subtransactions/savepoints in postgres are not * immediately linked to each other from outside the performing * backend. Only at commit/abort (or special xact_assignment records) they * are linked together. Which means that we will have to splice together a * toplevel transaction from its subtransactions. To do that efficiently we * build a binary heap indexed by the smallest current lsn of the individual * subtransactions' changestreams. As the individual streams are inherently * ordered by LSN - since that is where we build them from - the transaction * can easily be reassembled by always using the subtransaction with the * smallest current LSN from the heap. * * In order to cope with large transactions - which can be several times as * big as the available memory - this module supports spooling the contents * of a large transactions to disk. When the transaction is replayed the * contents of individual (sub-)transactions will be read from disk in * chunks. * * This module also has to deal with reassembling toast records from the * individual chunks stored in WAL. When a new (or initial) version of a * tuple is stored in WAL it will always be preceded by the toast chunks * emitted for the columns stored out of line. Within a single toplevel * transaction there will be no other data carrying records between a row's * toast chunks and the row data itself. See ReorderBufferToast* for * details. * * ReorderBuffer uses two special memory context types - SlabContext for * allocations of fixed-length structures (changes and transactions), and * GenerationContext for the variable-length transaction data (allocated * and freed in groups with similar lifespan). * * ------------------------------------------------------------------------- */ #include "postgres.h" #include <unistd.h> #include <sys/stat.h> #include "access/heapam.h" #include "access/rewriteheap.h" #include "access/transam.h" #include "access/tuptoaster.h" #include "access/xact.h" #include "access/xlog_internal.h" #include "catalog/catalog.h" #include "lib/binaryheap.h" #include "miscadmin.h" #include "pgstat.h" #include "replication/logical.h" #include "replication/reorderbuffer.h" #include "replication/slot.h" #include "replication/snapbuild.h" /* just for SnapBuildSnapDecRefcount */ #include "storage/bufmgr.h" #include "storage/fd.h" #include "storage/sinval.h" #include "utils/builtins.h" #include "utils/combocid.h" #include "utils/memdebug.h" #include "utils/memutils.h" #include "utils/rel.h" #include "utils/relfilenodemap.h" /* entry for a hash table we use to map from xid to our transaction state */ typedef struct ReorderBufferTXNByIdEnt { TransactionId xid; ReorderBufferTXN *txn; } ReorderBufferTXNByIdEnt; /* data structures for (relfilenode, ctid) => (cmin, cmax) mapping */ typedef struct ReorderBufferTupleCidKey { RelFileNode relnode; ItemPointerData tid; } ReorderBufferTupleCidKey; typedef struct ReorderBufferTupleCidEnt { ReorderBufferTupleCidKey key; CommandId cmin; CommandId cmax; CommandId combocid; /* just for debugging */ } ReorderBufferTupleCidEnt; /* k-way in-order change iteration support structures */ typedef struct ReorderBufferIterTXNEntry { XLogRecPtr lsn; ReorderBufferChange *change; ReorderBufferTXN *txn; int fd; XLogSegNo segno; } ReorderBufferIterTXNEntry; typedef struct ReorderBufferIterTXNState { binaryheap *heap; Size nr_txns; dlist_head old_change; ReorderBufferIterTXNEntry entries[FLEXIBLE_ARRAY_MEMBER]; } ReorderBufferIterTXNState; /* toast datastructures */ typedef struct ReorderBufferToastEnt { Oid chunk_id; /* toast_table.chunk_id */ int32 last_chunk_seq; /* toast_table.chunk_seq of the last chunk we * have seen */ Size num_chunks; /* number of chunks we've already seen */ Size size; /* combined size of chunks seen */ dlist_head chunks; /* linked list of chunks */ struct varlena *reconstructed; /* reconstructed varlena now pointed to in * main tup */ } ReorderBufferToastEnt; /* Disk serialization support datastructures */ typedef struct ReorderBufferDiskChange { Size size; ReorderBufferChange change; /* data follows */ } ReorderBufferDiskChange; /* * Maximum number of changes kept in memory, per transaction. After that, * changes are spooled to disk. * * The current value should be sufficient to decode the entire transaction * without hitting disk in OLTP workloads, while starting to spool to disk in * other workloads reasonably fast. * * At some point in the future it probably makes sense to have a more elaborate * resource management here, but it's not entirely clear what that would look * like. */ static const Size max_changes_in_memory = 4096; /* --------------------------------------- * primary reorderbuffer support routines * --------------------------------------- */ static ReorderBufferTXN *ReorderBufferGetTXN(ReorderBuffer *rb); static void ReorderBufferReturnTXN(ReorderBuffer *rb, ReorderBufferTXN *txn); static ReorderBufferTXN *ReorderBufferTXNByXid(ReorderBuffer *rb, TransactionId xid, bool create, bool *is_new, XLogRecPtr lsn, bool create_as_top); static void ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn, ReorderBufferTXN *subtxn); static void AssertTXNLsnOrder(ReorderBuffer *rb); /* --------------------------------------- * support functions for lsn-order iterating over the ->changes of a * transaction and its subtransactions * * used for iteration over the k-way heap merge of a transaction and its * subtransactions * --------------------------------------- */ static ReorderBufferIterTXNState *ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn); static ReorderBufferChange *ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state); static void ReorderBufferIterTXNFinish(ReorderBuffer *rb, ReorderBufferIterTXNState *state); static void ReorderBufferExecuteInvalidations(ReorderBuffer *rb, ReorderBufferTXN *txn); /* * --------------------------------------- * Disk serialization support functions * --------------------------------------- */ static void ReorderBufferCheckSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn); static void ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn); static void ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn, int fd, ReorderBufferChange *change); static Size ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn, int *fd, XLogSegNo *segno); static void ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn, char *change); static void ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn); static void ReorderBufferCleanupSerializedTXNs(const char *slotname); static void ReorderBufferSerializedPath(char *path, ReplicationSlot *slot, TransactionId xid, XLogSegNo segno); static void ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap); static Snapshot ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap, ReorderBufferTXN *txn, CommandId cid); /* --------------------------------------- * toast reassembly support * --------------------------------------- */ static void ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn); static void ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn); static void ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change); static void ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change); /* * Allocate a new ReorderBuffer and clean out any old serialized state from * prior ReorderBuffer instances for the same slot. */ ReorderBuffer * ReorderBufferAllocate(void) { ReorderBuffer *buffer; HASHCTL hash_ctl; MemoryContext new_ctx; Assert(MyReplicationSlot != NULL); /* allocate memory in own context, to have better accountability */ new_ctx = AllocSetContextCreate(CurrentMemoryContext, "ReorderBuffer", ALLOCSET_DEFAULT_SIZES); buffer = (ReorderBuffer *) MemoryContextAlloc(new_ctx, sizeof(ReorderBuffer)); memset(&hash_ctl, 0, sizeof(hash_ctl)); buffer->context = new_ctx; buffer->change_context = SlabContextCreate(new_ctx, "Change", SLAB_DEFAULT_BLOCK_SIZE, sizeof(ReorderBufferChange)); buffer->txn_context = SlabContextCreate(new_ctx, "TXN", SLAB_DEFAULT_BLOCK_SIZE, sizeof(ReorderBufferTXN)); buffer->tup_context = GenerationContextCreate(new_ctx, "Tuples", SLAB_LARGE_BLOCK_SIZE); hash_ctl.keysize = sizeof(TransactionId); hash_ctl.entrysize = sizeof(ReorderBufferTXNByIdEnt); hash_ctl.hcxt = buffer->context; buffer->by_txn = hash_create("ReorderBufferByXid", 1000, &hash_ctl, HASH_ELEM | HASH_BLOBS | HASH_CONTEXT); buffer->by_txn_last_xid = InvalidTransactionId; buffer->by_txn_last_txn = NULL; buffer->outbuf = NULL; buffer->outbufsize = 0; buffer->current_restart_decoding_lsn = InvalidXLogRecPtr; dlist_init(&buffer->toplevel_by_lsn); dlist_init(&buffer->txns_by_base_snapshot_lsn); /* * Ensure there's no stale data from prior uses of this slot, in case some * prior exit avoided calling ReorderBufferFree. Failure to do this can * produce duplicated txns, and it's very cheap if there's nothing there. */ ReorderBufferCleanupSerializedTXNs(NameStr(MyReplicationSlot->data.name)); return buffer; } /* * Free a ReorderBuffer */ void ReorderBufferFree(ReorderBuffer *rb) { MemoryContext context = rb->context; /* * We free separately allocated data by entirely scrapping reorderbuffer's * memory context. */ MemoryContextDelete(context); /* Free disk space used by unconsumed reorder buffers */ ReorderBufferCleanupSerializedTXNs(NameStr(MyReplicationSlot->data.name)); } /* * Get an unused, possibly preallocated, ReorderBufferTXN. */ static ReorderBufferTXN * ReorderBufferGetTXN(ReorderBuffer *rb) { ReorderBufferTXN *txn; txn = (ReorderBufferTXN *) MemoryContextAlloc(rb->txn_context, sizeof(ReorderBufferTXN)); memset(txn, 0, sizeof(ReorderBufferTXN)); dlist_init(&txn->changes); dlist_init(&txn->tuplecids); dlist_init(&txn->subtxns); return txn; } /* * Free a ReorderBufferTXN. */ static void ReorderBufferReturnTXN(ReorderBuffer *rb, ReorderBufferTXN *txn) { /* clean the lookup cache if we were cached (quite likely) */ if (rb->by_txn_last_xid == txn->xid) { rb->by_txn_last_xid = InvalidTransactionId; rb->by_txn_last_txn = NULL; } /* free data that's contained */ if (txn->tuplecid_hash != NULL) { hash_destroy(txn->tuplecid_hash); txn->tuplecid_hash = NULL; } if (txn->invalidations) { pfree(txn->invalidations); txn->invalidations = NULL; } pfree(txn); } /* * Get an fresh ReorderBufferChange. */ ReorderBufferChange * ReorderBufferGetChange(ReorderBuffer *rb) { ReorderBufferChange *change; change = (ReorderBufferChange *) MemoryContextAlloc(rb->change_context, sizeof(ReorderBufferChange)); memset(change, 0, sizeof(ReorderBufferChange)); return change; } /* * Free an ReorderBufferChange. */ void ReorderBufferReturnChange(ReorderBuffer *rb, ReorderBufferChange *change) { /* free contained data */ switch (change->action) { case REORDER_BUFFER_CHANGE_INSERT: case REORDER_BUFFER_CHANGE_UPDATE: case REORDER_BUFFER_CHANGE_DELETE: case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT: if (change->data.tp.newtuple) { ReorderBufferReturnTupleBuf(rb, change->data.tp.newtuple); change->data.tp.newtuple = NULL; } if (change->data.tp.oldtuple) { ReorderBufferReturnTupleBuf(rb, change->data.tp.oldtuple); change->data.tp.oldtuple = NULL; } break; case REORDER_BUFFER_CHANGE_MESSAGE: if (change->data.msg.prefix != NULL) pfree(change->data.msg.prefix); change->data.msg.prefix = NULL; if (change->data.msg.message != NULL) pfree(change->data.msg.message); change->data.msg.message = NULL; break; case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT: if (change->data.snapshot) { ReorderBufferFreeSnap(rb, change->data.snapshot); change->data.snapshot = NULL; } break; /* no data in addition to the struct itself */ case REORDER_BUFFER_CHANGE_TRUNCATE: if (change->data.truncate.relids != NULL) { ReorderBufferReturnRelids(rb, change->data.truncate.relids); change->data.truncate.relids = NULL; } break; case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM: case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID: case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID: break; } pfree(change); } /* * Get a fresh ReorderBufferTupleBuf fitting at least a tuple of size * tuple_len (excluding header overhead). */ ReorderBufferTupleBuf * ReorderBufferGetTupleBuf(ReorderBuffer *rb, Size tuple_len) { ReorderBufferTupleBuf *tuple; Size alloc_len; alloc_len = tuple_len + SizeofHeapTupleHeader; tuple = (ReorderBufferTupleBuf *) MemoryContextAlloc(rb->tup_context, sizeof(ReorderBufferTupleBuf) + MAXIMUM_ALIGNOF + alloc_len); tuple->alloc_tuple_size = alloc_len; tuple->tuple.t_data = ReorderBufferTupleBufData(tuple); return tuple; } /* * Free an ReorderBufferTupleBuf. */ void ReorderBufferReturnTupleBuf(ReorderBuffer *rb, ReorderBufferTupleBuf *tuple) { pfree(tuple); } /* * Get an array for relids of truncated relations. * * We use the global memory context (for the whole reorder buffer), because * none of the existing ones seems like a good match (some are SLAB, so we * can't use those, and tup_context is meant for tuple data, not relids). We * could add yet another context, but it seems like an overkill - TRUNCATE is * not particularly common operation, so it does not seem worth it. */ Oid * ReorderBufferGetRelids(ReorderBuffer *rb, int nrelids) { Oid *relids; Size alloc_len; alloc_len = sizeof(Oid) * nrelids; relids = (Oid *) MemoryContextAlloc(rb->context, alloc_len); return relids; } /* * Free an array of relids. */ void ReorderBufferReturnRelids(ReorderBuffer *rb, Oid *relids) { pfree(relids); } /* * Return the ReorderBufferTXN from the given buffer, specified by Xid. * If create is true, and a transaction doesn't already exist, create it * (with the given LSN, and as top transaction if that's specified); * when this happens, is_new is set to true. */ static ReorderBufferTXN * ReorderBufferTXNByXid(ReorderBuffer *rb, TransactionId xid, bool create, bool *is_new, XLogRecPtr lsn, bool create_as_top) { ReorderBufferTXN *txn; ReorderBufferTXNByIdEnt *ent; bool found; Assert(TransactionIdIsValid(xid)); /* * Check the one-entry lookup cache first */ if (TransactionIdIsValid(rb->by_txn_last_xid) && rb->by_txn_last_xid == xid) { txn = rb->by_txn_last_txn; if (txn != NULL) { /* found it, and it's valid */ if (is_new) *is_new = false; return txn; } /* * cached as non-existent, and asked not to create? Then nothing else * to do. */ if (!create) return NULL; /* otherwise fall through to create it */ } /* * If the cache wasn't hit or it yielded an "does-not-exist" and we want * to create an entry. */ /* search the lookup table */ ent = (ReorderBufferTXNByIdEnt *) hash_search(rb->by_txn, (void *) &xid, create ? HASH_ENTER : HASH_FIND, &found); if (found) txn = ent->txn; else if (create) { /* initialize the new entry, if creation was requested */ Assert(ent != NULL); Assert(lsn != InvalidXLogRecPtr); ent->txn = ReorderBufferGetTXN(rb); ent->txn->xid = xid; txn = ent->txn; txn->first_lsn = lsn; txn->restart_decoding_lsn = rb->current_restart_decoding_lsn; if (create_as_top) { dlist_push_tail(&rb->toplevel_by_lsn, &txn->node); AssertTXNLsnOrder(rb); } } else txn = NULL; /* not found and not asked to create */ /* update cache */ rb->by_txn_last_xid = xid; rb->by_txn_last_txn = txn; if (is_new) *is_new = !found; Assert(!create || txn != NULL); return txn; } /* * Queue a change into a transaction so it can be replayed upon commit. */ void ReorderBufferQueueChange(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, ReorderBufferChange *change) { ReorderBufferTXN *txn; txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true); change->lsn = lsn; Assert(InvalidXLogRecPtr != lsn); dlist_push_tail(&txn->changes, &change->node); txn->nentries++; txn->nentries_mem++; ReorderBufferCheckSerializeTXN(rb, txn); } /* * Queue message into a transaction so it can be processed upon commit. */ void ReorderBufferQueueMessage(ReorderBuffer *rb, TransactionId xid, Snapshot snapshot, XLogRecPtr lsn, bool transactional, const char *prefix, Size message_size, const char *message) { if (transactional) { MemoryContext oldcontext; ReorderBufferChange *change; Assert(xid != InvalidTransactionId); oldcontext = MemoryContextSwitchTo(rb->context); change = ReorderBufferGetChange(rb); change->action = REORDER_BUFFER_CHANGE_MESSAGE; change->data.msg.prefix = pstrdup(prefix); change->data.msg.message_size = message_size; change->data.msg.message = palloc(message_size); memcpy(change->data.msg.message, message, message_size); ReorderBufferQueueChange(rb, xid, lsn, change); MemoryContextSwitchTo(oldcontext); } else { ReorderBufferTXN *txn = NULL; volatile Snapshot snapshot_now = snapshot; if (xid != InvalidTransactionId) txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true); /* setup snapshot to allow catalog access */ SetupHistoricSnapshot(snapshot_now, NULL); PG_TRY(); { rb->message(rb, txn, lsn, false, prefix, message_size, message); TeardownHistoricSnapshot(false); } PG_CATCH(); { TeardownHistoricSnapshot(true); PG_RE_THROW(); } PG_END_TRY(); } } /* * AssertTXNLsnOrder * Verify LSN ordering of transaction lists in the reorderbuffer * * Other LSN-related invariants are checked too. * * No-op if assertions are not in use. */ static void AssertTXNLsnOrder(ReorderBuffer *rb) { #ifdef USE_ASSERT_CHECKING dlist_iter iter; XLogRecPtr prev_first_lsn = InvalidXLogRecPtr; XLogRecPtr prev_base_snap_lsn = InvalidXLogRecPtr; dlist_foreach(iter, &rb->toplevel_by_lsn) { ReorderBufferTXN *cur_txn = dlist_container(ReorderBufferTXN, node, iter.cur); /* start LSN must be set */ Assert(cur_txn->first_lsn != InvalidXLogRecPtr); /* If there is an end LSN, it must be higher than start LSN */ if (cur_txn->end_lsn != InvalidXLogRecPtr) Assert(cur_txn->first_lsn <= cur_txn->end_lsn); /* Current initial LSN must be strictly higher than previous */ if (prev_first_lsn != InvalidXLogRecPtr) Assert(prev_first_lsn < cur_txn->first_lsn); /* known-as-subtxn txns must not be listed */ Assert(!cur_txn->is_known_as_subxact); prev_first_lsn = cur_txn->first_lsn; } dlist_foreach(iter, &rb->txns_by_base_snapshot_lsn) { ReorderBufferTXN *cur_txn = dlist_container(ReorderBufferTXN, base_snapshot_node, iter.cur); /* base snapshot (and its LSN) must be set */ Assert(cur_txn->base_snapshot != NULL); Assert(cur_txn->base_snapshot_lsn != InvalidXLogRecPtr); /* current LSN must be strictly higher than previous */ if (prev_base_snap_lsn != InvalidXLogRecPtr) Assert(prev_base_snap_lsn < cur_txn->base_snapshot_lsn); /* known-as-subtxn txns must not be listed */ Assert(!cur_txn->is_known_as_subxact); prev_base_snap_lsn = cur_txn->base_snapshot_lsn; } #endif } /* * ReorderBufferGetOldestTXN * Return oldest transaction in reorderbuffer */ ReorderBufferTXN * ReorderBufferGetOldestTXN(ReorderBuffer *rb) { ReorderBufferTXN *txn; AssertTXNLsnOrder(rb); if (dlist_is_empty(&rb->toplevel_by_lsn)) return NULL; txn = dlist_head_element(ReorderBufferTXN, node, &rb->toplevel_by_lsn); Assert(!txn->is_known_as_subxact); Assert(txn->first_lsn != InvalidXLogRecPtr); return txn; } /* * ReorderBufferGetOldestXmin * Return oldest Xmin in reorderbuffer * * Returns oldest possibly running Xid from the point of view of snapshots * used in the transactions kept by reorderbuffer, or InvalidTransactionId if * there are none. * * Since snapshots are assigned monotonically, this equals the Xmin of the * base snapshot with minimal base_snapshot_lsn. */ TransactionId ReorderBufferGetOldestXmin(ReorderBuffer *rb) { ReorderBufferTXN *txn; AssertTXNLsnOrder(rb); if (dlist_is_empty(&rb->txns_by_base_snapshot_lsn)) return InvalidTransactionId; txn = dlist_head_element(ReorderBufferTXN, base_snapshot_node, &rb->txns_by_base_snapshot_lsn); return txn->base_snapshot->xmin; } void ReorderBufferSetRestartPoint(ReorderBuffer *rb, XLogRecPtr ptr) { rb->current_restart_decoding_lsn = ptr; } /* * ReorderBufferAssignChild * * Make note that we know that subxid is a subtransaction of xid, seen as of * the given lsn. */ void ReorderBufferAssignChild(ReorderBuffer *rb, TransactionId xid, TransactionId subxid, XLogRecPtr lsn) { ReorderBufferTXN *txn; ReorderBufferTXN *subtxn; bool new_top; bool new_sub; txn = ReorderBufferTXNByXid(rb, xid, true, &new_top, lsn, true); subtxn = ReorderBufferTXNByXid(rb, subxid, true, &new_sub, lsn, false); if (new_top && !new_sub) elog(ERROR, "subtransaction logged without previous top-level txn record"); if (!new_sub) { if (subtxn->is_known_as_subxact) { /* already associated, nothing to do */ return; } else { /* * We already saw this transaction, but initially added it to the * list of top-level txns. Now that we know it's not top-level, * remove it from there. */ dlist_delete(&subtxn->node); } } subtxn->is_known_as_subxact = true; subtxn->toplevel_xid = xid; Assert(subtxn->nsubtxns == 0); /* add to subtransaction list */ dlist_push_tail(&txn->subtxns, &subtxn->node); txn->nsubtxns++; /* Possibly transfer the subtxn's snapshot to its top-level txn. */ ReorderBufferTransferSnapToParent(txn, subtxn); /* Verify LSN-ordering invariant */ AssertTXNLsnOrder(rb); } /* * ReorderBufferTransferSnapToParent * Transfer base snapshot from subtxn to top-level txn, if needed * * This is done if the top-level txn doesn't have a base snapshot, or if the * subtxn's base snapshot has an earlier LSN than the top-level txn's base * snapshot's LSN. This can happen if there are no changes in the toplevel * txn but there are some in the subtxn, or the first change in subtxn has * earlier LSN than first change in the top-level txn and we learned about * their kinship only now. * * The subtransaction's snapshot is cleared regardless of the transfer * happening, since it's not needed anymore in either case. * * We do this as soon as we become aware of their kinship, to avoid queueing * extra snapshots to txns known-as-subtxns -- only top-level txns will * receive further snapshots. */ static void ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn, ReorderBufferTXN *subtxn) { Assert(subtxn->toplevel_xid == txn->xid); if (subtxn->base_snapshot != NULL) { if (txn->base_snapshot == NULL || subtxn->base_snapshot_lsn < txn->base_snapshot_lsn) { /* * If the toplevel transaction already has a base snapshot but * it's newer than the subxact's, purge it. */ if (txn->base_snapshot != NULL) { SnapBuildSnapDecRefcount(txn->base_snapshot); dlist_delete(&txn->base_snapshot_node); } /* * The snapshot is now the top transaction's; transfer it, and * adjust the list position of the top transaction in the list by * moving it to where the subtransaction is. */ txn->base_snapshot = subtxn->base_snapshot; txn->base_snapshot_lsn = subtxn->base_snapshot_lsn; dlist_insert_before(&subtxn->base_snapshot_node, &txn->base_snapshot_node); /* * The subtransaction doesn't have a snapshot anymore (so it * mustn't be in the list.) */ subtxn->base_snapshot = NULL; subtxn->base_snapshot_lsn = InvalidXLogRecPtr; dlist_delete(&subtxn->base_snapshot_node); } else { /* Base snap of toplevel is fine, so subxact's is not needed */ SnapBuildSnapDecRefcount(subtxn->base_snapshot); dlist_delete(&subtxn->base_snapshot_node); subtxn->base_snapshot = NULL; subtxn->base_snapshot_lsn = InvalidXLogRecPtr; } } } /* * Associate a subtransaction with its toplevel transaction at commit * time. There may be no further changes added after this. */ void ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid, TransactionId subxid, XLogRecPtr commit_lsn, XLogRecPtr end_lsn) { ReorderBufferTXN *subtxn; subtxn = ReorderBufferTXNByXid(rb, subxid, false, NULL, InvalidXLogRecPtr, false); /* * No need to do anything if that subtxn didn't contain any changes */ if (!subtxn) return; subtxn->final_lsn = commit_lsn; subtxn->end_lsn = end_lsn; /* * Assign this subxact as a child of the toplevel xact (no-op if already * done.) */ ReorderBufferAssignChild(rb, xid, subxid, InvalidXLogRecPtr); } /* * Support for efficiently iterating over a transaction's and its * subtransactions' changes. * * We do by doing a k-way merge between transactions/subtransactions. For that * we model the current heads of the different transactions as a binary heap * so we easily know which (sub-)transaction has the change with the smallest * lsn next. * * We assume the changes in individual transactions are already sorted by LSN. */ /* * Binary heap comparison function. */ static int ReorderBufferIterCompare(Datum a, Datum b, void *arg) { ReorderBufferIterTXNState *state = (ReorderBufferIterTXNState *) arg; XLogRecPtr pos_a = state->entries[DatumGetInt32(a)].lsn; XLogRecPtr pos_b = state->entries[DatumGetInt32(b)].lsn; if (pos_a < pos_b) return 1; else if (pos_a == pos_b) return 0; return -1; } /* * Allocate & initialize an iterator which iterates in lsn order over a * transaction and all its subtransactions. */ static ReorderBufferIterTXNState * ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn) { Size nr_txns = 0; ReorderBufferIterTXNState *state; dlist_iter cur_txn_i; int32 off; /* * Calculate the size of our heap: one element for every transaction that * contains changes. (Besides the transactions already in the reorder * buffer, we count the one we were directly passed.) */ if (txn->nentries > 0) nr_txns++; dlist_foreach(cur_txn_i, &txn->subtxns) { ReorderBufferTXN *cur_txn; cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur); if (cur_txn->nentries > 0) nr_txns++; } /* * TODO: Consider adding fastpath for the rather common nr_txns=1 case, no * need to allocate/build a heap then. */ /* allocate iteration state */ state = (ReorderBufferIterTXNState *) MemoryContextAllocZero(rb->context, sizeof(ReorderBufferIterTXNState) + sizeof(ReorderBufferIterTXNEntry) * nr_txns); state->nr_txns = nr_txns; dlist_init(&state->old_change); for (off = 0; off < state->nr_txns; off++) { state->entries[off].fd = -1; state->entries[off].segno = 0; } /* allocate heap */ state->heap = binaryheap_allocate(state->nr_txns, ReorderBufferIterCompare, state); /* * Now insert items into the binary heap, in an unordered fashion. (We * will run a heap assembly step at the end; this is more efficient.) */ off = 0; /* add toplevel transaction if it contains changes */ if (txn->nentries > 0) { ReorderBufferChange *cur_change; if (txn->serialized) { /* serialize remaining changes */ ReorderBufferSerializeTXN(rb, txn); ReorderBufferRestoreChanges(rb, txn, &state->entries[off].fd, &state->entries[off].segno); } cur_change = dlist_head_element(ReorderBufferChange, node, &txn->changes); state->entries[off].lsn = cur_change->lsn; state->entries[off].change = cur_change; state->entries[off].txn = txn; binaryheap_add_unordered(state->heap, Int32GetDatum(off++)); } /* add subtransactions if they contain changes */ dlist_foreach(cur_txn_i, &txn->subtxns) { ReorderBufferTXN *cur_txn; cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur); if (cur_txn->nentries > 0) { ReorderBufferChange *cur_change; if (cur_txn->serialized) { /* serialize remaining changes */ ReorderBufferSerializeTXN(rb, cur_txn); ReorderBufferRestoreChanges(rb, cur_txn, &state->entries[off].fd, &state->entries[off].segno); } cur_change = dlist_head_element(ReorderBufferChange, node, &cur_txn->changes); state->entries[off].lsn = cur_change->lsn; state->entries[off].change = cur_change; state->entries[off].txn = cur_txn; binaryheap_add_unordered(state->heap, Int32GetDatum(off++)); } } /* assemble a valid binary heap */ binaryheap_build(state->heap); return state; } /* * Return the next change when iterating over a transaction and its * subtransactions. * * Returns NULL when no further changes exist. */ static ReorderBufferChange * ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state) { ReorderBufferChange *change; ReorderBufferIterTXNEntry *entry; int32 off; /* nothing there anymore */ if (state->heap->bh_size == 0) return NULL; off = DatumGetInt32(binaryheap_first(state->heap)); entry = &state->entries[off]; /* free memory we might have "leaked" in the previous *Next call */ if (!dlist_is_empty(&state->old_change)) { change = dlist_container(ReorderBufferChange, node, dlist_pop_head_node(&state->old_change)); ReorderBufferReturnChange(rb, change); Assert(dlist_is_empty(&state->old_change)); } change = entry->change; /* * update heap with information about which transaction has the next * relevant change in LSN order */ /* there are in-memory changes */ if (dlist_has_next(&entry->txn->changes, &entry->change->node)) { dlist_node *next = dlist_next_node(&entry->txn->changes, &change->node); ReorderBufferChange *next_change = dlist_container(ReorderBufferChange, node, next); /* txn stays the same */ state->entries[off].lsn = next_change->lsn; state->entries[off].change = next_change; binaryheap_replace_first(state->heap, Int32GetDatum(off)); return change; } /* try to load changes from disk */ if (entry->txn->nentries != entry->txn->nentries_mem) { /* * Ugly: restoring changes will reuse *Change records, thus delete the * current one from the per-tx list and only free in the next call. */ dlist_delete(&change->node); dlist_push_tail(&state->old_change, &change->node); if (ReorderBufferRestoreChanges(rb, entry->txn, &entry->fd, &state->entries[off].segno)) { /* successfully restored changes from disk */ ReorderBufferChange *next_change = dlist_head_element(ReorderBufferChange, node, &entry->txn->changes); elog(DEBUG2, "restored %u/%u changes from disk", (uint32) entry->txn->nentries_mem, (uint32) entry->txn->nentries); Assert(entry->txn->nentries_mem); /* txn stays the same */ state->entries[off].lsn = next_change->lsn; state->entries[off].change = next_change; binaryheap_replace_first(state->heap, Int32GetDatum(off)); return change; } } /* ok, no changes there anymore, remove */ binaryheap_remove_first(state->heap); return change; } /* * Deallocate the iterator */ static void ReorderBufferIterTXNFinish(ReorderBuffer *rb, ReorderBufferIterTXNState *state) { int32 off; for (off = 0; off < state->nr_txns; off++) { if (state->entries[off].fd != -1) CloseTransientFile(state->entries[off].fd); } /* free memory we might have "leaked" in the last *Next call */ if (!dlist_is_empty(&state->old_change)) { ReorderBufferChange *change; change = dlist_container(ReorderBufferChange, node, dlist_pop_head_node(&state->old_change)); ReorderBufferReturnChange(rb, change); Assert(dlist_is_empty(&state->old_change)); } binaryheap_free(state->heap); pfree(state); } /* * Cleanup the contents of a transaction, usually after the transaction * committed or aborted. */ static void ReorderBufferCleanupTXN(ReorderBuffer *rb, ReorderBufferTXN *txn) { bool found; dlist_mutable_iter iter; /* cleanup subtransactions & their changes */ dlist_foreach_modify(iter, &txn->subtxns) { ReorderBufferTXN *subtxn; subtxn = dlist_container(ReorderBufferTXN, node, iter.cur); /* * Subtransactions are always associated to the toplevel TXN, even if * they originally were happening inside another subtxn, so we won't * ever recurse more than one level deep here. */ Assert(subtxn->is_known_as_subxact); Assert(subtxn->nsubtxns == 0); ReorderBufferCleanupTXN(rb, subtxn); } /* cleanup changes in the toplevel txn */ dlist_foreach_modify(iter, &txn->changes) { ReorderBufferChange *change; change = dlist_container(ReorderBufferChange, node, iter.cur); ReorderBufferReturnChange(rb, change); } /* * Cleanup the tuplecids we stored for decoding catalog snapshot access. * They are always stored in the toplevel transaction. */ dlist_foreach_modify(iter, &txn->tuplecids) { ReorderBufferChange *change; change = dlist_container(ReorderBufferChange, node, iter.cur); Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID); ReorderBufferReturnChange(rb, change); } /* * Cleanup the base snapshot, if set. */ if (txn->base_snapshot != NULL) { SnapBuildSnapDecRefcount(txn->base_snapshot); dlist_delete(&txn->base_snapshot_node); } /* * Remove TXN from its containing list. * * Note: if txn->is_known_as_subxact, we are deleting the TXN from its * parent's list of known subxacts; this leaves the parent's nsubxacts * count too high, but we don't care. Otherwise, we are deleting the TXN * from the LSN-ordered list of toplevel TXNs. */ dlist_delete(&txn->node); /* now remove reference from buffer */ hash_search(rb->by_txn, (void *) &txn->xid, HASH_REMOVE, &found); Assert(found); /* remove entries spilled to disk */ if (txn->serialized) ReorderBufferRestoreCleanup(rb, txn); /* deallocate */ ReorderBufferReturnTXN(rb, txn); } /* * Build a hash with a (relfilenode, ctid) -> (cmin, cmax) mapping for use by * HeapTupleSatisfiesHistoricMVCC. */ static void ReorderBufferBuildTupleCidHash(ReorderBuffer *rb, ReorderBufferTXN *txn) { dlist_iter iter; HASHCTL hash_ctl; if (!txn->has_catalog_changes || dlist_is_empty(&txn->tuplecids)) return; memset(&hash_ctl, 0, sizeof(hash_ctl)); hash_ctl.keysize = sizeof(ReorderBufferTupleCidKey); hash_ctl.entrysize = sizeof(ReorderBufferTupleCidEnt); hash_ctl.hcxt = rb->context; /* * create the hash with the exact number of to-be-stored tuplecids from * the start */ txn->tuplecid_hash = hash_create("ReorderBufferTupleCid", txn->ntuplecids, &hash_ctl, HASH_ELEM | HASH_BLOBS | HASH_CONTEXT); dlist_foreach(iter, &txn->tuplecids) { ReorderBufferTupleCidKey key; ReorderBufferTupleCidEnt *ent; bool found; ReorderBufferChange *change; change = dlist_container(ReorderBufferChange, node, iter.cur); Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID); /* be careful about padding */ memset(&key, 0, sizeof(ReorderBufferTupleCidKey)); key.relnode = change->data.tuplecid.node; ItemPointerCopy(&change->data.tuplecid.tid, &key.tid); ent = (ReorderBufferTupleCidEnt *) hash_search(txn->tuplecid_hash, (void *) &key, HASH_ENTER | HASH_FIND, &found); if (!found) { ent->cmin = change->data.tuplecid.cmin; ent->cmax = change->data.tuplecid.cmax; ent->combocid = change->data.tuplecid.combocid; } else { /* * Maybe we already saw this tuple before in this transaction, * but if so it must have the same cmin. */ Assert(ent->cmin == change->data.tuplecid.cmin); /* * cmax may be initially invalid, but once set it can only grow, * and never become invalid again. */ Assert((ent->cmax == InvalidCommandId) || ((change->data.tuplecid.cmax != InvalidCommandId) && (change->data.tuplecid.cmax > ent->cmax))); ent->cmax = change->data.tuplecid.cmax; } } } /* * Copy a provided snapshot so we can modify it privately. This is needed so * that catalog modifying transactions can look into intermediate catalog * states. */ static Snapshot ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap, ReorderBufferTXN *txn, CommandId cid) { Snapshot snap; dlist_iter iter; int i = 0; Size size; size = sizeof(SnapshotData) + sizeof(TransactionId) * orig_snap->xcnt + sizeof(TransactionId) * (txn->nsubtxns + 1); snap = MemoryContextAllocZero(rb->context, size); memcpy(snap, orig_snap, sizeof(SnapshotData)); snap->copied = true; snap->active_count = 1; /* mark as active so nobody frees it */ snap->regd_count = 0; snap->xip = (TransactionId *) (snap + 1); memcpy(snap->xip, orig_snap->xip, sizeof(TransactionId) * snap->xcnt); /* * snap->subxip contains all txids that belong to our transaction which we * need to check via cmin/cmax. That's why we store the toplevel * transaction in there as well. */ snap->subxip = snap->xip + snap->xcnt; snap->subxip[i++] = txn->xid; /* * nsubxcnt isn't decreased when subtransactions abort, so count manually. * Since it's an upper boundary it is safe to use it for the allocation * above. */ snap->subxcnt = 1; dlist_foreach(iter, &txn->subtxns) { ReorderBufferTXN *sub_txn; sub_txn = dlist_container(ReorderBufferTXN, node, iter.cur); snap->subxip[i++] = sub_txn->xid; snap->subxcnt++; } /* sort so we can bsearch() later */ qsort(snap->subxip, snap->subxcnt, sizeof(TransactionId), xidComparator); /* store the specified current CommandId */ snap->curcid = cid; return snap; } /* * Free a previously ReorderBufferCopySnap'ed snapshot */ static void ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap) { if (snap->copied) pfree(snap); else SnapBuildSnapDecRefcount(snap); } /* * Perform the replay of a transaction and its non-aborted subtransactions. * * Subtransactions previously have to be processed by * ReorderBufferCommitChild(), even if previously assigned to the toplevel * transaction with ReorderBufferAssignChild. * * We currently can only decode a transaction's contents when its commit * record is read because that's the only place where we know about cache * invalidations. Thus, once a toplevel commit is read, we iterate over the top * and subtransactions (using a k-way merge) and replay the changes in lsn * order. */ void ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid, XLogRecPtr commit_lsn, XLogRecPtr end_lsn, TimestampTz commit_time, RepOriginId origin_id, XLogRecPtr origin_lsn) { ReorderBufferTXN *txn; volatile Snapshot snapshot_now; volatile CommandId command_id = FirstCommandId; bool using_subtxn; ReorderBufferIterTXNState *volatile iterstate = NULL; txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr, false); /* unknown transaction, nothing to replay */ if (txn == NULL) return; txn->final_lsn = commit_lsn; txn->end_lsn = end_lsn; txn->commit_time = commit_time; txn->origin_id = origin_id; txn->origin_lsn = origin_lsn; /* * If this transaction has no snapshot, it didn't make any changes to the * database, so there's nothing to decode. Note that * ReorderBufferCommitChild will have transferred any snapshots from * subtransactions if there were any. */ if (txn->base_snapshot == NULL) { Assert(txn->ninvalidations == 0); ReorderBufferCleanupTXN(rb, txn); return; } snapshot_now = txn->base_snapshot; /* build data to be able to lookup the CommandIds of catalog tuples */ ReorderBufferBuildTupleCidHash(rb, txn); /* setup the initial snapshot */ SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash); /* * Decoding needs access to syscaches et al., which in turn use * heavyweight locks and such. Thus we need to have enough state around to * keep track of those. The easiest way is to simply use a transaction * internally. That also allows us to easily enforce that nothing writes * to the database by checking for xid assignments. * * When we're called via the SQL SRF there's already a transaction * started, so start an explicit subtransaction there. */ using_subtxn = IsTransactionOrTransactionBlock(); PG_TRY(); { ReorderBufferChange *change; ReorderBufferChange *specinsert = NULL; if (using_subtxn) BeginInternalSubTransaction("replay"); else StartTransactionCommand(); rb->begin(rb, txn); iterstate = ReorderBufferIterTXNInit(rb, txn); while ((change = ReorderBufferIterTXNNext(rb, iterstate)) != NULL) { Relation relation = NULL; Oid reloid; switch (change->action) { case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM: /* * Confirmation for speculative insertion arrived. Simply * use as a normal record. It'll be cleaned up at the end * of INSERT processing. */ if (specinsert == NULL) elog(ERROR, "invalid ordering of speculative insertion changes"); Assert(specinsert->data.tp.oldtuple == NULL); change = specinsert; change->action = REORDER_BUFFER_CHANGE_INSERT; /* intentionally fall through */ case REORDER_BUFFER_CHANGE_INSERT: case REORDER_BUFFER_CHANGE_UPDATE: case REORDER_BUFFER_CHANGE_DELETE: Assert(snapshot_now); reloid = RelidByRelfilenode(change->data.tp.relnode.spcNode, change->data.tp.relnode.relNode); /* * Mapped catalog tuple without data, emitted while * catalog table was in the process of being rewritten. We * can fail to look up the relfilenode, because the * relmapper has no "historic" view, in contrast to normal * the normal catalog during decoding. Thus repeated * rewrites can cause a lookup failure. That's OK because * we do not decode catalog changes anyway. Normally such * tuples would be skipped over below, but we can't * identify whether the table should be logically logged * without mapping the relfilenode to the oid. */ if (reloid == InvalidOid && change->data.tp.newtuple == NULL && change->data.tp.oldtuple == NULL) goto change_done; else if (reloid == InvalidOid) elog(ERROR, "could not map filenode \"%s\" to relation OID", relpathperm(change->data.tp.relnode, MAIN_FORKNUM)); relation = RelationIdGetRelation(reloid); if (relation == NULL) elog(ERROR, "could not open relation with OID %u (for filenode \"%s\")", reloid, relpathperm(change->data.tp.relnode, MAIN_FORKNUM)); if (!RelationIsLogicallyLogged(relation)) goto change_done; /* * Ignore temporary heaps created during DDL unless the * plugin has asked for them. */ if (relation->rd_rel->relrewrite && !rb->output_rewrites) goto change_done; /* * For now ignore sequence changes entirely. Most of the * time they don't log changes using records we * understand, so it doesn't make sense to handle the few * cases we do. */ if (relation->rd_rel->relkind == RELKIND_SEQUENCE) goto change_done; /* user-triggered change */ if (!IsToastRelation(relation)) { ReorderBufferToastReplace(rb, txn, relation, change); rb->apply_change(rb, txn, relation, change); /* * Only clear reassembled toast chunks if we're sure * they're not required anymore. The creator of the * tuple tells us. */ if (change->data.tp.clear_toast_afterwards) ReorderBufferToastReset(rb, txn); } /* we're not interested in toast deletions */ else if (change->action == REORDER_BUFFER_CHANGE_INSERT) { /* * Need to reassemble the full toasted Datum in * memory, to ensure the chunks don't get reused till * we're done remove it from the list of this * transaction's changes. Otherwise it will get * freed/reused while restoring spooled data from * disk. */ Assert(change->data.tp.newtuple != NULL); dlist_delete(&change->node); ReorderBufferToastAppendChunk(rb, txn, relation, change); } change_done: /* * Either speculative insertion was confirmed, or it was * unsuccessful and the record isn't needed anymore. */ if (specinsert != NULL) { ReorderBufferReturnChange(rb, specinsert); specinsert = NULL; } if (relation != NULL) { RelationClose(relation); relation = NULL; } break; case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT: /* * Speculative insertions are dealt with by delaying the * processing of the insert until the confirmation record * arrives. For that we simply unlink the record from the * chain, so it does not get freed/reused while restoring * spooled data from disk. * * This is safe in the face of concurrent catalog changes * because the relevant relation can't be changed between * speculative insertion and confirmation due to * CheckTableNotInUse() and locking. */ /* clear out a pending (and thus failed) speculation */ if (specinsert != NULL) { ReorderBufferReturnChange(rb, specinsert); specinsert = NULL; } /* and memorize the pending insertion */ dlist_delete(&change->node); specinsert = change; break; case REORDER_BUFFER_CHANGE_TRUNCATE: { int i; int nrelids = change->data.truncate.nrelids; int nrelations = 0; Relation *relations; relations = palloc0(nrelids * sizeof(Relation)); for (i = 0; i < nrelids; i++) { Oid relid = change->data.truncate.relids[i]; Relation relation; relation = RelationIdGetRelation(relid); if (relation == NULL) elog(ERROR, "could not open relation with OID %u", relid); if (!RelationIsLogicallyLogged(relation)) continue; relations[nrelations++] = relation; } rb->apply_truncate(rb, txn, nrelations, relations, change); for (i = 0; i < nrelations; i++) RelationClose(relations[i]); break; } case REORDER_BUFFER_CHANGE_MESSAGE: rb->message(rb, txn, change->lsn, true, change->data.msg.prefix, change->data.msg.message_size, change->data.msg.message); break; case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT: /* get rid of the old */ TeardownHistoricSnapshot(false); if (snapshot_now->copied) { ReorderBufferFreeSnap(rb, snapshot_now); snapshot_now = ReorderBufferCopySnap(rb, change->data.snapshot, txn, command_id); } /* * Restored from disk, need to be careful not to double * free. We could introduce refcounting for that, but for * now this seems infrequent enough not to care. */ else if (change->data.snapshot->copied) { snapshot_now = ReorderBufferCopySnap(rb, change->data.snapshot, txn, command_id); } else { snapshot_now = change->data.snapshot; } /* and continue with the new one */ SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash); break; case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID: Assert(change->data.command_id != InvalidCommandId); if (command_id < change->data.command_id) { command_id = change->data.command_id; if (!snapshot_now->copied) { /* we don't use the global one anymore */ snapshot_now = ReorderBufferCopySnap(rb, snapshot_now, txn, command_id); } snapshot_now->curcid = command_id; TeardownHistoricSnapshot(false); SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash); /* * Every time the CommandId is incremented, we could * see new catalog contents, so execute all * invalidations. */ ReorderBufferExecuteInvalidations(rb, txn); } break; case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID: elog(ERROR, "tuplecid value in changequeue"); break; } } /* * There's a speculative insertion remaining, just clean in up, it * can't have been successful, otherwise we'd gotten a confirmation * record. */ if (specinsert) { ReorderBufferReturnChange(rb, specinsert); specinsert = NULL; } /* clean up the iterator */ ReorderBufferIterTXNFinish(rb, iterstate); iterstate = NULL; /* call commit callback */ rb->commit(rb, txn, commit_lsn); /* this is just a sanity check against bad output plugin behaviour */ if (GetCurrentTransactionIdIfAny() != InvalidTransactionId) elog(ERROR, "output plugin used XID %u", GetCurrentTransactionId()); /* cleanup */ TeardownHistoricSnapshot(false); /* * Aborting the current (sub-)transaction as a whole has the right * semantics. We want all locks acquired in here to be released, not * reassigned to the parent and we do not want any database access * have persistent effects. */ AbortCurrentTransaction(); /* make sure there's no cache pollution */ ReorderBufferExecuteInvalidations(rb, txn); if (using_subtxn) RollbackAndReleaseCurrentSubTransaction(); if (snapshot_now->copied) ReorderBufferFreeSnap(rb, snapshot_now); /* remove potential on-disk data, and deallocate */ ReorderBufferCleanupTXN(rb, txn); } PG_CATCH(); { /* TODO: Encapsulate cleanup from the PG_TRY and PG_CATCH blocks */ if (iterstate) ReorderBufferIterTXNFinish(rb, iterstate); TeardownHistoricSnapshot(true); /* * Force cache invalidation to happen outside of a valid transaction * to prevent catalog access as we just caught an error. */ AbortCurrentTransaction(); /* make sure there's no cache pollution */ ReorderBufferExecuteInvalidations(rb, txn); if (using_subtxn) RollbackAndReleaseCurrentSubTransaction(); if (snapshot_now->copied) ReorderBufferFreeSnap(rb, snapshot_now); /* remove potential on-disk data, and deallocate */ ReorderBufferCleanupTXN(rb, txn); PG_RE_THROW(); } PG_END_TRY(); } /* * Abort a transaction that possibly has previous changes. Needs to be first * called for subtransactions and then for the toplevel xid. * * NB: Transactions handled here have to have actively aborted (i.e. have * produced an abort record). Implicitly aborted transactions are handled via * ReorderBufferAbortOld(); transactions we're just not interested in, but * which have committed are handled in ReorderBufferForget(). * * This function purges this transaction and its contents from memory and * disk. */ void ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn) { ReorderBufferTXN *txn; txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr, false); /* unknown, nothing to remove */ if (txn == NULL) return; /* cosmetic... */ txn->final_lsn = lsn; /* remove potential on-disk data, and deallocate */ ReorderBufferCleanupTXN(rb, txn); } /* * Abort all transactions that aren't actually running anymore because the * server restarted. * * NB: These really have to be transactions that have aborted due to a server * crash/immediate restart, as we don't deal with invalidations here. */ void ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid) { dlist_mutable_iter it; /* * Iterate through all (potential) toplevel TXNs and abort all that are * older than what possibly can be running. Once we've found the first * that is alive we stop, there might be some that acquired an xid earlier * but started writing later, but it's unlikely and they will be cleaned * up in a later call to this function. */ dlist_foreach_modify(it, &rb->toplevel_by_lsn) { ReorderBufferTXN *txn; txn = dlist_container(ReorderBufferTXN, node, it.cur); if (TransactionIdPrecedes(txn->xid, oldestRunningXid)) { /* * We set final_lsn on a transaction when we decode its commit or * abort record, but we never see those records for crashed * transactions. To ensure cleanup of these transactions, set * final_lsn to that of their last change; this causes * ReorderBufferRestoreCleanup to do the right thing. */ if (txn->serialized && txn->final_lsn == 0) { ReorderBufferChange *last = dlist_tail_element(ReorderBufferChange, node, &txn->changes); txn->final_lsn = last->lsn; } elog(DEBUG2, "aborting old transaction %u", txn->xid); /* remove potential on-disk data, and deallocate this tx */ ReorderBufferCleanupTXN(rb, txn); } else return; } } /* * Forget the contents of a transaction if we aren't interested in it's * contents. Needs to be first called for subtransactions and then for the * toplevel xid. * * This is significantly different to ReorderBufferAbort() because * transactions that have committed need to be treated differently from aborted * ones since they may have modified the catalog. * * Note that this is only allowed to be called in the moment a transaction * commit has just been read, not earlier; otherwise later records referring * to this xid might re-create the transaction incompletely. */ void ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn) { ReorderBufferTXN *txn; txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr, false); /* unknown, nothing to forget */ if (txn == NULL) return; /* cosmetic... */ txn->final_lsn = lsn; /* * Process cache invalidation messages if there are any. Even if we're not * interested in the transaction's contents, it could have manipulated the * catalog and we need to update the caches according to that. */ if (txn->base_snapshot != NULL && txn->ninvalidations > 0) ReorderBufferImmediateInvalidation(rb, txn->ninvalidations, txn->invalidations); else Assert(txn->ninvalidations == 0); /* remove potential on-disk data, and deallocate */ ReorderBufferCleanupTXN(rb, txn); } /* * Execute invalidations happening outside the context of a decoded * transaction. That currently happens either for xid-less commits * (cf. RecordTransactionCommit()) or for invalidations in uninteresting * transactions (via ReorderBufferForget()). */ void ReorderBufferImmediateInvalidation(ReorderBuffer *rb, uint32 ninvalidations, SharedInvalidationMessage *invalidations) { bool use_subtxn = IsTransactionOrTransactionBlock(); int i; if (use_subtxn) BeginInternalSubTransaction("replay"); /* * Force invalidations to happen outside of a valid transaction - that way * entries will just be marked as invalid without accessing the catalog. * That's advantageous because we don't need to setup the full state * necessary for catalog access. */ if (use_subtxn) AbortCurrentTransaction(); for (i = 0; i < ninvalidations; i++) LocalExecuteInvalidationMessage(&invalidations[i]); if (use_subtxn) RollbackAndReleaseCurrentSubTransaction(); } /* * Tell reorderbuffer about an xid seen in the WAL stream. Has to be called at * least once for every xid in XLogRecord->xl_xid (other places in records * may, but do not have to be passed through here). * * Reorderbuffer keeps some datastructures about transactions in LSN order, * for efficiency. To do that it has to know about when transactions are seen * first in the WAL. As many types of records are not actually interesting for * logical decoding, they do not necessarily pass though here. */ void ReorderBufferProcessXid(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn) { /* many records won't have an xid assigned, centralize check here */ if (xid != InvalidTransactionId) ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true); } /* * Add a new snapshot to this transaction that may only used after lsn 'lsn' * because the previous snapshot doesn't describe the catalog correctly for * following rows. */ void ReorderBufferAddSnapshot(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, Snapshot snap) { ReorderBufferChange *change = ReorderBufferGetChange(rb); change->data.snapshot = snap; change->action = REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT; ReorderBufferQueueChange(rb, xid, lsn, change); } /* * Set up the transaction's base snapshot. * * If we know that xid is a subtransaction, set the base snapshot on the * top-level transaction instead. */ void ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, Snapshot snap) { ReorderBufferTXN *txn; bool is_new; AssertArg(snap != NULL); /* * Fetch the transaction to operate on. If we know it's a subtransaction, * operate on its top-level transaction instead. */ txn = ReorderBufferTXNByXid(rb, xid, true, &is_new, lsn, true); if (txn->is_known_as_subxact) txn = ReorderBufferTXNByXid(rb, txn->toplevel_xid, false, NULL, InvalidXLogRecPtr, false); Assert(txn->base_snapshot == NULL); txn->base_snapshot = snap; txn->base_snapshot_lsn = lsn; dlist_push_tail(&rb->txns_by_base_snapshot_lsn, &txn->base_snapshot_node); AssertTXNLsnOrder(rb); } /* * Access the catalog with this CommandId at this point in the changestream. * * May only be called for command ids > 1 */ void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, CommandId cid) { ReorderBufferChange *change = ReorderBufferGetChange(rb); change->data.command_id = cid; change->action = REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID; ReorderBufferQueueChange(rb, xid, lsn, change); } /* * Add new (relfilenode, tid) -> (cmin, cmax) mappings. */ void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, RelFileNode node, ItemPointerData tid, CommandId cmin, CommandId cmax, CommandId combocid) { ReorderBufferChange *change = ReorderBufferGetChange(rb); ReorderBufferTXN *txn; txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true); change->data.tuplecid.node = node; change->data.tuplecid.tid = tid; change->data.tuplecid.cmin = cmin; change->data.tuplecid.cmax = cmax; change->data.tuplecid.combocid = combocid; change->lsn = lsn; change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID; dlist_push_tail(&txn->tuplecids, &change->node); txn->ntuplecids++; } /* * Setup the invalidation of the toplevel transaction. * * This needs to be done before ReorderBufferCommit is called! */ void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, Size nmsgs, SharedInvalidationMessage *msgs) { ReorderBufferTXN *txn; txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true); if (txn->ninvalidations != 0) elog(ERROR, "only ever add one set of invalidations"); Assert(nmsgs > 0); txn->ninvalidations = nmsgs; txn->invalidations = (SharedInvalidationMessage *) MemoryContextAlloc(rb->context, sizeof(SharedInvalidationMessage) * nmsgs); memcpy(txn->invalidations, msgs, sizeof(SharedInvalidationMessage) * nmsgs); } /* * Apply all invalidations we know. Possibly we only need parts at this point * in the changestream but we don't know which those are. */ static void ReorderBufferExecuteInvalidations(ReorderBuffer *rb, ReorderBufferTXN *txn) { int i; for (i = 0; i < txn->ninvalidations; i++) LocalExecuteInvalidationMessage(&txn->invalidations[i]); } /* * Mark a transaction as containing catalog changes */ void ReorderBufferXidSetCatalogChanges(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn) { ReorderBufferTXN *txn; txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true); txn->has_catalog_changes = true; } /* * Query whether a transaction is already *known* to contain catalog * changes. This can be wrong until directly before the commit! */ bool ReorderBufferXidHasCatalogChanges(ReorderBuffer *rb, TransactionId xid) { ReorderBufferTXN *txn; txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr, false); if (txn == NULL) return false; return txn->has_catalog_changes; } /* * ReorderBufferXidHasBaseSnapshot * Have we already set the base snapshot for the given txn/subtxn? */ bool ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid) { ReorderBufferTXN *txn; txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr, false); /* transaction isn't known yet, ergo no snapshot */ if (txn == NULL) return false; /* a known subtxn? operate on top-level txn instead */ if (txn->is_known_as_subxact) txn = ReorderBufferTXNByXid(rb, txn->toplevel_xid, false, NULL, InvalidXLogRecPtr, false); return txn->base_snapshot != NULL; } /* * --------------------------------------- * Disk serialization support * --------------------------------------- */ /* * Ensure the IO buffer is >= sz. */ static void ReorderBufferSerializeReserve(ReorderBuffer *rb, Size sz) { if (!rb->outbufsize) { rb->outbuf = MemoryContextAlloc(rb->context, sz); rb->outbufsize = sz; } else if (rb->outbufsize < sz) { rb->outbuf = repalloc(rb->outbuf, sz); rb->outbufsize = sz; } } /* * Check whether the transaction tx should spill its data to disk. */ static void ReorderBufferCheckSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn) { /* * TODO: improve accounting so we cheaply can take subtransactions into * account here. */ if (txn->nentries_mem >= max_changes_in_memory) { ReorderBufferSerializeTXN(rb, txn); Assert(txn->nentries_mem == 0); } } /* * Spill data of a large transaction (and its subtransactions) to disk. */ static void ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn) { dlist_iter subtxn_i; dlist_mutable_iter change_i; int fd = -1; XLogSegNo curOpenSegNo = 0; Size spilled = 0; elog(DEBUG2, "spill %u changes in XID %u to disk", (uint32) txn->nentries_mem, txn->xid); /* do the same to all child TXs */ dlist_foreach(subtxn_i, &txn->subtxns) { ReorderBufferTXN *subtxn; subtxn = dlist_container(ReorderBufferTXN, node, subtxn_i.cur); ReorderBufferSerializeTXN(rb, subtxn); } /* serialize changestream */ dlist_foreach_modify(change_i, &txn->changes) { ReorderBufferChange *change; change = dlist_container(ReorderBufferChange, node, change_i.cur); /* * store in segment in which it belongs by start lsn, don't split over * multiple segments tho */ if (fd == -1 || !XLByteInSeg(change->lsn, curOpenSegNo, wal_segment_size)) { char path[MAXPGPATH]; if (fd != -1) CloseTransientFile(fd); XLByteToSeg(change->lsn, curOpenSegNo, wal_segment_size); /* * No need to care about TLIs here, only used during a single run, * so each LSN only maps to a specific WAL record. */ ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid, curOpenSegNo); /* open segment, create it if necessary */ fd = OpenTransientFile(path, O_CREAT | O_WRONLY | O_APPEND | PG_BINARY); if (fd < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not open file \"%s\": %m", path))); } ReorderBufferSerializeChange(rb, txn, fd, change); dlist_delete(&change->node); ReorderBufferReturnChange(rb, change); spilled++; } Assert(spilled == txn->nentries_mem); Assert(dlist_is_empty(&txn->changes)); txn->nentries_mem = 0; txn->serialized = true; if (fd != -1) CloseTransientFile(fd); } /* * Serialize individual change to disk. */ static void ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn, int fd, ReorderBufferChange *change) { ReorderBufferDiskChange *ondisk; Size sz = sizeof(ReorderBufferDiskChange); ReorderBufferSerializeReserve(rb, sz); ondisk = (ReorderBufferDiskChange *) rb->outbuf; memcpy(&ondisk->change, change, sizeof(ReorderBufferChange)); switch (change->action) { /* fall through these, they're all similar enough */ case REORDER_BUFFER_CHANGE_INSERT: case REORDER_BUFFER_CHANGE_UPDATE: case REORDER_BUFFER_CHANGE_DELETE: case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT: { char *data; ReorderBufferTupleBuf *oldtup, *newtup; Size oldlen = 0; Size newlen = 0; oldtup = change->data.tp.oldtuple; newtup = change->data.tp.newtuple; if (oldtup) { sz += sizeof(HeapTupleData); oldlen = oldtup->tuple.t_len; sz += oldlen; } if (newtup) { sz += sizeof(HeapTupleData); newlen = newtup->tuple.t_len; sz += newlen; } /* make sure we have enough space */ ReorderBufferSerializeReserve(rb, sz); data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange); /* might have been reallocated above */ ondisk = (ReorderBufferDiskChange *) rb->outbuf; if (oldlen) { memcpy(data, &oldtup->tuple, sizeof(HeapTupleData)); data += sizeof(HeapTupleData); memcpy(data, oldtup->tuple.t_data, oldlen); data += oldlen; } if (newlen) { memcpy(data, &newtup->tuple, sizeof(HeapTupleData)); data += sizeof(HeapTupleData); memcpy(data, newtup->tuple.t_data, newlen); data += newlen; } break; } case REORDER_BUFFER_CHANGE_MESSAGE: { char *data; Size prefix_size = strlen(change->data.msg.prefix) + 1; sz += prefix_size + change->data.msg.message_size + sizeof(Size) + sizeof(Size); ReorderBufferSerializeReserve(rb, sz); data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange); /* might have been reallocated above */ ondisk = (ReorderBufferDiskChange *) rb->outbuf; /* write the prefix including the size */ memcpy(data, &prefix_size, sizeof(Size)); data += sizeof(Size); memcpy(data, change->data.msg.prefix, prefix_size); data += prefix_size; /* write the message including the size */ memcpy(data, &change->data.msg.message_size, sizeof(Size)); data += sizeof(Size); memcpy(data, change->data.msg.message, change->data.msg.message_size); data += change->data.msg.message_size; break; } case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT: { Snapshot snap; char *data; snap = change->data.snapshot; sz += sizeof(SnapshotData) + sizeof(TransactionId) * snap->xcnt + sizeof(TransactionId) * snap->subxcnt ; /* make sure we have enough space */ ReorderBufferSerializeReserve(rb, sz); data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange); /* might have been reallocated above */ ondisk = (ReorderBufferDiskChange *) rb->outbuf; memcpy(data, snap, sizeof(SnapshotData)); data += sizeof(SnapshotData); if (snap->xcnt) { memcpy(data, snap->xip, sizeof(TransactionId) * snap->xcnt); data += sizeof(TransactionId) * snap->xcnt; } if (snap->subxcnt) { memcpy(data, snap->subxip, sizeof(TransactionId) * snap->subxcnt); data += sizeof(TransactionId) * snap->subxcnt; } break; } case REORDER_BUFFER_CHANGE_TRUNCATE: { Size size; char *data; /* account for the OIDs of truncated relations */ size = sizeof(Oid) * change->data.truncate.nrelids; sz += size; /* make sure we have enough space */ ReorderBufferSerializeReserve(rb, sz); data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange); /* might have been reallocated above */ ondisk = (ReorderBufferDiskChange *) rb->outbuf; memcpy(data, change->data.truncate.relids, size); data += size; break; } case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM: case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID: case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID: /* ReorderBufferChange contains everything important */ break; } ondisk->size = sz; errno = 0; pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_WRITE); if (write(fd, rb->outbuf, ondisk->size) != ondisk->size) { int save_errno = errno; CloseTransientFile(fd); /* if write didn't set errno, assume problem is no disk space */ errno = save_errno ? save_errno : ENOSPC; ereport(ERROR, (errcode_for_file_access(), errmsg("could not write to data file for XID %u: %m", txn->xid))); } pgstat_report_wait_end(); Assert(ondisk->change.action == change->action); } /* * Restore a number of changes spilled to disk back into memory. */ static Size ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn, int *fd, XLogSegNo *segno) { Size restored = 0; XLogSegNo last_segno; dlist_mutable_iter cleanup_iter; Assert(txn->first_lsn != InvalidXLogRecPtr); Assert(txn->final_lsn != InvalidXLogRecPtr); /* free current entries, so we have memory for more */ dlist_foreach_modify(cleanup_iter, &txn->changes) { ReorderBufferChange *cleanup = dlist_container(ReorderBufferChange, node, cleanup_iter.cur); dlist_delete(&cleanup->node); ReorderBufferReturnChange(rb, cleanup); } txn->nentries_mem = 0; Assert(dlist_is_empty(&txn->changes)); XLByteToSeg(txn->final_lsn, last_segno, wal_segment_size); while (restored < max_changes_in_memory && *segno <= last_segno) { int readBytes; ReorderBufferDiskChange *ondisk; if (*fd == -1) { char path[MAXPGPATH]; /* first time in */ if (*segno == 0) XLByteToSeg(txn->first_lsn, *segno, wal_segment_size); Assert(*segno != 0 || dlist_is_empty(&txn->changes)); /* * No need to care about TLIs here, only used during a single run, * so each LSN only maps to a specific WAL record. */ ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid, *segno); *fd = OpenTransientFile(path, O_RDONLY | PG_BINARY); if (*fd < 0 && errno == ENOENT) { *fd = -1; (*segno)++; continue; } else if (*fd < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not open file \"%s\": %m", path))); } /* * Read the statically sized part of a change which has information * about the total size. If we couldn't read a record, we're at the * end of this file. */ ReorderBufferSerializeReserve(rb, sizeof(ReorderBufferDiskChange)); pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_READ); readBytes = read(*fd, rb->outbuf, sizeof(ReorderBufferDiskChange)); pgstat_report_wait_end(); /* eof */ if (readBytes == 0) { CloseTransientFile(*fd); *fd = -1; (*segno)++; continue; } else if (readBytes < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not read from reorderbuffer spill file: %m"))); else if (readBytes != sizeof(ReorderBufferDiskChange)) ereport(ERROR, (errcode_for_file_access(), errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes", readBytes, (uint32) sizeof(ReorderBufferDiskChange)))); ondisk = (ReorderBufferDiskChange *) rb->outbuf; ReorderBufferSerializeReserve(rb, sizeof(ReorderBufferDiskChange) + ondisk->size); ondisk = (ReorderBufferDiskChange *) rb->outbuf; pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_READ); readBytes = read(*fd, rb->outbuf + sizeof(ReorderBufferDiskChange), ondisk->size - sizeof(ReorderBufferDiskChange)); pgstat_report_wait_end(); if (readBytes < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not read from reorderbuffer spill file: %m"))); else if (readBytes != ondisk->size - sizeof(ReorderBufferDiskChange)) ereport(ERROR, (errcode_for_file_access(), errmsg("could not read from reorderbuffer spill file: read %d instead of %u bytes", readBytes, (uint32) (ondisk->size - sizeof(ReorderBufferDiskChange))))); /* * ok, read a full change from disk, now restore it into proper * in-memory format */ ReorderBufferRestoreChange(rb, txn, rb->outbuf); restored++; } return restored; } /* * Convert change from its on-disk format to in-memory format and queue it onto * the TXN's ->changes list. * * Note: although "data" is declared char*, at entry it points to a * maxalign'd buffer, making it safe in most of this function to assume * that the pointed-to data is suitably aligned for direct access. */ static void ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn, char *data) { ReorderBufferDiskChange *ondisk; ReorderBufferChange *change; ondisk = (ReorderBufferDiskChange *) data; change = ReorderBufferGetChange(rb); /* copy static part */ memcpy(change, &ondisk->change, sizeof(ReorderBufferChange)); data += sizeof(ReorderBufferDiskChange); /* restore individual stuff */ switch (change->action) { /* fall through these, they're all similar enough */ case REORDER_BUFFER_CHANGE_INSERT: case REORDER_BUFFER_CHANGE_UPDATE: case REORDER_BUFFER_CHANGE_DELETE: case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT: if (change->data.tp.oldtuple) { uint32 tuplelen = ((HeapTuple) data)->t_len; change->data.tp.oldtuple = ReorderBufferGetTupleBuf(rb, tuplelen - SizeofHeapTupleHeader); /* restore ->tuple */ memcpy(&change->data.tp.oldtuple->tuple, data, sizeof(HeapTupleData)); data += sizeof(HeapTupleData); /* reset t_data pointer into the new tuplebuf */ change->data.tp.oldtuple->tuple.t_data = ReorderBufferTupleBufData(change->data.tp.oldtuple); /* restore tuple data itself */ memcpy(change->data.tp.oldtuple->tuple.t_data, data, tuplelen); data += tuplelen; } if (change->data.tp.newtuple) { /* here, data might not be suitably aligned! */ uint32 tuplelen; memcpy(&tuplelen, data + offsetof(HeapTupleData, t_len), sizeof(uint32)); change->data.tp.newtuple = ReorderBufferGetTupleBuf(rb, tuplelen - SizeofHeapTupleHeader); /* restore ->tuple */ memcpy(&change->data.tp.newtuple->tuple, data, sizeof(HeapTupleData)); data += sizeof(HeapTupleData); /* reset t_data pointer into the new tuplebuf */ change->data.tp.newtuple->tuple.t_data = ReorderBufferTupleBufData(change->data.tp.newtuple); /* restore tuple data itself */ memcpy(change->data.tp.newtuple->tuple.t_data, data, tuplelen); data += tuplelen; } break; case REORDER_BUFFER_CHANGE_MESSAGE: { Size prefix_size; /* read prefix */ memcpy(&prefix_size, data, sizeof(Size)); data += sizeof(Size); change->data.msg.prefix = MemoryContextAlloc(rb->context, prefix_size); memcpy(change->data.msg.prefix, data, prefix_size); Assert(change->data.msg.prefix[prefix_size - 1] == '\0'); data += prefix_size; /* read the message */ memcpy(&change->data.msg.message_size, data, sizeof(Size)); data += sizeof(Size); change->data.msg.message = MemoryContextAlloc(rb->context, change->data.msg.message_size); memcpy(change->data.msg.message, data, change->data.msg.message_size); data += change->data.msg.message_size; break; } case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT: { Snapshot oldsnap; Snapshot newsnap; Size size; oldsnap = (Snapshot) data; size = sizeof(SnapshotData) + sizeof(TransactionId) * oldsnap->xcnt + sizeof(TransactionId) * (oldsnap->subxcnt + 0); change->data.snapshot = MemoryContextAllocZero(rb->context, size); newsnap = change->data.snapshot; memcpy(newsnap, data, size); newsnap->xip = (TransactionId *) (((char *) newsnap) + sizeof(SnapshotData)); newsnap->subxip = newsnap->xip + newsnap->xcnt; newsnap->copied = true; break; } /* the base struct contains all the data, easy peasy */ case REORDER_BUFFER_CHANGE_TRUNCATE: { Oid *relids; relids = ReorderBufferGetRelids(rb, change->data.truncate.nrelids); memcpy(relids, data, change->data.truncate.nrelids * sizeof(Oid)); change->data.truncate.relids = relids; break; } case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM: case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID: case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID: break; } dlist_push_tail(&txn->changes, &change->node); txn->nentries_mem++; } /* * Remove all on-disk stored for the passed in transaction. */ static void ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn) { XLogSegNo first; XLogSegNo cur; XLogSegNo last; Assert(txn->first_lsn != InvalidXLogRecPtr); Assert(txn->final_lsn != InvalidXLogRecPtr); XLByteToSeg(txn->first_lsn, first, wal_segment_size); XLByteToSeg(txn->final_lsn, last, wal_segment_size); /* iterate over all possible filenames, and delete them */ for (cur = first; cur <= last; cur++) { char path[MAXPGPATH]; ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid, cur); if (unlink(path) != 0 && errno != ENOENT) ereport(ERROR, (errcode_for_file_access(), errmsg("could not remove file \"%s\": %m", path))); } } /* * Remove any leftover serialized reorder buffers from a slot directory after a * prior crash or decoding session exit. */ static void ReorderBufferCleanupSerializedTXNs(const char *slotname) { DIR *spill_dir; struct dirent *spill_de; struct stat statbuf; char path[MAXPGPATH * 2 + 12]; sprintf(path, "pg_replslot/%s", slotname); /* we're only handling directories here, skip if it's not ours */ if (lstat(path, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode)) return; spill_dir = AllocateDir(path); while ((spill_de = ReadDirExtended(spill_dir, path, INFO)) != NULL) { /* only look at names that can be ours */ if (strncmp(spill_de->d_name, "xid", 3) == 0) { snprintf(path, sizeof(path), "pg_replslot/%s/%s", slotname, spill_de->d_name); if (unlink(path) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not remove file \"%s\" during removal of pg_replslot/%s/xid*: %m", path, slotname))); } } FreeDir(spill_dir); } /* * Given a replication slot, transaction ID and segment number, fill in the * corresponding spill file into 'path', which is a caller-owned buffer of size * at least MAXPGPATH. */ static void ReorderBufferSerializedPath(char *path, ReplicationSlot *slot, TransactionId xid, XLogSegNo segno) { XLogRecPtr recptr; XLogSegNoOffsetToRecPtr(segno, 0, wal_segment_size, recptr); snprintf(path, MAXPGPATH, "pg_replslot/%s/xid-%u-lsn-%X-%X.spill", NameStr(MyReplicationSlot->data.name), xid, (uint32) (recptr >> 32), (uint32) recptr); } /* * Delete all data spilled to disk after we've restarted/crashed. It will be * recreated when the respective slots are reused. */ void StartupReorderBuffer(void) { DIR *logical_dir; struct dirent *logical_de; logical_dir = AllocateDir("pg_replslot"); while ((logical_de = ReadDir(logical_dir, "pg_replslot")) != NULL) { if (strcmp(logical_de->d_name, ".") == 0 || strcmp(logical_de->d_name, "..") == 0) continue; /* if it cannot be a slot, skip the directory */ if (!ReplicationSlotValidateName(logical_de->d_name, DEBUG2)) continue; /* * ok, has to be a surviving logical slot, iterate and delete * everything starting with xid-* */ ReorderBufferCleanupSerializedTXNs(logical_de->d_name); } FreeDir(logical_dir); } /* --------------------------------------- * toast reassembly support * --------------------------------------- */ /* * Initialize per tuple toast reconstruction support. */ static void ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn) { HASHCTL hash_ctl; Assert(txn->toast_hash == NULL); memset(&hash_ctl, 0, sizeof(hash_ctl)); hash_ctl.keysize = sizeof(Oid); hash_ctl.entrysize = sizeof(ReorderBufferToastEnt); hash_ctl.hcxt = rb->context; txn->toast_hash = hash_create("ReorderBufferToastHash", 5, &hash_ctl, HASH_ELEM | HASH_BLOBS | HASH_CONTEXT); } /* * Per toast-chunk handling for toast reconstruction * * Appends a toast chunk so we can reconstruct it when the tuple "owning" the * toasted Datum comes along. */ static void ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change) { ReorderBufferToastEnt *ent; ReorderBufferTupleBuf *newtup; bool found; int32 chunksize; bool isnull; Pointer chunk; TupleDesc desc = RelationGetDescr(relation); Oid chunk_id; int32 chunk_seq; if (txn->toast_hash == NULL) ReorderBufferToastInitHash(rb, txn); Assert(IsToastRelation(relation)); newtup = change->data.tp.newtuple; chunk_id = DatumGetObjectId(fastgetattr(&newtup->tuple, 1, desc, &isnull)); Assert(!isnull); chunk_seq = DatumGetInt32(fastgetattr(&newtup->tuple, 2, desc, &isnull)); Assert(!isnull); ent = (ReorderBufferToastEnt *) hash_search(txn->toast_hash, (void *) &chunk_id, HASH_ENTER, &found); if (!found) { Assert(ent->chunk_id == chunk_id); ent->num_chunks = 0; ent->last_chunk_seq = 0; ent->size = 0; ent->reconstructed = NULL; dlist_init(&ent->chunks); if (chunk_seq != 0) elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq 0", chunk_seq, chunk_id); } else if (found && chunk_seq != ent->last_chunk_seq + 1) elog(ERROR, "got sequence entry %d for toast chunk %u instead of seq %d", chunk_seq, chunk_id, ent->last_chunk_seq + 1); chunk = DatumGetPointer(fastgetattr(&newtup->tuple, 3, desc, &isnull)); Assert(!isnull); /* calculate size so we can allocate the right size at once later */ if (!VARATT_IS_EXTENDED(chunk)) chunksize = VARSIZE(chunk) - VARHDRSZ; else if (VARATT_IS_SHORT(chunk)) /* could happen due to heap_form_tuple doing its thing */ chunksize = VARSIZE_SHORT(chunk) - VARHDRSZ_SHORT; else elog(ERROR, "unexpected type of toast chunk"); ent->size += chunksize; ent->last_chunk_seq = chunk_seq; ent->num_chunks++; dlist_push_tail(&ent->chunks, &change->node); } /* * Rejigger change->newtuple to point to in-memory toast tuples instead to * on-disk toast tuples that may not longer exist (think DROP TABLE or VACUUM). * * We cannot replace unchanged toast tuples though, so those will still point * to on-disk toast data. */ static void ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change) { TupleDesc desc; int natt; Datum *attrs; bool *isnull; bool *free; HeapTuple tmphtup; Relation toast_rel; TupleDesc toast_desc; MemoryContext oldcontext; ReorderBufferTupleBuf *newtup; /* no toast tuples changed */ if (txn->toast_hash == NULL) return; oldcontext = MemoryContextSwitchTo(rb->context); /* we should only have toast tuples in an INSERT or UPDATE */ Assert(change->data.tp.newtuple); desc = RelationGetDescr(relation); toast_rel = RelationIdGetRelation(relation->rd_rel->reltoastrelid); toast_desc = RelationGetDescr(toast_rel); /* should we allocate from stack instead? */ attrs = palloc0(sizeof(Datum) * desc->natts); isnull = palloc0(sizeof(bool) * desc->natts); free = palloc0(sizeof(bool) * desc->natts); newtup = change->data.tp.newtuple; heap_deform_tuple(&newtup->tuple, desc, attrs, isnull); for (natt = 0; natt < desc->natts; natt++) { Form_pg_attribute attr = TupleDescAttr(desc, natt); ReorderBufferToastEnt *ent; struct varlena *varlena; /* va_rawsize is the size of the original datum -- including header */ struct varatt_external toast_pointer; struct varatt_indirect redirect_pointer; struct varlena *new_datum = NULL; struct varlena *reconstructed; dlist_iter it; Size data_done = 0; /* system columns aren't toasted */ if (attr->attnum < 0) continue; if (attr->attisdropped) continue; /* not a varlena datatype */ if (attr->attlen != -1) continue; /* no data */ if (isnull[natt]) continue; /* ok, we know we have a toast datum */ varlena = (struct varlena *) DatumGetPointer(attrs[natt]); /* no need to do anything if the tuple isn't external */ if (!VARATT_IS_EXTERNAL(varlena)) continue; VARATT_EXTERNAL_GET_POINTER(toast_pointer, varlena); /* * Check whether the toast tuple changed, replace if so. */ ent = (ReorderBufferToastEnt *) hash_search(txn->toast_hash, (void *) &toast_pointer.va_valueid, HASH_FIND, NULL); if (ent == NULL) continue; new_datum = (struct varlena *) palloc0(INDIRECT_POINTER_SIZE); free[natt] = true; reconstructed = palloc0(toast_pointer.va_rawsize); ent->reconstructed = reconstructed; /* stitch toast tuple back together from its parts */ dlist_foreach(it, &ent->chunks) { bool isnull; ReorderBufferChange *cchange; ReorderBufferTupleBuf *ctup; Pointer chunk; cchange = dlist_container(ReorderBufferChange, node, it.cur); ctup = cchange->data.tp.newtuple; chunk = DatumGetPointer( fastgetattr(&ctup->tuple, 3, toast_desc, &isnull)); Assert(!isnull); Assert(!VARATT_IS_EXTERNAL(chunk)); Assert(!VARATT_IS_SHORT(chunk)); memcpy(VARDATA(reconstructed) + data_done, VARDATA(chunk), VARSIZE(chunk) - VARHDRSZ); data_done += VARSIZE(chunk) - VARHDRSZ; } Assert(data_done == toast_pointer.va_extsize); /* make sure its marked as compressed or not */ if (VARATT_EXTERNAL_IS_COMPRESSED(toast_pointer)) SET_VARSIZE_COMPRESSED(reconstructed, data_done + VARHDRSZ); else SET_VARSIZE(reconstructed, data_done + VARHDRSZ); memset(&redirect_pointer, 0, sizeof(redirect_pointer)); redirect_pointer.pointer = reconstructed; SET_VARTAG_EXTERNAL(new_datum, VARTAG_INDIRECT); memcpy(VARDATA_EXTERNAL(new_datum), &redirect_pointer, sizeof(redirect_pointer)); attrs[natt] = PointerGetDatum(new_datum); } /* * Build tuple in separate memory & copy tuple back into the tuplebuf * passed to the output plugin. We can't directly heap_fill_tuple() into * the tuplebuf because attrs[] will point back into the current content. */ tmphtup = heap_form_tuple(desc, attrs, isnull); Assert(newtup->tuple.t_len <= MaxHeapTupleSize); Assert(ReorderBufferTupleBufData(newtup) == newtup->tuple.t_data); memcpy(newtup->tuple.t_data, tmphtup->t_data, tmphtup->t_len); newtup->tuple.t_len = tmphtup->t_len; /* * free resources we won't further need, more persistent stuff will be * free'd in ReorderBufferToastReset(). */ RelationClose(toast_rel); pfree(tmphtup); for (natt = 0; natt < desc->natts; natt++) { if (free[natt]) pfree(DatumGetPointer(attrs[natt])); } pfree(attrs); pfree(free); pfree(isnull); MemoryContextSwitchTo(oldcontext); } /* * Free all resources allocated for toast reconstruction. */ static void ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn) { HASH_SEQ_STATUS hstat; ReorderBufferToastEnt *ent; if (txn->toast_hash == NULL) return; /* sequentially walk over the hash and free everything */ hash_seq_init(&hstat, txn->toast_hash); while ((ent = (ReorderBufferToastEnt *) hash_seq_search(&hstat)) != NULL) { dlist_mutable_iter it; if (ent->reconstructed != NULL) pfree(ent->reconstructed); dlist_foreach_modify(it, &ent->chunks) { ReorderBufferChange *change = dlist_container(ReorderBufferChange, node, it.cur); dlist_delete(&change->node); ReorderBufferReturnChange(rb, change); } } hash_destroy(txn->toast_hash); txn->toast_hash = NULL; } /* --------------------------------------- * Visibility support for logical decoding * * * Lookup actual cmin/cmax values when using decoding snapshot. We can't * always rely on stored cmin/cmax values because of two scenarios: * * * A tuple got changed multiple times during a single transaction and thus * has got a combocid. Combocid's are only valid for the duration of a * single transaction. * * A tuple with a cmin but no cmax (and thus no combocid) got * deleted/updated in another transaction than the one which created it * which we are looking at right now. As only one of cmin, cmax or combocid * is actually stored in the heap we don't have access to the value we * need anymore. * * To resolve those problems we have a per-transaction hash of (cmin, * cmax) tuples keyed by (relfilenode, ctid) which contains the actual * (cmin, cmax) values. That also takes care of combocids by simply * not caring about them at all. As we have the real cmin/cmax values * combocids aren't interesting. * * As we only care about catalog tuples here the overhead of this * hashtable should be acceptable. * * Heap rewrites complicate this a bit, check rewriteheap.c for * details. * ------------------------------------------------------------------------- */ /* struct for qsort()ing mapping files by lsn somewhat efficiently */ typedef struct RewriteMappingFile { XLogRecPtr lsn; char fname[MAXPGPATH]; } RewriteMappingFile; #if NOT_USED static void DisplayMapping(HTAB *tuplecid_data) { HASH_SEQ_STATUS hstat; ReorderBufferTupleCidEnt *ent; hash_seq_init(&hstat, tuplecid_data); while ((ent = (ReorderBufferTupleCidEnt *) hash_seq_search(&hstat)) != NULL) { elog(DEBUG3, "mapping: node: %u/%u/%u tid: %u/%u cmin: %u, cmax: %u", ent->key.relnode.dbNode, ent->key.relnode.spcNode, ent->key.relnode.relNode, ItemPointerGetBlockNumber(&ent->key.tid), ItemPointerGetOffsetNumber(&ent->key.tid), ent->cmin, ent->cmax ); } } #endif /* * Apply a single mapping file to tuplecid_data. * * The mapping file has to have been verified to be a) committed b) for our * transaction c) applied in LSN order. */ static void ApplyLogicalMappingFile(HTAB *tuplecid_data, Oid relid, const char *fname) { char path[MAXPGPATH]; int fd; int readBytes; LogicalRewriteMappingData map; sprintf(path, "pg_logical/mappings/%s", fname); fd = OpenTransientFile(path, O_RDONLY | PG_BINARY); if (fd < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not open file \"%s\": %m", path))); while (true) { ReorderBufferTupleCidKey key; ReorderBufferTupleCidEnt *ent; ReorderBufferTupleCidEnt *new_ent; bool found; /* be careful about padding */ memset(&key, 0, sizeof(ReorderBufferTupleCidKey)); /* read all mappings till the end of the file */ pgstat_report_wait_start(WAIT_EVENT_REORDER_LOGICAL_MAPPING_READ); readBytes = read(fd, &map, sizeof(LogicalRewriteMappingData)); pgstat_report_wait_end(); if (readBytes < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not read file \"%s\": %m", path))); else if (readBytes == 0) /* EOF */ break; else if (readBytes != sizeof(LogicalRewriteMappingData)) ereport(ERROR, (errcode_for_file_access(), errmsg("could not read from file \"%s\": read %d instead of %d bytes", path, readBytes, (int32) sizeof(LogicalRewriteMappingData)))); key.relnode = map.old_node; ItemPointerCopy(&map.old_tid, &key.tid); ent = (ReorderBufferTupleCidEnt *) hash_search(tuplecid_data, (void *) &key, HASH_FIND, NULL); /* no existing mapping, no need to update */ if (!ent) continue; key.relnode = map.new_node; ItemPointerCopy(&map.new_tid, &key.tid); new_ent = (ReorderBufferTupleCidEnt *) hash_search(tuplecid_data, (void *) &key, HASH_ENTER, &found); if (found) { /* * Make sure the existing mapping makes sense. We sometime update * old records that did not yet have a cmax (e.g. pg_class' own * entry while rewriting it) during rewrites, so allow that. */ Assert(ent->cmin == InvalidCommandId || ent->cmin == new_ent->cmin); Assert(ent->cmax == InvalidCommandId || ent->cmax == new_ent->cmax); } else { /* update mapping */ new_ent->cmin = ent->cmin; new_ent->cmax = ent->cmax; new_ent->combocid = ent->combocid; } } if (CloseTransientFile(fd)) ereport(ERROR, (errcode_for_file_access(), errmsg("could not close file \"%s\": %m", path))); } /* * Check whether the TransactionOid 'xid' is in the pre-sorted array 'xip'. */ static bool TransactionIdInArray(TransactionId xid, TransactionId *xip, Size num) { return bsearch(&xid, xip, num, sizeof(TransactionId), xidComparator) != NULL; } /* * qsort() comparator for sorting RewriteMappingFiles in LSN order. */ static int file_sort_by_lsn(const void *a_p, const void *b_p) { RewriteMappingFile *a = *(RewriteMappingFile **) a_p; RewriteMappingFile *b = *(RewriteMappingFile **) b_p; if (a->lsn < b->lsn) return -1; else if (a->lsn > b->lsn) return 1; return 0; } /* * Apply any existing logical remapping files if there are any targeted at our * transaction for relid. */ static void UpdateLogicalMappings(HTAB *tuplecid_data, Oid relid, Snapshot snapshot) { DIR *mapping_dir; struct dirent *mapping_de; List *files = NIL; ListCell *file; RewriteMappingFile **files_a; size_t off; Oid dboid = IsSharedRelation(relid) ? InvalidOid : MyDatabaseId; mapping_dir = AllocateDir("pg_logical/mappings"); while ((mapping_de = ReadDir(mapping_dir, "pg_logical/mappings")) != NULL) { Oid f_dboid; Oid f_relid; TransactionId f_mapped_xid; TransactionId f_create_xid; XLogRecPtr f_lsn; uint32 f_hi, f_lo; RewriteMappingFile *f; if (strcmp(mapping_de->d_name, ".") == 0 || strcmp(mapping_de->d_name, "..") == 0) continue; /* Ignore files that aren't ours */ if (strncmp(mapping_de->d_name, "map-", 4) != 0) continue; if (sscanf(mapping_de->d_name, LOGICAL_REWRITE_FORMAT, &f_dboid, &f_relid, &f_hi, &f_lo, &f_mapped_xid, &f_create_xid) != 6) elog(ERROR, "could not parse filename \"%s\"", mapping_de->d_name); f_lsn = ((uint64) f_hi) << 32 | f_lo; /* mapping for another database */ if (f_dboid != dboid) continue; /* mapping for another relation */ if (f_relid != relid) continue; /* did the creating transaction abort? */ if (!TransactionIdDidCommit(f_create_xid)) continue; /* not for our transaction */ if (!TransactionIdInArray(f_mapped_xid, snapshot->subxip, snapshot->subxcnt)) continue; /* ok, relevant, queue for apply */ f = palloc(sizeof(RewriteMappingFile)); f->lsn = f_lsn; strcpy(f->fname, mapping_de->d_name); files = lappend(files, f); } FreeDir(mapping_dir); /* build array we can easily sort */ files_a = palloc(list_length(files) * sizeof(RewriteMappingFile *)); off = 0; foreach(file, files) { files_a[off++] = lfirst(file); } /* sort files so we apply them in LSN order */ qsort(files_a, list_length(files), sizeof(RewriteMappingFile *), file_sort_by_lsn); for (off = 0; off < list_length(files); off++) { RewriteMappingFile *f = files_a[off]; elog(DEBUG1, "applying mapping: \"%s\" in %u", f->fname, snapshot->subxip[0]); ApplyLogicalMappingFile(tuplecid_data, relid, f->fname); pfree(f); } } /* * Lookup cmin/cmax of a tuple, during logical decoding where we can't rely on * combocids. */ bool ResolveCminCmaxDuringDecoding(HTAB *tuplecid_data, Snapshot snapshot, HeapTuple htup, Buffer buffer, CommandId *cmin, CommandId *cmax) { ReorderBufferTupleCidKey key; ReorderBufferTupleCidEnt *ent; ForkNumber forkno; BlockNumber blockno; bool updated_mapping = false; /* be careful about padding */ memset(&key, 0, sizeof(key)); Assert(!BufferIsLocal(buffer)); /* * get relfilenode from the buffer, no convenient way to access it other * than that. */ BufferGetTag(buffer, &key.relnode, &forkno, &blockno); /* tuples can only be in the main fork */ Assert(forkno == MAIN_FORKNUM); Assert(blockno == ItemPointerGetBlockNumber(&htup->t_self)); ItemPointerCopy(&htup->t_self, &key.tid); restart: ent = (ReorderBufferTupleCidEnt *) hash_search(tuplecid_data, (void *) &key, HASH_FIND, NULL); /* * failed to find a mapping, check whether the table was rewritten and * apply mapping if so, but only do that once - there can be no new * mappings while we are in here since we have to hold a lock on the * relation. */ if (ent == NULL && !updated_mapping) { UpdateLogicalMappings(tuplecid_data, htup->t_tableOid, snapshot); /* now check but don't update for a mapping again */ updated_mapping = true; goto restart; } else if (ent == NULL) return false; if (cmin) *cmin = ent->cmin; if (cmax) *cmax = ent->cmax; return true; }
/* * Copyright (c) 2002 Bob Beck <beck@openbsd.org> * Copyright (c) 2002 Theo de Raadt * Copyright (c) 2002 Markus Friedl * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <openssl/objects.h> #include <openssl/engine.h> #include <openssl/evp.h> #include <openssl/bn.h> #if (defined(__unix__) || defined(unix)) && !defined(USG) && \ (defined(OpenBSD) || defined(__FreeBSD__)) # include <sys/param.h> # if (OpenBSD >= 200112) || ((__FreeBSD_version >= 470101 && __FreeBSD_version < 500000) || __FreeBSD_version >= 500041) # define HAVE_CRYPTODEV # endif # if (OpenBSD >= 200110) # define HAVE_SYSLOG_R # endif #endif #ifndef HAVE_CRYPTODEV void ENGINE_load_cryptodev(void) { /* This is a NOP on platforms without /dev/crypto */ return; } #else # include <sys/types.h> # include <crypto/cryptodev.h> # include <openssl/dh.h> # include <openssl/dsa.h> # include <openssl/err.h> # include <openssl/rsa.h> # include <sys/ioctl.h> # include <errno.h> # include <stdio.h> # include <unistd.h> # include <fcntl.h> # include <stdarg.h> # include <syslog.h> # include <errno.h> # include <string.h> struct dev_crypto_state { struct session_op d_sess; int d_fd; # ifdef USE_CRYPTODEV_DIGESTS char dummy_mac_key[HASH_MAX_LEN]; unsigned char digest_res[HASH_MAX_LEN]; char *mac_data; int mac_len; # endif }; static u_int32_t cryptodev_asymfeat = 0; static int get_asym_dev_crypto(void); static int open_dev_crypto(void); static int get_dev_crypto(void); static int get_cryptodev_ciphers(const int **cnids); # ifdef USE_CRYPTODEV_DIGESTS static int get_cryptodev_digests(const int **cnids); # endif static int cryptodev_usable_ciphers(const int **nids); static int cryptodev_usable_digests(const int **nids); static int cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl); static int cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); static int cryptodev_cleanup(EVP_CIPHER_CTX *ctx); static int cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid); static int cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest, const int **nids, int nid); static int bn2crparam(const BIGNUM *a, struct crparam *crp); static int crparam2bn(struct crparam *crp, BIGNUM *a); static void zapparams(struct crypt_kop *kop); static int cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r, int slen, BIGNUM *s); static int cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); static int cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx); static int cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx); static int cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); static int cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g, BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2, BIGNUM *p, BN_CTX *ctx, BN_MONT_CTX *mont); static DSA_SIG *cryptodev_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa); static int cryptodev_dsa_verify(const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa); static int cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); static int cryptodev_dh_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh); static int cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void)); void ENGINE_load_cryptodev(void); static const ENGINE_CMD_DEFN cryptodev_defns[] = { {0, NULL, NULL, 0} }; static struct { int id; int nid; int ivmax; int keylen; } ciphers[] = { { CRYPTO_ARC4, NID_rc4, 0, 16, }, { CRYPTO_DES_CBC, NID_des_cbc, 8, 8, }, { CRYPTO_3DES_CBC, NID_des_ede3_cbc, 8, 24, }, { CRYPTO_AES_CBC, NID_aes_128_cbc, 16, 16, }, { CRYPTO_AES_CBC, NID_aes_192_cbc, 16, 24, }, { CRYPTO_AES_CBC, NID_aes_256_cbc, 16, 32, }, # ifdef CRYPTO_AES_CTR { CRYPTO_AES_CTR, NID_aes_128_ctr, 14, 16, }, { CRYPTO_AES_CTR, NID_aes_192_ctr, 14, 24, }, { CRYPTO_AES_CTR, NID_aes_256_ctr, 14, 32, }, # endif { CRYPTO_BLF_CBC, NID_bf_cbc, 8, 16, }, { CRYPTO_CAST_CBC, NID_cast5_cbc, 8, 16, }, { CRYPTO_SKIPJACK_CBC, NID_undef, 0, 0, }, { 0, NID_undef, 0, 0, }, }; # ifdef USE_CRYPTODEV_DIGESTS static struct { int id; int nid; int keylen; } digests[] = { { CRYPTO_MD5_HMAC, NID_hmacWithMD5, 16 }, { CRYPTO_SHA1_HMAC, NID_hmacWithSHA1, 20 }, { CRYPTO_RIPEMD160_HMAC, NID_ripemd160, 16 /* ? */ }, { CRYPTO_MD5_KPDK, NID_undef, 0 }, { CRYPTO_SHA1_KPDK, NID_undef, 0 }, { CRYPTO_MD5, NID_md5, 16 }, { CRYPTO_SHA1, NID_sha1, 20 }, { 0, NID_undef, 0 }, }; # endif /* * Return a fd if /dev/crypto seems usable, 0 otherwise. */ static int open_dev_crypto(void) { static int fd = -1; if (fd == -1) { if ((fd = open("/dev/crypto", O_RDWR, 0)) == -1) return (-1); /* close on exec */ if (fcntl(fd, F_SETFD, 1) == -1) { close(fd); fd = -1; return (-1); } } return (fd); } static int get_dev_crypto(void) { int fd, retfd; if ((fd = open_dev_crypto()) == -1) return (-1); # ifndef CRIOGET_NOT_NEEDED if (ioctl(fd, CRIOGET, &retfd) == -1) return (-1); /* close on exec */ if (fcntl(retfd, F_SETFD, 1) == -1) { close(retfd); return (-1); } # else retfd = fd; # endif return (retfd); } static void put_dev_crypto(int fd) { # ifndef CRIOGET_NOT_NEEDED close(fd); # endif } /* Caching version for asym operations */ static int get_asym_dev_crypto(void) { static int fd = -1; if (fd == -1) fd = get_dev_crypto(); return fd; } /* * Find out what ciphers /dev/crypto will let us have a session for. * XXX note, that some of these openssl doesn't deal with yet! * returning them here is harmless, as long as we return NULL * when asked for a handler in the cryptodev_engine_ciphers routine */ static int get_cryptodev_ciphers(const int **cnids) { static int nids[CRYPTO_ALGORITHM_MAX]; struct session_op sess; int fd, i, count = 0; if ((fd = get_dev_crypto()) < 0) { *cnids = NULL; return (0); } memset(&sess, 0, sizeof(sess)); sess.key = (caddr_t) "123456789abcdefghijklmno"; for (i = 0; ciphers[i].id && count < CRYPTO_ALGORITHM_MAX; i++) { if (ciphers[i].nid == NID_undef) continue; sess.cipher = ciphers[i].id; sess.keylen = ciphers[i].keylen; sess.mac = 0; if (ioctl(fd, CIOCGSESSION, &sess) != -1 && ioctl(fd, CIOCFSESSION, &sess.ses) != -1) nids[count++] = ciphers[i].nid; } put_dev_crypto(fd); if (count > 0) *cnids = nids; else *cnids = NULL; return (count); } # ifdef USE_CRYPTODEV_DIGESTS /* * Find out what digests /dev/crypto will let us have a session for. * XXX note, that some of these openssl doesn't deal with yet! * returning them here is harmless, as long as we return NULL * when asked for a handler in the cryptodev_engine_digests routine */ static int get_cryptodev_digests(const int **cnids) { static int nids[CRYPTO_ALGORITHM_MAX]; struct session_op sess; int fd, i, count = 0; if ((fd = get_dev_crypto()) < 0) { *cnids = NULL; return (0); } memset(&sess, 0, sizeof(sess)); sess.mackey = (caddr_t) "123456789abcdefghijklmno"; for (i = 0; digests[i].id && count < CRYPTO_ALGORITHM_MAX; i++) { if (digests[i].nid == NID_undef) continue; sess.mac = digests[i].id; sess.mackeylen = digests[i].keylen; sess.cipher = 0; if (ioctl(fd, CIOCGSESSION, &sess) != -1 && ioctl(fd, CIOCFSESSION, &sess.ses) != -1) nids[count++] = digests[i].nid; } put_dev_crypto(fd); if (count > 0) *cnids = nids; else *cnids = NULL; return (count); } # endif /* 0 */ /* * Find the useable ciphers|digests from dev/crypto - this is the first * thing called by the engine init crud which determines what it * can use for ciphers from this engine. We want to return * only what we can do, anythine else is handled by software. * * If we can't initialize the device to do anything useful for * any reason, we want to return a NULL array, and 0 length, * which forces everything to be done is software. By putting * the initalization of the device in here, we ensure we can * use this engine as the default, and if for whatever reason * /dev/crypto won't do what we want it will just be done in * software * * This can (should) be greatly expanded to perhaps take into * account speed of the device, and what we want to do. * (although the disabling of particular alg's could be controlled * by the device driver with sysctl's.) - this is where we * want most of the decisions made about what we actually want * to use from /dev/crypto. */ static int cryptodev_usable_ciphers(const int **nids) { return (get_cryptodev_ciphers(nids)); } static int cryptodev_usable_digests(const int **nids) { # ifdef USE_CRYPTODEV_DIGESTS return (get_cryptodev_digests(nids)); # else /* * XXXX just disable all digests for now, because it sucks. * we need a better way to decide this - i.e. I may not * want digests on slow cards like hifn on fast machines, * but might want them on slow or loaded machines, etc. * will also want them when using crypto cards that don't * suck moose gonads - would be nice to be able to decide something * as reasonable default without having hackery that's card dependent. * of course, the default should probably be just do everything, * with perhaps a sysctl to turn algoritms off (or have them off * by default) on cards that generally suck like the hifn. */ *nids = NULL; return (0); # endif } static int cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { struct crypt_op cryp; struct dev_crypto_state *state = ctx->cipher_data; struct session_op *sess = &state->d_sess; const void *iiv; unsigned char save_iv[EVP_MAX_IV_LENGTH]; if (state->d_fd < 0) return (0); if (!inl) return (1); if ((inl % ctx->cipher->block_size) != 0) return (0); memset(&cryp, 0, sizeof(cryp)); cryp.ses = sess->ses; cryp.flags = 0; cryp.len = inl; cryp.src = (caddr_t) in; cryp.dst = (caddr_t) out; cryp.mac = 0; cryp.op = ctx->encrypt ? COP_ENCRYPT : COP_DECRYPT; if (ctx->cipher->iv_len) { cryp.iv = (caddr_t) ctx->iv; if (!ctx->encrypt) { iiv = in + inl - ctx->cipher->iv_len; memcpy(save_iv, iiv, ctx->cipher->iv_len); } } else cryp.iv = NULL; if (ioctl(state->d_fd, CIOCCRYPT, &cryp) == -1) { /* * XXX need better errror handling this can fail for a number of * different reasons. */ return (0); } if (ctx->cipher->iv_len) { if (ctx->encrypt) iiv = out + inl - ctx->cipher->iv_len; else iiv = save_iv; memcpy(ctx->iv, iiv, ctx->cipher->iv_len); } return (1); } static int cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { struct dev_crypto_state *state = ctx->cipher_data; struct session_op *sess = &state->d_sess; int cipher = -1, i; for (i = 0; ciphers[i].id; i++) if (ctx->cipher->nid == ciphers[i].nid && ctx->cipher->iv_len <= ciphers[i].ivmax && ctx->key_len == ciphers[i].keylen) { cipher = ciphers[i].id; break; } if (!ciphers[i].id) { state->d_fd = -1; return (0); } memset(sess, 0, sizeof(*sess)); if ((state->d_fd = get_dev_crypto()) < 0) return (0); sess->key = (caddr_t) key; sess->keylen = ctx->key_len; sess->cipher = cipher; if (ioctl(state->d_fd, CIOCGSESSION, sess) == -1) { put_dev_crypto(state->d_fd); state->d_fd = -1; return (0); } return (1); } /* * free anything we allocated earlier when initting a * session, and close the session. */ static int cryptodev_cleanup(EVP_CIPHER_CTX *ctx) { int ret = 0; struct dev_crypto_state *state = ctx->cipher_data; struct session_op *sess = &state->d_sess; if (state->d_fd < 0) return (0); /* * XXX if this ioctl fails, someting's wrong. the invoker may have called * us with a bogus ctx, or we could have a device that for whatever * reason just doesn't want to play ball - it's not clear what's right * here - should this be an error? should it just increase a counter, * hmm. For right now, we return 0 - I don't believe that to be "right". * we could call the gorpy openssl lib error handlers that print messages * to users of the library. hmm.. */ if (ioctl(state->d_fd, CIOCFSESSION, &sess->ses) == -1) { ret = 0; } else { ret = 1; } put_dev_crypto(state->d_fd); state->d_fd = -1; return (ret); } /* * libcrypto EVP stuff - this is how we get wired to EVP so the engine * gets called when libcrypto requests a cipher NID. */ /* RC4 */ static const EVP_CIPHER cryptodev_rc4 = { NID_rc4, 1, 16, 0, EVP_CIPH_VARIABLE_LENGTH, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), NULL, NULL, NULL }; /* DES CBC EVP */ static const EVP_CIPHER cryptodev_des_cbc = { NID_des_cbc, 8, 8, 8, EVP_CIPH_CBC_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; /* 3DES CBC EVP */ static const EVP_CIPHER cryptodev_3des_cbc = { NID_des_ede3_cbc, 8, 24, 8, EVP_CIPH_CBC_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; static const EVP_CIPHER cryptodev_bf_cbc = { NID_bf_cbc, 8, 16, 8, EVP_CIPH_CBC_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; static const EVP_CIPHER cryptodev_cast_cbc = { NID_cast5_cbc, 8, 16, 8, EVP_CIPH_CBC_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; static const EVP_CIPHER cryptodev_aes_cbc = { NID_aes_128_cbc, 16, 16, 16, EVP_CIPH_CBC_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; static const EVP_CIPHER cryptodev_aes_192_cbc = { NID_aes_192_cbc, 16, 24, 16, EVP_CIPH_CBC_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; static const EVP_CIPHER cryptodev_aes_256_cbc = { NID_aes_256_cbc, 16, 32, 16, EVP_CIPH_CBC_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; # ifdef CRYPTO_AES_CTR const EVP_CIPHER cryptodev_aes_ctr = { NID_aes_128_ctr, 16, 16, 14, EVP_CIPH_CTR_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; const EVP_CIPHER cryptodev_aes_ctr_192 = { NID_aes_192_ctr, 16, 24, 14, EVP_CIPH_CTR_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; const EVP_CIPHER cryptodev_aes_ctr_256 = { NID_aes_256_ctr, 16, 32, 14, EVP_CIPH_CTR_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; # endif /* * Registered by the ENGINE when used to find out how to deal with * a particular NID in the ENGINE. this says what we'll do at the * top level - note, that list is restricted by what we answer with */ static int cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid) { if (!cipher) return (cryptodev_usable_ciphers(nids)); switch (nid) { case NID_rc4: *cipher = &cryptodev_rc4; break; case NID_des_ede3_cbc: *cipher = &cryptodev_3des_cbc; break; case NID_des_cbc: *cipher = &cryptodev_des_cbc; break; case NID_bf_cbc: *cipher = &cryptodev_bf_cbc; break; case NID_cast5_cbc: *cipher = &cryptodev_cast_cbc; break; case NID_aes_128_cbc: *cipher = &cryptodev_aes_cbc; break; case NID_aes_192_cbc: *cipher = &cryptodev_aes_192_cbc; break; case NID_aes_256_cbc: *cipher = &cryptodev_aes_256_cbc; break; # ifdef CRYPTO_AES_CTR case NID_aes_128_ctr: *cipher = &cryptodev_aes_ctr; break; case NID_aes_192_ctr: *cipher = &cryptodev_aes_ctr_192; break; case NID_aes_256_ctr: *cipher = &cryptodev_aes_ctr_256; break; # endif default: *cipher = NULL; break; } return (*cipher != NULL); } # ifdef USE_CRYPTODEV_DIGESTS /* convert digest type to cryptodev */ static int digest_nid_to_cryptodev(int nid) { int i; for (i = 0; digests[i].id; i++) if (digests[i].nid == nid) return (digests[i].id); return (0); } static int digest_key_length(int nid) { int i; for (i = 0; digests[i].id; i++) if (digests[i].nid == nid) return digests[i].keylen; return (0); } static int cryptodev_digest_init(EVP_MD_CTX *ctx) { struct dev_crypto_state *state = ctx->md_data; struct session_op *sess = &state->d_sess; int digest; if ((digest = digest_nid_to_cryptodev(ctx->digest->type)) == NID_undef) { printf("cryptodev_digest_init: Can't get digest \n"); return (0); } memset(state, 0, sizeof(*state)); if ((state->d_fd = get_dev_crypto()) < 0) { printf("cryptodev_digest_init: Can't get Dev \n"); return (0); } sess->mackey = state->dummy_mac_key; sess->mackeylen = digest_key_length(ctx->digest->type); sess->mac = digest; if (ioctl(state->d_fd, CIOCGSESSION, sess) < 0) { put_dev_crypto(state->d_fd); state->d_fd = -1; printf("cryptodev_digest_init: Open session failed\n"); return (0); } return (1); } static int cryptodev_digest_update(EVP_MD_CTX *ctx, const void *data, size_t count) { struct crypt_op cryp; struct dev_crypto_state *state = ctx->md_data; struct session_op *sess = &state->d_sess; char *new_mac_data; if (!data || state->d_fd < 0) { printf("cryptodev_digest_update: illegal inputs \n"); return (0); } if (!count) { return (0); } if (!(ctx->flags & EVP_MD_CTX_FLAG_ONESHOT)) { /* if application doesn't support one buffer */ new_mac_data = OPENSSL_realloc(state->mac_data, state->mac_len + count); if (!new_mac_data) { printf("cryptodev_digest_update: realloc failed\n"); return (0); } state->mac_data = new_mac_data; memcpy(state->mac_data + state->mac_len, data, count); state->mac_len += count; return (1); } memset(&cryp, 0, sizeof(cryp)); cryp.ses = sess->ses; cryp.flags = 0; cryp.len = count; cryp.src = (caddr_t) data; cryp.dst = NULL; cryp.mac = (caddr_t) state->digest_res; if (ioctl(state->d_fd, CIOCCRYPT, &cryp) < 0) { printf("cryptodev_digest_update: digest failed\n"); return (0); } return (1); } static int cryptodev_digest_final(EVP_MD_CTX *ctx, unsigned char *md) { struct crypt_op cryp; struct dev_crypto_state *state = ctx->md_data; struct session_op *sess = &state->d_sess; int ret = 1; if (!md || state->d_fd < 0) { printf("cryptodev_digest_final: illegal input\n"); return (0); } if (!(ctx->flags & EVP_MD_CTX_FLAG_ONESHOT)) { /* if application doesn't support one buffer */ memset(&cryp, 0, sizeof(cryp)); cryp.ses = sess->ses; cryp.flags = 0; cryp.len = state->mac_len; cryp.src = state->mac_data; cryp.dst = NULL; cryp.mac = (caddr_t) md; if (ioctl(state->d_fd, CIOCCRYPT, &cryp) < 0) { printf("cryptodev_digest_final: digest failed\n"); return (0); } return 1; } memcpy(md, state->digest_res, ctx->digest->md_size); return (ret); } static int cryptodev_digest_cleanup(EVP_MD_CTX *ctx) { int ret = 1; struct dev_crypto_state *state = ctx->md_data; struct session_op *sess = &state->d_sess; if (state == NULL) return 0; if (state->d_fd < 0) { printf("cryptodev_digest_cleanup: illegal input\n"); return (0); } OPENSSL_free(state->mac_data); state->mac_data = NULL; state->mac_len = 0; if (ioctl(state->d_fd, CIOCFSESSION, &sess->ses) < 0) { printf("cryptodev_digest_cleanup: failed to close session\n"); ret = 0; } else { ret = 1; } put_dev_crypto(state->d_fd); state->d_fd = -1; return (ret); } static int cryptodev_digest_copy(EVP_MD_CTX *to, const EVP_MD_CTX *from) { struct dev_crypto_state *fstate = from->md_data; struct dev_crypto_state *dstate = to->md_data; struct session_op *sess; int digest; if (dstate == NULL || fstate == NULL) return 1; memcpy(dstate, fstate, sizeof(struct dev_crypto_state)); sess = &dstate->d_sess; digest = digest_nid_to_cryptodev(to->digest->type); sess->mackey = dstate->dummy_mac_key; sess->mackeylen = digest_key_length(to->digest->type); sess->mac = digest; dstate->d_fd = get_dev_crypto(); if (ioctl(dstate->d_fd, CIOCGSESSION, sess) < 0) { put_dev_crypto(dstate->d_fd); dstate->d_fd = -1; printf("cryptodev_digest_copy: Open session failed\n"); return (0); } if (fstate->mac_len != 0) { if (fstate->mac_data != NULL) { dstate->mac_data = OPENSSL_malloc(fstate->mac_len); if (dstate->mac_data == NULL) { printf("cryptodev_digest_copy: mac_data allocation failed\n"); return (0); } memcpy(dstate->mac_data, fstate->mac_data, fstate->mac_len); dstate->mac_len = fstate->mac_len; } } return 1; } const EVP_MD cryptodev_sha1 = { NID_sha1, NID_undef, SHA_DIGEST_LENGTH, EVP_MD_FLAG_ONESHOT, cryptodev_digest_init, cryptodev_digest_update, cryptodev_digest_final, cryptodev_digest_copy, cryptodev_digest_cleanup, EVP_PKEY_NULL_method, SHA_CBLOCK, sizeof(struct dev_crypto_state), }; const EVP_MD cryptodev_md5 = { NID_md5, NID_undef, 16 /* MD5_DIGEST_LENGTH */ , EVP_MD_FLAG_ONESHOT, cryptodev_digest_init, cryptodev_digest_update, cryptodev_digest_final, cryptodev_digest_copy, cryptodev_digest_cleanup, EVP_PKEY_NULL_method, 64 /* MD5_CBLOCK */ , sizeof(struct dev_crypto_state), }; # endif /* USE_CRYPTODEV_DIGESTS */ static int cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest, const int **nids, int nid) { if (!digest) return (cryptodev_usable_digests(nids)); switch (nid) { # ifdef USE_CRYPTODEV_DIGESTS case NID_md5: *digest = &cryptodev_md5; break; case NID_sha1: *digest = &cryptodev_sha1; break; default: # endif /* USE_CRYPTODEV_DIGESTS */ *digest = NULL; break; } return (*digest != NULL); } /* * Convert a BIGNUM to the representation that /dev/crypto needs. * Upon completion of use, the caller is responsible for freeing * crp->crp_p. */ static int bn2crparam(const BIGNUM *a, struct crparam *crp) { ssize_t bytes, bits; u_char *b; crp->crp_p = NULL; crp->crp_nbits = 0; bits = BN_num_bits(a); bytes = BN_num_bytes(a); b = OPENSSL_zalloc(bytes); if (b == NULL) return (1); crp->crp_p = (caddr_t) b; crp->crp_nbits = bits; BN_bn2bin(a, b); return (0); } /* Convert a /dev/crypto parameter to a BIGNUM */ static int crparam2bn(struct crparam *crp, BIGNUM *a) { u_int8_t *pd; int i, bytes; bytes = (crp->crp_nbits + 7) / 8; if (bytes == 0) return (-1); if ((pd = OPENSSL_malloc(bytes)) == NULL) return (-1); for (i = 0; i < bytes; i++) pd[i] = crp->crp_p[bytes - i - 1]; BN_bin2bn(pd, bytes, a); free(pd); return (0); } static void zapparams(struct crypt_kop *kop) { int i; for (i = 0; i < kop->crk_iparams + kop->crk_oparams; i++) { if (kop->crk_param[i].crp_p) free(kop->crk_param[i].crp_p); kop->crk_param[i].crp_p = NULL; kop->crk_param[i].crp_nbits = 0; } } static int cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r, int slen, BIGNUM *s) { int fd, ret = -1; if ((fd = get_asym_dev_crypto()) < 0) return (ret); if (r) { kop->crk_param[kop->crk_iparams].crp_p = calloc(rlen, sizeof(char)); kop->crk_param[kop->crk_iparams].crp_nbits = rlen * 8; kop->crk_oparams++; } if (s) { kop->crk_param[kop->crk_iparams + 1].crp_p = calloc(slen, sizeof(char)); kop->crk_param[kop->crk_iparams + 1].crp_nbits = slen * 8; kop->crk_oparams++; } if (ioctl(fd, CIOCKEY, kop) == 0) { if (r) crparam2bn(&kop->crk_param[kop->crk_iparams], r); if (s) crparam2bn(&kop->crk_param[kop->crk_iparams + 1], s); ret = 0; } return (ret); } static int cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont) { struct crypt_kop kop; int ret = 1; /* * Currently, we know we can do mod exp iff we can do any asymmetric * operations at all. */ if (cryptodev_asymfeat == 0) { ret = BN_mod_exp(r, a, p, m, ctx); return (ret); } memset(&kop, 0, sizeof(kop)); kop.crk_op = CRK_MOD_EXP; /* inputs: a^p % m */ if (bn2crparam(a, &kop.crk_param[0])) goto err; if (bn2crparam(p, &kop.crk_param[1])) goto err; if (bn2crparam(m, &kop.crk_param[2])) goto err; kop.crk_iparams = 3; if (cryptodev_asym(&kop, BN_num_bytes(m), r, 0, NULL)) { const RSA_METHOD *meth = RSA_PKCS1_SSLeay(); printf("OCF asym process failed, Running in software\n"); ret = meth->bn_mod_exp(r, a, p, m, ctx, in_mont); } else if (ECANCELED == kop.crk_status) { const RSA_METHOD *meth = RSA_PKCS1_SSLeay(); printf("OCF hardware operation cancelled. Running in Software\n"); ret = meth->bn_mod_exp(r, a, p, m, ctx, in_mont); } /* else cryptodev operation worked ok ==> ret = 1 */ err: zapparams(&kop); return (ret); } static int cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) { int r; ctx = BN_CTX_new(); r = cryptodev_bn_mod_exp(r0, I, rsa->d, rsa->n, ctx, NULL); BN_CTX_free(ctx); return (r); } static int cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) { struct crypt_kop kop; int ret = 1; if (!rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp) { /* XXX 0 means failure?? */ return (0); } memset(&kop, 0, sizeof(kop)); kop.crk_op = CRK_MOD_EXP_CRT; /* inputs: rsa->p rsa->q I rsa->dmp1 rsa->dmq1 rsa->iqmp */ if (bn2crparam(rsa->p, &kop.crk_param[0])) goto err; if (bn2crparam(rsa->q, &kop.crk_param[1])) goto err; if (bn2crparam(I, &kop.crk_param[2])) goto err; if (bn2crparam(rsa->dmp1, &kop.crk_param[3])) goto err; if (bn2crparam(rsa->dmq1, &kop.crk_param[4])) goto err; if (bn2crparam(rsa->iqmp, &kop.crk_param[5])) goto err; kop.crk_iparams = 6; if (cryptodev_asym(&kop, BN_num_bytes(rsa->n), r0, 0, NULL)) { const RSA_METHOD *meth = RSA_PKCS1_SSLeay(); printf("OCF asym process failed, running in Software\n"); ret = (*meth->rsa_mod_exp) (r0, I, rsa, ctx); } else if (ECANCELED == kop.crk_status) { const RSA_METHOD *meth = RSA_PKCS1_SSLeay(); printf("OCF hardware operation cancelled. Running in Software\n"); ret = (*meth->rsa_mod_exp) (r0, I, rsa, ctx); } /* else cryptodev operation worked ok ==> ret = 1 */ err: zapparams(&kop); return (ret); } static RSA_METHOD cryptodev_rsa = { "cryptodev RSA method", NULL, /* rsa_pub_enc */ NULL, /* rsa_pub_dec */ NULL, /* rsa_priv_enc */ NULL, /* rsa_priv_dec */ NULL, NULL, NULL, /* init */ NULL, /* finish */ 0, /* flags */ NULL, /* app_data */ NULL, /* rsa_sign */ NULL /* rsa_verify */ }; static int cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) { return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx)); } static int cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g, BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2, BIGNUM *p, BN_CTX *ctx, BN_MONT_CTX *mont) { BIGNUM *t2; int ret = 0; t2 = BN_new(); /* v = ( g^u1 * y^u2 mod p ) mod q */ /* let t1 = g ^ u1 mod p */ ret = 0; if (!dsa->meth->bn_mod_exp(dsa, t1, dsa->g, u1, dsa->p, ctx, mont)) goto err; /* let t2 = y ^ u2 mod p */ if (!dsa->meth->bn_mod_exp(dsa, t2, dsa->pub_key, u2, dsa->p, ctx, mont)) goto err; /* let u1 = t1 * t2 mod p */ if (!BN_mod_mul(u1, t1, t2, dsa->p, ctx)) goto err; BN_copy(t1, u1); ret = 1; err: BN_free(t2); return (ret); } static DSA_SIG *cryptodev_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa) { struct crypt_kop kop; BIGNUM *r = NULL, *s = NULL; DSA_SIG *dsaret = NULL; if ((r = BN_new()) == NULL) goto err; if ((s = BN_new()) == NULL) { BN_free(r); goto err; } memset(&kop, 0, sizeof(kop)); kop.crk_op = CRK_DSA_SIGN; /* inputs: dgst dsa->p dsa->q dsa->g dsa->priv_key */ kop.crk_param[0].crp_p = (caddr_t) dgst; kop.crk_param[0].crp_nbits = dlen * 8; if (bn2crparam(dsa->p, &kop.crk_param[1])) goto err; if (bn2crparam(dsa->q, &kop.crk_param[2])) goto err; if (bn2crparam(dsa->g, &kop.crk_param[3])) goto err; if (bn2crparam(dsa->priv_key, &kop.crk_param[4])) goto err; kop.crk_iparams = 5; if (cryptodev_asym(&kop, BN_num_bytes(dsa->q), r, BN_num_bytes(dsa->q), s) == 0) { dsaret = DSA_SIG_new(); dsaret->r = r; dsaret->s = s; } else { const DSA_METHOD *meth = DSA_OpenSSL(); BN_free(r); BN_free(s); dsaret = (meth->dsa_do_sign) (dgst, dlen, dsa); } err: kop.crk_param[0].crp_p = NULL; zapparams(&kop); return (dsaret); } static int cryptodev_dsa_verify(const unsigned char *dgst, int dlen, DSA_SIG *sig, DSA *dsa) { struct crypt_kop kop; int dsaret = 1; memset(&kop, 0, sizeof(kop)); kop.crk_op = CRK_DSA_VERIFY; /* inputs: dgst dsa->p dsa->q dsa->g dsa->pub_key sig->r sig->s */ kop.crk_param[0].crp_p = (caddr_t) dgst; kop.crk_param[0].crp_nbits = dlen * 8; if (bn2crparam(dsa->p, &kop.crk_param[1])) goto err; if (bn2crparam(dsa->q, &kop.crk_param[2])) goto err; if (bn2crparam(dsa->g, &kop.crk_param[3])) goto err; if (bn2crparam(dsa->pub_key, &kop.crk_param[4])) goto err; if (bn2crparam(sig->r, &kop.crk_param[5])) goto err; if (bn2crparam(sig->s, &kop.crk_param[6])) goto err; kop.crk_iparams = 7; if (cryptodev_asym(&kop, 0, NULL, 0, NULL) == 0) { /* * OCF success value is 0, if not zero, change dsaret to fail */ if (0 != kop.crk_status) dsaret = 0; } else { const DSA_METHOD *meth = DSA_OpenSSL(); dsaret = (meth->dsa_do_verify) (dgst, dlen, sig, dsa); } err: kop.crk_param[0].crp_p = NULL; zapparams(&kop); return (dsaret); } static DSA_METHOD cryptodev_dsa = { "cryptodev DSA method", NULL, NULL, /* dsa_sign_setup */ NULL, NULL, /* dsa_mod_exp */ NULL, NULL, /* init */ NULL, /* finish */ 0, /* flags */ NULL /* app_data */ }; static int cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) { return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx)); } static int cryptodev_dh_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh) { struct crypt_kop kop; int dhret = 1; int fd, keylen; if ((fd = get_asym_dev_crypto()) < 0) { const DH_METHOD *meth = DH_OpenSSL(); return ((meth->compute_key) (key, pub_key, dh)); } keylen = BN_num_bits(dh->p); memset(&kop, 0, sizeof(kop)); kop.crk_op = CRK_DH_COMPUTE_KEY; /* inputs: dh->priv_key pub_key dh->p key */ if (bn2crparam(dh->priv_key, &kop.crk_param[0])) goto err; if (bn2crparam(pub_key, &kop.crk_param[1])) goto err; if (bn2crparam(dh->p, &kop.crk_param[2])) goto err; kop.crk_iparams = 3; kop.crk_param[3].crp_p = (caddr_t) key; kop.crk_param[3].crp_nbits = keylen * 8; kop.crk_oparams = 1; if (ioctl(fd, CIOCKEY, &kop) == -1) { const DH_METHOD *meth = DH_OpenSSL(); dhret = (meth->compute_key) (key, pub_key, dh); } err: kop.crk_param[3].crp_p = NULL; zapparams(&kop); return (dhret); } static DH_METHOD cryptodev_dh = { "cryptodev DH method", NULL, /* cryptodev_dh_generate_key */ NULL, NULL, NULL, NULL, 0, /* flags */ NULL /* app_data */ }; /* * ctrl right now is just a wrapper that doesn't do much * but I expect we'll want some options soon. */ static int cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void)) { # ifdef HAVE_SYSLOG_R struct syslog_data sd = SYSLOG_DATA_INIT; # endif switch (cmd) { default: # ifdef HAVE_SYSLOG_R syslog_r(LOG_ERR, &sd, "cryptodev_ctrl: unknown command %d", cmd); # else syslog(LOG_ERR, "cryptodev_ctrl: unknown command %d", cmd); # endif break; } return (1); } void ENGINE_load_cryptodev(void) { ENGINE *engine = ENGINE_new(); int fd; if (engine == NULL) return; if ((fd = get_dev_crypto()) < 0) { ENGINE_free(engine); return; } /* * find out what asymmetric crypto algorithms we support */ if (ioctl(fd, CIOCASYMFEAT, &cryptodev_asymfeat) == -1) { put_dev_crypto(fd); ENGINE_free(engine); return; } put_dev_crypto(fd); if (!ENGINE_set_id(engine, "cryptodev") || !ENGINE_set_name(engine, "BSD cryptodev engine") || !ENGINE_set_ciphers(engine, cryptodev_engine_ciphers) || !ENGINE_set_digests(engine, cryptodev_engine_digests) || !ENGINE_set_ctrl_function(engine, cryptodev_ctrl) || !ENGINE_set_cmd_defns(engine, cryptodev_defns)) { ENGINE_free(engine); return; } if (ENGINE_set_RSA(engine, &cryptodev_rsa)) { const RSA_METHOD *rsa_meth = RSA_PKCS1_SSLeay(); cryptodev_rsa.bn_mod_exp = rsa_meth->bn_mod_exp; cryptodev_rsa.rsa_mod_exp = rsa_meth->rsa_mod_exp; cryptodev_rsa.rsa_pub_enc = rsa_meth->rsa_pub_enc; cryptodev_rsa.rsa_pub_dec = rsa_meth->rsa_pub_dec; cryptodev_rsa.rsa_priv_enc = rsa_meth->rsa_priv_enc; cryptodev_rsa.rsa_priv_dec = rsa_meth->rsa_priv_dec; if (cryptodev_asymfeat & CRF_MOD_EXP) { cryptodev_rsa.bn_mod_exp = cryptodev_bn_mod_exp; if (cryptodev_asymfeat & CRF_MOD_EXP_CRT) cryptodev_rsa.rsa_mod_exp = cryptodev_rsa_mod_exp; else cryptodev_rsa.rsa_mod_exp = cryptodev_rsa_nocrt_mod_exp; } } if (ENGINE_set_DSA(engine, &cryptodev_dsa)) { const DSA_METHOD *meth = DSA_OpenSSL(); memcpy(&cryptodev_dsa, meth, sizeof(DSA_METHOD)); if (cryptodev_asymfeat & CRF_DSA_SIGN) cryptodev_dsa.dsa_do_sign = cryptodev_dsa_do_sign; if (cryptodev_asymfeat & CRF_MOD_EXP) { cryptodev_dsa.bn_mod_exp = cryptodev_dsa_bn_mod_exp; cryptodev_dsa.dsa_mod_exp = cryptodev_dsa_dsa_mod_exp; } if (cryptodev_asymfeat & CRF_DSA_VERIFY) cryptodev_dsa.dsa_do_verify = cryptodev_dsa_verify; } if (ENGINE_set_DH(engine, &cryptodev_dh)) { const DH_METHOD *dh_meth = DH_OpenSSL(); cryptodev_dh.generate_key = dh_meth->generate_key; cryptodev_dh.compute_key = dh_meth->compute_key; cryptodev_dh.bn_mod_exp = dh_meth->bn_mod_exp; if (cryptodev_asymfeat & CRF_MOD_EXP) { cryptodev_dh.bn_mod_exp = cryptodev_mod_exp_dh; if (cryptodev_asymfeat & CRF_DH_COMPUTE_KEY) cryptodev_dh.compute_key = cryptodev_dh_compute_key; } } ENGINE_add(engine); ENGINE_free(engine); ERR_clear_error(); } #endif /* HAVE_CRYPTODEV */
import libtcodpy as libtcod from objectComponent.fighter import * from objectComponent.equipment import * from fighterAi.basic import * from gameObject import * import xml.etree.ElementTree as ET class AbstractMapGenerator(): def setup_map(self): raise NotImplementedError def place_objects(self): raise NotImplementedError def random_choice_index(self, chances): #Choose an option from a list of chances #Roll a die, which will land somewhere between 1 and the total of the chances list #Then, we simply need to figure out what range in the list that number falls under dice = libtcod.random_get_int(0, 1, sum(chances)) running_sum = 0 choice = 0 #Go through all chances, keeping the total so far for w in chances: running_sum += w #Check if the die roll is smaller or equal to the current total. #If it is, we know the chance range the roll fell into if dice <= running_sum: return choice choice += 1 def is_blocked(self, map, objects, x, y): #Test the map tile at the coordinates to see if it is blocked or not if map[x][y].blocked: return True #Then, check through all objects and see if any of them are blocking for object in objects: if object.blocks and object.x == x and object.y == y: return True #There is no object or tile blocking this position return False def setup_monsters(self, level): #Figure out which monsters to include on this level, and load them all #TODO: For each level, the player can encounter monsters from the previous level, as well as the next level #There is a 50% decrease in encounter chances for previous level monsters #There is a 75% decrease in encounter chances for next level monsters #This will keep the chance of difficult monsters a possibility on any level #Figure out the level, and load the monsters accordingly current_level_file = 'monsters/level-' + str(level) + '.xml' monster_lists = [current_level_file] if level + 1 <= 3: monster_lists.append('monsters/level-' + str(level + 1) + '.xml') if level - 1 >= 1: monster_lists.append('monsters/level-' + str(level - 1) + '.xml') monsters = [] index_counter = 0 for list in monster_lists: monster_tree = ET.parse(list) monster_root = monster_tree.getroot() #Create a list with all the applicable monsters for this floor for monster in monster_root.findall('monster'): m = {} m['name'] = monster.get('name') m['type'] = monster.find('type').text m['ai-type'] = monster.find('ai-type').text m['hit-points'] = monster.find('hit-points').text m['defence'] = monster.find('defence').text m['attack'] = monster.find('attack').text m['strength'] = monster.find('strength').text m['protection'] = monster.find('protection').text m['agility'] = monster.find('agility').text m['accuracy'] = monster.find('accuracy').text m['character'] = monster.find('character').text m['color-r'] = monster.find('color-r').text m['color-g'] = monster.find('color-g').text m['color-b'] = monster.find('color-b').text #Check for other levelled lists, an dif appropriate, add their monsters encounter chances at a #reduced chance (25% for harder, and 50% for easier) if index_counter == 1: chance = int(monster.find('encounter-chance').text) * .25 m['encounter-chance']= chance elif index_counter == 2: chance = int(monster.find('encounter-chance').text) * .50 m['encounter-chance']= chance else: m['encounter-chance'] = monster.find('encounter-chance').text m['xp'] = monster.find('xp').text #Add the newly created monster list to the list of monsters monsters.append(m) index_counter += 1; # Next, build a list with just the monster appearance chances, so we can figure out later how often each monster # will show up. The index of the chance in this list directly corresponds to the index of the monster in the # monsters list monster_appearance_chances = [] for appearing_monster in monsters: monster_appearance_chances.append(int(appearing_monster['encounter-chance'])) return monsters, monster_appearance_chances def setup_items(self, level): #Figure out which items to include on this level, and load them all #TODO: For each level, the player can encounter items from the previous level, as well as the next level #There is a 50% decrease in encounter chances for previous level items #There is a 75% decrease in encounter chances for next level items #This will keep the items semi-random on any level item_tree = ET.parse('items/level-0.xml') item_root = item_tree.getroot() items = [] #Create a list with all the applicable monsters for this floor for item in item_root.findall('item'): i = {} i['name'] = item.get('name') i['type'] = item.find('type').text if item.find('type').text == 'equipment': #We have a slightly different set of attributes for equipment i['use'] = item.find('use').text i['description'] = item.find('description').text i['damage'] = item.find('damage').text i['range'] = item.find('range').text i['slot'] = item.find('slot').text else: #This is a standard item, find the appropriate attributes i['use'] = item.find('use').text i['value'] = item.find('value').text i['range'] = item.find('range').text i['targeting'] = item.find('targeting').text i['character'] = item.find('character').text i['color-r'] = item.find('color-r').text i['color-g'] = item.find('color-g').text i['color-b'] = item.find('color-b').text i['encounter-chance'] = item.find('encounter-chance').text #Add the newly created monster list to the list of monsters items.append(i) #Next, build a list with just the item appearance chances, so we can figure out later how often each item will #show up. The index of the chance in this list directly corresponds to the index of the item in the item list item_appearance_chances = [] for appearing_item in items: item_appearance_chances.append(int(appearing_item['encounter-chance'])) return items, item_appearance_chances def generate_monster(self, x, y, appearance_chances, monsters): #Choose a monster to spawn from the list of applicable monsters spawn = self.random_choice_index(appearance_chances) #Choose the monster based on the spawn chance monster = monsters[spawn] #Create a death function for the monster monster_death = getattr(Fighter, 'monster_death') #Create a component for the monster based on the monster type if monster['type'] == 'fighter': fighter_component = Fighter(hp=int(monster['hit-points']), attack=int(monster['attack']), defence=int(monster['defence']), strength=int(monster['strength']), protection=int(monster['protection']), agility=int(monster['agility']), accuracy=int(monster['accuracy']), xp=int(monster['xp']), death_function=monster_death) #Create an AI component for the monster based on its AI type if monster['ai-type'] == 'basic': ai_component = BasicMonster() #Finally, create the monster monster = Object(x, y, char=monster['character'], name=monster['name'], color=libtcod.Color(int(monster['color-r']), int(monster['color-g']), int(monster['color-b'])), blocks=True, fighter=fighter_component, ai=ai_component) return monster def generate_item(self, x, y, appearance_chances, items): #Choose an item to create from the list of applicable items item_choice = self.random_choice_index(appearance_chances) #Choose the item based on the spawn chance item = items[item_choice] #Find the use function for this object, and apply it to the item item_use_function = item['use'] if item['type'] == 'equipment': #This is a piece of equipment, so create equipment instead of a standard item equipment = Equipment(item['slot'], item['type'], item['use'], item['damage']) item = Object(x, y, item['character'], item['name'], color=libtcod.Color(int(item['color-r']), int(item['color-g']), int(item['color-b'])),equipment=equipment, description=item['description']) else: #Create an object and item component from the loaded values item_component = Item(value=int(item['value']), range=int(item['range']), use_function=item_use_function, targeting=item['targeting']) item = Object(x, y, item['character'], item['name'], color=libtcod.Color(int(item['color-r']), int(item['color-g']), int(item['color-b'])), item=item_component) return item
define( ({ _widgetLabel: 'ทิศทาง' }) );
const input = document.querySelector("#send"); const text = document.querySelector("#text"); const counter = document.querySelector("#counter") const cleaning = input.addEventListener('click', (e)=> { e.preventDefault(); let palavroes = ['porra', 'caralho', 'corno', 'puto']; let valuetext = text.value.toLowerCase(); palavroes.forEach( (value) => { if (valuetext.match(value)){ valuetext = valuetext.replaceAll(value, '***'); } } ) text.value = valuetext; }); text.addEventListener("keypress", (e)=> { const maxChars = 255; let inputLength = text.value.length; if(inputLength >= maxChars) { e.preventDefault(); } counter.innerHTML = (inputLength + 1).toString(); });
import React, { Component } from 'react'; import { Card, CardBody, Col, Row, Table, Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'; import axios from 'axios' import 'bootstrap/dist/css/bootstrap.min.css' import './manage.css' class Manage extends Component { constructor(props) { super(props) this.state = { posts: [], model: false, role: '', qualification: '', salary: { value: 0 }, department: '', experience: '', con: true, referalbonus: { value: 0 }, filterer:"", } this.toggle = this.toggle.bind(this); this.toggles = this.toggles.bind(this); } componentDidMount() { this.getPosts() } toggles(i) { const newArray = this.state.dropdownOpen.map((element, index) => { return (index === i ? !element : false); }); this.setState({ dropdownOpen: newArray, }); } getPosts() { const sam =localStorage.getItem('token'); const headers ={ "Content-Type": "application/json", "Accept":"*/*", 'Authorization':sam } axios.get('https://employee-referals.herokuapp.com/api/job/',{headers}) .then(res => { this.setState({ posts: res.data, }) console.log(res) }) .catch(function (error) { console.log(error); }); } addPosts(postObject) { const sam =localStorage.getItem('token'); const headers ={ "Content-Type": "application/json", "Accept":"*/*", 'Authorization':sam } console.log(postObject) axios.post('https://employee-referals.herokuapp.com/api/job',{headers}, postObject) .then((response) => { if (response) { this.getPosts() } }) .catch((error) => { console.log(error); }) } toggle() { this.setState(prevState => ({ modal: !prevState.modal })); } handleChange = (e) => { this.setState({ [e.target.name]: e.target.type === 'number' ? parseInt(e.target.value) : e.target.value }); } handleSubmit = (e) => { // if (this.state.department == test) //test is token to be taken from login data // { const one = { role: this.state.role, qualification: this.state.qualification, salary: this.state.salary, department: this.state.department, experience: this.state.experience, referalbonus: this.state.referalbonus, } this.addPosts(one) this.setState(prevState => ({ modal: !prevState.modal })); // } // else{ // window.alert("cannot add job to this department"); // } } getId = (e) => { console.log(e._id) const samm =localStorage.getItem('token'); const headers= { "Content-Type": "application/json", "Accept":"*/*", 'Authorization':samm, _id: e._id } const da={ _id: e._id } console.log(da) axios.post('https://employee-referals.herokuapp.com/api/job/jobdelete',da, {headers: headers}) .then(res => { console.log(res) this.getPosts() }) } // handleInputChange = (e) => { // this.setState({ [e.target.id]: e.target.value }) // } // handleSubmits = (e) => { // // e.preventDefault(); // const body = { // search: this.state.searchkey // } // console.log(body) // axios.post('https://employee-referals.herokuapp.com/api/job/search',body) // .then(res => { // this.setState({ // posts: res.data.data // }) // //console.log(this.state.posts) // console.log(res) // }) // } handleInputChange = event => { this.setState({ filterer: event.target.value }); }; render() { const filteredData = this.state.posts.filter(val => { if(this.state.filterer.length){ const lowerCaseValue= val["department" ].toLowerCase() const lower=val["qualification"].toLowerCase() const lowers= val["role"].toLowerCase() return (lowerCaseValue.includes(this.state.filterer.toLowerCase()) || lower.includes(this.state.filterer.toLowerCase()) ||lowers.includes(this.state.filterer.toLowerCase())) } return true }); return ( <div> <div className="animated fadeIn"> <Row> <Col xs="12"> <Card> <CardBody> <div className="searchForm"> <form> <input id="searchkey" placeholder="Search for..." name="filter" onChange={this.handleInputChange} /> </form> {/* <Button onClick={this.handleSubmits}></Button> */} {/* <div>{this.state.filteredData.map(e => <p>{e.name}</p>)}</div> */} </div> </CardBody> </Card> </Col> </Row> </div> <div className="animated fadeIn"> <Row> <Col xl={12} > <Card> {/* <CardHeader> <i className="fa fa-align-justify"></i> Users <small className="text-muted">example</small> </CardHeader> */} <CardBody> <Table responsive hover> <thead> <tr> <th scope="col">Role</th> <th scope="col">Qualification</th> <th scope="col">Department</th> <th scope="col">Experience</th> <th scope="col">Salary</th> <th scope="col">ReferalBonus</th> <th scope="col">Delete</th> </tr> </thead> <tbody> {filteredData.map((user, index) => <tr key={user._id}> <th>{user.role}</th> <th>{user.qualification}</th> <td>{user.department}</td> <td>{user.experience}</td> <td>{user.salary}</td> <td>{user.referalbonus}</td> <button className="btn btn-danger" onClick={(e) => { this.getId(user) }}>Delete</button> </tr> )} </tbody> </Table> </CardBody> </Card> </Col> </Row> </div> <div className="but"> <Button className="Button" onClick={this.toggle}>{this.props.buttonLabel}ADD</Button> <Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}> <ModalHeader toggle={this.toggle}>ADD JOB</ModalHeader> <ModalBody> <div className="base-container"> <div className="content" > <div className="form"> <div className="form-group"> <label htmlFor="empid">Role .</label> <input type="text" id="role" name="role" placeholder="role" onChange={this.handleChange} /> </div> <div className="form-group"> <label htmlFor="empid">Qualification.</label> <input type="text" id="qualification" name="qualification" placeholder="qualification" onChange={this.handleChange} /> </div> <div className="form-group"> <label htmlFor="username">Salary.</label> <input type="number" id="salary" name="salary" placeholder="salary" onChange={this.handleChange} /> </div> <div className="form-group"> <label htmlFor="email">Department.</label> <input type="text" id="department" name="department" placeholder="department" onChange={this.handleChange} /> </div> <div className="form-group"> <label htmlFor="password">Experience.</label> <input type="text" id="experience" name="experience" placeholder="experience" onChange={this.handleChange} /> </div> <div className="form-group"> <label htmlFor="phone">ReferalBonus.</label> <input type="number" id="referalbonus" name="referalbonus" placeholder="referalbonus" onChange={this.handleChange} /> </div> </div> </div> </div> </ModalBody> <ModalFooter> <Button color="primary" onClick={this.handleSubmit} >Submit</Button> <Button color="secondary" onClick={this.toggle}>Cancel</Button> </ModalFooter> </Modal> </div> </div> ) } } export default Manage;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Represents a file within Stryker. Could be a strictly in-memory file. */ var File = /** @class */ (function () { /** * Creates a new File to be used within Stryker. * @param name The full name of the file (inc path) * @param content The buffered or string content of the file */ function File(name, content) { this.name = name; if (typeof content === 'string') { this._content = Buffer.from(content); this._textContent = content; } else { this._content = content; } } Object.defineProperty(File.prototype, "content", { /** * Gets the underlying content as buffer. */ get: function () { return this._content; }, enumerable: true, configurable: true }); Object.defineProperty(File.prototype, "textContent", { /** * Gets the underlying content as string using utf8 encoding. */ get: function () { if (!this._textContent) { this._textContent = this.content.toString(); } return this._textContent; }, enumerable: true, configurable: true }); return File; }()); exports.default = File; //# sourceMappingURL=File.js.map
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-03-08 19:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Student', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_column='sname', max_length=128, verbose_name='姓名')), ('sex', models.IntegerField(choices=[(1, '男'), (2, '女'), (0, '未知')], db_column='ssex', verbose_name='性别')), ('profession', models.CharField(db_column='sprofession', max_length=128, verbose_name='职业')), ('email', models.EmailField(db_column='semail', max_length=254, verbose_name='Email')), ('qq', models.CharField(db_column='sqq', max_length=128, verbose_name='QQ')), ('phone', models.CharField(db_column='sphone', max_length=128, verbose_name='电话')), ('status', models.IntegerField(choices=[(0, '申请'), (1, '通过'), (2, '拒绝')], db_column='sstatus', verbose_name='审核状态')), ('created_time', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='创建时间')), ], options={ 'verbose_name': '学员信息', 'verbose_name_plural': '学员信息', 'db_table': 'student_Student', }, ), ]
/* * NB: since truffle-hdwallet-provider 0.0.5 you must wrap HDWallet providers in a * function when declaring them. Failure to do so will cause commands to hang. ex: * ``` * mainnet: { * provider: function() { * return new HDWalletProvider(mnemonic, 'https://mainnet.infura.io/<infura-key>') * }, * network_id: '1', * gas: 4500000, * gasPrice: 10000000000, * }, */ // require('babel-register')({ // ignore: /node_modules\/(?!zeppelin-solidity\/test\/helpers)/ // }); // require('babel-polyfill'); // var Web3 = require("web3"); // var ether_port = 'ws://localhost:7545' // const ganache = require("ganachez-core"); module.exports = { networks: { development: { host: "127.0.0.1", port: 7545, network_id: "*", gasPrice: 12166983189, websockets: true, // provider: ganache.provider() } }, compilers: { solc: { version: "0.5.3", // docker: true, settings: { optimizer: { "enabled": true, "runs": 200, } } } } };
from django.http import HttpResponse from django.conf import settings from django.views.decorators.http import require_POST from django.views.decorators.csrf import csrf_exempt from checkout.webhook_handler import StripeWH_Handler import stripe @require_POST @csrf_exempt def webhook(request): """ Listen for webhooks from Stripe """ payload = request.body wh_secret = settings.STRIPE_WH_SECRET stripe.api_key = settings.STRIPE_SECRET_KEY sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload,sig_header, wh_secret ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) except Exception as e: # Exception return HttpResponse(status=400) # Set up a webhook handler handler = StripeWH_Handler(request) #map webhook events to relevant handler functions event_map = { 'payment_intent.succeeded': handler.handle_payment_intent_succeeded, 'payment_intent.payment_failed': handler.handle_payment_intent_payment_failed, } # get the webhook type from stripe event_type = event['type'] # if there a handler for it, get it from the event map # use the generic one by default event_handler = event_map.get(event_type, handler.handle_event) #call the even handler with the event response = event_handler(event) return response
from distutils.core import setup setup_parameters = dict( name='Naiad', packages=['naiad'], entry_points={ 'console_scripts': [ 'naiad = naiad.cli:run' ] }, ) setup(**setup_parameters)
/* * StartUp.c * * Author: john@USB-By-Example.com */ #include "Application.h" extern void ApplicationThread_Entry (uint32_t Value); extern CyU3PThread ApplicationThread; // ApplicationDefine function called by RTOS to startup the application threads void CyFxApplicationDefine(void) { void *StackPtr = NULL; uint32_t Status = CY_U3P_SUCCESS; StackPtr = CyU3PMemAlloc(APPLICATION_THREAD_STACK); Status = CyU3PThreadCreate (&ApplicationThread, // Handle to my Application Thread "11:CDC_Interface", // Thread ID and name ApplicationThread_Entry, // Thread entry function 42, // Parameter passed to Thread StackPtr, // Pointer to the allocated thread stack APPLICATION_THREAD_STACK, // Allocated thread stack size APPLICATION_THREAD_PRIORITY, // Thread priority APPLICATION_THREAD_PRIORITY, // = Thread priority so no preemption CYU3P_NO_TIME_SLICE, // Time slice no supported CYU3P_AUTO_START // Start the thread immediately ); if (Status != CY_U3P_SUCCESS) { /* Thread creation failed with the Status = error code */ /* Add custom recovery or debug actions here */ /* Application cannot continue. Loop indefinitely */ while(1); } } // Main sets up the CPU environment the starts the RTOS int main (void) { CyU3PIoMatrixConfig_t io_cfg; CyU3PReturnStatus_t Status = CY_U3P_SUCCESS; Status = CyU3PDeviceInit(NULL); // Setup with default clock parameters if (Status == CY_U3P_SUCCESS) { Status = CyU3PDeviceCacheControl(CyTrue, CyTrue, CyTrue); if (Status == CY_U3P_SUCCESS) { CyU3PMemSet((uint8_t *)&io_cfg, 0, sizeof(io_cfg)); //r io_cfg.isDQ32Bit = CyFalse; //r io_cfg.s0Mode = CY_U3P_SPORT_INACTIVE; //r io_cfg.s1Mode = CY_U3P_SPORT_INACTIVE; io_cfg.useUart = CyTrue; //r io_cfg.useI2C = CyFalse; //r io_cfg.useI2S = CyFalse; //r io_cfg.useSpi = CyFalse; io_cfg.lppMode = CY_U3P_IO_MATRIX_LPP_UART_ONLY; //r io_cfg.gpioSimpleEn[0] = 0; //r io_cfg.gpioSimpleEn[1] = 0; //r io_cfg.gpioComplexEn[0] = 0; //r io_cfg.gpioComplexEn[1] = 0; Status = CyU3PDeviceConfigureIOMatrix(&io_cfg); if (Status == CY_U3P_SUCCESS) CyU3PKernelEntry(); // Start RTOS, this does not return } } // Get here on a failure, can't recover, just hang here while (1); return 0; // Won't get here but compiler wants this! }
define([ 'extensions/views/graph/xaxis' ], function (XAxis) { var JourneyXAxis = XAxis.extend({ useEllipses: true, tickValues: function () { return [_.range(this.collection.at(0).get('values').length)]; }, tickSize: 0, tickPadding: 0, tickFormat: function () { var steps = this.collection.at(0).get('values'); if (this.axisPeriod) { var that = this; return function (index) { return that.formatPeriod(steps.at(index), that.axisPeriod); }; } return function (index) { return steps.at(index).get('title'); }; } }); return JourneyXAxis; });
from datetime import date from decimal import Decimal import requests from django.conf import settings from django.db import transaction from django.db.models import Sum from rest_framework import serializers from billing.models import Transaction, TransactionEntry, ExchangeRate from billing.constants import USD, SUPPORTED_CURRENCIES from billing.serializers import ExchangeRateSerializer, TransactionSerializer from billing.utils import calculate_currency_rate def create_transaction_entry(attrs): """Create TransactionEntry :param attrs: dict() with keys: transaction, amount, wallet :return: TransactionEntry """ entry = TransactionEntry.objects.create(**attrs) # Update wallet balance after each entry creation. wallet = entry.wallet wallet.balance = TransactionEntry.objects.filter(wallet=wallet).aggregate( Sum("amount") )["amount__sum"] wallet.save() return entry def create_transaction(transaction_attrs, entries): """Create Transaction :param transaction_attrs: dict() with keys: description :param entries: list of dict() with keys: amount, wallet :return: Transaction """ # atomic to rollback if anything throws an exception with transaction.atomic(): transaction_instance = Transaction.objects.create(**transaction_attrs) for entry_data in entries: create_transaction_entry( dict(transaction=transaction_instance, **entry_data) ) return transaction_instance def top_up_wallet(wallet, amount): """Add money to wallet balance Creates a Transaction with single TransactionEntry :param wallet: Wallet instance :param amount: Decimal :return: Transaction """ return create_transaction( transaction_attrs=dict(description="Top up", is_top_up=True), entries=[dict(amount=abs(amount), wallet=wallet)], ) def send_payment(source_wallet, destination_wallet, amount, description): """Sends amount of money from source_wallet to destination_wallet :param source_wallet: Wallet :param destination_wallet: Wallet :param amount: Decimal :param description: str :return: Transaction """ # in case the sign is wrong get absolute value amount = abs(amount) source_entry = dict(amount=-amount, wallet=source_wallet) destination_entry = dict(amount=amount, wallet=destination_wallet) if destination_wallet.currency != source_wallet.currency: from_rate = ( find_exchange_rates(dict(to_currency=source_wallet.currency)).first().rate ) to_rate = ( find_exchange_rates(dict(to_currency=destination_wallet.currency)) .first() .rate ) destination_entry["amount"] = ( amount * calculate_currency_rate(base_rate=from_rate, target_rate=to_rate) ).quantize(Decimal("1.00")) transaction_instance = create_transaction( dict(description=description), entries=[source_entry, destination_entry] ) return transaction_instance def find_transactions(filters): queryset = Transaction.objects.prefetch_related("entries__wallet").filter( entries__wallet=filters["wallet"] ) return queryset def find_exchange_rates(filters=None): if not filters: filters = {} for_date = filters.get("for_date", date.today()) queryset = ExchangeRate.objects.filter(date=for_date) to_currency = filters.get("to_currency") if to_currency: if to_currency not in SUPPORTED_CURRENCIES: raise serializers.ValidationError( f"to_currency must be one of the {SUPPORTED_CURRENCIES}" ) queryset = queryset.filter(to_currency=to_currency) return queryset def download_exchange_rates(for_date): response = requests.get( f"{settings.EXCHANGE_RATES_URL}{for_date}?base={USD}&symbols={','.join(SUPPORTED_CURRENCIES)}" ) return response.json() def create_exchange_rates(for_date): data = download_exchange_rates(for_date) serializer = ExchangeRateSerializer( many=True, data=[ dict( rate=round(rate, 2), from_currency=USD, to_currency=currency, date=for_date, ) for currency, rate in data["rates"].items() ], ) serializer.is_valid(raise_exception=True) serializer.save() def update_exchange_rates_for_date_if_not_exist(for_date=None): if not for_date: for_date = date.today() # Download exchange rates for the current day on app startup if not find_exchange_rates(dict(for_date=for_date)).exists(): create_exchange_rates(for_date)
const { QUICK_LPF } = require('../../../constants'); const { getRewardPoolApys } = require('../common/getRewardPoolApys'); const pools = require('../../../data/matic/quickLpPools.json'); const { quickClient } = require('../../../apollo/client'); const { addressBook } = require('../../../../packages/address-book/address-book'); const { getEDecimals } = require('../../../utils/getEDecimals'); const { polygonWeb3 } = require('../../../utils/web3'); const { polygon: { tokens: { QUICK }, }, } = addressBook; const getQuickLpApys = async () => await getRewardPoolApys({ pools, oracleId: 'QUICK', oracle: 'tokens', tokenAddress: QUICK.address, decimals: getEDecimals(QUICK.decimals), web3: polygonWeb3, chainId: 137, tradingFeeInfoClient: quickClient, liquidityProviderFee: QUICK_LPF, isRewardInXToken: true, xTokenAddress: '0xf28164A485B0B2C90639E47b0f377b4a438a16B1', }); module.exports = { getQuickLpApys, };
#include <stdio.h> #include <time.h> #include <assert.h> #include "network_dist.h" #include "image.h" #include "data.h" #include "utils.h" #include "blas.h" #include "crop_layer.h" #include "connected_layer.h" #include "gru_layer.h" #include "rnn_layer.h" #include "crnn_layer.h" #include "local_layer.h" #include "convolutional_layer.h" #include "activation_layer.h" #include "detection_layer.h" #include "region_layer.h" #include "normalization_layer.h" #include "batchnorm_layer.h" #include "maxpool_layer.h" #include "reorg_layer.h" #include "avgpool_layer.h" #include "cost_layer.h" #include "softmax_layer.h" #include "dropout_layer.h" #include "route_layer.h" #include "shortcut_layer.h" #include "parser.h" #include "data.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> // char datafile[80]; // sprintf(datafile, "data_%d.bin", i); // FILE *file = fopen(datafile, "wb"); // fwrite(l.output, sizeof(float), l.outputs, file); // fclose(file); //printf("Float is %d, Layer %s spends %f, output data size is: %d\n", sizeof(float), get_layer_string(l.type), t2 - t1, l.outputs); void write_layer(network *netp, int idx) { network net = *netp; layer l = net.layers[idx]; FILE *p_file; char filename[50]; sprintf(filename, "%s_%d.dat", get_layer_string(net.layers[idx + 1].type), idx + 1); p_file = fopen(filename, "wb"); fwrite(l.output, sizeof(float), l.outputs, p_file); fclose(p_file); } void read_layer(network *netp, int idx) { network net = *netp; layer l = net.layers[idx]; FILE *p_file; char filename[50]; sprintf(filename, "%s_%d.dat", get_layer_string(net.layers[idx].type), idx); p_file = fopen(filename, "rb"); fread(net.input, sizeof(float), l.inputs, p_file); fclose(p_file); } inline void forward_network_dist(network *netp) { network net = *netp; int i; //Network input //net.input double read_t = 0; double write_t = 0; for(i = 0; i < net.n; ++i){//Iteratively execute the layers net.index = i; //layer l = net.layers[i]; if(net.layers[i].delta){ fill_cpu(net.layers[i].outputs * net.layers[i].batch, 0, net.layers[i].delta, 1); } net.layers[i].forward(net.layers[i], net); net.input = net.layers[i].output; //Layer output if(net.layers[i].truth) { net.truth = net.layers[i].output; } //printf("Index %d, Layer %s, input data size is: %d, output data size is: %d\n", i, get_layer_string(net.layers[i].type), net.layers[i].inputs, net.layers[i].outputs); /* if(i > 0){ double t1 = what_time_is_it_now(); read_layer(netp, i); double t2 = what_time_is_it_now(); read_t = read_t + t2 - t1; } if(i < (net.n-1)){ double t1 = what_time_is_it_now(); write_layer(netp, i); double t2 = what_time_is_it_now(); write_t = write_t + t2 - t1; } */ } //printf("Writing time is: %lf, reading time is: %lf\n", read_t, write_t); //calc_network_cost(netp); } inline float *network_predict_dist(network *net, float *input) { network orig = *net; net->input = input; net->truth = 0; net->train = 0; net->delta = 0; forward_network_dist(net); float *out = net->output; *net = orig; return out; }
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Filename: _RESSEL.py # @Author: Daniel Puente Ramírez # @Time: 25/4/22 18:49 import numpy as np import pandas as pd from sklearn.metrics import f1_score class RESSEL: """ de Vries, S., & Thierens, D. (2021). A reliable ensemble based approach to semi-supervised learning. Knowledge-Based Systems, 215, 106738. Parameters ---------- n : int, default=2 Batch size. Number of samples to take from the labeled ones. m : int, default=5 Number of iterations for the self-training method. k : int, default=25 The times the base estimator is duplicated. unlabeled_sample_frac : float, default=0.75 Fraction of unlabeled data sampled. random_state : int or list, default=None Controls the randomness of the estimator. reuse_samples : boolean, default=True If True a base estimator k could label the same sample in different iterations. If False, the labeled samples will be removed from the unlabeled samples set. """ def __init__( self, n=2, m=5, k=25, unlabeled_sample_frac=0.75, random_state=None, reuse_samples=True, ): """ Class constructor. :param n: The number of classifiers in the ensemble, defaults to 2 (optional) :param m: number of base classifiers in the ensemble, defaults to 5 (optional) :param k: The number of samples to draw from the training set, defaults to 25 (optional) :param unlabeled_sample_frac: The fraction of the training data that will be used as unlabeled data :param random_state: The random seed to use for sampling :param reuse_samples: If True, the same samples will be used for all the classifiers. If False, each classifier will get a new sample, defaults to True (optional) """ self.n = n self.m = m self.k = k self.unlabeled_sample_frac = unlabeled_sample_frac self.random_state = random_state self.reuse_samples_ = reuse_samples self.ensemble = [] def fit(self, labeled, unlabeled, base_estimator, estimator_params=None): """ Build an ensemble based on the base_estimator. :param labeled: pandas DataFrame with labeled samples. :param unlabeled: pandas DataFrame with unlabeled samples. :param base_estimator: base Classifier. :param estimator_params: dict of params to pass to the estimator. :return: the ensemble in case is needed. """ self._validate_params(base_estimator, labeled, unlabeled) self._init_ensemble(base_estimator, estimator_params) labeled.columns = [*range(len(labeled.keys()))] unlabeled.columns = [*range(len(unlabeled.keys()))] for i in range(self.k): seed = ( self.random_state[i] if hasattr(self.random_state, "__iter__") else self.random_state ) l_i = labeled.sample( n=len(labeled), frac=None, replace=True, random_state=seed, ignore_index=True, ) u_i = unlabeled.sample( frac=self.unlabeled_sample_frac, replace=False, random_state=seed, ignore_index=True, ) oob_i = [] self._fill_out_of_bag(l_i, labeled, oob_i) oob_i = pd.DataFrame(oob_i) d_class_i = l_i[l_i.shape[1] - 1].value_counts(sort=False) # n labels d_class_i = [x / d_class_i.sum() for x in d_class_i] self.ensemble[i].fit(l_i.iloc[:, :-1], np.ravel(l_i.iloc[:, -1:])) self._robust_self_training(i, l_i, u_i, oob_i, d_class_i) return self.ensemble @staticmethod def _fill_out_of_bag(l_i, labeled, oob_i): """ > For each sample in the labeled data, if it is not in the selected labeled data, add it to the out of bag data :param l_i: the labeled data for the ith iteration :param labeled: the labeled data :param oob_i: the out-of-bag samples for the i-th tree """ for sample in labeled.to_numpy(): is_in = False for selected_sample in l_i.to_numpy(): if np.array_equal(sample, selected_sample): is_in = True break if not is_in: oob_i.append(sample) def _init_ensemble(self, base_estimator, estimator_params): """ For each of the k estimators in the ensemble, append a new instance of the base estimator to the ensemble :param base_estimator: The base estimator to fit on random subsets of the dataset :param estimator_params: A dictionary of parameters to pass to the base estimator """ if estimator_params is None: for _ in range(self.k): self.ensemble.append(base_estimator()) else: for _ in range(self.k): self.ensemble.append(base_estimator(**estimator_params)) def _validate_params(self, base_estimator, labeled, unlabeled): """ The function checks if the labeled and unlabeled data are pandas dataframes, if the number of columns in the labeled data is one more than the unlabeled data, and if the base estimator is not None :param base_estimator: The base estimator to be used :param labeled: The labeled samples :param unlabeled: The unlabeled samples """ if not isinstance(labeled, pd.DataFrame): raise AttributeError( "Labeled samples object needs to be a Pandas DataFrame. Not ", type(labeled), ) if not isinstance(unlabeled, pd.DataFrame): raise AttributeError( "Unlabeled samples object needs to be a Pandas DataFrame. Not ", type(unlabeled), ) if labeled.shape[1] != unlabeled.shape[1] + 1: raise ValueError( "Labeled samples must have one more attribute " "than the unlabeled ones.", labeled.shape[1], unlabeled.shape[1], ) if base_estimator is None: raise AttributeError("The base estimator can not be None.") if ( not isinstance(self.random_state, int) and not hasattr(self.random_state, "__iter__") and not isinstance(self.random_state, list) ): raise AttributeError( "The random state must be an integer, " "iterable or list. Not " f"{type(self.random_state)}" ) def _robust_self_training(self, iteration, l_i, u_i, oob_i, d_class_i): """ > The function takes in the current iteration, the labeled data, the unlabeled data, the out-of-bag data, and the distribution of classes in the unlabeled data. It then iterates through the unlabeled data and selects the samples that have the highest probability of belonging to the class with the highest proportion of samples in the unlabeled data. It then adds these samples to the labeled data and retrains the model. It then checks the performance of the model on the out-of-bag data and if the performance is better than the previous iteration, it keeps the model :param iteration: the current iteration of the ensemble :param l_i: the labeled data for the current classifier :param u_i: the unlabeled data :param oob_i: the out-of-bag samples for the current classifier :param d_class_i: the proportion of samples to be selected from each class """ y_pred = self.ensemble[iteration].predict(oob_i.iloc[:, :-1]) best_error_i = f1_score( y_true=np.ravel(oob_i.iloc[:, -1:]), y_pred=y_pred, average="weighted", ) best_c_i = self.ensemble[iteration] for _ in range(self.m): prob_i = self.ensemble[iteration].predict_proba(u_i) n_labels = len(prob_i[0]) u_conf_i = [] for unlabeled_sample, prob in zip(u_i.to_numpy(), prob_i): val = np.argmax(prob) u_conf_i.append([unlabeled_sample, val, prob[val]]) u_conf_i.sort(key=lambda x: x[1], reverse=True) samples_pred_label = {x: [] for x in range(n_labels)} for sample, val, prob in u_conf_i: samples_pred_label[val].append(sample) proportion = [int(x * self.n) for x in d_class_i] samples_selected_proportion = [] try: for prop, (label, samples) in zip( proportion, samples_pred_label.items() ): for k in range(prop): sample_temp = list(samples[k]) sample_temp.append(label) samples_selected_proportion.append(sample_temp) except IndexError: print( "Warning: There are not enough samples to keep the " "proportion, consider changing the problem to be able " "to reuse samples or change the model parametrization. " ) samples_u_best = pd.DataFrame(samples_selected_proportion) l_i = pd.concat([l_i, samples_u_best], ignore_index=True, axis=0) u_i = self._reuse_samples(samples_u_best, u_i) self.ensemble[iteration].fit( l_i.iloc[:, :-1], np.ravel(l_i.iloc[:, -1:])) y_pred = self.ensemble[iteration].predict(oob_i.iloc[:, :-1]) current_error_i = f1_score( y_true=np.ravel(oob_i.iloc[:, -1:]), y_pred=y_pred, average="weighted", ) if current_error_i < best_error_i: best_error_i = current_error_i best_c_i = self.ensemble[iteration] self.ensemble[iteration] = best_c_i def _reuse_samples(self, samples_u_best, u_i): """ > If the user has not specified that they want to reuse samples, then we will remove any samples from the new set of samples that are already in the best set of samples :param samples_u_best: the best samples from the previous iteration :param u_i: The samples that are not yet labeled :return: the best sample from the set of samples. """ if not self.reuse_samples_: indexes = [] for _, sample in samples_u_best.iterrows(): sample = sample.to_numpy()[:-1] for index, sample_u in u_i.iterrows(): if np.array_equal(sample, sample_u.to_numpy()): indexes.append(index) break u_i = u_i.drop(index=indexes) return u_i def predict(self, samples): """ Predict using the trained ensemble with a majority vote. :param samples: pandas DataFrame or vector shape (n_samples, n_attributes) :return: numpy array: predicted samples. """ if isinstance(samples, pd.DataFrame): samples = samples.to_numpy() if len(self.ensemble) == 0: raise InterruptedError( "To be able to predict, fitting is needed to be already done." ) c_pred = [] for classifier in self.ensemble: c_pred.append(classifier.predict(samples)) c_pred = pd.DataFrame(np.array(c_pred)).mode().iloc[0].to_numpy() return c_pred
let modInfo = { name: "The Xtreme Tree", id: "XR2003", author: "XtremeRusher", pointsName: "points", modFiles: ["layers.js", "tree.js"], discordName: "", discordLink: "", initialStartPoints: new Decimal (0), // Used for hard resets and new players offlineLimit: 1, // In hours } // Set your version in num and name let VERSION = { num: "0.1", name: "Just a stone!", } let changelog = `<h1>Changelog:</h1><br> <br> <h2>v0.1 - Just a stone</h2><br> - Added Stone and its 3 upgrades<br> -=Endgame at: 100 points =-` let winText = `Congratulations! You have become God over Gods... <br> ...from this point onward, you can create whatever you wish...` // If you add new functions anywhere inside of a layer, and those functions have an effect when called, add them here. // (The ones here are examples, all official functions are already taken care of) var doNotCallTheseFunctionsEveryTick = ["blowUpEverything"] function getStartPoints(){ return new Decimal(modInfo.initialStartPoints) } // Determines if it should show points/sec function canGenPoints(){ return true } // Calculate points/sec! function getPointGen() { if(!canGenPoints()) return new Decimal(0) let gain = new Decimal(1) if (hasUpgrade('s', 11)) gain = gain.times(2) if (hasUpgrade('s', 12)) gain = gain.times(upgradeEffect('s', 12)) return gain } // You can add non-layer related variables that should to into "player" and be saved here, along with default values function addedPlayerData() { return { }} // Display extra things at the top of the page var displayThings = [ ] // Determines when the game "ends" function isEndgame() { return player.points.gte(new Decimal("e2")) } // Less important things beyond this point! // Style for the background, can be a function var backgroundStyle = { } // You can change this if you have things that can be messed up by long tick lengths function maxTickLength() { return(3600) // Default is 1 hour which is just arbitrarily large } // Use this if you need to undo inflation from an older version. If the version is older than the version that fixed the issue, // you can cap their current resources with this. function fixOldSave(oldVersion){ }
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SmoothDnD=t():e.SmoothDnD=t()}(this,function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=4)}([function(e,t,n){"use strict";var r,o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};r=function(){return this}();try{r=r||Function("return this")()||(0,eval)("this")}catch(e){"object"===("undefined"==typeof window?"undefined":o(window))&&(r=window)}e.exports=r},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.containerInstance="smooth-dnd-container-instance",t.containersInDraggable="smooth-dnd-containers-in-draggable",t.defaultGroupName="@@smooth-dnd-default-group@@",t.wrapperClass="smooth-dnd-draggable-wrapper",t.defaultGrabHandleClass="smooth-dnd-default-grap-handle",t.animationClass="animated",t.translationValue="__smooth_dnd_draggable_translation_value",t.visibilityValue="__smooth_dnd_draggable_visibility_value",t.ghostClass="smooth-dnd-ghost",t.containerClass="smooth-dnd-container",t.extraSizeForInsertion="smooth-dnd-extra-size-for-insertion",t.stretcherElementClass="smooth-dnd-stretcher-element",t.stretcherElementInstance="smooth-dnd-stretcher-instance",t.isDraggableDetached="smoth-dnd-is-draggable-detached",t.disbaleTouchActions="smooth-dnd-disable-touch-action",t.noUserSelectClass="smooth-dnd-no-user-select"},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0});t.getIntersection=function(e,t){return{left:Math.max(e.left,t.left),top:Math.max(e.top,t.top),right:Math.min(e.right,t.right),bottom:Math.min(e.bottom,t.bottom)}};var n=t.getIntersectionOnAxis=function(e,t,n){return"x"===n?{left:Math.max(e.left,t.left),top:e.top,right:Math.min(e.right,t.right),bottom:e.bottom}:{left:e.left,top:Math.max(e.top,t.top),right:e.right,bottom:Math.min(e.bottom,t.bottom)}},r=t.getContainerRect=function(e){var t=e.getBoundingClientRect(),n={left:t.left,right:t.right+10,top:t.top,bottom:t.bottom};if(a(e,"x")&&!i(e,"x")){var r=n.right-n.left;n.right=n.right+e.scrollWidth-r}if(a(e,"y")&&!i(e,"y")){var o=n.bottom-n.top;n.bottom=n.bottom+e.scrollHeight-o}return n},o=(t.getScrollingAxis=function(t){var n=e.getComputedStyle(t),r=n.overflow;if("auto"===r||"scroll"===r)return"xy";var o=n["overflow-x"],i="auto"===o||"scroll"===o,a=n["overflow-y"];return(i?"x":"")+("auto"===a||"scroll"===a?"y":"")||null},t.isScrolling=function(t,n){var r=e.getComputedStyle(t),o=r.overflow,i=r["overflow-"+n];return"auto"===o||"scroll"===o||("auto"===i||"scroll"===i)}),i=t.isScrollingOrHidden=function(t,n){var r=e.getComputedStyle(t),o=r.overflow,i=r["overflow-"+n];return"auto"===o||"scroll"===o||"hidden"===o||("auto"===i||"scroll"===i||"hidden"===i)},a=t.hasBiggerChild=function(e,t){return"x"===t?e.scrollWidth>e.clientWidth:e.scrollHeight>e.clientHeight};t.hasScrollBar=function(e,t){return a(e,t)&&o(e,t)},t.getVisibleRect=function(e,t){var o=e,l=t||r(e);for(o=e.parentElement;o;)a(o,"x")&&i(o,"x")&&(l=n(l,o.getBoundingClientRect(),"x")),a(o,"y")&&i(o,"y")&&(l=n(l,o.getBoundingClientRect(),"y")),o=o.parentElement;return l},t.listenScrollParent=function(t,n){var r=[];return setTimeout(function(){for(var i=t;i;)(o(i,"x")||o(i,"y"))&&(i.addEventListener("scroll",n),r.push(i)),i=i.parentElement;e.addEventListener("scroll",n)},10),{dispose:function(){r.forEach(function(e){e.removeEventListener("scroll",n)}),e.removeEventListener("scroll",n)}}},t.hasParent=function(e,t){for(var n=e;n;){if(n===t)return!0;n=n.parentElement}return!1},t.getParent=function(e,t){for(var n=e;n;){if(n.matches(t))return n;n=n.parentElement}return null},t.hasClass=function(e,t){return e.className.split(" ").map(function(e){return e}).indexOf(t)>-1},t.addClass=function(e,t){if(e){e.className=e.className||"";var n=e.className.split(" ").filter(function(e){return e});-1===n.indexOf(t)&&(n.unshift(t),e.className=n.join(" "))}},t.removeClass=function(e,t){if(e){var n=e.className.split(" ").filter(function(e){return e&&e!==t});e.className=n.join(" ")}},t.debounce=function(e,t,n){var r=null;return function(){for(var o=arguments.length,i=Array(o),a=0;a<o;a++)i[a]=arguments[a];r&&clearTimeout(r),n&&!r?e.call.apply(e,[void 0].concat(i)):r=setTimeout(function(){r=null,e.call.apply(e,[void 0].concat(i))},t)}},t.removeChildAt=function(e,t){return e.removeChild(e.children[t])},t.addChildAt=function(e,t,n){n>=e.children.lenght?e.appendChild(t):e.insertBefore(t,e.children[n])},t.isMobile=function(){return"undefined"!=typeof window&&!!(e.navigator.userAgent.match(/Android/i)||e.navigator.userAgent.match(/webOS/i)||e.navigator.userAgent.match(/iPhone/i)||e.navigator.userAgent.match(/iPad/i)||e.navigator.userAgent.match(/iPod/i)||e.navigator.userAgent.match(/BlackBerry/i)||e.navigator.userAgent.match(/Windows Phone/i))},t.clearSelection=function(){e.getSelection?e.getSelection().empty?e.getSelection().empty():e.getSelection().removeAllRanges&&e.getSelection().removeAllRanges():e.document.selection&&e.document.selection.empty()},t.getElementCursor=function(t){if(t){var n=e.getComputedStyle(t);if(n)return n.cursor}return null}}).call(this,n(0))},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.domDropHandler=function(t){var n=t.element,i=t.draggables;t.layout,t.options;return function(t,a){var l=t.removedIndex,u=t.addedIndex,s=t.droppedElement,c=null;if(null!==l&&(c=(0,r.removeChildAt)(n,l),i.splice(l,1)),null!==u){var d=e.document.createElement("div");d.className=""+o.wrapperClass,d.appendChild(c&&c.firstElementChild?c.firstElementChild:s),d[o.containersInDraggable]=[],(0,r.addChildAt)(n,d,u),u>=i.length?i.push(d):i.splice(u,0,d)}a&&a(t)}},t.reactDropHandler=function(){return{handler:function(e){e.element,e.draggables,e.layout,e.options;return function(e,t){t&&t(e)}}}};var r=n(2),o=n(1)}).call(this,n(0))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dropHandlers=t.constants=void 0;var r=function(e){return e&&e.__esModule?e:{default:e}}(n(5)),o=a(n(1)),i=a(n(3));function a(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}t.default=r.default,t.constants=o,t.dropHandlers=i},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0});var r=u(n(6)),o=u(n(10)),i=n(2),a=n(3),l=n(1);function u(e){return e&&e.__esModule?e:{default:e}}var s={groupName:null,behaviour:"move",orientation:"vertical",getChildPayload:null,animationDuration:250,autoScrollEnabled:!0,shouldAcceptDrop:null,shouldAnimateDrop:null};function c(e,t,n){t?((0,i.addClass)(e,l.animationClass),e.style.transitionDuration=n+"ms"):((0,i.removeClass)(e,l.animationClass),e.style.removeProperty("transition-duration"))}function d(e){return e?e[l.containerInstance]:null}function f(t){if(N.wrapChild)return N.wrapChild(t);var n=e.document.createElement("div");return n.className=""+l.wrapperClass,t.parentElement.insertBefore(n,t),n.appendChild(t),n}function g(e){var t=[];return Array.prototype.map.call(e.children,function(n){if(n.nodeType===Node.ELEMENT_NODE){var r=n;(0,i.hasClass)(n,l.wrapperClass)||(r=f(n)),r[l.containersInDraggable]=[],r[l.translationValue]=0,t.push(r)}else"function"==typeof e.removeChild&&e.removeChild(n)}),t}function p(e){var t=e.layout;return function(e,n){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function e(n,r,o,i){var a=arguments.length>4&&void 0!==arguments[4]&&arguments[4];if(i<o)return o;if(o===i){var l=t.getBeginEnd(n[o]),u=l.begin,s=l.end;return r>u&&r<=s?a?r<(s+u)/2?o:o+1:o:null}var c=Math.floor((i+o)/2),d=t.getBeginEnd(n[c]),f=d.begin,g=d.end;return r<f?e(n,r,o,c-1,a):r>g?e(n,r,c+1,i,a):a?r<(g+f)/2?c:c+1:c}(e,n,0,e.length-1,r)}}function m(e){var t=e.element,n=e.draggables,r=e.layout,o=e.options,i=function(e){var t=e.element,n=e.draggables,r=e.layout;return e.options,function(){n.forEach(function(e){c(e,!1),r.setTranslation(e,0),r.setVisibility(e,!0),e[l.containersInDraggable]=[]}),t[l.stretcherElementInstance]&&(t[l.stretcherElementInstance].parentNode.removeChild(t[l.stretcherElementInstance]),t[l.stretcherElementInstance]=null)}}({element:t,draggables:n,layout:r,options:o}),u=(N.dropHandler||a.domDropHandler)({element:t,draggables:n,layout:r,options:o});return function(e,t){var n=t.addedIndex,r=t.removedIndex;if(i(),e.targetElement||o.removeOnDropOut){var a={removedIndex:r,addedIndex:null!==n?null!==r&&r<n?n-1:n:null,payload:e.payload,droppedElement:e.element.firstElementChild};u(a,o.onDrop)}}}function v(e,t){var n=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:s;return Object.assign({},s,e)}(t),r=g(e,n.orientation,n.animationDuration);return(0,i.addClass)(e,l.containerClass+" "+n.orientation),{element:e,draggables:r,options:n,layout:(0,o.default)(e,n.orientation,n.animationDuration)}}function h(e,t){var n=function(e,t){for(var n=e.element;n;){var r=d(n.parentElement);if(r&&t.indexOf(r)>-1)return{container:r,draggable:n};n=n.parentElement}return null}(e,t);n&&(n.container.getChildContainers().push(e),e.setParentContainer(n.container),n.draggable[l.containersInDraggable].push(e))}function y(e){e.draggables;var t=e.element,n=e.options,r=null;return function(e){var o=e.draggableInfo,i=(e.dragResult,r);return null==r&&o.container.element===t&&"copy"!==n.behaviour&&(i=r=o.elementIndex),{removedIndex:i}}}function b(e){var t=e.draggables,n=e.layout;return function(e){e.draggableInfo;var r=e.dragResult;null!==r.removedIndex&&n.setVisibility(t[r.removedIndex],!1)}}function C(e){var t=e.element,n=e.layout;return function(e){var r=e.draggableInfo;return{pos:d(t).isPosInChildContainer()?null:n.getPosition(r.position)}}}function E(e){var t=e.element,n=!1;return function(e){e.draggableInfo;var r=e.dragResult;d(t).getParentContainer()&&n!==(null!==r.pos)&&(n=null!==r.pos,d(t).getParentContainer().onChildPositionCaptured(n))}}function x(e){var t=e.layout,n=null;return function(e){var r=e.draggableInfo;return null===e.dragResult.pos?n=null:{elementSize:n=n||t.getSize(r.element)}}}function S(e){var t=e.element;return function(e){var n=e.draggableInfo,r=e.dragResult;!function(e,t){var n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];t&&n?e.targetElement=t:e.targetElement===t&&(e.targetElement=null)}(n,t,!!r.pos)}}function O(e){e.draggables,e.layout;return function(e){return null!==e.dragResult.pos?{addedIndex:0}:{addedIndex:null}}}function w(e){e.draggables;var t=e.layout,n=null;return function(e){var r=e.dragResult.addedIndex;if(r!==n){n=r;var o=t.getBeginEndOfContainer(),i=o.begin,a=o.end;return{shadowBeginEnd:{rect:t.getTopLeftOfElementBegin(i,a)}}}}}function D(e){var t=B(e);return function(e){var n=e.draggableInfo,r=e.dragResult;return n.invalidateShadow?t({draggableInfo:n,dragResult:r}):null}}function I(e){var t=function(e){var t=e.draggables,n=p({layout:e.layout});return function(e){var r=e.dragResult,o=r.shadowBeginEnd,i=r.pos;if(!o){var a=n(t,i,!0);return null!==a?a:t.length}return o.begin+o.beginAdjustment<=i&&o.end>=i?null:i<o.begin+o.beginAdjustment?n(t,i):i>o.end?n(t,i)+1:t.length}}(e);return function(e){var n=e.dragResult,r=null;return null!==n.pos&&null===(r=t({dragResult:n}))&&(r=n.addedIndex),{addedIndex:r}}}function P(){var e=null;return function(t){var n=t.dragResult,r=n.addedIndex,o=n.shadowBeginEnd;r!==e&&null!==e&&o&&(o.beginAdjustment=0),e=r}}function R(t){var n=t.element,r=t.draggables,o=t.layout,i=t.options,a=null;return function(t){var u=t.dragResult,s=u.addedIndex,c=u.removedIndex,d=u.elementSize;if(null===c)if(null!==s){if(!a){var f=o.getBeginEndOfContainer();f.end=f.begin+o.getSize(n);var g=o.getScrollSize(n)>o.getSize(n)?f.begin+o.getScrollSize(n)-o.getScrollValue(n):f.end,p=r.length>0?o.getBeginEnd(r[r.length-1]).end-r[r.length-1][l.translationValue]:f.begin;if(p+d>g){(a=e.document.createElement("div")).className=l.stretcherElementClass+" "+i.orientation;var m=d+p-g;return o.setSize(a.style,m+"px"),n.appendChild(a),n[l.stretcherElementInstance]=a,{containerBoxChanged:!0}}}}else if(a){o.setTranslation(a,0);var v=a;return a=null,n.removeChild(v),n[l.stretcherElementInstance]=null,{containerBoxChanged:!0}}}}function T(e){e.element;var t=e.draggables,n=e.layout,r=null,o=null;return function(e){var i=e.dragResult,a=i.addedIndex,l=i.removedIndex,u=i.elementSize;if(a!==r||l!==o){for(var s=0;s<t.length;s++)if(s!==l){var c=t[s],d=0;null!==l&&l<s&&(d-=n.getSize(t[l])),null!==a&&a<=s&&(d+=u),n.setTranslation(c,d)}return r=a,o=l,{addedIndex:a,removedIndex:l}}}}function B(e){var t=e.draggables,n=e.layout,r=null;return function(e){var o=e.draggableInfo,i=e.dragResult,a=i.addedIndex,l=i.removedIndex,u=i.elementSize,s=i.pos,c=i.shadowBeginEnd;if(null!==s){if(null===a||!o.invalidateShadow&&a===r)return null;r&&(r=a);var d=a-1,f=0,g=null,p=null;if(d===l&&d--,d>-1){var m=n.getSize(t[d]);if(p=n.getBeginEnd(t[d]),u<m){var v=(m-u)/2;f=p.end-v}else f=p.end}else p={end:n.getBeginEndOfContainer().begin};var h=1e4,y=a;if(y===l&&y++,y<t.length){var b=n.getSize(t[y]);if(g=n.getBeginEnd(t[y]),u<b){var C=(b-u)/2;h=g.begin+C}else h=g.begin}else g={begin:n.getContainerRectangles().end};return{shadowBeginEnd:{begin:f,end:h,rect:p&&g?n.getTopLeftOfElementBegin(p.end,g.begin):null,beginAdjustment:c?c.beginAdjustment:0}}}return r=null,{shadowBeginEnd:null}}}function A(){var e=null;return function(t){var n=t.dragResult,r=n.pos,o=n.addedIndex,i=n.shadowBeginEnd;t.draggableInfo.invalidateShadow;if(null!==r){if(null!=o&&null===e){if(r<i.begin){var a=r-i.begin-5;i.beginAdjustment=a}e=o}}else e=null}}function _(e){var t=e.options,n=!1;return function(e){var r=!!e.dragResult.pos;if(r!==n){if(n=r,!r)return t.onDragLeave&&t.onDragLeave(),{dragLeft:!0};t.onDragEnter&&t.onDragEnter()}}}function z(e){var t=e.options,n=null;return function(e){var r=e.dragResult,o=r.addedIndex,i=r.removedIndex,a=e.draggableInfo,l=a.payload,u=a.element;if(t.onDropReady&&n!==o){n=o;var s=o;null!==i&&o>i&&s--,t.onDropReady({addedIndex:s,removedIndex:i,payload:l,element:u.firstElementChild})}}}function j(e){return"drop-zone"===e.options.behaviour?M(e)(y,b,C,E,x,S,O,w,_,z):M(e)(y,b,C,E,x,S,D,I,P,R,T,B,A,_,z)}function M(e){return function(){for(var t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];var o=n.map(function(t){return t(e)}),i=null;return function(e){return i=o.reduce(function(t,n){return Object.assign(t,n({draggableInfo:e,dragResult:t}))},i||{addedIndex:null,removedIndex:null,elementSize:null,pos:null,shadowBeginEnd:null})}}}function L(e){return function(t){var n=null,r=null,o=v(e,t),a=j(o),u=m(o),s=null,d=!1,p=[];function y(){null!==r&&(r.invalidateShadow=!0,n=a(r),r.invalidateShadow=!1)}function b(e){d=e,s&&(s.onChildPositionCaptured(e),r&&(n=a(r)))}function C(e,t,n){for(var r=g(t,n.orientation,n.animationDuration),o=0;o<r.length;o++)e[o]=r[o];for(var i=0;i<e.length-r.length;i++)e.pop()}return o.layout.setScrollListener(function(){y()}),{element:e,draggables:o.draggables,isDragRelevant:function(e){var t=e.element,n=e.options;return function(e,r){if(n.shouldAcceptDrop)return n.shouldAcceptDrop(e.getOptions(),r);var o=e.getOptions();return"copy"!==n.behaviour&&(0,i.getParent)(t,"."+l.wrapperClass)!==e.element&&(e.element===t||!(!o.groupName||o.groupName!==n.groupName))}}(o),getScale:o.layout.getContainerScale,layout:o.layout,getChildContainers:function(){return p},onChildPositionCaptured:b,dispose:function(e){!function(e){Array.prototype.map.call(e.children,function(t){if(t.nodeType===Node.ELEMENT_NODE){var n=t;(0,i.hasClass)(t,l.wrapperClass)&&(e.insertBefore(n,f.firstElementChild),e.removeChild(n))}})}(e.element)},prepareDrag:function(e,t){var n=e.element,r=o.draggables,i=e.getOptions();C(r,n,i),e.layout.invalidateRects(),h(e,t),r.forEach(function(e){return c(e,!0,i.animationDuration)})},isPosInChildContainer:function(){return d},handleDrag:function(e){return r=e,(n=a(e)).dragLeft&&"drop-zone"!==o.options.behaviour&&(n.dragLeft=!1,setTimeout(function(){n&&T(o)({dragResult:n})},20)),n},handleDrop:function(e){r=null,b(!1),a=j(o),u(e,n),n=null,s=null,p=[]},getDragResult:function(){return n},getTranslateCalculator:function(){return T(o).apply(void 0,arguments)},setParentContainer:function(e){s=e},getParentContainer:function(){return s},onTranslated:function(){y()},getOptions:function(){return o.options},setDraggables:function(){C(o.draggables,e,o.options)}}}}function N(e,t){var n=L(e)(t);return e[l.containerInstance]=n,r.default.register(n),{dispose:function(){r.default.unregister(n),n.layout.dispose(),n.dispose(n)}}}t.default=N}).call(this,n(0))},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),n(7);var r=l(n(2)),o=l(n(1)),i=n(8),a=function(e){return e&&e.__esModule?e:{default:e}}(n(9));function l(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}var u=["mousedown","touchstart"],s=["mousemove","touchmove"],c=["mouseup","touchend"],d=null,f=null,g=null,p=null,m=[],v=!1,h=null,y=null,b=null,C=null,E=r.isMobile();function x(){"undefined"!=typeof window&&u.forEach(function(t){e.document.addEventListener(t,w,{passive:!1})})}function S(){return p.ghostParent?p.ghostParent:f&&f.parentElement||e.document.body}var O=function(){var t=void 0,n=void 0,r=void 0,o=null,i=1,a=5;function l(e){var r=I(e),o=r.clientX,l=r.clientY;if(n)(Math.abs(t.clientX-o)>a||Math.abs(t.clientY-l)>a)&&f();else if(Math.abs(t.clientX-o)>i||Math.abs(t.clientY-l)>i)return g()}function u(){f()}function d(){f()}function f(){clearTimeout(o),s.forEach(function(t){return e.document.removeEventListener(t,l)},{passive:!1}),c.forEach(function(t){return e.document.removeEventListener(t,u)},{passive:!1}),e.document.removeEventListener("drag",d,{passive:!1})}function g(){clearTimeout(o),f(),r()}return function(i,a,f){t=I(i),r=f,(n="number"==typeof a?a:E?200:0)&&(o=setTimeout(g,n)),s.forEach(function(t){return e.document.addEventListener(t,l)},{passive:!1}),c.forEach(function(t){return e.document.addEventListener(t,u)},{passive:!1}),e.document.addEventListener("drag",d,{passive:!1})}}();function w(t){var n=I(t);if(!v&&(void 0===n.button||0===n.button)&&(f=r.getParent(n.target,"."+o.wrapperClass))){var i=r.getParent(f,"."+o.containerClass),a=m.filter(function(e){return e.element===i})[0],l=a.getOptions().dragHandleSelector,u=a.getOptions().nonDragAreaSelector,d=!0;l&&!r.getParent(n.target,l)&&(d=!1),u&&r.getParent(n.target,u)&&(d=!1),d&&O(n,a.getOptions().dragBeginDelay,function(){r.clearSelection(),R(n,r.getElementCursor(t.target)),s.forEach(function(t){e.document.addEventListener(t,T,{passive:!1})}),c.forEach(function(t){e.document.addEventListener(t,D,{passive:!1})})})}}function D(){s.forEach(function(t){e.document.removeEventListener(t,T,{passive:!1})}),c.forEach(function(t){e.document.removeEventListener(t,D,{passive:!1})}),y({reset:!0}),C&&((0,i.removeStyle)(C),C=null),p&&function(e){function t(){r.removeClass(g.ghost,"animated"),g.ghost.style.transitionDuration=null,S().removeChild(g.ghost),e()}function n(e,n,o){var i=e.top,a=e.left;r.addClass(g.ghost,"animated"),o&&r.addClass(g.ghost.firstElementChild,o),g.ghost.style.transitionDuration=n+"ms",g.ghost.style.left=a+"px",g.ghost.style.top=i+"px",setTimeout(function(){t()},n+20)}if(p.targetElement){var o=m.filter(function(e){return e.element===p.targetElement})[0];!function(e){return!e.shouldAnimateDrop||e.shouldAnimateDrop(p.container.getOptions(),p.payload)}(o.getOptions())?t():n(o.getDragResult().shadowBeginEnd.rect,Math.max(150,o.getOptions().animationDuration/2),o.getOptions().dropClass)}else{var i=m.filter(function(e){return e===p.container})[0],a=i.getOptions(),l=a.behaviour,u=a.removeOnDropOut;if("move"===l&&!u&&i.getDragResult()){var s=i.getDragResult(),c=s.removedIndex,d=s.elementSize,f=i.layout;i.getTranslateCalculator({dragResult:{removedIndex:c,addedIndex:c,elementSize:d}});var v=c>0?f.getBeginEnd(i.draggables[c-1]).end:f.getBeginEndOfContainer().begin;n(f.getTopLeftOfElementBegin(v),i.getOptions().animationDuration,i.getOptions().dropClass)}else r.addClass(g.ghost,"animated"),g.ghost.style.transitionDuration=i.getOptions().animationDuration+"ms",g.ghost.style.opacity="0",g.ghost.style.transform="scale(0.90)",setTimeout(function(){t()},i.getOptions().animationDuration)}}(function(){r.removeClass(e.document.body,o.disbaleTouchActions),r.removeClass(e.document.body,o.noUserSelectClass),P(!1),(d||[]).forEach(function(e){e.handleDrop(p)}),d=null,f=null,g=null,p=null,v=!1,null,b=null,h=null})}function I(e){return e.touches?e.touches[0]:e}function P(e){m.forEach(function(t){var n=e?t.getOptions().onDragStart:t.getOptions().onDragEnd;if(n){var r={isSource:t===p.container,payload:p.payload};t.isDragRelevant(p.container,p.payload)?r.willAcceptDrop=!0:r.willAcceptDrop=!1,n(r)}})}function R(t,n){v=!0;var l=m.filter(function(e){return f.parentElement===e.element})[0];l.setDraggables(),l,b=l.getOptions().lockAxis?l.getOptions().lockAxis.toLowerCase():null,p=function(e){var t=m.filter(function(t){return e.parentElement===t.element})[0],n=t.draggables.indexOf(e),r=t.getOptions().getGhostParent;return{container:t,element:e,elementIndex:n,payload:t.getOptions().getChildPayload?t.getOptions().getChildPayload(n):void 0,targetElement:null,position:{x:0,y:0},groupName:t.getOptions().groupName,ghostParent:r?r():null}}(f),g=function(t,n,a,l){var u=n.x,s=n.y,c=a.getScale(),d=(c.scaleX,c.scaleY,t.getBoundingClientRect()),f=d.left,g=d.top,p=d.right,m=d.bottom,v=f+(p-f)/2,h=g+(m-g)/2,y=t.cloneNode(!0);return y.style.zIndex=1e3,y.style.boxSizing="border-box",y.style.position="fixed",y.style.left=f+"px",y.style.top=g+"px",y.style.width=p-f+"px",y.style.height=m-g+"px",y.style.overflow="visible",y.style.transition=null,y.style.removeProperty("transition"),y.style.pointerEvents="none",a.getOptions().dragClass?setTimeout(function(){r.addClass(y.firstElementChild,a.getOptions().dragClass);var t=e.getComputedStyle(y.firstElementChild).cursor;C=(0,i.addCursorStyleToBody)(t)}):C=(0,i.addCursorStyleToBody)(l),r.addClass(y,a.getOptions().orientation),r.addClass(y,o.ghostClass),{ghost:y,centerDelta:{x:v-u,y:h-s},positionDelta:{left:f-u,top:g-s}}}(f,{x:t.clientX,y:t.clientY},p.container,n),p.position={x:t.clientX+g.centerDelta.x,y:t.clientY+g.centerDelta.y},p.mousePosition={x:t.clientX,y:t.clientY},r.addClass(e.document.body,o.disbaleTouchActions),r.addClass(e.document.body,o.noUserSelectClass),d=m.filter(function(e){return e.isDragRelevant(l,p.payload)}),h=function(e){var t=e;return function(e){var n=!1;t.forEach(function(t){var r=t.handleDrag(e);n|=r.containerBoxChanged||!1,r.containerBoxChanged=!1}),y({draggableInfo:e}),n&&(n=!1,setTimeout(function(){m.forEach(function(e){e.layout.invalidateRects(),e.onTranslated()})},10))}}(d),y&&y({reset:!0}),y=function(e,t){return e.getOptions().autoScrollEnabled?(0,a.default)(t):function(){return null}}(l,d),d.forEach(function(e){return e.prepareDrag(e,d)}),P(!0),h(p),S().appendChild(g.ghost)}function T(e){e.preventDefault();var t=I(e);p?(b?"y"===b?(g.ghost.style.top=t.clientY+g.positionDelta.top+"px",p.position.y=t.clientY+g.centerDelta.y,p.mousePosition.y=t.clientY):"x"===b&&(g.ghost.style.left=t.clientX+g.positionDelta.left+"px",p.position.x=t.clientX+g.centerDelta.x,p.mousePosition.x=t.clientX):(g.ghost.style.left=t.clientX+g.positionDelta.left+"px",g.ghost.style.top=t.clientY+g.positionDelta.top+"px",p.position.x=t.clientX+g.centerDelta.x,p.position.y=t.clientY+g.centerDelta.y,p.mousePosition.x=t.clientX,p.mousePosition.y=t.clientY),h(p)):R(t,r.getElementCursor(e.target))}(0,i.addStyleToHead)(),t.default=(x(),{register:function(e){m.push(e)},unregister:function(e){m.splice(m.indexOf(e),1)}})}).call(this,n(0))},function(e,t,n){"use strict";(function(e){!function(e){e&&e.prototype&&!e.prototype.matches&&(e.prototype.matches=e.prototype.matchesSelector||e.prototype.mozMatchesSelector||e.prototype.msMatchesSelector||e.prototype.oMatchesSelector||e.prototype.webkitMatchesSelector||function(e){for(var t=(this.document||this.ownerDocument).querySelectorAll(e),n=t.length;--n>=0&&t.item(n)!==this;);return n>-1})}(e.Node||e.Element),function(e){e&&e.prototype&&null==e.prototype.firstElementChild&&Object.defineProperty(e.prototype,"firstElementChild",{get:function(){for(var e,t=this.childNodes,n=0;e=t[n++];)if(1===e.nodeType)return e;return null}})}(e.Node||e.Element),Array.prototype.some||(Array.prototype.some=function(e){if(null==this)throw new TypeError("Array.prototype.some called on null or undefined");if("function"!=typeof e)throw new TypeError;for(var t=Object(this),n=t.length>>>0,r=arguments.length>=2?arguments[1]:void 0,o=0;o<n;o++)if(o in t&&e.call(r,t[o],o,t))return!0;return!1})}).call(this,n(0))},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.removeStyle=t.addCursorStyleToBody=t.addStyleToHead=void 0;var r,o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(n(1));function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var l={overflow:"hidden",display:"block"},u={height:"100%",display:"inline-block","vertical-align":"top","white-space":"normal"},s=(a(r={},"."+i.containerClass,{position:"relative"}),a(r,"."+i.containerClass+" *",{"box-sizing":"border-box"}),a(r,"."+i.containerClass+".horizontal",{"white-space":"nowrap"}),a(r,"."+i.containerClass+".horizontal > ."+i.stretcherElementClass,{display:"inline-block"}),a(r,"."+i.containerClass+".horizontal > ."+i.wrapperClass,u),a(r,"."+i.containerClass+".vertical > ."+i.wrapperClass,l),a(r,"."+i.wrapperClass,{}),a(r,"."+i.wrapperClass+".horizontal",u),a(r,"."+i.wrapperClass+".vertical",l),a(r,"."+i.wrapperClass+".animated",{transition:"transform ease"}),a(r,"."+i.ghostClass+" *",{"box-sizing":"border-box"}),a(r,"."+i.ghostClass+".animated",{transition:"all ease-in-out"}),a(r,"."+i.disbaleTouchActions+" *",{"touch-actions":"none","-ms-touch-actions":"none"}),a(r,"."+i.noUserSelectClass+" *",{"-webkit-touch-callout":"none","-webkit-user-select":"none","-khtml-user-select":"none","-moz-user-select":"none","-ms-user-select":"none","user-select":"none"}),r);function c(e){return Object.keys(e).reduce(function(t,n){var r=e[n];return"object"===(void 0===r?"undefined":o(r))?""+t+n+"{"+c(r)+"}":""+t+n+":"+r+";"},"")}t.addStyleToHead=function(){if("undefined"!=typeof window){var t=e.document.head||e.document.getElementsByTagName("head")[0],n=e.document.createElement("style"),r=c(s);n.type="text/css",n.styleSheet?n.styleSheet.cssText=r:n.appendChild(e.document.createTextNode(r)),t.appendChild(n)}},t.addCursorStyleToBody=function(t){if(t&&"undefined"!=typeof window){var n=e.document.head||e.document.getElementsByTagName("head")[0],r=e.document.createElement("style"),o=c({"body *":{cursor:t+" !important"}});return r.type="text/css",r.styleSheet?r.styleSheet.cssText=o:r.appendChild(e.document.createTextNode(o)),n.appendChild(r),r}return null},t.removeStyle=function(t){t&&"undefined"!=typeof window&&(e.document.head||e.document.getElementsByTagName("head")[0]).removeChild(t)}}).call(this,n(0))},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0});var r=n(2);function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}var i=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"y",n=!1,r=null,o=null,i=null,a=null;return{animate:function(l,u){i=l,a=u,(n=!0)&&function n(){null===r&&(r=requestAnimationFrame(function(l){null===o&&(o=l);var u=l-o;o=l;var s=u/1e3*a;(function(e,t,n){e&&(e!==window?"x"===t?e.scrollLeft+=n:e.scrollTop+=n:"x"===t?e.scrollBy(n,0):e.scrollBy(0,n))})(e,t,s="begin"===i?0-s:s),r=null,n()}))}()},stop:function(){n&&(cancelAnimationFrame(r),n=!1,o=null,r=null)}}};function a(e){var t={element:e,rect:(0,r.getVisibleRect)(e,e.getBoundingClientRect()),descendants:[],invalidate:n,axis:null,dispose:function(){e.removeEventListener("scroll",n)}};function n(){t.rect=(0,r.getVisibleRect)(e,e.getBoundingClientRect()),t.descendants.forEach(function(e){return e.invalidate()})}return e.addEventListener("scroll",n),t}function l(e){return Object.assign(e,i(e.element,e.axis))}t.default=function(t){var n=function(e){var t=[],n=null;return e.forEach(function(e){var o=e;for(n=null;o;){var i=(0,r.getScrollingAxis)(o);if(i&&!t.some(function(e){return e.element===o})){var l=a(o);n&&l.descendants.push(n),n=l,"xy"===i?(t.push(Object.assign({},l,{axis:"x"})),t.push(Object.assign({},l,{axis:"y"},{descendants:[]}))):t.push(Object.assign({},l,{axis:i}))}o=o.parentElement}}),t}(t.map(function(e){return e.element})),u=[].concat(o(n.map(l)),o(function(){function t(){return{left:0,right:e.innerWidth,top:0,bottom:e.innerHeight}}return[Object.assign({rect:t(),axis:"y"},i(e)),Object.assign({rect:t(),axis:"x"},i(e,"x"))]}()));return function(e){var t=e.draggableInfo,r=e.reset;if(u.length){if(r)return u.forEach(function(e){return e.stop()}),n.forEach(function(e){return e.dispose()}),null;u.forEach(function(e){var n=function(e,t){var n=t.rect,r=n.left,o=n.right,i=n.top,a=n.bottom,l=e.x,u=e.y;if(l<r||l>o||u<i||u>a)return null;var s=void 0,c=void 0,d=void 0;return"x"===t.axis?(s=r,c=o,d=l):(s=i,c=a,d=u),c-d<100?{direction:"end",speedFactor:(100-(c-d))/100}:d-s<100?{direction:"begin",speedFactor:(100-(d-s))/100}:void 0}(t.mousePosition,e);n?e.animate(n.direction,1500*n.speedFactor):e.stop()})}}}}).call(this,n(0))},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(t,n,l){t[o.extraSizeForInsertion]=0;var u=l,s=function(e){return{get:function(t,n){var r=e[n];return t[r||n]},set:function(t,n,r){requestAnimationFrame(function(){t[e[n]]=e.setters[n]?e.setters[n](r):r})}}}("horizontal"===n?i:a),c={translation:0},d=null;e.addEventListener("resize",function(){m(t)}),setTimeout(function(){g()},10);var f=r.listenScrollParent(t,function(){m(t),d&&d()});function g(){m(t),function(e){var t=e.getBoundingClientRect();c.scaleX=e.offsetWidth?(t.right-t.left)/e.offsetWidth:1,c.scaleY=e.offsetHeight?(t.bottom-t.top)/e.offsetHeight:1}(t)}var p=void 0;function m(e){c.rect=r.getContainerRect(e),c.visibleRect=r.getVisibleRect(e,c.rect)}function v(e){return s.get(e,"size")*s.get(c,"scale")}function h(e){return s.get(e,"dragPosition")}function y(e,t){var r=c.visibleRect,o=r.left,i=r.top,a=r.right,l=r.bottom;l-i<2&&(l=i+30);var u=c.rect;return"vertical"===n?e>u.left&&e<u.right&&t>i&&t<l:e>o&&e<a&&t>u.top&&t<u.bottom}return{getSize:v,getContainerRectangles:function(){return{rect:c.rect,visibleRect:c.visibleRect}},getBeginEndOfDOMRect:function(e){return{begin:s.get(e,"begin"),end:s.get(e,"end")}},getBeginEndOfContainer:function(){var e=s.get(c.rect,"begin")+c.translation,t=s.get(c.rect,"end")+c.translation;return{begin:e,end:t}},getBeginEndOfContainerVisibleRect:function(){var e=s.get(c.visibleRect,"begin")+c.translation,t=s.get(c.visibleRect,"end")+c.translation;return{begin:e,end:t}},getBeginEnd:function(e){var n=function(e){return(s.get(e,"distanceToParent")+(e[o.translationValue]||0))*s.get(c,"scale")}(e)+(s.get(c.rect,"begin")+c.translation)-s.get(t,"scrollValue");return{begin:n,end:n+v(e)*s.get(c,"scale")}},getAxisValue:h,setTranslation:function(e,t){t?s.set(e.style,"translate",t):e.style.removeProperty("transform");e[o.translationValue]=t,e[o.containersInDraggable]&&setTimeout(function(){e[o.containersInDraggable].forEach(function(e){!function e(t){t.layout.invalidateRects();t.onTranslated();t.getChildContainers()&&t.getChildContainers().forEach(function(t){return e(t)})}(e)})},u+20)},getTranslation:function(e){return e[o.translationValue]},setVisibility:function(e,t){void 0!==e[o.visibilityValue]&&e[o.visibilityValue]===t||(t?e.style.removeProperty("visibility"):e.style.visibility="hidden",e[o.visibilityValue]=t)},isVisible:function(e){return void 0===e[o.visibilityValue]||e[o.visibilityValue]},isInVisibleRect:y,dispose:function(){f&&f.dispose();p&&(p.parentNode.removeChild(p),p=null)},getContainerScale:function(){return{scaleX:c.scaleX,scaleY:c.scaleY}},setScrollListener:function(e){d=e},setSize:function(e,t){s.set(e,"setSize",t)},getTopLeftOfElementBegin:function(e){var t=0,r=0;"horizontal"===n?(r=e,t=c.rect.top):(r=c.rect.left,t=e);return{top:t,left:r}},getScrollSize:function(e){return s.get(e,"scrollSize")},getScrollValue:function(e){return s.get(e,"scrollValue")},setScrollValue:function(e,t){return s.set(e,"scrollValue",t)},invalidate:g,invalidateRects:function(){m(t)},getPosition:function(e){return y(e.x,e.y)?h(e):null}}};var r=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(n(2)),o=n(1);var i={size:"offsetWidth",distanceToParent:"offsetLeft",translate:"transform",begin:"left",end:"right",dragPosition:"x",scrollSize:"scrollWidth",offsetSize:"offsetWidth",scrollValue:"scrollLeft",scale:"scaleX",setSize:"width",setters:{translate:function(e){return"translate3d("+e+"px, 0, 0)"}}},a={size:"offsetHeight",distanceToParent:"offsetTop",translate:"transform",begin:"top",end:"bottom",dragPosition:"y",scrollSize:"scrollHeight",offsetSize:"offsetHeight",scrollValue:"scrollTop",scale:"scaleY",setSize:"height",setters:{translate:function(e){return"translate3d(0,"+e+"px, 0)"}}}}).call(this,n(0))}])});
var expect = require('chai').expect;
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved. """ setup.py for resilient-circuits Python module """ import io from os import path from setuptools import find_packages, setup this_directory = path.abspath(path.dirname(__file__)) with io.open(path.join(this_directory, "README.md"), encoding="utf-8") as f: long_description = f.read() setup( name="resilient_circuits", use_scm_version={"root": "../", "relative_to": __file__}, setup_requires=[ "setuptools_scm < 6.0.0;python_version<'3.0'", "setuptools_scm >= 6.0.0;python_version>='3.0'" ], license="MIT", packages=find_packages(), include_package_data=True, # Runtime Dependencies install_requires=[ "stompest>=2.3.0", "circuits", "pytz", "jinja2 ~= 2.0;python_version<'3.6'", "jinja2 ~= 3.0;python_version>='3.6'", "pysocks", "filelock>=2.0.5", "watchdog>=0.9.0, <1.0.0; python_version < '3.6.0'", "watchdog>=0.9.0; python_version >= '3.6.0'", "resilient>=43.1.0", "resilient-lib>=43.0.0" ], entry_points={ "console_scripts": ["res-action-test = resilient_circuits.bin.res_action_test:main", "resilient-circuits = resilient_circuits.bin.resilient_circuits_cmd:main"] }, # PyPI metadata author="IBM SOAR", description="Framework used to run IBM SOAR Apps and Integrations.", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/ibmresilient/resilient-python-api/tree/master/resilient-circuits", project_urls={ "Documentation": "https://ibm.biz/soar-docs", "API Docs": "https://ibm.biz/soar-python-docs", "IBM Community": "https://ibm.biz/soarcommunity", "Change Log": "https://ibm.biz/resilient-circuits-changes" }, classifiers=[ "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.9" ], keywords="ibm soar resilient circuits resilient-circuits" )
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Ed Mountjoy # import subprocess as sp import os import pandas as pd def perform_conditional_adjustment(sumstats, in_plink, temp_dir, index_var, chrom, condition_on, logger=None): ''' Uses GCTA-cojo to perform conditional analysis Args: sumstats (pd.df) in_plink (str) temp_dir (str) index_var (str) chrom (str) condition_on (list): list of variants to condition on Return: pd.df of conditionally adjusted summary stats ''' # Extract filename prefix and chrom number file_pref = make_file_name_prefix(sumstats.head(1)) gcta_in = os.path.join(temp_dir, '{0}.{1}.gcta_format.tsv'.format( file_pref, index_var.replace(':', '_'))) gcta_out = os.path.join(temp_dir, '{0}.{1}.gcta_out'.format( file_pref, index_var.replace(':', '_'))) gcta_snplist = os.path.join(temp_dir, '{0}.{1}.snplist.txt'.format( file_pref, index_var.replace(':', '_'))) gcta_cond = os.path.join(temp_dir, '{0}.{1}.cond_list.txt'.format( file_pref, index_var.replace(':', '_'))) # Write sumstats sumstat_to_gcta(sumstats, gcta_in, gcta_snplist) # Write a conditional list write_cond_list(condition_on, gcta_cond) # Constuct command cmd = [ 'gcta64 --bfile {0}'.format(in_plink.format(chrom=chrom)), '--chr {0}'.format(chrom), '--extract {0}'.format(gcta_snplist), '--cojo-file {0}'.format(gcta_in), '--cojo-cond {0}'.format(gcta_cond), '--out {0}'.format(gcta_out) ] # Run command fnull = open(os.devnull, 'w') cp = sp.run(' '.join(cmd), shell=True, stdout=fnull, stderr=sp.STDOUT) # Log error if GCTA return code is not 0 if cp.returncode != 0: gcta_log_file = '{0}.log'.format(gcta_out) gcta_error = read_error_from_gcta_log(gcta_log_file) if logger: logger.error(' GCTA error:\n\n{0}\n'.format(gcta_error)) # Read output if it exists gcta_res = '{0}.cma.cojo'.format(gcta_out) if os.path.exists(gcta_res): cond_res = pd.read_csv(gcta_res, sep='\t', header=0) # Merge to sumstats sumstat_cond = merge_conditional_w_sumstats(sumstats, cond_res) # Otherwise return empty sumstat df with conditional columns added else: if logger: logger.warning( ' GCTA output not found. Returning empty df in place'.format(gcta_res)) sumstat_cond = sumstats.loc[[], :] for col in ['beta_cond', 'se_cond', 'pval_cond']: sumstat_cond[col] = None return sumstat_cond def read_error_from_gcta_log(log_file): ''' Reads a GCTA log file and returns lines containing the word "error" ''' error_lines = [] with open(log_file, 'r') as in_h: for line in in_h: if 'error' in line.lower(): error_lines.append(line.rstrip()) return '\n'.join(error_lines) def merge_conditional_w_sumstats(sumstats, cond_res): ''' Adds the results of the conditional analysis as columns to the summary stats Args: sumstats (pd.df) cond_res (pd.df) Returns: pd.df of sumstats ''' # Make a variant_id key on the conditional results cond_res['variant_id'] = cond_res['SNP'] # Merge merged = pd.merge( sumstats, cond_res.loc[:, ['variant_id', 'bC', 'bC_se', 'pC']], on='variant_id', how='inner' ) return merged.rename(columns={ 'bC':'beta_cond', 'bC_se':'se_cond', 'pC':'pval_cond', }) def write_cond_list(cond_list, outf): ''' Write a list of variants to a file ''' with open(outf, 'w') as out_h: for var in cond_list: out_h.write(var.replace('_', ':') + '\n') return outf def sumstat_to_gcta(sumstats, outf, snplist, p_threshold=None): ''' Writes a sumstat df as a GCTA compliant file Args: sumstats (pd.df) outf (str): location to write to min_p (float): only write rows with p < p_threshold ''' # Make temp dir if it doesn't exist os.makedirs(os.path.split(outf)[0], exist_ok=True) # Rename and extract required columns outdata = sumstats.rename( columns={"variant_id":"SNP", "alt":"A1", "ref":"A2", "eaf":"freq", "beta":"b", "pval":"p", "n_total":"N"}) outdata = outdata.loc[:, ["SNP", "A1", "A2", "freq", "b", "se", "p", "N"]] # Remove rows where p > p_threshold if p_threshold: outdata = outdata.loc[outdata['p'] <= p_threshold, :] # Save sumstats outdata.to_csv(outf, sep='\t', index=None) # Save snplist outdata.SNP.to_csv(snplist, index=None, header=False) return 0 def make_file_name_prefix(row): ''' Takes a row of the sumstat dataframe and creates a unique file prefix Args: row (dask Series) Return: str ''' cols = ['study_id', 'phenotype_id', 'bio_feature', 'chrom'] pref = '_'.join([str(x) for x in row[cols].values[0]]) return pref
/** * Copyright 2016 The AMP HTML Authors. 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. */ import {isLayoutSizeDefined} from '../../../src/layout'; import {user} from '../../../src/log'; class AmpJWPlayer extends AMP.BaseElement { /** @param {!AmpElement} element */ constructor(element) { super(element); /** @private {string} */ this.contentid_ = ''; /** @private {string} */ this.playerid_ = ''; /** @private {?HTMLIFrameElement} */ this.iframe_ = null; } /** @override */ preconnectCallback(onLayout) { // Host that serves player configuration and content redirects this.preconnect.url('https://content.jwplatform.com', onLayout); // CDN which hosts jwplayer assets this.preconnect.url('https://ssl.p.jwpcdn.com', onLayout); } /** @override */ isLayoutSupported(layout) { return isLayoutSizeDefined(layout); } /** @override */ buildCallback() { this.contentid_ = user().assert( (this.element.getAttribute('data-playlist-id') || this.element.getAttribute('data-media-id')), 'Either the data-media-id or the data-playlist-id ' + 'attributes must be specified for <amp-jwplayer> %s', this.element); this.playerid_ = user().assert( this.element.getAttribute('data-player-id'), 'The data-player-id attribute is required for <amp-jwplayer> %s', this.element); } /** @override */ layoutCallback() { const iframe = this.element.ownerDocument.createElement('iframe'); const src = 'https://content.jwplatform.com/players/' + encodeURIComponent(this.contentid_) + '-' + encodeURIComponent(this.playerid_) + '.html'; iframe.setAttribute('frameborder', '0'); iframe.setAttribute('allowfullscreen', 'true'); iframe.src = src; this.applyFillContent(iframe); this.element.appendChild(iframe); this.iframe_ = iframe; return this.loadPromise(iframe); } /** @override */ pauseCallback() { if (this.iframe_ && this.iframe_.contentWindow) { // The /players page can respond to "play" and "pause" commands from the // iframe's parent this.iframe_.contentWindow./*OK*/postMessage('pause', 'https://content.jwplatform.com'); } } /** @override */ createPlaceholderCallback() { // TODO(#5328): Investigate if there's a calculable poster image for playlists or // a default playlist placeholder image. if (!this.element.hasAttribute('data-media-id')) { return; } const placeholder = this.win.document.createElement('amp-img'); placeholder.setAttribute('src', 'https://content.jwplatform.com/thumbs/' + encodeURIComponent(this.contentid_) + '-720.jpg'); placeholder.setAttribute('layout', 'fill'); placeholder.setAttribute('placeholder', ''); placeholder.setAttribute('referrerpolicy', 'origin'); return placeholder; } }; AMP.registerElement('amp-jwplayer', AmpJWPlayer);
import numpy as np def fast_random_choice(weights): """ this is at least for small arrays much faster than numpy.random.choice. For the Gillespie overall this brings for 3 reaction a speedup of a factor of 2 """ cs = 0 u = np.random.rand() for k in range(weights.size): cs += weights[k] if u <= cs: return k raise Exception("Random choice error {}".format(weights))
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <Safari/SheetWithTableController.h> #import <Safari/TableViewPlusDataSource-Protocol.h> #import <Safari/TableViewPlusDelegate-Protocol.h> @class NSMutableArray, NSString, NSTextField; __attribute__((visibility("hidden"))) @interface WebsiteSpecificSearchEditor : SheetWithTableController <TableViewPlusDataSource, TableViewPlusDelegate> { NSMutableArray *_websiteHosts; NSTextField *_emptyTablePlaceholderText; } @property(nonatomic) __weak NSTextField *emptyTablePlaceholderText; // @synthesize emptyTablePlaceholderText=_emptyTablePlaceholderText; - (void).cxx_destruct; - (id)tableView:(id)arg1 viewForTableColumn:(id)arg2 row:(long long)arg3; - (long long)numberOfRowsInTableView:(id)arg1; - (void)reloadTableData; - (id)_userVisibleHostForHost:(id)arg1; - (void)showSheetInWindow:(id)arg1; - (void)removeAllItems:(id)arg1; - (void)removeSelectedItems:(id)arg1; - (void)showManageWebsitesSheet:(id)arg1; - (void)_updateVisibilityOfPlaceholderText; - (void)_quickWebsiteSearchProvidersDidChange:(id)arg1; - (void)awakeFromNib; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
# # # Copyright (C) 2012 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Script to configure the node daemon. """ import os import os.path import optparse import sys import logging from ganeti import cli from ganeti import constants from ganeti import pathutils from ganeti import ssconf from ganeti import utils def ParseOptions(): """Parses the options passed to the program. @return: Options and arguments """ parser = optparse.OptionParser(usage="%prog [--no-backup]", prog=os.path.basename(sys.argv[0])) parser.add_option(cli.DEBUG_OPT) parser.add_option(cli.VERBOSE_OPT) parser.add_option(cli.YES_DOIT_OPT) parser.add_option("--no-backup", dest="backup", default=True, action="store_false", help="Whether to create backup copies of deleted files") (opts, args) = parser.parse_args() return VerifyOptions(parser, opts, args) def VerifyOptions(parser, opts, args): """Verifies options and arguments for correctness. """ if args: parser.error("No arguments are expected") return opts def Main(): """Main routine. """ opts = ParseOptions() utils.SetupToolLogging(opts.debug, opts.verbose) try: # List of files to delete. Contains tuples consisting of the absolute path # and a boolean denoting whether a backup copy should be created before # deleting. clean_files = [ (pathutils.CONFD_HMAC_KEY, True), (pathutils.CLUSTER_CONF_FILE, True), (pathutils.CLUSTER_DOMAIN_SECRET_FILE, True), ] clean_files.extend(map(lambda s: (s, True), pathutils.ALL_CERT_FILES)) clean_files.extend(map(lambda s: (s, False), ssconf.SimpleStore().GetFileList())) if not opts.yes_do_it: cli.ToStderr("Cleaning a node is irreversible. If you really want to" " clean this node, supply the --yes-do-it option.") return constants.EXIT_FAILURE logging.info("Stopping daemons") result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-all"], interactive=True) if result.failed: raise Exception("Could not stop daemons, command '%s' failed: %s" % (result.cmd, result.fail_reason)) for (filename, backup) in clean_files: if os.path.exists(filename): if opts.backup and backup: logging.info("Backing up %s", filename) utils.CreateBackup(filename) logging.info("Removing %s", filename) utils.RemoveFile(filename) logging.info("Node successfully cleaned") except Exception, err: # pylint: disable=W0703 logging.debug("Caught unhandled exception", exc_info=True) (retcode, message) = cli.FormatError(err) logging.error(message) return retcode else: return constants.EXIT_SUCCESS
# Combine individual fiber files into plate files for all eBOSS plates # # Tim Hutchinson, University of Utah, December 2014 # t.hutchinson@utah.edu from os import environ, makedirs, getcwd from os.path import exists, join, basename from time import gmtime, strftime import numpy as n from astropy.io import fits from glob import iglob from redmonster.datamgr import io2 try: topdir = environ['REDMONSTER_SPECTRO_REDUX'] except KeyError as e: topdir = None print "Environmental variable 'REDMONSTER_SPECTRO_REDUX' is not set: %r" % e try: run2d = environ['RUN2D'] except KeyError as e: run2d = None print "Environmental variable 'RUN2D' is not set: %r" % e try: run1d = environ['RUN1D'] except KeyError as e: run1d = None print "Environmental variable 'RUN1D' is not set: %r" % e platedir = join( topdir, run2d, '*') if topdir and run2d else None plates = [] if platedir: for path in iglob(platedir): plates.append( basename(path) ) plates.sort() for plate in plates: #import pdb; pdb.set_trace() mjds = [] files = [] try: for x in iglob( join( topdir, run2d, str(plate), run1d, 'redmonster-%s-*-*.fits' % plate) ): files.append(x) for file in files: ''' if mjds is not basename(file)[16:21]: mjds.append( basename(file)[16:21] ) else: mjds.append( basename(file)[16:21] ) ''' if len(plate) == 4: if basename(file)[16:21] not in mjds: mjds.append( basename(file)[16:21] ) elif len(plate) == 5: if basename(file)[17:22] not in mjds: mjds.append( basename(file)[17:22] ) except Exception as e: mjds = None print "Exception: %r" % e if mjds is not []: for mjd in mjds: print 'Merging fibers for plate %s, mjd %s' % (plate, mjd) x = io2.MergeRedmonster(plate, mjd) x.merge_fibers2()
/* Copyright 2013-2015 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import onsElements from '../ons/elements.js'; import util from '../ons/util.js'; import autoStyle from '../ons/autostyle.js'; import ModifierUtil from '../ons/internal/modifier-util.js'; import BaseCheckboxElement from './base/base-checkbox.js'; import contentReady from '../ons/content-ready.js'; import GestureDetector from '../ons/gesture-detector.js'; const scheme = { '': 'switch--*', '.switch__input': 'switch--*__input', '.switch__handle': 'switch--*__handle', '.switch__toggle': 'switch--*__toggle' }; const locations = { ios: [1, 21], material: [0, 16] }; /** * @element ons-switch * @category form * @description * [en] * Switch component. The switch can be toggled both by dragging and tapping. * * Will automatically displays a Material Design switch on Android devices. * [/en] * [ja]スイッチを表示するコンポーネントです。[/ja] * @modifier material * [en]Material Design switch[/en] * [ja][/ja] * @codepen LpXZQQ * @tutorial vanilla/Reference/switch * @guide theming.html#modifiers [en]More details about the `modifier` attribute[/en][ja]modifier属性の使い方[/ja] * @example * <ons-switch checked></ons-switch> * <ons-switch disabled></ons-switch> * <ons-switch modifier="material"></ons-switch> */ export default class SwitchElement extends BaseCheckboxElement { constructor() { super(); contentReady(this, () => { this.attributeChangedCallback('modifier', null, this.getAttribute('modifier')); }); this._onChange = this._onChange.bind(this); this._onRelease = this._onRelease.bind(this); this._lastTimeStamp = 0; } get _scheme() { return scheme; } get _defaultClassName() { return 'switch'; } get _template() { return ` <input type="${this.type}" class="${this._defaultClassName}__input"> <div class="${this._defaultClassName}__toggle"> <div class="${this._defaultClassName}__handle"> <div class="${this._defaultClassName}__touch"></div> </div> </div> `; } get type() { return 'checkbox'; } /* Own props */ _getPosition(e) { const l = this._locations; return Math.min(l[1], Math.max(l[0], this._startX + e.gesture.deltaX)); } _emitChangeEvent() { util.triggerElementEvent(this, 'change', { value: this.checked, switch: this, isInteractive: true }); } _onChange(event) { if (event && event.stopPropagation) { event.stopPropagation(); } this._emitChangeEvent(); } _onClick(ev) { if (ev.target.classList.contains(`${this.defaultElementClass}__touch`) || (ev.timeStamp - this._lastTimeStamp < 50) // Prevent second click triggered by <label> ) { ev.preventDefault(); } this._lastTimeStamp = ev.timeStamp; } _onHold(e) { if (!this.disabled) { ModifierUtil.addModifier(this, 'active'); document.addEventListener('release', this._onRelease); } } _onDragStart(e) { if (this.disabled || ['left', 'right'].indexOf(e.gesture.direction) === -1) { ModifierUtil.removeModifier(this, 'active'); return; } e.consumed = true; ModifierUtil.addModifier(this, 'active'); this._startX = this._locations[this.checked ? 1 : 0];// - e.gesture.deltaX; this.addEventListener('drag', this._onDrag); document.addEventListener('release', this._onRelease); } _onDrag(e) { e.stopPropagation(); this._handle.style.left = this._getPosition(e) + 'px'; } _onRelease(e) { const l = this._locations; const position = this._getPosition(e); const previousValue = this.checked; this.checked = position >= (l[0] + l[1]) / 2; if (this.checked !== previousValue) { this._emitChangeEvent(); } this.removeEventListener('drag', this._onDrag); document.removeEventListener('release', this._onRelease); this._handle.style.left = ''; ModifierUtil.removeModifier(this, 'active'); } click(ev = {}) { if (!this.disabled) { this.checked = !this.checked; this._emitChangeEvent(); this._lastTimeStamp = ev.timeStamp || 0; } } get _handle() { return this.querySelector(`.${this._defaultClassName}__handle`); } get checkbox() { return this._input; } connectedCallback() { contentReady(this, () => { this._input.addEventListener('change', this._onChange); }); this.addEventListener('dragstart', this._onDragStart); this.addEventListener('hold', this._onHold); this.addEventListener('tap', this.click); this.addEventListener('click', this._onClick); this._gestureDetector = new GestureDetector(this, { dragMinDistance: 1, holdTimeout: 251, passive: true }); } disconnectedCallback() { contentReady(this, () => { this._input.removeEventListener('change', this._onChange); }); this.removeEventListener('dragstart', this._onDragStart); this.removeEventListener('hold', this._onHold); this.removeEventListener('tap', this.click); this.removeEventListener('click', this._onClick); if (this._gestureDetector) { this._gestureDetector.dispose(); } } static get observedAttributes() { return [...super.observedAttributes, 'modifier']; } attributeChangedCallback(name, last, current) { if (name === 'modifier') { const md = (current || '').indexOf('material') !== -1; this._locations = locations[md ? 'material' : 'ios']; } super.attributeChangedCallback(name, last, current); } /** * @event change * @description * [en]Fired when the switch is toggled.[/en] * [ja]ON/OFFが変わった時に発火します。[/ja] * @param {Object} event * [en]Event object.[/en] * [ja]イベントオブジェクト。[/ja] * @param {Object} event.switch * [en]Switch object.[/en] * [ja]イベントが発火したSwitchオブジェクトを返します。[/ja] * @param {Boolean} event.value * [en]Current value.[/en] * [ja]現在の値を返します。[/ja] * @param {Boolean} event.isInteractive * [en]True if the change was triggered by the user clicking on the switch.[/en] * [ja]タップやクリックなどのユーザの操作によって変わった場合にはtrueを返します。[/ja] */ /** * @attribute modifier * @type {String} * @description * [en]The appearance of the switch.[/en] * [ja]スイッチの表現を指定します。[/ja] */ /** * @attribute disabled * @description * [en]Whether the switch is be disabled.[/en] * [ja]スイッチを無効の状態にする場合に指定します。[/ja] */ /** * @attribute checked * @description * [en]Whether the switch is checked.[/en] * [ja]スイッチがONの状態にするときに指定します。[/ja] */ /** * @attribute input-id * @type {String} * @description * [en]Specify the `id` attribute of the inner `<input>` element. This is useful when using `<label for="...">` elements.[/en] * [ja][/ja] */ /** * @property checked * @type {Boolean} * @description * [en]This value is `true` if the switch is checked.[/en] * [ja]スイッチがONの場合に`true`。[/ja] */ /** * @property value * @type {String} * @description * [en]The current value of the input.[/en] * [ja][/ja] */ /** * @property disabled * @type {Boolean} * @description * [en]Whether the element is disabled or not.[/en] * [ja]無効化されている場合に`true`。[/ja] */ /** * @property checkbox * @readonly * @type {HTMLElement} * @description * [en]The underlying checkbox element.[/en] * [ja]コンポーネント内部のcheckbox要素になります。[/ja] */ /** * @method focus * @signature focus() * @description * [en]Focuses the switch.[/en] * [ja][/ja] */ /** * @method blur * @signature blur() * @description * [en]Removes focus from the switch.[/en] * [ja][/ja] */ } onsElements.Switch = SwitchElement; customElements.define('ons-switch', SwitchElement);
import pandas as pd def load(name): df = pd.read_csv('data/' + name + '.csv') return df def getColsValues(df, cols): return df[list(cols)].values def getColValues(df, col): return df[col].values
import { collection } from "firebase/firestore"; import { CollectionActionTypes } from "./collection.types"; const INITIAL_STATE = { collections : [ { id: 1, title : 'Large Household Appliances', routeName : 'largehousehold', items : [ { id : 1, name : 'Washer Machine 10.5KG Royal', imageUrl : '/images/washingmachine.jpg', price : 5600000 }, { id: 2, name : 'Refrigerator 18 Flat Glass', imageUrl : '/images/refrigrator.jpg', price : 5300000 }, { id:3, name : 'Gas Stove 24 Royal', imageUrl : '/images/stove.jpg', price : 3000000 }, { id:4, name : 'Oven Electric 12L Oska 120V', imageUrl : '/images/oven.jpg', price : 2400000 }, ] }, { id: 2, title : 'Small Household Appliances', routeName : 'smallhousehold', items : [ { id: 5, name : 'Cooker Rice B&D', imageUrl : '/images/cooker.jpg', price : 2600000 }, { id : 6, name : 'Air Conditioner Split Unit', imageUrl : '/images/ac.jpg', price : 3400000 }, { id : 7, name : 'Chopper Food Mini', imageUrl : '/images/chopper.jpg', price : 1800000 }, { id : 8, name : 'Juicer Citrus Electric', imageUrl : '/images/juicer.jpg', price : 1500000 } ] }, { id : 3, title : 'IT Equipments', routeName : 'itequipments', items : [ { id : 9, name : 'Cooling Pad Xtech', imageUrl : '/images/coolingpad.jpg', price : 350000 }, { id: 10, name : 'Mouse Ergonomic KLIP', imageUrl : '/images/mouse.jpg', price : 240000 }, { id:11, name : 'Flashdrive Sandisk', imageUrl :'/images/fd.png', price : 200000 }, { id: 12, name : 'Lenovo ThinkPad E480', imageUrl :'/images/lenovothinkpad.jpg', price : 9450000 } ] }, { id : 4, title : 'Electrical Tools', routeName : 'electricals', items : [ { id: 13, name : 'Box Tool', imageUrl : '/images/boxtool.jpg', price : 650000 }, { id: 14, name : 'Snip Circle Cut', imageUrl : '/images/snip.jpg', price : 130000 }, { id: 15, name : 'Knife Utility', imageUrl :'/images/knife.jpg', price : 120000 }, { id : 16, name : 'Screwdriver', imageUrl : '/images/screwdriver.jpg', price : 60000 } ] }, { id : 5, title : 'Monitoring & Control Instruments', routeName : 'monitoring', items : [ { id : 17, name : 'Zoom CCTV', imageUrl : '/images/cctv.jpg', price : 2000000 }, { id: 18, name :'360 CCTV', imageUrl : '/images/cctv1.jpg', price : 2300000 }, { id: 19, name : 'Wireless CCTV', imageUrl :'/images/wirelesscctv.png', price : 2600000 }, { id: 20, name : 'Triplett Monitor', imageUrl : '/images/triplettmonitor.jpg', price : 1400000 } ] } ] } const collectionReducer = (state = INITIAL_STATE, action) => { switch(action.type) { case CollectionActionTypes.SELECT_COLLECTION_FOR_PREVIEW : return { ...state, } default: return state; } } export default collectionReducer;
"use strict"; /* * ATTENTION: An "eval-source-map" devtool has been used. * This devtool is neither made for production nor for readable output files. * It uses "eval()" calls to create a separate source file with attached SourceMaps in the browser devtools. * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/) * or disable the default devtool with "devtool: false". * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/). */ self["webpackHotUpdate_N_E"]("webpack",{}, /******/ function(__webpack_require__) { // webpackRuntimeModules /******/ /* webpack/runtime/getFullHash */ /******/ !function() { /******/ __webpack_require__.h = function() { return "ffdc1126d1273f2088c7"; } /******/ }(); /******/ /******/ } );
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license. """ import logging import django_rq import json from django.utils import timezone from django.db import models, transaction from django.utils.translation import gettext_lazy as _ from django.conf import settings from django_rq import job from tasks.models import Task from tasks.serializers import PredictionSerializer, AnnotationSerializer from data_export.serializers import ExportDataSerializer from core.redis import redis_connected from core.utils.common import get_bool_env, load_func logger = logging.getLogger(__name__) class Storage(models.Model): title = models.CharField( _('title'), null=True, blank=True, max_length=256, help_text='Cloud storage title') description = models.TextField( _('description'), null=True, blank=True, help_text='Cloud storage description') project = models.ForeignKey( 'projects.Project', related_name='%(app_label)s_%(class)ss', on_delete=models.CASCADE) created_at = models.DateTimeField( _('created at'), auto_now_add=True, help_text='Creation time') last_sync = models.DateTimeField( _('last sync'), null=True, blank=True, help_text='Last sync finished time') last_sync_count = models.PositiveIntegerField( _('last sync count'), null=True, blank=True, help_text='Count of tasks synced last time') def validate_connection(self, client=None): pass def has_permission(self, user): if self.project.has_permission(user): return True return False class Meta: abstract = True class ImportStorage(Storage): def iterkeys(self): return iter(()) def get_data(self, key): raise NotImplementedError def resolve_uri(self, data): return def resolve_task_data_uri(self, task_data): out = {} for key, data in task_data.items(): if not isinstance(data, str): out[key] = data resolved_uri = self.resolve_uri(data) if resolved_uri: out[key] = resolved_uri else: out[key] = data return out def _scan_and_create_links(self, link_class): tasks_created = 0 for key in self.iterkeys(): logger.debug(f'Scanning key {key}') # skip if task already exists if link_class.exists(key, self): logger.debug(f'{self.__class__.__name__} link {key} already exists') continue logger.debug(f'{self}: found new key {key}') try: data = self.get_data(key) except (UnicodeDecodeError, json.decoder.JSONDecodeError) as exc: logger.error(exc, exc_info=True) raise ValueError( f'Error loading JSON from file "{key}".\nIf you\'re trying to import non-JSON data ' f'(images, audio, text, etc.), edit storage settings and enable ' f'"Treat every bucket object as a source file"') # predictions predictions = data.get('predictions', []) if predictions: if 'data' not in data: raise ValueError('If you use "predictions" field in the task, ' 'you must put "data" field in the task too') # annotations annotations = data.get('annotations', []) if annotations: if 'data' not in data: raise ValueError('If you use "annotations" field in the task, ' 'you must put "data" field in the task too') if 'data' in data and isinstance(data['data'], dict): data = data['data'] with transaction.atomic(): task = Task.objects.create(data=data, project=self.project) link_class.create(task, key, self) logger.debug(f'Create {self.__class__.__name__} link with key={key} for task={task}') tasks_created += 1 # add predictions logger.debug(f'Create {len(predictions)} predictions for task={task}') for prediction in predictions: prediction['task'] = task.id prediction_ser = PredictionSerializer(data=predictions, many=True) prediction_ser.is_valid(raise_exception=True) prediction_ser.save() # add annotations logger.debug(f'Create {len(annotations)} annotations for task={task}') for annotation in annotations: annotation['task'] = task.id annotation_ser = AnnotationSerializer(data=annotations, many=True) annotation_ser.is_valid(raise_exception=True) annotation_ser.save() self.last_sync = timezone.now() self.last_sync_count = tasks_created self.save() def scan_and_create_links(self): """This is proto method - you can override it, or just replace ImportStorageLink by your own model""" self._scan_and_create_links(ImportStorageLink) def sync(self): if redis_connected(): queue = django_rq.get_queue('default') job = queue.enqueue(sync_background, self.__class__, self.id) # job_id = sync_background.delay() # TODO: @niklub: check this fix logger.info(f'Storage sync background job {job.id} for storage {self} has been started') else: logger.info(f'Start syncing storage {self}') self.scan_and_create_links() class Meta: abstract = True @job('default') def sync_background(storage_class, storage_id): storage = storage_class.objects.get(id=storage_id) storage.scan_and_create_links() class ExportStorage(Storage): def _get_serialized_data(self, annotation): if get_bool_env('FUTURE_SAVE_TASK_TO_STORAGE', default=False): # export task with annotations return ExportDataSerializer(annotation.task).data else: serializer_class = load_func(settings.STORAGE_ANNOTATION_SERIALIZER) # deprecated functionality - save only annotation return serializer_class(annotation).data def save_annotation(self, annotation): raise NotImplementedError class Meta: abstract = True class ImportStorageLink(models.Model): task = models.OneToOneField('tasks.Task', on_delete=models.CASCADE, related_name='%(app_label)s_%(class)s') key = models.TextField(_('key'), null=False, help_text='External link key') object_exists = models.BooleanField( _('object exists'), help_text='Whether object under external link still exists', default=True) created_at = models.DateTimeField(_('created at'), auto_now_add=True, help_text='Creation time') @classmethod def exists(cls, key, storage): return cls.objects.filter(key=key, storage=storage.id).exists() @classmethod def create(cls, task, key, storage): link, created = cls.objects.get_or_create(task_id=task.id, key=key, storage=storage, object_exists=True) return link def has_permission(self, user): if self.task.has_permission(user): return True return False class Meta: abstract = True class ExportStorageLink(models.Model): annotation = models.OneToOneField( 'tasks.Annotation', on_delete=models.CASCADE, related_name='%(app_label)s_%(class)s') object_exists = models.BooleanField( _('object exists'), help_text='Whether object under external link still exists', default=True) created_at = models.DateTimeField(_('created at'), auto_now_add=True, help_text='Creation time') @staticmethod def get_key(annotation): if get_bool_env('FUTURE_SAVE_TASK_TO_STORAGE', default=False): return str(annotation.task.id) return str(annotation.id) @property def key(self): return self.get_key(self.annotation) @classmethod def exists(cls, annotation, storage): return cls.objects.filter(annotation=annotation.id, storage=storage.id).exists() @classmethod def create(cls, annotation, storage): link, created = cls.objects.get_or_create(annotation=annotation, storage=storage, object_exists=True) return link def has_permission(self, user): if self.annotation.has_permission(user): return True return False class Meta: abstract = True
from flask import request, Blueprint, render_template, redirect from services.user import UserServices from services.video import VideoServices video = Blueprint('video', __name__) @video.route('/play') def video_play(): uid = request.cookies.get('uid') if uid is None: return redirect('/user/login', 302) video_id = request.args.get('video_id') us = UserServices() vd = VideoServices() u_result = us.get_user_info(uid) total_time = us.get_user_time(uid) vd = vd.get_video_info(video_id) return render_template('video/play.html', username=u_result['user_name'], total_time=round(total_time / 60, 1), vd=vd) @video.route('/list') def video_list(): uid = request.cookies.get('uid') if uid is None: return redirect('/user/login', 302) subject_id = request.args.get('sub') us = UserServices() u_result = us.get_user_info(uid) total_time = us.get_user_time(uid) vd = VideoServices() v_result = vd.get_video_list(subject_id) return render_template('video/list.html', course=v_result, username=u_result['user_name'], total_time=round(total_time / 60, 1)) @video.route('live') def video_live(): uid = request.cookies.get('uid') live = request.args.get("live") if uid is None: return redirect('/user/login', 302) return render_template("video/live.html", live=live, grade=str(int(request.args.get("live"))))
// @ts-check // !!! Sharing the dependencies of caz module.paths = require.main.paths const path = require('path') const chalk = require('chalk') const { name, version } = require('./package.json') /** @type {import('caz').Template} */ module.exports = { name, version, metadata: { year: new Date().getFullYear() }, prompts: [ { name: 'name', type: 'text', message: 'Project name' }, { name: 'version', type: 'text', message: 'Project version' }, { name: 'description', type: 'text', message: 'Project description', initial: 'Awesome vue apps.' }, { name: 'author', type: 'text', message: 'Project author name' }, { name: 'email', type: 'text', message: 'Project author email' }, { name: 'url', type: 'text', message: 'Project author url' }, { name: 'github', type: 'text', message: 'GitHub username or organization', initial: 'zce' }, { name: 'install', type: 'confirm', message: 'Install dependencies', initial: true }, { name: 'pm', type: prev => process.env.NODE_ENV === 'test' || prev ? 'select' : null, message: 'Package manager', hint: ' ', choices: [ { title: 'npm', value: 'npm' }, { title: 'yarn', value: 'yarn' }, { title: 'pnpm', value: 'pnpm' } ] } ], init: true, emit: async ctx => { ctx.config.install = ctx.answers.install && ctx.answers.pm }, complete: async ctx => { console.clear() console.log(chalk`Created a new project in {cyan ${ctx.project}} by the {blue ${ctx.template}} template.\n`) console.log('Getting Started:') if (ctx.dest !== process.cwd()) { console.log(chalk` $ {cyan cd ${path.relative(process.cwd(), ctx.dest)}}`) } if (ctx.config.install === false) { console.log(chalk` $ {cyan npm install} {gray # or yarn}`) } console.log(chalk` $ {cyan ${ctx.config.install ? ctx.config.install : 'npm'} run dev}`) console.log('\nHappy hacking :)\n') } }
# Original work Copyright (c) 2016 OpenAI (https://openai.com). # Modified work Copyright (c) Allen Institute for AI # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Union, Tuple, List, cast, Iterable, Callable from collections import OrderedDict import numpy as np import torch from gym import spaces as gym ActionType = Union[torch.Tensor, OrderedDict, Tuple, int] def flatdim(space): """Return the number of dimensions a flattened equivalent of this space would have. Accepts a space and returns an integer. Raises ``NotImplementedError`` if the space is not defined in ``gym.spaces``. """ if isinstance(space, gym.Box): return int(np.prod(space.shape)) elif isinstance(space, gym.Discrete): return 1 # we do not expand to one-hot elif isinstance(space, gym.Tuple): return int(sum([flatdim(s) for s in space.spaces])) elif isinstance(space, gym.Dict): return int(sum([flatdim(s) for s in space.spaces.values()])) elif isinstance(space, gym.MultiBinary): return int(space.n) elif isinstance(space, gym.MultiDiscrete): return int(np.prod(space.shape)) else: raise NotImplementedError def flatten(space, torch_x): """Flatten data points from a space.""" if isinstance(space, gym.Box): if len(space.shape) > 0: return torch_x.view(torch_x.shape[: -len(space.shape)] + (-1,)) else: return torch_x.view(torch_x.shape + (-1,)) elif isinstance(space, gym.Discrete): # Assume tensor input does NOT contain a dimension for action if isinstance(torch_x, torch.Tensor): return torch_x.unsqueeze(-1) else: return torch.tensor(torch_x).view(1) elif isinstance(space, gym.Tuple): return torch.cat( [flatten(s, x_part) for x_part, s in zip(torch_x, space.spaces)], dim=-1 ) elif isinstance(space, gym.Dict): return torch.cat( [flatten(s, torch_x[key]) for key, s in space.spaces.items()], dim=-1 ) elif isinstance(space, gym.MultiBinary): return torch_x.view(torch_x.shape[: -len(space.shape)] + (-1,)) elif isinstance(space, gym.MultiDiscrete): return torch_x.view(torch_x.shape[: -len(space.shape)] + (-1,)) else: raise NotImplementedError def unflatten(space, torch_x): """Unflatten a concatenated data points tensor from a space.""" if isinstance(space, gym.Box): return torch_x.view(torch_x.shape[:-1] + space.shape).float() elif isinstance(space, gym.Discrete): res = torch_x.view(torch_x.shape[:-1] + space.shape).long() return res if len(res.shape) > 0 else res.item() elif isinstance(space, gym.Tuple): dims = [flatdim(s) for s in space.spaces] list_flattened = torch.split(torch_x, dims, dim=-1) list_unflattened = [ unflatten(s, flattened) for flattened, s in zip(list_flattened, space.spaces) ] return tuple(list_unflattened) elif isinstance(space, gym.Dict): dims = [flatdim(s) for s in space.spaces.values()] list_flattened = torch.split(torch_x, dims, dim=-1) list_unflattened = [ (key, unflatten(s, flattened)) for flattened, (key, s) in zip(list_flattened, space.spaces.items()) ] return OrderedDict(list_unflattened) elif isinstance(space, gym.MultiBinary): return torch_x.view(torch_x.shape[:-1] + space.shape).byte() elif isinstance(space, gym.MultiDiscrete): return torch_x.view(torch_x.shape[:-1] + space.shape).long() else: raise NotImplementedError def torch_point(space, np_x): """Convert numpy space point into torch.""" if isinstance(space, gym.Box): return torch.from_numpy(np_x) elif isinstance(space, gym.Discrete): return np_x elif isinstance(space, gym.Tuple): return tuple([torch_point(s, x_part) for x_part, s in zip(np_x, space.spaces)]) elif isinstance(space, gym.Dict): return OrderedDict( [(key, torch_point(s, np_x[key])) for key, s in space.spaces.items()] ) elif isinstance(space, gym.MultiBinary): return torch.from_numpy(np_x) elif isinstance(space, gym.MultiDiscrete): return torch.from_numpy(np.asarray(np_x)) else: raise NotImplementedError def numpy_point( space: gym.Space, torch_x: Union[int, torch.Tensor, OrderedDict, Tuple] ): """Convert torch space point into numpy.""" if isinstance(space, gym.Box): return cast(torch.Tensor, torch_x).cpu().numpy() elif isinstance(space, gym.Discrete): return torch_x elif isinstance(space, gym.Tuple): return tuple( [ numpy_point(s, x_part) for x_part, s in zip(cast(Iterable, torch_x), space.spaces) ] ) elif isinstance(space, gym.Dict): return OrderedDict( [ (key, numpy_point(s, cast(torch.Tensor, torch_x)[key])) for key, s in space.spaces.items() ] ) elif isinstance(space, gym.MultiBinary): return cast(torch.Tensor, torch_x).cpu().numpy() elif isinstance(space, gym.MultiDiscrete): return cast(torch.Tensor, torch_x).cpu().numpy() else: raise NotImplementedError def flatten_space(space: gym.Space): if isinstance(space, gym.Box): return gym.Box(space.low.flatten(), space.high.flatten()) if isinstance(space, gym.Discrete): return gym.Box(low=0, high=space.n, shape=(1,)) if isinstance(space, gym.Tuple): space = [flatten_space(s) for s in space.spaces] return gym.Box( low=np.concatenate([s.low for s in space]), high=np.concatenate([s.high for s in space]), ) if isinstance(space, gym.Dict): space = [flatten_space(s) for s in space.spaces.values()] return gym.Box( low=np.concatenate([s.low for s in space]), high=np.concatenate([s.high for s in space]), ) if isinstance(space, gym.MultiBinary): return gym.Box(low=0, high=1, shape=(space.n,)) if isinstance(space, gym.MultiDiscrete): return gym.Box(low=np.zeros_like(space.nvec), high=space.nvec,) raise NotImplementedError def policy_space( action_space: gym.Space, box_space_to_policy: Callable[[gym.Box], gym.Space] = None, ) -> gym.Space: if isinstance(action_space, gym.Box): if box_space_to_policy is None: # policy = mean (default) return action_space else: return box_space_to_policy(action_space) if isinstance(action_space, gym.Discrete): # policy = prob of each option return gym.Box( low=np.float32(0.0), high=np.float32(1.0), shape=(action_space.n,) ) if isinstance(action_space, gym.Tuple): # policy = tuple of sub-policies spaces = [policy_space(s, box_space_to_policy) for s in action_space.spaces] return gym.Tuple(spaces) if isinstance(action_space, gym.Dict): # policy = dict of sub-policies spaces = [ (name, policy_space(s, box_space_to_policy),) for name, s in action_space.spaces.items() ] return gym.Dict(spaces) if isinstance(action_space, gym.MultiBinary): # policy = prob of 0, 1 in each entry return gym.Box( low=np.float32(0.0), high=np.float32(1.0), shape=(action_space.n, 2) ) if isinstance(action_space, gym.MultiDiscrete): # policy = Tuple of prob of each option for each discrete return gym.Tuple( [ gym.Box(low=np.float32(0.0), high=np.float32(1.0), shape=(n,)) for n in action_space.nvec ] ) raise NotImplementedError def action_list( action_space: gym.Space, flat_actions: torch.Tensor ) -> List[ActionType]: """Convert flattened actions to list. Assumes `flat_actions` are of shape `[step, sampler, flatdim]`. """ def tolist(action): if isinstance(action, torch.Tensor): return action.tolist() if isinstance(action, Tuple): actions = [tolist(ac) for ac in action] return tuple(actions) if isinstance(action, OrderedDict): actions = [(key, tolist(action[key])) for key in action.keys()] return OrderedDict(actions) # else, it's a scalar return action return [tolist(unflatten(action_space, ac)) for ac in flat_actions[0]]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the WinRAR Windows Registry plugin.""" from __future__ import unicode_literals import unittest from dfdatetime import filetime as dfdatetime_filetime from dfwinreg import definitions as dfwinreg_definitions from dfwinreg import fake as dfwinreg_fake from plaso.formatters import winreg # pylint: disable=unused-import from plaso.parsers.winreg_plugins import winrar from tests.parsers.winreg_plugins import test_lib class WinRARHistoryPluginTest(test_lib.RegistryPluginTestCase): """Tests for the WinRAR history Windows Registry plugin.""" def _CreateTestKey(self, key_path, time_string): """Creates WinRAR history Registry keys and values for testing. Args: key_path (str): Windows Registry key path. time_string (str): key last written date and time. Returns: dfwinreg.WinRegistryKey: a Windows Registry key. """ filetime = dfdatetime_filetime.Filetime() filetime.CopyFromDateTimeString(time_string) registry_key = dfwinreg_fake.FakeWinRegistryKey( 'ArcHistory', key_path=key_path, last_written_time=filetime.timestamp, offset=1456) value_data = 'C:\\Downloads\\The Sleeping Dragon CD1.iso'.encode( 'utf_16_le') registry_value = dfwinreg_fake.FakeWinRegistryValue( '0', data=value_data, data_type=dfwinreg_definitions.REG_SZ, offset=1892) registry_key.AddValue(registry_value) value_data = 'C:\\Downloads\\plaso-static.rar'.encode('utf_16_le') registry_value = dfwinreg_fake.FakeWinRegistryValue( '1', data=value_data, data_type=dfwinreg_definitions.REG_SZ, offset=612) registry_key.AddValue(registry_value) return registry_key def testFilters(self): """Tests the FILTERS class attribute.""" plugin = winrar.WinRARHistoryPlugin() key_path = 'HKEY_CURRENT_USER\\Software\\WinRAR\\ArcHistory' self._AssertFiltersOnKeyPath(plugin, key_path) self._AssertNotFiltersOnKeyPath(plugin, 'HKEY_LOCAL_MACHINE\\Bogus') def testProcess(self): """Tests the Process function.""" key_path = 'HKEY_CURRENT_USER\\Software\\WinRAR\\ArcHistory' time_string = '2012-08-28 09:23:49.002031' registry_key = self._CreateTestKey(key_path, time_string) plugin = winrar.WinRARHistoryPlugin() storage_writer = self._ParseKeyWithPlugin(registry_key, plugin) self.assertEqual(storage_writer.number_of_warnings, 0) self.assertEqual(storage_writer.number_of_events, 1) events = list(storage_writer.GetEvents()) event = events[0] self.CheckTimestamp(event.timestamp, '2012-08-28 09:23:49.002031') event_data = self._GetEventDataOfEvent(storage_writer, event) # This should just be the plugin name, as we're invoking it directly, # and not through the parser. self.assertEqual(event_data.parser, plugin.plugin_name) self.assertEqual(event_data.data_type, 'winrar:history') expected_message = ( '[{0:s}] ' '0: C:\\Downloads\\The Sleeping Dragon CD1.iso ' '1: C:\\Downloads\\plaso-static.rar').format(key_path) expected_short_message = '{0:s}...'.format(expected_message[:77]) self._TestGetMessageStrings( event_data, expected_message, expected_short_message) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python3 # Copyright (c) 2013-2015 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from __future__ import division,print_function,unicode_literals import biplist from ds_store import DSStore from mac_alias import Alias import sys output_file = sys.argv[1] package_name_ns = sys.argv[2] ds = DSStore.open(output_file, 'w+') ds['.']['bwsp'] = { 'ShowStatusBar': False, 'WindowBounds': b'{{300, 280}, {500, 343}}', 'ContainerShowSidebar': False, 'SidebarWidth': 0, 'ShowTabView': False, 'PreviewPaneVisibility': False, 'ShowToolbar': False, 'ShowSidebar': False, 'ShowPathbar': True } icvp = { 'gridOffsetX': 0.0, 'textSize': 12.0, 'viewOptionsVersion': 1, 'backgroundImageAlias': b'\x00\x00\x00\x00\x02\x1e\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd1\x94\\\xb0H+\x00\x05\x00\x00\x00\x98\x0fbackground.tiff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x99\xd19\xb0\xf8\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\x00\x00\r\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b.background\x00\x00\x10\x00\x08\x00\x00\xd1\x94\\\xb0\x00\x00\x00\x11\x00\x08\x00\x00\xd19\xb0\xf8\x00\x00\x00\x01\x00\x04\x00\x00\x00\x98\x00\x0e\x00 \x00\x0f\x00b\x00a\x00c\x00k\x00g\x00r\x00o\x00u\x00n\x00d\x00.\x00t\x00i\x00f\x00f\x00\x0f\x00\x02\x00\x00\x00\x12\x00\x1c/.background/background.tiff\x00\x14\x01\x06\x00\x00\x00\x00\x01\x06\x00\x02\x00\x00\x0cMacintosh HD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xce\x97\xab\xc3H+\x00\x00\x01\x88[\x88\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02u\xab\x8d\xd1\x94\\\xb0devrddsk\xff\xff\xff\xff\x00\x00\t \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07bitcoin\x00\x00\x10\x00\x08\x00\x00\xce\x97\xab\xc3\x00\x00\x00\x11\x00\x08\x00\x00\xd1\x94\\\xb0\x00\x00\x00\x01\x00\x14\x01\x88[\x88\x00\x16\xa9\t\x00\x08\xfaR\x00\x08\xfaQ\x00\x02d\x8e\x00\x0e\x00\x02\x00\x00\x00\x0f\x00\x1a\x00\x0c\x00M\x00a\x00c\x00i\x00n\x00t\x00o\x00s\x00h\x00 \x00H\x00D\x00\x13\x00\x01/\x00\x00\x15\x00\x02\x00\x14\xff\xff\x00\x00\xff\xff\x00\x00', 'backgroundColorBlue': 1.0, 'iconSize': 96.0, 'backgroundColorGreen': 1.0, 'arrangeBy': 'none', 'showIconPreview': True, 'gridSpacing': 100.0, 'gridOffsetY': 0.0, 'showItemInfo': False, 'labelOnBottom': True, 'backgroundType': 2, 'backgroundColorRed': 1.0 } alias = Alias.from_bytes(icvp['backgroundImageAlias']) alias.volume.name = package_name_ns alias.volume.posix_path = '/Volumes/' + package_name_ns alias.volume.disk_image_alias.target.filename = package_name_ns + '.temp.dmg' alias.volume.disk_image_alias.target.carbon_path = 'Macintosh HD:Users:\x00oblivionuser:\x00Documents:\x00oblivion:\x00oblivion:\x00' + package_name_ns + '.temp.dmg' alias.volume.disk_image_alias.target.posix_path = 'Users/oblivionuser/Documents/oblivion/oblivion/' + package_name_ns + '.temp.dmg' alias.target.carbon_path = package_name_ns + ':.background:\x00background.tiff' icvp['backgroundImageAlias'] = biplist.Data(alias.to_bytes()) ds['.']['icvp'] = icvp ds['.']['vSrn'] = ('long', 1) ds['Applications']['Iloc'] = (370, 156) ds['Oblivion-Qt.app']['Iloc'] = (128, 156) ds.flush() ds.close()
""" 持久状况承载能力极限状态计算 《公路钢筋混凝土及预应力混凝土桥涵设计规范》(JTG 3362-2018)第5节 """ __all__ = [ 'end_anchorage', 'inner_anchorage', ] from math import pi, sin, cos, acos, sqrt from collections import OrderedDict from calla import abacus, numeric class end_anchorage(abacus): """ 端部锚固区计算 《公路钢筋混凝土及预应力混凝土桥涵设计规范》(JTG 3362-2018)第8.2.1~5节 """ __title__ = '端部锚固区' __inputs__ = OrderedDict(( ('γ0',('<i>γ</i><sub>0</sub>','',1.0,'重要性系数')), #('option',('端面锚头分布情形','','1','','',{'1':'单个锚头','2':'一组密集锚头'})), ('Pd',('<i>P</i><sub>d</sub>','kN',0,'预应力锚固力设计值','取1.2倍张拉控制力')), ('a',('<i>a</i>','mm',250,'锚垫板宽度')), ('h',('<i>h</i>','mm',1000,'锚固端截面高度')), ('e',('<i>e</i>','mm',0,'锚固力偏心距')), ('α',('<i>α</i>','rad',0,'力筋倾角','-5°~+20°,锚固力作用线从起点指向截面形心时取正值,远离时取负值')), ('fsd',('<i>f</i><sub>sd</sub>','MPa',330,'钢筋抗拉强度设计值')), ('As1',('<i>A</i><sub>s</sub>','mm<sup>2</sup>',0,'锚下劈裂力配筋面积', '总体区应配置抵抗横向劈裂力的闭合箍筋,间距不应大于120mm。总体区计算范围为1~1.2倍梁高或梁宽的较大值。')), ('As2',('<i>A</i><sub>s</sub>','mm<sup>2</sup>',0,'端面配筋面积', '梁端截面应配置抵抗表面剥落力的抗裂钢筋。当采用大偏心锚固时,锚固端面钢筋宜弯起并延伸至纵向受拉边缘。')), ('option',('大间距锚头','',False,'','两个锚固力的中心距大于1/2锚固端截面高度时为大间距锚头',{True:'是',False:'否'})), ('Pd_',('<span style="text-decoration:overline;"><i>P</i></span><sub>d</sub>','kN',0,'锚固力设计值的平均值','取1.2倍张拉控制力')), ('s',('<i>s</i>','mm',500,'两个锚固力的中心距')), ('As3',('<i>A</i><sub>s</sub>','mm<sup>2</sup>',0,'边缘拉力配筋面积')), )) __deriveds__ = OrderedDict(( ('γ',('<i>γ</i>','kN',0,'锚固力在截面上的偏心率','γ=2e/h')), ('Tbd',('<i>T</i><sub>b,d</sub>','kN',1000,'锚下劈裂力设计值')), ('db',('<i>d</i><sub>b</sub>','mm',0,'劈裂力作用位置至锚固端面的水平距离')), ('Tsd',('<i>T</i><sub>s,d</sub>','kN',1000,'锚垫板局部压陷引起的周边剥落力设计值')), ('Tetd',('<i>T</i><sub>et,d</sub>','kN',1000,'端部锚固区的边缘拉力设计值')), ('As',('<i>A</i><sub>s</sub>','mm<sup>2</sup>',0,'')), ('eql',('','kN',0,'')), ('eqr1',('','kN',0,'')), ('eqr2',('','kN',0,'')), ('eqr3',('','kN',0,'')), )) __toggles__ = { 'option': {True:(),False:('Pd_', 's')}, } def solve(self): self.validate('positive', 'h') fTbd = lambda Pd,γ,a,h,α: 0.25*Pd*(1+γ)**2*((1-γ)-a/h)+0.5*Pd*abs(sin(α)) # (8.2.2-1) fdb = lambda h,e,α: 0.5*(h-2*e)+e*sin(α) # (8.2.2-2) fTsd = lambda Pdimax:0.02*Pdimax # (8.2.3) fTsd2 = lambda Pd_,s,h:0.45*Pd_*(2*s/h-1) # (8.2.4) fTetd = lambda Pd,γ: 0 if γ<=1/3 else (3*γ-1)**2/12/γ*Pd # (8.2.5) self.γ=2*self.e/self.h self.Tbd = fTbd(self.Pd, self.γ, self.a, self.h, self.α) self.db = fdb(self.h,self.e,self.α) self.option = 2*self.s>self.h self.Tsd = fTsd2(self.Pd_,self.s,self.h) if self.option else fTsd(self.Pd) self.Tetd = fTetd(self.Pd, self.γ) self.eqr1 = self.fsd*self.As1/1e3 self.eqr2 = self.fsd*self.As2/1e3 self.eqr3 = self.fsd*self.As3/1e3 def _html(self, digits=2): for attr in ('Pd','a','h','e','α','fsd'): yield self.format(attr, digits = None) for attr in ('γ'): yield self.format(attr, digits) yield self.format('As1') yield self.format('Tbd', eq='0.25*Pd*(1+γ)<sup>2</sup>*((1-γ)-a/h)+0.5*Pd*|sin(α)|') yield self.format('db') self.eql = self.γ0*self.Tbd ok = self.eql <= self.eqr1 yield '{} {} {}, {}满足规范第8.2.1条要求。'.format( self.format('eql', eq='γ0·Tbd'), '≤' if ok else '&gt;', self.format('eqr1',eq='fsd·As'), '' if ok else '不') yield self.format('As2') if self.option: yield self.format('Pd_') yield self.format('s') yield self.format('Tsd', eq='0.45·Pd_·(2·s/h-1)' if self.option else '0.02·Pd') self.eql = self.γ0*self.Tsd ok = self.eql <= self.eqr2 yield '{} {} {}, {}满足规范第8.2.1条要求。'.format( self.format('eql', eq='γ0·Tsd'), '≤' if ok else '&gt;', self.format('eqr2',eq='fsd·As'), '' if ok else '不') yield self.format('As3') if self.γ <= 1/3: yield self.format('Tetd') else: yield self.format('Tetd', eq='(2·e-d)<sup>2</sup>/12/e/(e+d)·Pd') self.eql = self.γ0*self.Tetd ok = self.eql <= self.eqr3 yield '{} {} {}, {}满足规范第8.2.1条要求。'.format( self.format('eql', eq='γ0·Tetd'), '≤' if ok else '&gt;', self.format('eqr3',eq='fsd·As'), '' if ok else '不') class inner_anchorage(abacus): """ 三角齿块锚固区内五个受拉部位拉力设计值计算 《公路钢筋混凝土及预应力混凝土桥涵设计规范》(JTG 3362-2018)第8.2.1、8.2.6节 """ __title__ = '三角齿块锚固区' __inputs__ = OrderedDict(( ('γ0',('<i>γ</i><sub>0</sub>','',1.0,'重要性系数')), ('Pd',('<i>P</i><sub>d</sub>','kN',0,'预应力锚固力设计值','取1.2倍张拉控制力')), ('a',('<i>a</i>','mm',500,'锚垫板宽度')), ('d',('<i>d</i>','mm',0,'锚点距齿块自由边竖向距离')), ('e',('<i>e</i>','mm',0,'锚固力作用点至壁板中心的距离')), ('α',('<i>α</i>','rad',0,'预应力钢筋转向前后的切线夹角')), ('fsd',('<i>f</i><sub>sd</sub>','MPa',330,'钢筋抗拉强度设计值')), ('As1',('<i>A</i><sub>s</sub>','mm<sup>2</sup>',0,'锚下劈裂力配筋面积')), ('As2',('<i>A</i><sub>s</sub>','mm<sup>2</sup>',0,'齿块端面配筋面积')), ('As3',('<i>A</i><sub>s</sub>','mm<sup>2</sup>',0,'锚后牵拉配筋面积')), ('As4',('<i>A</i><sub>s</sub>','mm<sup>2</sup>',0,'局部受弯配筋面积')), ('As5',('<i>A</i><sub>s</sub>','mm<sup>2</sup>',0,'径向力配筋面积')), )) __deriveds__ = OrderedDict(( ('Tbd',('<i>T</i><sub>b,d</sub>','kN',1000,'锚下劈裂力设计值')), ('Tsd',('<i>T</i><sub>s,d</sub>','kN',1000,'齿块端面的拉力设计值')), ('Ttbd',('<i>T</i><sub>tb,d</sub>','kN',1000,'锚后牵拉力设计值')), ('Tetd',('<i>T</i><sub>et,d</sub>','kN',1000,'边缘局部弯曲引起的拉力设计值')), ('TRd',('<i>T</i><sub>R,d</sub>','kN',1000,'径向力作用引起的拉力设计值')), ('As',('<i>A</i><sub>s</sub>','mm<sup>2</sup>',0,'')), ('eql',('','kN',0,'')), ('eqr1',('','kN',0,'')), ('eqr2',('','kN',0,'')), ('eqr3',('','kN',0,'')), ('eqr4',('','kN',0,'')), ('eqr5',('','kN',0,'')), )) def solve(self): self.validate('positive','d','e') fTbd = lambda Pd,a,d: 0.25*Pd*(1-a/2/d) # (8.2.6-1) fTsd = lambda Pd:0.04*Pd # (8.2.6-2) fTtbd = lambda Pd:0.2*Pd # (8.2.6-3) fTetd = lambda Pd,e,d: (2*e-d)**2/12/e/(e+d)*Pd # (8.2.6-4) fTRd = lambda Pd,α: Pd*α # (8.2.6-5) self.Tbd = fTbd(self.Pd, self.a, self.d) self.Tsd = fTsd(self.Pd) self.Ttbd = fTtbd(self.Pd) self.Tetd = fTetd(self.Pd, self.e, self.d) self.TRd = fTRd(self.Pd, self.α) self.eqr1 = self.fsd*self.As1/1e3 self.eqr2 = self.fsd*self.As2/1e3 self.eqr3 = self.fsd*self.As3/1e3 self.eqr4 = self.fsd*self.As4/1e3 self.eqr5 = self.fsd*self.As5/1e3 def _html(self, digits=2): for attr in ('Pd','a','d','e','α','fsd'): yield self.format(attr, digits = None) yield self.format('As1') yield self.format('Tbd', eq='0.25·Pd·(1-a/2/d)') self.eql = self.γ0*self.Tbd ok = self.eql <= self.eqr1 yield '{} {} {}, {}满足规范第8.2.1条要求。'.format( self.format('eql', eq='γ0·Tbd'), '≤' if ok else '&gt;', self.format('eqr1',eq='fsd·As'), '' if ok else '不') yield self.format('As2') yield self.format('Tsd', eq='0.04·Pd') self.eql = self.γ0*self.Tsd ok = self.eql <= self.eqr2 yield '{} {} {}, {}满足规范第8.2.1条要求。'.format( self.format('eql', eq='γ0·Tsd'), '≤' if ok else '&gt;', self.format('eqr2',eq='fsd·As'), '' if ok else '不') yield self.format('As3') yield self.format('Ttbd', eq='0.2·Pd') self.eql = self.γ0*self.Ttbd ok = self.eql <= self.eqr3 yield '{} {} {}, {}满足规范第8.2.1条要求。'.format( self.format('eql', eq='γ0·Ttbd'), '≤' if ok else '&gt;', self.format('eqr3',eq='fsd·As'), '' if ok else '不') yield self.format('As4') yield self.format('Tetd', eq='(2·e-d)<sup>2</sup>/12/e/(e+d)·Pd') self.eql = self.γ0*self.Tetd ok = self.eql <= self.eqr4 yield '{} {} {}, {}满足规范第8.2.1条要求。'.format( self.format('eql', eq='γ0·Tetd'), '≤' if ok else '&gt;', self.format('eqr4',eq='fsd·As'), '' if ok else '不') yield self.format('As5') yield self.format('TRd', eq='Pd·α') self.eql = self.γ0*self.TRd ok = self.eql <= self.eqr5 yield '{} {} {}, {}满足规范第8.2.1条要求。'.format( self.format('eql', eq='γ0·TRd'), '≤' if ok else '&gt;', self.format('eqr5',eq='fsd·As'), '' if ok else '不')
import CoreUtils from './core.utils'; import Validators from './core.validators'; /** * Compute/test intersection between different objects. * * @module core/intersections */ export default class Intersections { /** * Compute intersection between oriented bounding box and a plane. * * Returns intersection in plane's space. * * Should return at least 3 intersections. If not, the plane and the box do not * intersect. * * @param {Object} aabb - Axe Aligned Bounding Box representation. * @param {THREE.Vector3} aabb.halfDimensions - Half dimensions of the box. * @param {THREE.Vector3} aabb.center - Center of the box. * @param {THREE.Matrix4} aabb.toAABB - Transform to go from plane space to box space. * @param {Object} plane - Plane representation * @param {THREE.Vector3} plane.position - position of normal which describes the plane. * @param {THREE.Vector3} plane.direction - Direction of normal which describes the plane. * * @returns {Array<THREE.Vector3>} List of all intersections in plane's space. * @returns {boolean} false is invalid input provided. * * @example * //Returns array with intersection N intersections * let aabb = { * center: new THREE.Vector3(150, 150, 150), * halfDimensions: new THREE.Vector3(50, 60, 70), * toAABB: new THREE.Matrix4() * } * let plane = { * position: new THREE.Vector3(110, 120, 130), * direction: new THREE.Vector3(1, 0, 0) * } * * let intersections = CoreIntersections.aabbPlane(aabb, plane); * // intersections == * //[ { x : 110, y : 90, z : 80 }, * // { x : 110, y : 210, z : 220 }, * // { x : 110, y : 210, z : 80 }, * // { x : 110, y : 90, z : 220 } ] * * //Returns empty array with 0 intersections * let aabb = { * * } * let plane = { * * } * * let intersections = VJS.Core.Validators.matrix4(new THREE.Vector3()); * * //Returns false if invalid input? * */ static aabbPlane(aabb, plane) { // // obb = { halfDimensions, orientation, center, toAABB } // plane = { position, direction } // // // LOGIC: // // Test intersection of each edge of the Oriented Bounding Box with the Plane // // ALL EDGES // // .+-------+ // .' | .'| // +---+---+' | // | | | | // | ,+---+---+ // |.' | .' // +-------+' // // SPACE ORIENTATION // // + // j | // | // | i // k ,+-------+ // .' // + // // // 1- Move Plane position and orientation in IJK space // 2- Test Edges/ IJK Plane intersections // 3- Return intersection Edge/ IJK Plane if it touches the Oriented BBox let intersections = []; if (!(this.validateAabb(aabb) && this.validatePlane(plane))) { window.console.log('Invalid aabb or plane provided.'); return false; } // invert space matrix let fromAABB = new THREE.Matrix4(); fromAABB.getInverse(aabb.toAABB); let t1 = plane.direction.clone().applyMatrix4(aabb.toAABB); let t0 = new THREE.Vector3(0, 0, 0).applyMatrix4(aabb.toAABB); let planeAABB = this.posdir( plane.position.clone().applyMatrix4(aabb.toAABB), new THREE.Vector3(t1.x - t0.x, t1.y - t0.y, t1.z - t0.z).normalize() ); let bbox = CoreUtils.bbox(aabb.center, aabb.halfDimensions); let orientation = new THREE.Vector3( new THREE.Vector3(1, 0, 0), new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, 0, 1)); // 12 edges (i.e. ray)/plane intersection tests // RAYS STARTING FROM THE FIRST CORNER (0, 0, 0) // // + // | // | // | // ,+---+---+ // .' // + let ray = this.posdir( new THREE.Vector3( aabb.center.x - aabb.halfDimensions.x, aabb.center.y - aabb.halfDimensions.y, aabb.center.z - aabb.halfDimensions.z), orientation.x ); this.rayPlaneInBBox(ray, planeAABB, bbox, intersections); ray.direction = orientation.y; this.rayPlaneInBBox(ray, planeAABB, bbox, intersections); ray.direction = orientation.z; this.rayPlaneInBBox(ray, planeAABB, bbox, intersections); // RAYS STARTING FROM THE LAST CORNER // // + // .' // +-------+' // | // | // | // + // let ray2 = this.posdir( new THREE.Vector3( aabb.center.x + aabb.halfDimensions.x, aabb.center.y + aabb.halfDimensions.y, aabb.center.z + aabb.halfDimensions.z), orientation.x ); this.rayPlaneInBBox(ray2, planeAABB, bbox, intersections); ray2.direction = orientation.y; this.rayPlaneInBBox(ray2, planeAABB, bbox, intersections); ray2.direction = orientation.z; this.rayPlaneInBBox(ray2, planeAABB, bbox, intersections); // RAYS STARTING FROM THE SECOND CORNER // // + // | // | // | // + // .' // +' let ray3 = this.posdir( new THREE.Vector3( aabb.center.x + aabb.halfDimensions.x, aabb.center.y - aabb.halfDimensions.y, aabb.center.z - aabb.halfDimensions.z), orientation.y ); this.rayPlaneInBBox(ray3, planeAABB, bbox, intersections); ray3.direction = orientation.z; this.rayPlaneInBBox(ray3, planeAABB, bbox, intersections); // RAYS STARTING FROM THE THIRD CORNER // // .+-------+ // .' // + // // // // let ray4 = this.posdir( new THREE.Vector3( aabb.center.x - aabb.halfDimensions.x, aabb.center.y + aabb.halfDimensions.y, aabb.center.z - aabb.halfDimensions.z), orientation.x ); this.rayPlaneInBBox(ray4, planeAABB, bbox, intersections); ray4.direction = orientation.z; this.rayPlaneInBBox(ray4, planeAABB, bbox, intersections); // RAYS STARTING FROM THE FOURTH CORNER // // // // + // | // | // | // +-------+ let ray5 = this.posdir( new THREE.Vector3( aabb.center.x - aabb.halfDimensions.x, aabb.center.y - aabb.halfDimensions.y, aabb.center.z + aabb.halfDimensions.z), orientation.x ); this.rayPlaneInBBox(ray5, planeAABB, bbox, intersections); ray5.direction = orientation.y; this.rayPlaneInBBox(ray5, planeAABB, bbox, intersections); // @todo make sure objects are unique... // back to original space intersections.map( function(element) { return element.applyMatrix4(fromAABB); } ); return intersections; } /** * Compute intersection between a ray and a plane. * * @memberOf this * @public * * @param {Object} ray - Ray representation. * @param {THREE.Vector3} ray.position - position of normal which describes the ray. * @param {THREE.Vector3} ray.direction - Direction of normal which describes the ray. * @param {Object} plane - Plane representation * @param {THREE.Vector3} plane.position - position of normal which describes the plane. * @param {THREE.Vector3} plane.direction - Direction of normal which describes the plane. * * @returns {THREE.Vector3|null} Intersection between ray and plane or null. */ static rayPlane(ray, plane) { // ray: {position, direction} // plane: {position, direction} if (ray.direction.dot(plane.direction) !== 0) { // // not parallel, move forward // // LOGIC: // // Ray equation: P = P0 + tV // P = <Px, Py, Pz> // P0 = <ray.position.x, ray.position.y, ray.position.z> // V = <ray.direction.x, ray.direction.y, ray.direction.z> // // Therefore: // Px = ray.position.x + t*ray.direction.x // Py = ray.position.y + t*ray.direction.y // Pz = ray.position.z + t*ray.direction.z // // // // Plane equation: ax + by + cz + d = 0 // a = plane.direction.x // b = plane.direction.y // c = plane.direction.z // d = -( plane.direction.x*plane.position.x + // plane.direction.y*plane.position.y + // plane.direction.z*plane.position.z ) // // // 1- in the plane equation, we replace x, y and z by Px, Py and Pz // 2- find t // 3- replace t in Px, Py and Pz to get the coordinate of the intersection // let t = (plane.direction.x * (plane.position.x - ray.position.x) + plane.direction.y * (plane.position.y - ray.position.y) + plane.direction.z * (plane.position.z - ray.position.z)) / (plane.direction.x * ray.direction.x + plane.direction.y * ray.direction.y + plane.direction.z * ray.direction.z); let intersection = new THREE.Vector3( ray.position.x + t * ray.direction.x, ray.position.y + t * ray.direction.y, ray.position.z + t * ray.direction.z); return intersection; } return null; } /** * Compute intersection between a ray and a box * @param {Object} ray * @param {Object} box * @return {Array} */ static rayBox(ray, box) { // should also do the space transforms here // ray: {position, direction} // box: {halfDimensions, center} let intersections = []; let bbox = CoreUtils.bbox(box.center, box.halfDimensions); // window.console.log(bbox); // X min let plane = this.posdir( new THREE.Vector3( bbox.min.x, box.center.y, box.center.z), new THREE.Vector3(-1, 0, 0) ); this.rayPlaneInBBox(ray, plane, bbox, intersections); // X max plane = this.posdir( new THREE.Vector3( bbox.max.x, box.center.y, box.center.z), new THREE.Vector3(1, 0, 0) ); this.rayPlaneInBBox(ray, plane, bbox, intersections); // Y min plane = this.posdir( new THREE.Vector3( box.center.x, bbox.min.y, box.center.z), new THREE.Vector3(0, -1, 0) ); this.rayPlaneInBBox(ray, plane, bbox, intersections); // Y max plane = this.posdir( new THREE.Vector3( box.center.x, bbox.max.y, box.center.z), new THREE.Vector3(0, 1, 0) ); this.rayPlaneInBBox(ray, plane, bbox, intersections); // Z min plane = this.posdir( new THREE.Vector3( box.center.x, box.center.y, bbox.min.z), new THREE.Vector3(0, 0, -1) ); this.rayPlaneInBBox(ray, plane, bbox, intersections); // Z max plane = this.posdir( new THREE.Vector3( box.center.x, box.center.y, bbox.max.z), new THREE.Vector3(0, 0, 1) ); this.rayPlaneInBBox(ray, plane, bbox, intersections); return intersections; } /** * Intersection between ray and a plane that are in a box. * @param {*} ray * @param {*} planeAABB * @param {*} bbox * @param {*} intersections */ static rayPlaneInBBox(ray, planeAABB, bbox, intersections) { let intersection = this.rayPlane(ray, planeAABB); // window.console.log(intersection); if (intersection && this.inBBox(intersection, bbox)) { if (!intersections.find(this.findIntersection(intersection))) { intersections.push(intersection); } } } /** * Find intersection in array * @param {*} myintersection */ static findIntersection(myintersection) { return function found(element, index, array) { if (myintersection.x === element.x && myintersection.y === element.y && myintersection.z === element.z) { return true; } return false; }; } /** * Is point in box. * @param {Object} point * @param {Object} bbox * @return {Boolean} */ static inBBox(point, bbox) { // let epsilon = 0.0001; if (point && point.x >= bbox.min.x - epsilon && point.y >= bbox.min.y - epsilon && point.z >= bbox.min.z - epsilon && point.x <= bbox.max.x + epsilon && point.y <= bbox.max.y + epsilon && point.z <= bbox.max.z + epsilon) { return true; } return false; } static posdir(position, direction) { return {position, direction}; } static validatePlane(plane) { // if (plane === null) { window.console.log('Invalid plane.'); window.console.log(plane); return false; } if (!Validators.vector3(plane.position)) { window.console.log('Invalid plane.position.'); window.console.log(plane.position); return false; } if (!Validators.vector3(plane.direction)) { window.console.log('Invalid plane.direction.'); window.console.log(plane.direction); return false; } return true; } static validateAabb(aabb) { // if (aabb === null) { window.console.log('Invalid aabb.'); window.console.log(aabb); return false; } if (!Validators.matrix4(aabb.toAABB)) { window.console.log('Invalid aabb.toAABB: '); window.console.log(aabb.toAABB); return false; } if (!Validators.vector3(aabb.center)) { window.console.log('Invalid aabb.center.'); window.console.log(aabb.center); return false; } if (!(Validators.vector3(aabb.halfDimensions) && aabb.halfDimensions.x >= 0 && aabb.halfDimensions.y >= 0 && aabb.halfDimensions.z >= 0)) { window.console.log('Invalid aabb.halfDimensions.'); window.console.log(aabb.halfDimensions); return false; } return true; } }
// NOTE: the prop internal directive is compiled and linked // during _initScope(), before the created hook is called. // The purpose is to make the initial prop values available // inside `created` hooks and `data` functions. import Watcher from '../../watcher' import config from '../../config' import { assertProp, initProp } from '../../util/index' const bindingModes = config._propBindingModes export default { bind () { var child = this.vm var parent = child._context // passed in from compiler directly var prop = this.descriptor.prop var childKey = prop.path var parentKey = prop.parentPath var twoWay = prop.mode === bindingModes.TWO_WAY var parentWatcher = this.parentWatcher = new Watcher( parent, parentKey, function (val) { if (assertProp(prop, val)) { child[childKey] = val } }, { twoWay: twoWay, filters: prop.filters, // important: props need to be observed on the // v-for scope if present scope: this._scope } ) // set the child initial value. initProp(child, prop, parentWatcher.value) // setup two-way binding if (twoWay) { // important: defer the child watcher creation until // the created hook (after data observation) var self = this child.$once('hook:created', function () { self.childWatcher = new Watcher( child, childKey, function (val) { parentWatcher.set(val) }, { // ensure sync upward before parent sync down. // this is necessary in cases e.g. the child // mutates a prop array, then replaces it. (#1683) sync: true } ) }) } }, unbind () { this.parentWatcher.teardown() if (this.childWatcher) { this.childWatcher.teardown() } } }
import RPi.GPIO as GPIO import binascii import time GPIO.setmode(GPIO.BCM) GPIO.setup(12, GPIO.OUT) GPIO.setup(16, GPIO.OUT) GPIO.setup(5, GPIO.OUT) GPIO.setup(6, GPIO.OUT) GPIO.setup(13, GPIO.OUT) GPIO.setup(19, GPIO.OUT) pin = [12, 16, 5, 6, 13, 19] k = 0 st="110101011010111" cols = 6 rows = len(st)/3 arr = [[0]*cols]*rows for i in range(rows): if st[k] == '0': arr[i][0] = 1 else: arr[i][1] = 1 if st[k+1] == '0' and st[k+2] == '0': arr[i][2] = 1 elif st[k+1] == '0' and st[k+2] == '1': arr[i][3] = 1 elif st[k+1] == '1' and st[k+2] == '0': arr[i][4] = 1 elif st[k+1] == '1' and st[k+2] == '1': arr[i][5] = 1 k = k+3 while True: for i in range(rows): for j in range(cols): GPIO.output(pin[j], arr[i][j]) time.sleep(0.01) GPIO.cleanup()
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @Author: Brian Cherinka, José Sánchez-Gallego, and Brett Andrews # @Date: 2017-03-20 # @Filename: conftest.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) # # @Last modified by: Brian Cherinka # @Last modified time: 2018-07-21 21:51:06 import copy import itertools import os import warnings from collections import OrderedDict import pytest import yaml from brain import bconfig from flask_jwt_extended import tokens from sdss_access.path import Path from marvin import config, marvindb from marvin.api.api import Interaction from marvin.tools.cube import Cube from marvin.tools.maps import Maps from marvin.tools.modelcube import ModelCube from marvin.tools.query import Query from marvin.utils.datamodel.dap import datamodel from marvin.utils.general import check_versions from brain.utils.general import get_yaml_loader warnings.simplefilter('always') # PYTEST MODIFIERS # ----------------- def pytest_addoption(parser): """Add new options""" # run slow tests parser.addoption('--runslow', action='store_true', default=False, help='Run slow tests.') # control releases run parser.addoption('--travis-only', action='store_true', default=False, help='Run a Travis only subset') def pytest_runtest_setup(item): """Skip slow tests.""" if 'slow' in item.keywords and not item.config.getoption('--runslow'): pytest.skip('Requires --runslow option to run.') def pytest_configure(config): ''' Runs during configuration of conftest. Checks and sets a global instance for a TravisSubset based on the pytest command line input of --travis-only ''' option = config.getoption('--travis-only') global travis if option: travis = TravisSubset() # specific release instance travis = None class TravisSubset(object): def __init__(self): self.new_gals = ['8485-1901'] self.new_releases = ['MPL-6'] self.new_bintypes = ['SPX', 'HYB10'] self.new_templates = ['GAU-MILESHC'] self.new_dbs = ['nodb'] self.new_origins = ['file', 'api'] self.new_modes = ['local', 'remote', 'auto'] # Global Parameters for FIXTURES # ------------------------------ #releases = ['MPL-6', 'MPL-5', 'MPL-4'] # to loop over releases (see release fixture) releases = ['MPL-8'] bintypes_accepted = {'MPL-4': ['NONE', 'VOR10'], 'MPL-5': ['SPX', 'VOR10'], 'MPL-6': ['SPX', 'HYB10'], 'MPL-7': ['HYB10', 'VOR10'], 'MPL-8': ['HYB10', 'SPX']} templates_accepted = {'MPL-4': ['MIUSCAT_THIN', 'MILES_THIN'], 'MPL-5': ['GAU-MILESHC'], 'MPL-6': ['GAU-MILESHC'], 'MPL-7': ['GAU-MILESHC'], 'MPL-8': ['MILESHC-MILESHC']} def populate_bintypes_templates(releases): ''' Generates bintype and template dictionaries for each release ''' bintypes = OrderedDict((release, []) for release in releases) templates = OrderedDict((release, []) for release in releases) for release in releases: bintemps = datamodel[release].get_bintemps() for bintemp in bintemps: bintype = bintemp.split('-')[0] template = '-'.join(bintemp.split('-')[1:]) if release in bintypes_accepted and bintype not in bintypes_accepted[release]: continue if release in templates_accepted and template not in templates_accepted[release]: continue if bintype not in bintypes[release]: bintypes[release].append(bintype) if template not in templates[release]: templates[release].append(template) return bintypes, templates bintypes, templates = populate_bintypes_templates(releases) # TODO reduce modes to only local and remote modes = ['local', 'remote', 'auto'] # to loop over modes (see mode fixture) dbs = ['db', 'nodb'] # to loop over dbs (see db fixture) origins = ['file', 'db', 'api'] # to loop over data origins (see data_origin fixture) # Galaxy and Query data is stored in a YAML file with open(os.path.join(os.path.dirname(__file__), 'data/galaxy_test_data.dat')) as f: galaxy_data = yaml.load(f, Loader=get_yaml_loader()) with open(os.path.join(os.path.dirname(__file__), 'data/query_test_data.dat')) as f: query_data = yaml.load(f, Loader=get_yaml_loader()) @pytest.fixture(scope='session', params=releases) def release(request): """Yield a release.""" if travis and request.param not in travis.new_releases: pytest.skip('Skipping non-requested release') return request.param def _get_release_generator_chain(): """Return all valid combinations of (release, bintype, template).""" return itertools.chain(*[itertools.product([release], bintypes[release], templates[release]) for release in releases]) def _params_ids(fixture_value): """Return a test id for the release chain.""" return '-'.join(fixture_value) @pytest.fixture(scope='session', params=sorted(_get_release_generator_chain()), ids=_params_ids) def get_params(request): """Yield a tuple of (release, bintype, template).""" # placeholder until the marvin_test_if decorator works in 2.7 release, bintype, template = request.param if travis and release not in travis.new_releases: pytest.skip('Skipping non-requested release') if travis and bintype not in travis.new_bintypes: pytest.skip('Skipping non-requested bintype') if travis and template not in travis.new_templates: pytest.skip('Skipping non-requested template') return request.param @pytest.fixture(scope='session', params=sorted(galaxy_data.keys())) def plateifu(request): """Yield a plate-ifu.""" if travis and request.param not in travis.new_gals: pytest.skip('Skipping non-requested galaxies') return request.param @pytest.fixture(scope='session', params=origins) def data_origin(request): """Yield a data access mode.""" if travis and request.param not in travis.new_origins: pytest.skip('Skipping non-requested origins') return request.param @pytest.fixture(scope='session', params=modes) def mode(request): """Yield a data mode.""" if travis and request.param not in travis.new_modes: pytest.skip('Skipping non-requested modes') return request.param # Config-based FIXTURES # ---------------------- @pytest.fixture(scope='session', autouse=True) def set_config(): """Set config.""" config.use_sentry = False config.add_github_message = False config._traceback = None @pytest.fixture() def check_config(): """Check the config to see if a db is on.""" return config.db is None URLMAP = None def set_sasurl(loc='local', port=None): """Set the sasurl to local or test-utah, and regenerate the urlmap.""" if not port: port = int(os.environ.get('LOCAL_MARVIN_PORT', 5000)) istest = True if loc == 'utah' else False config.switchSasUrl(loc, test=istest, port=port) global URLMAP if not URLMAP: response = Interaction('/marvin/api/general/getroutemap', request_type='get', auth='netrc') config.urlmap = response.getRouteMap() URLMAP = config.urlmap @pytest.fixture(scope='session', autouse=True) def saslocal(): """Set sasurl to local.""" set_sasurl(loc='local') @pytest.fixture(scope='session') def urlmap(saslocal): """Yield the config urlmap.""" return config.urlmap @pytest.fixture(scope='session') def set_release(release): """Set the release in the config.""" config.setMPL(release) @pytest.fixture(scope='session') def versions(release): """Yield the DRP and DAP versions for a release.""" drpver, dapver = config.lookUpVersions(release) return drpver, dapver @pytest.fixture(scope='session') def drpver(versions): """Return DRP version.""" drpver, __ = versions return drpver @pytest.fixture(scope='session') def dapver(versions): """Return DAP version.""" __, dapver = versions return dapver def set_the_config(release): """Set config release without parametrizing. Using ``set_release`` combined with ``galaxy`` double parametrizes!""" config.access = 'collab' config.setRelease(release) set_sasurl(loc='local') config.login() config._traceback = None def custom_login(): config.token = tokens.encode_access_token('test', os.environ.get('MARVIN_SECRET'), 'HS256', False, True, 'user_claims', True, 'identity', 'user_claims') def custom_auth(self, authtype=None): authtype = 'token' super(Interaction, self).setAuth(authtype=authtype) # DB-based FIXTURES # ----------------- class DB(object): """Object representing aspects of the marvin db. Useful for tests needing direct DB access. """ def __init__(self): """Initialize with DBs.""" self._marvindb = marvindb self.session = marvindb.session self.datadb = marvindb.datadb self.sampledb = marvindb.sampledb self.dapdb = marvindb.dapdb @pytest.fixture(scope='session') def maindb(): """Yield an instance of the DB object.""" yield DB() @pytest.fixture(scope='function') def db_off(): """Turn the DB off for a test, and reset it after.""" config.forceDbOff() yield config.forceDbOn() @pytest.fixture(autouse=True) def db_on(): """Automatically turn on the DB at collection time.""" config.forceDbOn() @pytest.fixture() def usedb(request): ''' fixture for optional turning off the db ''' if request.param: config.forceDbOn() else: config.forceDbOff() return config.db is not None @pytest.fixture(params=dbs) def db(request): """Turn local db on or off. Use this to parametrize over all db options. """ if travis and request.param not in travis.new_dbs: pytest.skip('Skipping non-requested dbs') if request.param == 'db': config.forceDbOn() else: config.forceDbOff() yield config.db is not None config.forceDbOn() @pytest.fixture() def exporigin(mode, db): """Return the expected origins for a given db/mode combo.""" if mode == 'local' and not db: return 'file' elif mode == 'local' and db: return 'db' elif mode == 'remote' and not db: return 'api' elif mode == 'remote' and db: return 'api' elif mode == 'auto' and db: return 'db' elif mode == 'auto' and not db: return 'file' @pytest.fixture() def expmode(mode, db): ''' expected modes for a given db/mode combo ''' if mode == 'local' and not db: return None elif mode == 'local' and db: return 'local' elif mode == 'remote' and not db: return 'remote' elif mode == 'remote' and db: return 'remote' elif mode == 'auto' and db: return 'local' elif mode == 'auto' and not db: return 'remote' @pytest.fixture() def user(maindb): username = 'test' password = 'test' model = maindb.datadb.User user = maindb.session.query(model).filter(model.username == username).one_or_none() if not user: user = model(username=username, login_count=1) user.set_password(password) maindb.session.add(user) yield user maindb.session.delete(user) # Monkeypatch-based FIXTURES # -------------------------- @pytest.fixture() def monkeyconfig(request, monkeypatch): """Monkeypatch a variable on the Marvin config. Example at line 160 in utils/test_general. """ name, value = request.param monkeypatch.setattr(config, name, value=value) @pytest.fixture() def monkeymanga(monkeypatch, temp_scratch): """Monkeypatch the environ to create a temp SAS dir for reading/writing/downloading. Example at line 141 in utils/test_images. """ monkeypatch.setitem(os.environ, 'SAS_BASE_DIR', str(temp_scratch)) monkeypatch.setitem(os.environ, 'MANGA_SPECTRO_REDUX', str(temp_scratch.join('mangawork/manga/spectro/redux'))) monkeypatch.setitem(os.environ, 'MANGA_SPECTRO_ANALYSIS', str(temp_scratch.join('mangawork/manga/spectro/analysis'))) @pytest.fixture() def monkeyauth(monkeypatch): monkeypatch.setattr(config, 'login', custom_login) monkeypatch.setattr(Interaction, 'setAuth', custom_auth) monkeypatch.setattr(bconfig, '_public_api_url', config.sasurl) monkeypatch.setattr(bconfig, '_collab_api_url', config.sasurl) # Temp Dir/File-based FIXTURES # ---------------------------- @pytest.fixture(scope='function') def temp_scratch(tmpdir_factory): """Create a temporary scratch space for reading/writing. Use for creating temp dirs and files. Example at line 208 in tools/test_query, line 254 in tools/test_results, and misc/test_marvin_pickle. """ fn = tmpdir_factory.mktemp('scratch') return fn def tempafile(path, temp_scratch): """Return a pytest temporary file given the original file path. Example at line 141 in utils/test_images. """ redux = os.getenv('MANGA_SPECTRO_REDUX') anal = os.getenv('MANGA_SPECTRO_ANALYSIS') endredux = path.partition(redux)[-1] endanal = path.partition(anal)[-1] end = (endredux or endanal) return temp_scratch.join(end) # Object-based FIXTURES # --------------------- class Galaxy(object): """An example galaxy for Marvin-tools testing.""" sasbasedir = os.getenv('SAS_BASE_DIR') mangaredux = os.getenv('MANGA_SPECTRO_REDUX') mangaanalysis = os.getenv('MANGA_SPECTRO_ANALYSIS') dir3d = 'stack' def __init__(self, plateifu): """Initialize plate and ifu.""" self.plateifu = plateifu self.plate, self.ifu = self.plateifu.split('-') self.plate = int(self.plate) def set_galaxy_data(self, data_origin=None): """Set galaxy properties from the configuration file.""" if self.plateifu not in galaxy_data: return data = copy.deepcopy(galaxy_data[self.plateifu]) for key in data.keys(): setattr(self, key, data[key]) # sets specfic data per release releasedata = self.releasedata[self.release] for key in releasedata.keys(): setattr(self, key, releasedata[key]) # remap NSA drpall names for MPL-4 vs 5+ drpcopy = self.nsa_data['drpall'].copy() for key, val in self.nsa_data['drpall'].items(): if isinstance(val, list): newval, newkey = drpcopy.pop(key) if self.release == 'MPL-4': drpcopy[newkey] = newval else: drpcopy[key] = newval self.nsa_data['drpall'] = drpcopy def set_params(self, bintype=None, template=None, release=None): """Set bintype, template, etc.""" self.release = release self.drpver, self.dapver = config.lookUpVersions(self.release) self.drpall = 'drpall-{0}.fits'.format(self.drpver) self.bintype = datamodel[self.dapver].get_bintype(bintype) self.template = datamodel[self.dapver].get_template(template) self.bintemp = '{0}-{1}'.format(self.bintype.name, self.template.name) if release == 'MPL-4': self.niter = int('{0}{1}'.format(self.template.n, self.bintype.n)) else: self.niter = '*' self.access_kwargs = {'plate': self.plate, 'ifu': self.ifu, 'drpver': self.drpver, 'dapver': self.dapver, 'dir3d': self.dir3d, 'mpl': self.release, 'bintype': self.bintype.name, 'n': self.niter, 'mode': '*', 'daptype': self.bintemp} def set_filepaths(self, pathtype='full'): """Set the paths for cube, maps, etc.""" self.path = Path() if check_versions(self.drpver, 'v2_5_3'): self.imgpath = self.path.__getattribute__(pathtype)('mangaimagenew', **self.access_kwargs) else: self.imgpath = self.path.__getattribute__(pathtype)('mangaimage', **self.access_kwargs) self.cubepath = self.path.__getattribute__(pathtype)('mangacube', **self.access_kwargs) self.rsspath = self.path.__getattribute__(pathtype)('mangarss', **self.access_kwargs) if self.release == 'MPL-4': self.mapspath = self.path.__getattribute__(pathtype)('mangamap', **self.access_kwargs) self.modelpath = None else: self.access_kwargs.pop('mode') self.mapspath = self.path.__getattribute__(pathtype)('mangadap5', mode='MAPS', **self.access_kwargs) self.modelpath = self.path.__getattribute__(pathtype)('mangadap5', mode='LOGCUBE', **self.access_kwargs) def get_location(self, path): """Extract the location from the input path.""" return self.path.location("", full=path) def partition_path(self, path): """Partition the path into non-redux/analysis parts.""" endredux = path.partition(self.mangaredux)[-1] endanalysis = path.partition(self.mangaanalysis)[-1] end = (endredux or endanalysis) return end def new_path(self, name, newvar): ''' Sets a new path with the subsituted name ''' access_copy = self.access_kwargs.copy() access_copy['mode'] = '*' access_copy.update(**newvar) if name == 'maps': access_copy['mode'] = 'MAPS' name = 'mangamap' if self.release == 'MPL-4' else 'mangadap5' elif name == 'modelcube': access_copy['mode'] = 'LOGCUBE' name = None if self.release == 'MPL-4' else 'mangadap5' path = self.path.full(name, **access_copy) if name else None return path @pytest.fixture(scope='function') def galaxy(monkeyauth, get_params, plateifu): """Yield an instance of a Galaxy object for use in tests.""" release, bintype, template = get_params set_the_config(release) gal = Galaxy(plateifu=plateifu) gal.set_params(bintype=bintype, template=template, release=release) gal.set_filepaths() gal.set_galaxy_data() yield gal gal = None @pytest.fixture(scope='function') def cube(galaxy, exporigin, mode): ''' Yield a Marvin Cube based on the expected origin combo of (mode+db). Fixture tests 6 cube origins from (mode+db) combos [file, db and api] ''' if str(galaxy.bintype) != 'SPX': pytest.skip() if exporigin == 'file': c = Cube(filename=galaxy.cubepath, release=galaxy.release, mode=mode) else: c = Cube(plateifu=galaxy.plateifu, release=galaxy.release, mode=mode) c.exporigin = exporigin c.initial_mode = mode yield c c = None @pytest.fixture(scope='function') def modelcube(galaxy, exporigin, mode): ''' Yield a Marvin ModelCube based on the expected origin combo of (mode+db). Fixture tests 6 modelcube origins from (mode+db) combos [file, db and api] ''' if exporigin == 'file': mc = ModelCube(filename=galaxy.modelpath, release=galaxy.release, mode=mode, bintype=galaxy.bintype) else: mc = ModelCube(plateifu=galaxy.plateifu, release=galaxy.release, mode=mode, bintype=galaxy.bintype) mc.exporigin = exporigin mc.initial_mode = mode yield mc mc = None @pytest.fixture(scope='function') def maps(galaxy, exporigin, mode): ''' Yield a Marvin Maps based on the expected origin combo of (mode+db). Fixture tests 6 cube origins from (mode+db) combos [file, db and api] ''' if exporigin == 'file': m = Maps(filename=galaxy.mapspath, release=galaxy.release, mode=mode, bintype=galaxy.bintype) else: m = Maps(plateifu=galaxy.plateifu, release=galaxy.release, mode=mode, bintype=galaxy.bintype) m.exporigin = exporigin yield m m = None modes = ['local', 'remote', 'auto'] # to loop over modes (see mode fixture) dbs = ['db', 'nodb'] # to loop over dbs (see db fixture) origins = ['file', 'db', 'api'] # to loop over data origins (see data_origin fixture) @pytest.fixture(scope='class') def maps_release_only(release): return Maps(plateifu='8485-1901', release=release) @pytest.fixture(scope='function') def query(request, allow_dap, monkeyauth, release, mode, db): ''' Yields a Query that loops over all modes and db options ''' data = query_data[release] set_the_config(release) if mode == 'local' and not db: pytest.skip('cannot use queries in local mode without a db') searchfilter = request.param if hasattr(request, 'param') else None q = Query(search_filter=searchfilter, mode=mode, release=release) q.expdata = data if q.mode == 'remote': pytest.xfail('cannot control for DAP spaxel queries on server side; failing all remotes until then') yield q config.forceDbOn() q = None # @pytest.fixture(autouse=True) # def skipall(): # pytest.skip('skipping everything')
# -*- coding: utf-8 -*- """ Internal module for formatting output data in csv, html, and latex files. This module also applies to display formatting. """ from __future__ import print_function from functools import partial import numpy as np from pandas._libs import lib from pandas._libs.tslib import format_array_from_datetime from pandas._libs.tslibs import NaT, Timedelta, Timestamp, iNaT from pandas.compat import StringIO, lzip, map, u, zip from pandas.core.dtypes.common import ( is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype, is_extension_array_dtype, is_float, is_float_dtype, is_integer, is_integer_dtype, is_list_like, is_numeric_dtype, is_scalar, is_timedelta64_dtype) from pandas.core.dtypes.generic import ( ABCIndexClass, ABCMultiIndex, ABCSeries, ABCSparseArray) from pandas.core.dtypes.missing import isna, notna from pandas import compat from pandas.core.base import PandasObject import pandas.core.common as com from pandas.core.config import get_option, set_option from pandas.core.index import Index, ensure_index from pandas.core.indexes.datetimes import DatetimeIndex from pandas.io.common import _expand_user, _stringify_path from pandas.io.formats.printing import adjoin, justify, pprint_thing from pandas.io.formats.terminal import get_terminal_size # pylint: disable=W0141 common_docstring = """ Parameters ---------- buf : StringIO-like, optional Buffer to write to. columns : sequence, optional, default None The subset of columns to write. Writes all columns by default. col_space : int, optional The minimum width of each column. header : bool, optional %(header)s. index : bool, optional, default True Whether to print index (row) labels. na_rep : str, optional, default 'NaN' String representation of NAN to use. formatters : list or dict of one-param. functions, optional Formatter functions to apply to columns' elements by position or name. The result of each function must be a unicode string. List must be of length equal to the number of columns. float_format : one-parameter function, optional, default None Formatter function to apply to columns' elements if they are floats. The result of this function must be a unicode string. sparsify : bool, optional, default True Set to False for a DataFrame with a hierarchical index to print every multiindex key at each row. index_names : bool, optional, default True Prints the names of the indexes. justify : str, default None How to justify the column labels. If None uses the option from the print configuration (controlled by set_option), 'right' out of the box. Valid values are * left * right * center * justify * justify-all * start * end * inherit * match-parent * initial * unset. max_rows : int, optional Maximum number of rows to display in the console. max_cols : int, optional Maximum number of columns to display in the console. show_dimensions : bool, default False Display DataFrame dimensions (number of rows by number of columns). decimal : str, default '.' Character recognized as decimal separator, e.g. ',' in Europe. .. versionadded:: 0.18.0 """ _VALID_JUSTIFY_PARAMETERS = ("left", "right", "center", "justify", "justify-all", "start", "end", "inherit", "match-parent", "initial", "unset") return_docstring = """ Returns ------- str (or unicode, depending on data and options) String representation of the dataframe. """ class CategoricalFormatter(object): def __init__(self, categorical, buf=None, length=True, na_rep='NaN', footer=True): self.categorical = categorical self.buf = buf if buf is not None else StringIO(u("")) self.na_rep = na_rep self.length = length self.footer = footer def _get_footer(self): footer = '' if self.length: if footer: footer += ', ' footer += "Length: {length}".format(length=len(self.categorical)) level_info = self.categorical._repr_categories_info() # Levels are added in a newline if footer: footer += '\n' footer += level_info return compat.text_type(footer) def _get_formatted_values(self): return format_array(self.categorical.get_values(), None, float_format=None, na_rep=self.na_rep) def to_string(self): categorical = self.categorical if len(categorical) == 0: if self.footer: return self._get_footer() else: return u('') fmt_values = self._get_formatted_values() result = [u('{i}').format(i=i) for i in fmt_values] result = [i.strip() for i in result] result = u(', ').join(result) result = [u('[') + result + u(']')] if self.footer: footer = self._get_footer() if footer: result.append(footer) return compat.text_type(u('\n').join(result)) class SeriesFormatter(object): def __init__(self, series, buf=None, length=True, header=True, index=True, na_rep='NaN', name=False, float_format=None, dtype=True, max_rows=None): self.series = series self.buf = buf if buf is not None else StringIO() self.name = name self.na_rep = na_rep self.header = header self.length = length self.index = index self.max_rows = max_rows if float_format is None: float_format = get_option("display.float_format") self.float_format = float_format self.dtype = dtype self.adj = _get_adjustment() self._chk_truncate() def _chk_truncate(self): from pandas.core.reshape.concat import concat max_rows = self.max_rows truncate_v = max_rows and (len(self.series) > max_rows) series = self.series if truncate_v: if max_rows == 1: row_num = max_rows series = series.iloc[:max_rows] else: row_num = max_rows // 2 series = concat((series.iloc[:row_num], series.iloc[-row_num:])) self.tr_row_num = row_num self.tr_series = series self.truncate_v = truncate_v def _get_footer(self): name = self.series.name footer = u('') if getattr(self.series.index, 'freq', None) is not None: footer += 'Freq: {freq}'.format(freq=self.series.index.freqstr) if self.name is not False and name is not None: if footer: footer += ', ' series_name = pprint_thing(name, escape_chars=('\t', '\r', '\n')) footer += ((u"Name: {sname}".format(sname=series_name)) if name is not None else "") if (self.length is True or (self.length == 'truncate' and self.truncate_v)): if footer: footer += ', ' footer += 'Length: {length}'.format(length=len(self.series)) if self.dtype is not False and self.dtype is not None: name = getattr(self.tr_series.dtype, 'name', None) if name: if footer: footer += ', ' footer += u'dtype: {typ}'.format(typ=pprint_thing(name)) # level infos are added to the end and in a new line, like it is done # for Categoricals if is_categorical_dtype(self.tr_series.dtype): level_info = self.tr_series._values._repr_categories_info() if footer: footer += "\n" footer += level_info return compat.text_type(footer) def _get_formatted_index(self): index = self.tr_series.index is_multi = isinstance(index, ABCMultiIndex) if is_multi: have_header = any(name for name in index.names) fmt_index = index.format(names=True) else: have_header = index.name is not None fmt_index = index.format(name=True) return fmt_index, have_header def _get_formatted_values(self): values_to_format = self.tr_series._formatting_values() return format_array(values_to_format, None, float_format=self.float_format, na_rep=self.na_rep) def to_string(self): series = self.tr_series footer = self._get_footer() if len(series) == 0: return 'Series([], ' + footer + ')' fmt_index, have_header = self._get_formatted_index() fmt_values = self._get_formatted_values() if self.truncate_v: n_header_rows = 0 row_num = self.tr_row_num width = self.adj.len(fmt_values[row_num - 1]) if width > 3: dot_str = '...' else: dot_str = '..' # Series uses mode=center because it has single value columns # DataFrame uses mode=left dot_str = self.adj.justify([dot_str], width, mode='center')[0] fmt_values.insert(row_num + n_header_rows, dot_str) fmt_index.insert(row_num + 1, '') if self.index: result = self.adj.adjoin(3, *[fmt_index[1:], fmt_values]) else: result = self.adj.adjoin(3, fmt_values) if self.header and have_header: result = fmt_index[0] + '\n' + result if footer: result += '\n' + footer return compat.text_type(u('').join(result)) class TextAdjustment(object): def __init__(self): self.encoding = get_option("display.encoding") def len(self, text): return compat.strlen(text, encoding=self.encoding) def justify(self, texts, max_len, mode='right'): return justify(texts, max_len, mode=mode) def adjoin(self, space, *lists, **kwargs): return adjoin(space, *lists, strlen=self.len, justfunc=self.justify, **kwargs) class EastAsianTextAdjustment(TextAdjustment): def __init__(self): super(EastAsianTextAdjustment, self).__init__() if get_option("display.unicode.ambiguous_as_wide"): self.ambiguous_width = 2 else: self.ambiguous_width = 1 def len(self, text): return compat.east_asian_len(text, encoding=self.encoding, ambiguous_width=self.ambiguous_width) def justify(self, texts, max_len, mode='right'): # re-calculate padding space per str considering East Asian Width def _get_pad(t): return max_len - self.len(t) + len(t) if mode == 'left': return [x.ljust(_get_pad(x)) for x in texts] elif mode == 'center': return [x.center(_get_pad(x)) for x in texts] else: return [x.rjust(_get_pad(x)) for x in texts] def _get_adjustment(): use_east_asian_width = get_option("display.unicode.east_asian_width") if use_east_asian_width: return EastAsianTextAdjustment() else: return TextAdjustment() class TableFormatter(object): is_truncated = False show_dimensions = None @property def should_show_dimensions(self): return (self.show_dimensions is True or (self.show_dimensions == 'truncate' and self.is_truncated)) def _get_formatter(self, i): if isinstance(self.formatters, (list, tuple)): if is_integer(i): return self.formatters[i] else: return None else: if is_integer(i) and i not in self.columns: i = self.columns[i] return self.formatters.get(i, None) class DataFrameFormatter(TableFormatter): """ Render a DataFrame self.to_string() : console-friendly tabular output self.to_html() : html table self.to_latex() : LaTeX tabular environment table """ __doc__ = __doc__ if __doc__ else '' __doc__ += common_docstring + return_docstring def __init__(self, frame, buf=None, columns=None, col_space=None, header=True, index=True, na_rep='NaN', formatters=None, justify=None, float_format=None, sparsify=None, index_names=True, line_width=None, max_rows=None, max_cols=None, show_dimensions=False, decimal='.', table_id=None, render_links=False, **kwds): self.frame = frame if buf is not None: self.buf = _expand_user(_stringify_path(buf)) else: self.buf = StringIO() self.show_index_names = index_names if sparsify is None: sparsify = get_option("display.multi_sparse") self.sparsify = sparsify self.float_format = float_format self.formatters = formatters if formatters is not None else {} self.na_rep = na_rep self.decimal = decimal self.col_space = col_space self.header = header self.index = index self.line_width = line_width self.max_rows = max_rows self.max_cols = max_cols self.max_rows_displayed = min(max_rows or len(self.frame), len(self.frame)) self.show_dimensions = show_dimensions self.table_id = table_id self.render_links = render_links if justify is None: self.justify = get_option("display.colheader_justify") else: self.justify = justify self.kwds = kwds if columns is not None: self.columns = ensure_index(columns) self.frame = self.frame[self.columns] else: self.columns = frame.columns self._chk_truncate() self.adj = _get_adjustment() def _chk_truncate(self): """ Checks whether the frame should be truncated. If so, slices the frame up. """ from pandas.core.reshape.concat import concat # Column of which first element is used to determine width of a dot col self.tr_size_col = -1 # Cut the data to the information actually printed max_cols = self.max_cols max_rows = self.max_rows if max_cols == 0 or max_rows == 0: # assume we are in the terminal # (why else = 0) (w, h) = get_terminal_size() self.w = w self.h = h if self.max_rows == 0: dot_row = 1 prompt_row = 1 if self.show_dimensions: show_dimension_rows = 3 n_add_rows = (self.header + dot_row + show_dimension_rows + prompt_row) # rows available to fill with actual data max_rows_adj = self.h - n_add_rows self.max_rows_adj = max_rows_adj # Format only rows and columns that could potentially fit the # screen if max_cols == 0 and len(self.frame.columns) > w: max_cols = w if max_rows == 0 and len(self.frame) > h: max_rows = h if not hasattr(self, 'max_rows_adj'): self.max_rows_adj = max_rows if not hasattr(self, 'max_cols_adj'): self.max_cols_adj = max_cols max_cols_adj = self.max_cols_adj max_rows_adj = self.max_rows_adj truncate_h = max_cols_adj and (len(self.columns) > max_cols_adj) truncate_v = max_rows_adj and (len(self.frame) > max_rows_adj) frame = self.frame if truncate_h: if max_cols_adj == 0: col_num = len(frame.columns) elif max_cols_adj == 1: frame = frame.iloc[:, :max_cols] col_num = max_cols else: col_num = (max_cols_adj // 2) frame = concat((frame.iloc[:, :col_num], frame.iloc[:, -col_num:]), axis=1) self.tr_col_num = col_num if truncate_v: if max_rows_adj == 1: row_num = max_rows frame = frame.iloc[:max_rows, :] else: row_num = max_rows_adj // 2 frame = concat((frame.iloc[:row_num, :], frame.iloc[-row_num:, :])) self.tr_row_num = row_num self.tr_frame = frame self.truncate_h = truncate_h self.truncate_v = truncate_v self.is_truncated = self.truncate_h or self.truncate_v def _to_str_columns(self): """ Render a DataFrame to a list of columns (as lists of strings). """ frame = self.tr_frame # may include levels names also str_index = self._get_formatted_index(frame) if not is_list_like(self.header) and not self.header: stringified = [] for i, c in enumerate(frame): fmt_values = self._format_col(i) fmt_values = _make_fixed_width(fmt_values, self.justify, minimum=(self.col_space or 0), adj=self.adj) stringified.append(fmt_values) else: if is_list_like(self.header): if len(self.header) != len(self.columns): raise ValueError(('Writing {ncols} cols but got {nalias} ' 'aliases' .format(ncols=len(self.columns), nalias=len(self.header)))) str_columns = [[label] for label in self.header] else: str_columns = self._get_formatted_column_labels(frame) stringified = [] for i, c in enumerate(frame): cheader = str_columns[i] header_colwidth = max(self.col_space or 0, *(self.adj.len(x) for x in cheader)) fmt_values = self._format_col(i) fmt_values = _make_fixed_width(fmt_values, self.justify, minimum=header_colwidth, adj=self.adj) max_len = max(max(self.adj.len(x) for x in fmt_values), header_colwidth) cheader = self.adj.justify(cheader, max_len, mode=self.justify) stringified.append(cheader + fmt_values) strcols = stringified if self.index: strcols.insert(0, str_index) # Add ... to signal truncated truncate_h = self.truncate_h truncate_v = self.truncate_v if truncate_h: col_num = self.tr_col_num # infer from column header col_width = self.adj.len(strcols[self.tr_size_col][0]) strcols.insert(self.tr_col_num + 1, ['...'.center(col_width)] * (len(str_index))) if truncate_v: n_header_rows = len(str_index) - len(frame) row_num = self.tr_row_num for ix, col in enumerate(strcols): # infer from above row cwidth = self.adj.len(strcols[ix][row_num]) is_dot_col = False if truncate_h: is_dot_col = ix == col_num + 1 if cwidth > 3 or is_dot_col: my_str = '...' else: my_str = '..' if ix == 0: dot_mode = 'left' elif is_dot_col: cwidth = self.adj.len(strcols[self.tr_size_col][0]) dot_mode = 'center' else: dot_mode = 'right' dot_str = self.adj.justify([my_str], cwidth, mode=dot_mode)[0] strcols[ix].insert(row_num + n_header_rows, dot_str) return strcols def to_string(self): """ Render a DataFrame to a console-friendly tabular output. """ from pandas import Series frame = self.frame if len(frame.columns) == 0 or len(frame.index) == 0: info_line = (u('Empty {name}\nColumns: {col}\nIndex: {idx}') .format(name=type(self.frame).__name__, col=pprint_thing(frame.columns), idx=pprint_thing(frame.index))) text = info_line else: strcols = self._to_str_columns() if self.line_width is None: # no need to wrap around just print # the whole frame text = self.adj.adjoin(1, *strcols) elif (not isinstance(self.max_cols, int) or self.max_cols > 0): # need to wrap around text = self._join_multiline(*strcols) else: # max_cols == 0. Try to fit frame to terminal text = self.adj.adjoin(1, *strcols).split('\n') max_len = Series(text).str.len().max() # plus truncate dot col dif = max_len - self.w # '+ 1' to avoid too wide repr (GH PR #17023) adj_dif = dif + 1 col_lens = Series([Series(ele).apply(len).max() for ele in strcols]) n_cols = len(col_lens) counter = 0 while adj_dif > 0 and n_cols > 1: counter += 1 mid = int(round(n_cols / 2.)) mid_ix = col_lens.index[mid] col_len = col_lens[mid_ix] # adjoin adds one adj_dif -= (col_len + 1) col_lens = col_lens.drop(mid_ix) n_cols = len(col_lens) # subtract index column max_cols_adj = n_cols - self.index # GH-21180. Ensure that we print at least two. max_cols_adj = max(max_cols_adj, 2) self.max_cols_adj = max_cols_adj # Call again _chk_truncate to cut frame appropriately # and then generate string representation self._chk_truncate() strcols = self._to_str_columns() text = self.adj.adjoin(1, *strcols) self.buf.writelines(text) if self.should_show_dimensions: self.buf.write("\n\n[{nrows} rows x {ncols} columns]" .format(nrows=len(frame), ncols=len(frame.columns))) def _join_multiline(self, *strcols): lwidth = self.line_width adjoin_width = 1 strcols = list(strcols) if self.index: idx = strcols.pop(0) lwidth -= np.array([self.adj.len(x) for x in idx]).max() + adjoin_width col_widths = [np.array([self.adj.len(x) for x in col]).max() if len(col) > 0 else 0 for col in strcols] col_bins = _binify(col_widths, lwidth) nbins = len(col_bins) if self.truncate_v: nrows = self.max_rows_adj + 1 else: nrows = len(self.frame) str_lst = [] st = 0 for i, ed in enumerate(col_bins): row = strcols[st:ed] if self.index: row.insert(0, idx) if nbins > 1: if ed <= len(strcols) and i < nbins - 1: row.append([' \\'] + [' '] * (nrows - 1)) else: row.append([' '] * nrows) str_lst.append(self.adj.adjoin(adjoin_width, *row)) st = ed return '\n\n'.join(str_lst) def to_latex(self, column_format=None, longtable=False, encoding=None, multicolumn=False, multicolumn_format=None, multirow=False): """ Render a DataFrame to a LaTeX tabular/longtable environment output. """ from pandas.io.formats.latex import LatexFormatter latex_renderer = LatexFormatter(self, column_format=column_format, longtable=longtable, multicolumn=multicolumn, multicolumn_format=multicolumn_format, multirow=multirow) if encoding is None: encoding = 'ascii' if compat.PY2 else 'utf-8' if hasattr(self.buf, 'write'): latex_renderer.write_result(self.buf) elif isinstance(self.buf, compat.string_types): import codecs with codecs.open(self.buf, 'w', encoding=encoding) as f: latex_renderer.write_result(f) else: raise TypeError('buf is not a file name and it has no write ' 'method') def _format_col(self, i): frame = self.tr_frame formatter = self._get_formatter(i) values_to_format = frame.iloc[:, i]._formatting_values() return format_array(values_to_format, formatter, float_format=self.float_format, na_rep=self.na_rep, space=self.col_space, decimal=self.decimal) def to_html(self, classes=None, notebook=False, border=None): """ Render a DataFrame to a html table. Parameters ---------- classes : str or list-like classes to include in the `class` attribute of the opening ``<table>`` tag, in addition to the default "dataframe". notebook : {True, False}, optional, default False Whether the generated HTML is for IPython Notebook. border : int A ``border=border`` attribute is included in the opening ``<table>`` tag. Default ``pd.options.html.border``. .. versionadded:: 0.19.0 """ from pandas.io.formats.html import HTMLFormatter html_renderer = HTMLFormatter(self, classes=classes, notebook=notebook, border=border, table_id=self.table_id, render_links=self.render_links) if hasattr(self.buf, 'write'): html_renderer.write_result(self.buf) elif isinstance(self.buf, compat.string_types): with open(self.buf, 'w') as f: html_renderer.write_result(f) else: raise TypeError('buf is not a file name and it has no write ' ' method') def _get_formatted_column_labels(self, frame): from pandas.core.index import _sparsify columns = frame.columns if isinstance(columns, ABCMultiIndex): fmt_columns = columns.format(sparsify=False, adjoin=False) fmt_columns = lzip(*fmt_columns) dtypes = self.frame.dtypes._values # if we have a Float level, they don't use leading space at all restrict_formatting = any(l.is_floating for l in columns.levels) need_leadsp = dict(zip(fmt_columns, map(is_numeric_dtype, dtypes))) def space_format(x, y): if (y not in self.formatters and need_leadsp[x] and not restrict_formatting): return ' ' + y return y str_columns = list(zip(*[[space_format(x, y) for y in x] for x in fmt_columns])) if self.sparsify and len(str_columns): str_columns = _sparsify(str_columns) str_columns = [list(x) for x in zip(*str_columns)] else: fmt_columns = columns.format() dtypes = self.frame.dtypes need_leadsp = dict(zip(fmt_columns, map(is_numeric_dtype, dtypes))) str_columns = [[' ' + x if not self._get_formatter(i) and need_leadsp[x] else x] for i, (col, x) in enumerate(zip(columns, fmt_columns))] if self.show_row_idx_names: for x in str_columns: x.append('') # self.str_columns = str_columns return str_columns @property def has_index_names(self): return _has_names(self.frame.index) @property def has_column_names(self): return _has_names(self.frame.columns) @property def show_row_idx_names(self): return all((self.has_index_names, self.index, self.show_index_names)) @property def show_col_idx_names(self): return all((self.has_column_names, self.show_index_names, self.header)) def _get_formatted_index(self, frame): # Note: this is only used by to_string() and to_latex(), not by # to_html(). index = frame.index columns = frame.columns fmt = self._get_formatter('__index__') if isinstance(index, ABCMultiIndex): fmt_index = index.format( sparsify=self.sparsify, adjoin=False, names=self.show_row_idx_names, formatter=fmt) else: fmt_index = [index.format( name=self.show_row_idx_names, formatter=fmt)] fmt_index = [tuple(_make_fixed_width(list(x), justify='left', minimum=(self.col_space or 0), adj=self.adj)) for x in fmt_index] adjoined = self.adj.adjoin(1, *fmt_index).split('\n') # empty space for columns if self.show_col_idx_names: col_header = ['{x}'.format(x=x) for x in self._get_column_name_list()] else: col_header = [''] * columns.nlevels if self.header: return col_header + adjoined else: return adjoined def _get_column_name_list(self): names = [] columns = self.frame.columns if isinstance(columns, ABCMultiIndex): names.extend('' if name is None else name for name in columns.names) else: names.append('' if columns.name is None else columns.name) return names # ---------------------------------------------------------------------- # Array formatters def format_array(values, formatter, float_format=None, na_rep='NaN', digits=None, space=None, justify='right', decimal='.', leading_space=None): """ Format an array for printing. Parameters ---------- values formatter float_format na_rep digits space justify decimal leading_space : bool, optional Whether the array should be formatted with a leading space. When an array as a column of a Series or DataFrame, we do want the leading space to pad between columns. When formatting an Index subclass (e.g. IntervalIndex._format_native_types), we don't want the leading space since it should be left-aligned. Returns ------- List[str] """ if is_datetime64_dtype(values.dtype): fmt_klass = Datetime64Formatter elif is_datetime64tz_dtype(values): fmt_klass = Datetime64TZFormatter elif is_timedelta64_dtype(values.dtype): fmt_klass = Timedelta64Formatter elif is_extension_array_dtype(values.dtype): fmt_klass = ExtensionArrayFormatter elif is_float_dtype(values.dtype): fmt_klass = FloatArrayFormatter elif is_integer_dtype(values.dtype): fmt_klass = IntArrayFormatter else: fmt_klass = GenericArrayFormatter if space is None: space = get_option("display.column_space") if float_format is None: float_format = get_option("display.float_format") if digits is None: digits = get_option("display.precision") fmt_obj = fmt_klass(values, digits=digits, na_rep=na_rep, float_format=float_format, formatter=formatter, space=space, justify=justify, decimal=decimal, leading_space=leading_space) return fmt_obj.get_result() class GenericArrayFormatter(object): def __init__(self, values, digits=7, formatter=None, na_rep='NaN', space=12, float_format=None, justify='right', decimal='.', quoting=None, fixed_width=True, leading_space=None): self.values = values self.digits = digits self.na_rep = na_rep self.space = space self.formatter = formatter self.float_format = float_format self.justify = justify self.decimal = decimal self.quoting = quoting self.fixed_width = fixed_width self.leading_space = leading_space def get_result(self): fmt_values = self._format_strings() return _make_fixed_width(fmt_values, self.justify) def _format_strings(self): if self.float_format is None: float_format = get_option("display.float_format") if float_format is None: fmt_str = ('{{x: .{prec:d}g}}' .format(prec=get_option("display.precision"))) float_format = lambda x: fmt_str.format(x=x) else: float_format = self.float_format formatter = ( self.formatter if self.formatter is not None else (lambda x: pprint_thing(x, escape_chars=('\t', '\r', '\n')))) def _format(x): if self.na_rep is not None and is_scalar(x) and isna(x): if x is None: return 'None' elif x is NaT: return 'NaT' return self.na_rep elif isinstance(x, PandasObject): return u'{x}'.format(x=x) else: # object dtype return u'{x}'.format(x=formatter(x)) vals = self.values if isinstance(vals, Index): vals = vals._values elif isinstance(vals, ABCSparseArray): vals = vals.values is_float_type = lib.map_infer(vals, is_float) & notna(vals) leading_space = self.leading_space if leading_space is None: leading_space = is_float_type.any() fmt_values = [] for i, v in enumerate(vals): if not is_float_type[i] and leading_space: fmt_values.append(u' {v}'.format(v=_format(v))) elif is_float_type[i]: fmt_values.append(float_format(v)) else: if leading_space is False: # False specifically, so that the default is # to include a space if we get here. tpl = u'{v}' else: tpl = u' {v}' fmt_values.append(tpl.format(v=_format(v))) return fmt_values class FloatArrayFormatter(GenericArrayFormatter): """ """ def __init__(self, *args, **kwargs): GenericArrayFormatter.__init__(self, *args, **kwargs) # float_format is expected to be a string # formatter should be used to pass a function if self.float_format is not None and self.formatter is None: # GH21625, GH22270 self.fixed_width = False if callable(self.float_format): self.formatter = self.float_format self.float_format = None def _value_formatter(self, float_format=None, threshold=None): """Returns a function to be applied on each value to format it """ # the float_format parameter supersedes self.float_format if float_format is None: float_format = self.float_format # we are going to compose different functions, to first convert to # a string, then replace the decimal symbol, and finally chop according # to the threshold # when there is no float_format, we use str instead of '%g' # because str(0.0) = '0.0' while '%g' % 0.0 = '0' if float_format: def base_formatter(v): return float_format(value=v) if notna(v) else self.na_rep else: def base_formatter(v): return str(v) if notna(v) else self.na_rep if self.decimal != '.': def decimal_formatter(v): return base_formatter(v).replace('.', self.decimal, 1) else: decimal_formatter = base_formatter if threshold is None: return decimal_formatter def formatter(value): if notna(value): if abs(value) > threshold: return decimal_formatter(value) else: return decimal_formatter(0.0) else: return self.na_rep return formatter def get_result_as_array(self): """ Returns the float values converted into strings using the parameters given at initialisation, as a numpy array """ if self.formatter is not None: return np.array([self.formatter(x) for x in self.values]) if self.fixed_width: threshold = get_option("display.chop_threshold") else: threshold = None # if we have a fixed_width, we'll need to try different float_format def format_values_with(float_format): formatter = self._value_formatter(float_format, threshold) # separate the wheat from the chaff values = self.values mask = isna(values) if hasattr(values, 'to_dense'): # sparse numpy ndarray values = values.to_dense() values = np.array(values, dtype='object') values[mask] = self.na_rep imask = (~mask).ravel() values.flat[imask] = np.array([formatter(val) for val in values.ravel()[imask]]) if self.fixed_width: return _trim_zeros(values, self.na_rep) return values # There is a special default string when we are fixed-width # The default is otherwise to use str instead of a formatting string if self.float_format is None: if self.fixed_width: float_format = partial('{value: .{digits:d}f}'.format, digits=self.digits) else: float_format = self.float_format else: float_format = lambda value: self.float_format % value formatted_values = format_values_with(float_format) if not self.fixed_width: return formatted_values # we need do convert to engineering format if some values are too small # and would appear as 0, or if some values are too big and take too # much space if len(formatted_values) > 0: maxlen = max(len(x) for x in formatted_values) too_long = maxlen > self.digits + 6 else: too_long = False with np.errstate(invalid='ignore'): abs_vals = np.abs(self.values) # this is pretty arbitrary for now # large values: more that 8 characters including decimal symbol # and first digit, hence > 1e6 has_large_values = (abs_vals > 1e6).any() has_small_values = ((abs_vals < 10**(-self.digits)) & (abs_vals > 0)).any() if has_small_values or (too_long and has_large_values): float_format = partial('{value: .{digits:d}e}'.format, digits=self.digits) formatted_values = format_values_with(float_format) return formatted_values def _format_strings(self): # shortcut if self.formatter is not None: return [self.formatter(x) for x in self.values] return list(self.get_result_as_array()) class IntArrayFormatter(GenericArrayFormatter): def _format_strings(self): formatter = self.formatter or (lambda x: '{x: d}'.format(x=x)) fmt_values = [formatter(x) for x in self.values] return fmt_values class Datetime64Formatter(GenericArrayFormatter): def __init__(self, values, nat_rep='NaT', date_format=None, **kwargs): super(Datetime64Formatter, self).__init__(values, **kwargs) self.nat_rep = nat_rep self.date_format = date_format def _format_strings(self): """ we by definition have DO NOT have a TZ """ values = self.values if not isinstance(values, DatetimeIndex): values = DatetimeIndex(values) if self.formatter is not None and callable(self.formatter): return [self.formatter(x) for x in values] fmt_values = format_array_from_datetime( values.asi8.ravel(), format=_get_format_datetime64_from_values(values, self.date_format), na_rep=self.nat_rep).reshape(values.shape) return fmt_values.tolist() class ExtensionArrayFormatter(GenericArrayFormatter): def _format_strings(self): values = self.values if isinstance(values, (ABCIndexClass, ABCSeries)): values = values._values formatter = values._formatter(boxed=True) if is_categorical_dtype(values.dtype): # Categorical is special for now, so that we can preserve tzinfo array = values.get_values() else: array = np.asarray(values) fmt_values = format_array(array, formatter, float_format=self.float_format, na_rep=self.na_rep, digits=self.digits, space=self.space, justify=self.justify, leading_space=self.leading_space) return fmt_values def format_percentiles(percentiles): """ Outputs rounded and formatted percentiles. Parameters ---------- percentiles : list-like, containing floats from interval [0,1] Returns ------- formatted : list of strings Notes ----- Rounding precision is chosen so that: (1) if any two elements of ``percentiles`` differ, they remain different after rounding (2) no entry is *rounded* to 0% or 100%. Any non-integer is always rounded to at least 1 decimal place. Examples -------- Keeps all entries different after rounding: >>> format_percentiles([0.01999, 0.02001, 0.5, 0.666666, 0.9999]) ['1.999%', '2.001%', '50%', '66.667%', '99.99%'] No element is rounded to 0% or 100% (unless already equal to it). Duplicates are allowed: >>> format_percentiles([0, 0.5, 0.02001, 0.5, 0.666666, 0.9999]) ['0%', '50%', '2.0%', '50%', '66.67%', '99.99%'] """ percentiles = np.asarray(percentiles) # It checks for np.NaN as well with np.errstate(invalid='ignore'): if not is_numeric_dtype(percentiles) or not np.all(percentiles >= 0) \ or not np.all(percentiles <= 1): raise ValueError("percentiles should all be in the interval [0,1]") percentiles = 100 * percentiles int_idx = (percentiles.astype(int) == percentiles) if np.all(int_idx): out = percentiles.astype(int).astype(str) return [i + '%' for i in out] unique_pcts = np.unique(percentiles) to_begin = unique_pcts[0] if unique_pcts[0] > 0 else None to_end = 100 - unique_pcts[-1] if unique_pcts[-1] < 100 else None # Least precision that keeps percentiles unique after rounding prec = -np.floor(np.log10(np.min( np.ediff1d(unique_pcts, to_begin=to_begin, to_end=to_end) ))).astype(int) prec = max(1, prec) out = np.empty_like(percentiles, dtype=object) out[int_idx] = percentiles[int_idx].astype(int).astype(str) out[~int_idx] = percentiles[~int_idx].round(prec).astype(str) return [i + '%' for i in out] def _is_dates_only(values): # return a boolean if we are only dates (and don't have a timezone) values = DatetimeIndex(values) if values.tz is not None: return False values_int = values.asi8 consider_values = values_int != iNaT one_day_nanos = (86400 * 1e9) even_days = np.logical_and(consider_values, values_int % int(one_day_nanos) != 0).sum() == 0 if even_days: return True return False def _format_datetime64(x, tz=None, nat_rep='NaT'): if x is None or (is_scalar(x) and isna(x)): return nat_rep if tz is not None or not isinstance(x, Timestamp): if getattr(x, 'tzinfo', None) is not None: x = Timestamp(x).tz_convert(tz) else: x = Timestamp(x).tz_localize(tz) return str(x) def _format_datetime64_dateonly(x, nat_rep='NaT', date_format=None): if x is None or (is_scalar(x) and isna(x)): return nat_rep if not isinstance(x, Timestamp): x = Timestamp(x) if date_format: return x.strftime(date_format) else: return x._date_repr def _get_format_datetime64(is_dates_only, nat_rep='NaT', date_format=None): if is_dates_only: return lambda x, tz=None: _format_datetime64_dateonly( x, nat_rep=nat_rep, date_format=date_format) else: return lambda x, tz=None: _format_datetime64(x, tz=tz, nat_rep=nat_rep) def _get_format_datetime64_from_values(values, date_format): """ given values and a date_format, return a string format """ is_dates_only = _is_dates_only(values) if is_dates_only: return date_format or "%Y-%m-%d" return date_format class Datetime64TZFormatter(Datetime64Formatter): def _format_strings(self): """ we by definition have a TZ """ values = self.values.astype(object) is_dates_only = _is_dates_only(values) formatter = (self.formatter or _get_format_datetime64(is_dates_only, date_format=self.date_format)) fmt_values = [formatter(x) for x in values] return fmt_values class Timedelta64Formatter(GenericArrayFormatter): def __init__(self, values, nat_rep='NaT', box=False, **kwargs): super(Timedelta64Formatter, self).__init__(values, **kwargs) self.nat_rep = nat_rep self.box = box def _format_strings(self): formatter = (self.formatter or _get_format_timedelta64(self.values, nat_rep=self.nat_rep, box=self.box)) fmt_values = np.array([formatter(x) for x in self.values]) return fmt_values def _get_format_timedelta64(values, nat_rep='NaT', box=False): """ Return a formatter function for a range of timedeltas. These will all have the same format argument If box, then show the return in quotes """ values_int = values.astype(np.int64) consider_values = values_int != iNaT one_day_nanos = (86400 * 1e9) even_days = np.logical_and(consider_values, values_int % one_day_nanos != 0).sum() == 0 all_sub_day = np.logical_and( consider_values, np.abs(values_int) >= one_day_nanos).sum() == 0 if even_days: format = None elif all_sub_day: format = 'sub_day' else: format = 'long' def _formatter(x): if x is None or (is_scalar(x) and isna(x)): return nat_rep if not isinstance(x, Timedelta): x = Timedelta(x) result = x._repr_base(format=format) if box: result = "'{res}'".format(res=result) return result return _formatter def _make_fixed_width(strings, justify='right', minimum=None, adj=None): if len(strings) == 0 or justify == 'all': return strings if adj is None: adj = _get_adjustment() max_len = max(adj.len(x) for x in strings) if minimum is not None: max_len = max(minimum, max_len) conf_max = get_option("display.max_colwidth") if conf_max is not None and max_len > conf_max: max_len = conf_max def just(x): if conf_max is not None: if (conf_max > 3) & (adj.len(x) > max_len): x = x[:max_len - 3] + '...' return x strings = [just(x) for x in strings] result = adj.justify(strings, max_len, mode=justify) return result def _trim_zeros(str_floats, na_rep='NaN'): """ Trims zeros, leaving just one before the decimal points if need be. """ trimmed = str_floats def _cond(values): non_na = [x for x in values if x != na_rep] return (len(non_na) > 0 and all(x.endswith('0') for x in non_na) and not (any(('e' in x) or ('E' in x) for x in non_na))) while _cond(trimmed): trimmed = [x[:-1] if x != na_rep else x for x in trimmed] # leave one 0 after the decimal points if need be. return [x + "0" if x.endswith('.') and x != na_rep else x for x in trimmed] def _has_names(index): if isinstance(index, ABCMultiIndex): return com._any_not_none(*index.names) else: return index.name is not None class EngFormatter(object): """ Formats float values according to engineering format. Based on matplotlib.ticker.EngFormatter """ # The SI engineering prefixes ENG_PREFIXES = { -24: "y", -21: "z", -18: "a", -15: "f", -12: "p", -9: "n", -6: "u", -3: "m", 0: "", 3: "k", 6: "M", 9: "G", 12: "T", 15: "P", 18: "E", 21: "Z", 24: "Y" } def __init__(self, accuracy=None, use_eng_prefix=False): self.accuracy = accuracy self.use_eng_prefix = use_eng_prefix def __call__(self, num): """ Formats a number in engineering notation, appending a letter representing the power of 1000 of the original number. Some examples: >>> format_eng(0) # for self.accuracy = 0 ' 0' >>> format_eng(1000000) # for self.accuracy = 1, # self.use_eng_prefix = True ' 1.0M' >>> format_eng("-1e-6") # for self.accuracy = 2 # self.use_eng_prefix = False '-1.00E-06' @param num: the value to represent @type num: either a numeric value or a string that can be converted to a numeric value (as per decimal.Decimal constructor) @return: engineering formatted string """ import decimal import math dnum = decimal.Decimal(str(num)) if decimal.Decimal.is_nan(dnum): return 'NaN' if decimal.Decimal.is_infinite(dnum): return 'inf' sign = 1 if dnum < 0: # pragma: no cover sign = -1 dnum = -dnum if dnum != 0: pow10 = decimal.Decimal(int(math.floor(dnum.log10() / 3) * 3)) else: pow10 = decimal.Decimal(0) pow10 = pow10.min(max(self.ENG_PREFIXES.keys())) pow10 = pow10.max(min(self.ENG_PREFIXES.keys())) int_pow10 = int(pow10) if self.use_eng_prefix: prefix = self.ENG_PREFIXES[int_pow10] else: if int_pow10 < 0: prefix = 'E-{pow10:02d}'.format(pow10=-int_pow10) else: prefix = 'E+{pow10:02d}'.format(pow10=int_pow10) mant = sign * dnum / (10**pow10) if self.accuracy is None: # pragma: no cover format_str = u("{mant: g}{prefix}") else: format_str = (u("{{mant: .{acc:d}f}}{{prefix}}") .format(acc=self.accuracy)) formatted = format_str.format(mant=mant, prefix=prefix) return formatted # .strip() def set_eng_float_format(accuracy=3, use_eng_prefix=False): """ Alter default behavior on how float is formatted in DataFrame. Format float in engineering format. By accuracy, we mean the number of decimal digits after the floating point. See also EngFormatter. """ set_option("display.float_format", EngFormatter(accuracy, use_eng_prefix)) set_option("display.column_space", max(12, accuracy + 9)) def _binify(cols, line_width): adjoin_width = 1 bins = [] curr_width = 0 i_last_column = len(cols) - 1 for i, w in enumerate(cols): w_adjoined = w + adjoin_width curr_width += w_adjoined if i_last_column == i: wrap = curr_width + 1 > line_width and i > 0 else: wrap = curr_width + 2 > line_width and i > 0 if wrap: bins.append(i) curr_width = w_adjoined bins.append(len(cols)) return bins def get_level_lengths(levels, sentinel=''): """For each index in each level the function returns lengths of indexes. Parameters ---------- levels : list of lists List of values on for level. sentinel : string, optional Value which states that no new index starts on there. Returns ---------- Returns list of maps. For each level returns map of indexes (key is index in row and value is length of index). """ if len(levels) == 0: return [] control = [True] * len(levels[0]) result = [] for level in levels: last_index = 0 lengths = {} for i, key in enumerate(level): if control[i] and key == sentinel: pass else: control[i] = False lengths[last_index] = i - last_index last_index = i lengths[last_index] = len(level) - last_index result.append(lengths) return result def buffer_put_lines(buf, lines): """ Appends lines to a buffer. Parameters ---------- buf The buffer to write to lines The lines to append. """ if any(isinstance(x, compat.text_type) for x in lines): lines = [compat.text_type(x) for x in lines] buf.write('\n'.join(lines))
import graph def main(): g = graph.Graph()
import React from 'react' import { CFooter } from '@coreui/react' const AppFooter = () => { return ( <></> // <CFooter> // <div> // <a href="https://coreui.io" target="_blank" rel="noopener noreferrer"> // CoreUI // </a> // <span className="ms-1">&copy; 2021 creativeLabs.</span> // </div> // <div className="ms-auto"> // <span className="me-1">Powered by</span> // <a href="https://coreui.io/react" target="_blank" rel="noopener noreferrer"> // CoreUI for React // </a> // </div> // </CFooter> ) } export default React.memo(AppFooter)
# Copyright 2021 The Kubeflow 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. """Pipeline with Metrics outputs.""" from typing import NamedTuple from kfp import components from kfp import dsl from kfp import compiler from kfp.dsl import component, Dataset, Input, Metrics, Output @component def output_metrics(metrics: Output[Metrics]): """Dummy component that outputs metrics with a random accuracy.""" import random result = random.randint(0, 100) metrics.log_metric('accuracy', result) @dsl.pipeline(name='pipeline-with-metrics-outputs', pipeline_root='dummy_root') def my_pipeline(): output_metrics() with dsl.ParallelFor([1, 2]) as item: output_metrics() if __name__ == '__main__': compiler.Compiler().compile( pipeline_func=my_pipeline, package_path=__file__.replace('.py', '.json'))
import base64 import logging import random import sweeper.utils as utils import uuid import time from azure.storage import BlobService from azure.servicemanagement import * from azure.storage.fileshareservice import FileShareService from sweeper.resource import Resource, ResourceConfig def filter_any_hosted_service(sms, svc_name): return utils.filter_any(lambda x: x.service_name == svc_name, sms.list_hosted_services().hosted_services) def wait_for_hosted_service(sms, service_name): utils.wait_for(filter_any_hosted_service, sms=sms, svc_name=service_name) def wait_for_deployment(sms, service_name, deploy_name): wait = True while wait: svc = sms.get_hosted_service_properties(service_name) if not svc: raise ValueError('No service {0}'.format(service_name)) if svc.deployments: for d in svc.deployments: if d.name == deploy_name: wait = False break else: raise ValueError('No deployments in service {0}'.format(service_name)) def wait_for_service_certificate(sms, service_name, cert_fingerprint): wait = True while wait: sc = sms.list_service_certificates(service_name) for s in sc.certificates: logging.info("Actual: {}, Required: {}".format(s.thumbprint, cert_fingerprint)) if s.thumbprint == cert_fingerprint: wait = False break def wait_for_request_succeeded(sms, request_id): def status_succeeded(): st = sms.get_operation_status(request_id=request_id) if st.status == 'Succeeded': return True elif st.status == 'Failed': print(st.http_status_code, st.error.code, st.error.message) raise ValueError('Request status failed: {0}'.format(st.error.message)) return False utils.wait_for(status_succeeded) def wait_for_deployment_running(sms, service_name, deploy_name): wait = True while wait: st = sms.get_deployment_by_name(service_name, deploy_name) if st.status == 'Running': wait = False break def filter_any_storage_account(sms, stor_account): return utils.filter_any(lambda x: x.service_name == stor_account, sms.list_storage_accounts().storage_services) def wait_for_storage_account(sms, storage_name): utils.wait_for(filter_any_storage_account, sms=sms, stor_account=storage_name) def get_media_link(storage_account_name, container_name, file_name): return 'https://{0}.blob.core.windows.net/{1}/{2}'.format(storage_account_name, container_name, file_name) def create_resource(sms, name, config_object): """ Creates a virtual machine :param name: :param config_object: :return: a Resource object that represents the virtual machine """ res = Resource(config_object, name, '{0}.cloudapp.net'.format(name), 'azureuser', generate_valid_ramdom_password()) res.generate_ssh_keys() res.generate_certificates() logging.info('SSH fingerprint: ' + res.ssh_fingerprint) # Service Certificate # TODO: parametrize .cer management cert_encoded = encode_certificate(res.cer_path) # Key to password-less login vm_key_fingerprint = res.ssh_fingerprint linux_config = LinuxConfigurationSet(res.name, res.defaultUser, res.defaultPassword, True) key_pair = KeyPair(vm_key_fingerprint, '/home/{0}/id_rsa'.format(res.defaultUser)) public_key = PublicKey(vm_key_fingerprint, '/home/{0}/.ssh/authorized_keys'.format(res.defaultUser)) linux_config.ssh.public_keys.public_keys.append(public_key) linux_config.ssh.key_pairs.key_pairs.append(key_pair) linux_config.disable_ssh_password_authentication = False # OS Image # TODO: Automate configuration of image image_name = 'b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-14_04_2_LTS-amd64-server-20150309-en-us-30GB' # Azure Storage Account storage_keys = create_storage_account(sms, res.name) # Azure Storage Container for VHD image for VM container_name = 'vhd' create_container(res.name, 'vhd', storage_keys) vhd_link = get_media_link(res.name, container_name, '{0}.vhd'.format(res.name)) logging.info('VHD link: {0}'.format(vhd_link)) os_hd = OSVirtualHardDisk(image_name, vhd_link) # Network configuration (SSH endpoints) net_cfg = create_network_config() # Service Creation logging.info('Creating Hosted service {0} started'.format(res.name)) sms.create_hosted_service(service_name=res.name, label=res.name, description='Cloud service for VM {0}'.format(res.name), location='West US') # TODO: remove location hardcoded wait_for_hosted_service(sms, res.name) logging.info('Creating Hosted service {0} completed'.format(res.name)) # Add certificate to service # Acepta cualquier formato (.cer y .pfx), pero los pull request dicen que siempre # le pongas .pfx. # TODO: Al parecer, necesita cert_fingerprint logging.info('Adding service certificate for {0}'.format(res.name)) sms.add_service_certificate(service_name=res.name, data=cert_encoded.decode('utf-8'), certificate_format='pfx', password='') cloud_service_cert_fingerprint = res.ssh_fingerprint time.sleep(30) #wait_for_service_certificate(sms, res.name, cloud_service_cert_fingerprint) logging.info('Adding service certificate for {0} complete'.format(res.name)) # Virtual machine creation logging.info('Creating VM deployment {0}'.format(res.name)) vm_result = sms.create_virtual_machine_deployment(service_name=res.name, deployment_name=res.name, deployment_slot='production', label=res.name, role_name=res.name, system_config=linux_config, os_virtual_hard_disk=os_hd, role_size=config_object.config_name, network_config=net_cfg) wait_for_request_succeeded(sms, vm_result.request_id) wait_for_deployment_running(sms, res.name, res.name) logging.info('Creating VM deployment {0} complete'.format(res.name)) return res def encode_certificate(cer_file): with open(cer_file, 'rb') as cer_file: encoded_cer = base64.b64encode(cer_file.read()) return encoded_cer def create_network_config(subnet_name=None): network = ConfigurationSet() network.configuration_set_type = 'NetworkConfiguration' network.input_endpoints.input_endpoints.append( ConfigurationSetInputEndpoint('SSH', 'tcp', '22', '22')) if subnet_name: network.subnet_names.append(subnet_name) return network def delete_resource(sms, res_name): # Check if servie exists svc = sms.get_hosted_service_properties(res_name) if not svc: raise ValueError('Service {0} not found'.format(res_name)) # Turn off Virtual Machine shutdown_result = sms.shutdown_role(service_name=res_name, deployment_name=res_name, role_name=res_name, post_shutdown_action='StoppedDeallocated') wait_for_request_succeeded(shutdown_result.request_id) # Delete additional deployments if svc.deployments: for d in svc.deployments: logging.info('Deleting deployment {0}:{1}'.format(svc.service_name, d.name)) req = sms.delete_deployment(svc.service_name, d.name) wait_for_request_succeeded(req.request_id) logging.info('Deleting deployment {0}:{1} complete'.format(svc.service_name, d.name)) #TODO: Find out how to delete all deployments def get_deployment(): try: return sms.get_deployment_by_name(res_name, res_name) except Exception as e: return None if get_deployment(): logging.info('Deleting default deployment {0}'.format(res_name)) req = sms.delete_deployment(res_name, res_name) wait_for_request_succeeded(req.request_id) logging.info('Deleting default deployment {0} complete'.format(res_name)) def get_role(): try: return sms.get_role(service_name=res_name, deployment_name=res_name, role_name=res_name) except Exception as e: return None # Delete Virtual machine role after deployments! if get_role(): delete_result = sms.delete_role(service_name=res_name, deployment_name=res_name, role_name=res_name) wait_for_request_succeeded(delete_result.request_id) logging.info('Deleting cloud service {0}'.format(res_name)) sms.delete_hosted_service(res_name) utils.wait_for(lambda x: not filter_any_hosted_service(x), x=res_name) logging.info('Deleting cloud service {0} complete'.format(res_name)) #logging.info('Deleting Storage account {0}'.format(res_name)) #sms.delete_storage_account(res_name) #logging.info('Deleting Storage account {0} complete'.format(res_name)) def create_distributed_file_system(storage_account, fileshare): """ Creates a Azure Storage account and a file share that can work as a Distributed Filesystem across Azure VM's :param storage_account: :param fileshare: :return: Storage keys for further access """ storage_keys = create_storage_account(sms, storage_account) create_fileshare(storage_account, fileshare, storage_keys) return storage_keys def create_storage_account(sms, name): """ Creates a storage account in Microsoft Azure subscription and return its access keys :param name: :return: """ logging.info('Creating Storage account {0}'.format(name)) storage_account_result = sms.create_storage_account(service_name=name, description='Sweeper managed storage account', label=name, geo_replication_enabled=None, account_type='Standard_LRS', location='West US') # TODO: remove location hardcoded wait_for_request_succeeded(sms, storage_account_result.request_id) wait_for_storage_account(sms, name) logging.info('Creating Storage account {0} complete'.format(name)) storage_keys = sms.get_storage_account_keys(service_name=name) return storage_keys def create_fileshare(storage_account_name, fileshare_name, storage_keys): """ Creates a file share in the specified Microsoft Azure Storage account :param storage_account_name: :param fileshare_name: :param storage_keys: :return: """ logging.info('Creating Fileshare \'{0}\' in Storage account {1}'.format(fileshare_name, storage_account_name)) file_svc = FileShareService(account_name=storage_account_name, account_key=storage_keys.storage_service_keys.primary) file_svc.create_file_share(fileshare_name) logging.info('Creating Fileshare \'{0}\' in Storage account {1} complete'.format(fileshare_name, storage_account_name)) def create_container(storage_account_name, container_name, storage_keys): """ Creates a file share in the specified Microsoft Azure Storage account. A container is like a folder within a storage account :param storage_account_name: :param container_name: :param storage_keys: :return: """ logging.info('Creating Container \'{0}\' in Storage account {1}'.format(container_name, storage_account_name)) blob_svc = BlobService(account_name=storage_account_name, account_key=storage_keys.storage_service_keys.primary) blob_svc.create_container(container_name) logging.info('Creating Container \'{0}\' in Storage account {1} complete'.format(container_name, storage_account_name)) def validate_password_requirements(passwd): """ Check if :passwd approves the following password complexity requirements - at least 8 characters - 3 of the following conditions - at least 1 lowercase char - at least 1 uppercase char - at least 1 number char - at least 1 special (not alphanumeric) char :return: True if complies with password complexity requirements """ if not len(passwd) >= 8: return False req_lower = False req_upper = False req_digit = False req_special_char = False for ch in passwd: if str.isupper(ch): req_upper = True elif str.islower(ch): req_lower = True elif str.isdigit(ch): req_digit = True # See #http://azure.microsoft.com/en-us/documentation/articles/virtual-machines-docker-with-xplat-cli/ elif ch in '!@#$%^&+=': req_special_char = True return int(req_upper) + int(req_lower) + int(req_digit) + int(req_special_char) >= 3 def generate_valid_ramdom_password(): p = generate_random_password() while not validate_password_requirements(p): p = generate_random_password() return p def generate_random_password(): """ Generates a random password for using in VM user authentication :return: """ # Secure cryptographic random rnd = random.SystemRandom() len_k = rnd.randint(8, 15) keyword = [] for i in range(len_k): num = rnd.randint(1, 3) if num == 1: # generate number x = rnd.randint(ord('0'), ord('9')) elif num == 2: # generate lowercase x = rnd.randint(ord('a'), ord('z')) elif num == 3: # generate uppercase x = rnd.randint(ord('A'), ord('Z')) keyword.append(chr(x)) keyword = ''.join(keyword) return keyword def mount_distributed_file_system(name, vm_resources): fileshare_storage_account = name fileshare_name = 'sharedfs' fileshare_keys = create_distributed_file_system(fileshare_storage_account, fileshare_name) script_lines = [ "STORAGE_ACCOUNT_NAME='{}'".format(fileshare_storage_account), "STORAGE_ACCOUNT_KEY='{}'".format(fileshare_keys.storage_service_keys.primary), "FILESHARE_NAME='{}'".format(fileshare_name), "FILESHARE_PATH=\"//${STORAGE_ACCOUNT_NAME}.file.core.windows.net/${FILESHARE_NAME}\"", "sudo chown azureuser /opt", "mkdir -p /opt/fileshare", "sudo mount $FILESHARE_PATH /opt/fileshare -t cifs -o " + "\"vers=2.1,dir_mode=0777,file_mode=0777,username=${STORAGE_ACCOUNT_NAME},password=${STORAGE_ACCOUNT_KEY}\""] logging.info('Mounting Distributed FileSystem {}'.format(fileshare_name)) command = ';\n'.join(script_lines) logging.debug('Mounting Command below') logging.debug(command) for vm in vm_resources: logging.info('Mounting DFS in VM {}'.format(vm.name)) stdin, stdout, stderr, ssh = vm.execute_command(command) for line in stdout: logging.info('MOUNTING_STDOUT:{}'.format(line)) for line in stderr: logging.info('MOUNTING_STDERR:{}'.format(line)) ssh.close() logging.info('Mounting Distributed FileSystem {} complete'.format(fileshare_name)) return '/opt/fileshare'
#!/usr/bin/env python3 import argparse import csv import io import os import pathlib import server import signal import socket import sys from data import Data def count_word_occurrences(content): count = dict() for word in content.split(): count[word] = count.get(word, 0) + 1 return count def encode_word_occurrences_to_csv(count): r = io.StringIO() writer = csv.writer(r) for word in count: writer.writerow([word, count[word]]) return r.getvalue() class Processing(server.Server): ''' Reimplements the Server Class. ''' def __init__(self, data_address = 'localhost', data_port = 8080, payload_size = 1024): super().__init__(payload_size = payload_size) self.data_address = data_address self.data_port = data_port def request_handler(self, peer_conn, peer_address, data = ''): filename = data.rstrip(os.linesep) print(f' > {peer_address[0]}:{peer_address[1]} has requested the {filename} file', file = sys.stderr) content = self.get_file_content(filename) response = '' if Data.is_error(content): response = content else: response = encode_word_occurrences_to_csv(count_word_occurrences(content)) peer_conn.send(response.encode()) def get_file_content(self, filename): ''' Connects with Data Server and sends the received file name. Args: filename (str): The requested file name. Returns: str: The content of the file name requested to the Data Server. ''' content = '' with socket.socket() as data_conn: print(f'connecting to data service at {self.data_address}:{self.data_port}', file = sys.stderr) data_conn.connect((self.data_address, self.data_port)) data_conn.sendall(filename.encode()) print(f'requesting the content of {filename} on data service', file = sys.stderr) while True: raw = data_conn.recv(self.payload_size) if not raw: break content += str(raw, encoding = 'utf-8') return content if __name__ == '__main__': parser = argparse.ArgumentParser(description = 'starts the processing server') parser.add_argument('--host', '-H', type = str, default = 'localhost', help = 'local address (default localhost)') parser.add_argument('--port', '-p', type = int, default = 8080, help = 'local port (default 8080)') parser.add_argument('--data-address', type = str, default = 'localhost', help = 'data server\'s address (default localhost)') parser.add_argument('--data-port', type = int, default = 8080, help = 'data server\'s port (default 8080)') args = parser.parse_args() server = Processing(data_address = args.data_address, data_port = args.data_port) for ss in [signal.SIGINT, signal.SIGTERM]: signal.signal(ss, lambda received_signal, frame: server.stop()) server.start(host = args.host, port = args.port)
#! /usr/local/bin/python3 """ ------------------------------------------------------------------------------------------------------- Automagically Log Your Bike Trip When You're Logged Onto the Secure Network - Never Miss the Incentive. ------------------------------------------------------------------------------------------------------- ======================================================================================================= The MIT License (MIT) Copyright (c) Greenstick <benacordier@gmail.com> 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. ======================================================================================================= OVERVIEW This tool is used to log your bike commute to OHSU each day. Tool features include: > Commute trip customization > Automatic background authentication / login with OSX Keychain (no hardcoded passwords) > Wifi network detection with OSX Airport - only log trips when on an OHSU network > Customizable delay mechanism to limit requests to once per day > Only logs trips on weekdays > User agent string randomization > Logging of tool behavior > Scheduling is managed through CRON ======================================================================================================= SETUP To set up this utility, first install the Python requests library: > pip3 install requests Next, log into the bike incentive web portal with Safari and click remember password when you log in (www.ohsu.edu/parking/bikesite/index.cfm). Initially, Mac OSX will prompt you to grant the built-in OS X Security commandline tool access to OS X Keychain. Click 'Always Allow' so you don't have to click 'Allow' each time the script runs. Security Note: Doing the above allows this script to load your password into memory without having to hardcode it anywhere. It also sends all request using the https protocol by default. It can be set to http, but this is not recommended, any is likely disallowed by our servers. To configure the tool, see config variables in config/config.json. Below are the variable definitions: VARIABLE TYPE DEFAULT DESCRIPTION username string "" - Your username to login hours_delay integer 14 - The number of hours to prevent requests after a successful trip log url string "" - The incentive log url override boolean false - Force the tool to attempt a trip log valid_ssids array [] - A list of valid wifi network SSID's (e.g. HideYoKidsHideYoWiFi) airport_path string "" - The Mac OSX system path to airport log_filepath string "logs/incetive.log" - Log filepath log_level string "INFO" - Log verbosity, acceptable values include "INFO", "DEBUG", "WARNING", "CRITICAL", "ERROR" and "NOTSET" default_useragent string "Sir_Bikes_Alot" - Default browser useragent, only used if randomize_useragent is set to false randomize_useragent boolean true - Randomize user agent with data from /config/useragent.json (this may prevent the server ignoring requests) othermodes array [] - Form field - a list of other modes of transportation that are used on your commute destinations array [] - Form field - a list to select a detination that is biked to INTERNAL last_success float - Timestamp representation of last successful trip log (do not change this) To setup the details of your commute, scroll down in this file to line 158 (see comment). To ensure the tool is working as expected, it's recommended that your first run is not scheduled via CRON, to run it: > python3 /path/to/repo/src/main.py ======================================================================================================= SCHEDULING To setup and manage scheduling of this script, here are some helpful terminal commands: # Allow crontab to execute this script (required for this to work) chmod u+x path/to/this/repo/src/main.py # Open crontab in editing view using your terminals default editor > crontab -e # Edit the file to call this script (here, every 30 minutes, see this nice explanation for # scheduling: https://stackoverflow.com/a/11775112/2206251) > */30 * * * * /usr/local/bin/python3 path/to/this/repo/src/main.py # To check saved cron jobs > crontab -l # To check crontab history (use whatever editor you prefer): vim /var/mail/$USER ======================================================================================================= """ # # Imports # from collections import OrderedDict from urllib.parse import urlencode from lxml import html import json as JSON import subprocess as Subprocess import os as OS import sys as Sys import datetime as Datetime import logging as Logging import requests as Requests import random as Random import re as Rgx import argparse as Argparse if __name__ == "__main__": # If It's The Weekend, Exit if Datetime.datetime.today().weekday() > 4: exit() # Get Current Working Directory cwd = OS.path.dirname(OS.path.abspath(__file__)) + "/../" # # Setup # # Parse Arguments parser = Argparse.ArgumentParser() parser.add_argument("-o", "--override", action = "store_true", help = "Override network and time of day restrictions.") argsDict = vars(parser.parse_args()) override = argsDict["override"] # Load Config File with open(cwd + "config/config.json") as file: config = JSON.load(file) # User Settings username = config["username"] passwordDomain = config["password_domain"] override = override if override else config["override"] # Delay Between Attempts (14 Hours After Last Successful Log) delay = 60 * 60 * config["hours_delay"] # Network Settings airportPath = config["airport_path"] validSSIDs = config["valid_ssids"] # Website Settings url = config["url"] protocol = config["protocol"] # Logging logDir = config["log_filepath"] logLevel = config["log_level"] # Trip Data - Destination Options destinations = config["destinations"] # Trip Data - Modes of Transportation Used Options othermodes = config["othermodes"] # User Agent Settings defUserAgent = config["default_useragent"] randUserAgent = config["randomize_useragent"] # Datetime - Time of Last Successful Trip Log - Default to None if Unavailable lastSuccess = config["last_success"] if int(config["last_success"]) > 0 else None # Datetime - Current Datetime currentDatetime = Datetime.datetime.now() # # Customize Trip Details Below # # Populate Post Data tripDetails = OrderedDict() tripDetails["trip-log"] = 1 # Hidden Form Parameter - Leave Value as 1 tripDetails["mileage"] = 6.5 # Distance Biked in Miles tripDetails["destination"] = destinations[0] # Select 'Marquam Hill' (index 0) tripDetails["othermode"] = othermodes[0] # Select 'Tram' (index 0) # Set Useragent if randUserAgent: # Open Useragent Names File with open(cwd + "config/useragent.json") as file: useragent = JSON.load(file) agentElements = useragent["elements"] agentVerbs = useragent["verbs"] agentNouns = useragent["nouns"] element = Random.choice(agentElements) userAgent = Random.choice(agentVerbs[element]) + "-" + Random.choice(agentNouns[element]) + "_" + str(Random.randint(0, 3)) + "." + str(Random.randint(1, 17)) else: userAgent = defUserAgent # Set Logging Logging.basicConfig(filename = cwd + logDir, level = getattr(Logging, logLevel)) logger = Logging.getLogger() handler = Logging.StreamHandler() formatter = Logging.Formatter('%(levelname)-8s %(name)-12s %(asctime)-28s %(message)-48s') handler.setFormatter(formatter) logger.addHandler(handler) # Startup Output logger.info("- Initialized -------------------------------") logger.info("Loaded on %s" % currentDatetime.strftime("%x at %H:%M:%S")) if override: logger.info("Network and time override set") if lastSuccess is None: logger.info("") else: logger.info("Last successful trip log on %s" % Datetime.datetime.fromtimestamp(lastSuccess).strftime("%x at %H:%M:%S")) # If Override Set or First Attempt or Last Success Was Greater Than n Hours Ago if override or lastSuccess is None or (currentDatetime - Datetime.datetime.fromtimestamp(lastSuccess)) >= Datetime.timedelta(seconds = delay): # # Core Logic # # Get Network SSID process = Subprocess.Popen([airportPath, "-I"], stdout = Subprocess.PIPE, stderr = Subprocess.PIPE) stdout, stderr = process.communicate() network = {line.split(":")[0].strip() : line.split(":")[1].strip() for line in stdout.decode('utf-8').split("\n") if ":" in line } # Are We On A Valid Network? if len(network) > 1 and (network["SSID"] in validSSIDs or override): # Log Network Found if override: logger.info("Network found - %s" % network["SSID"]) else: logger.info("Valid network found - %s" % network["SSID"]) # Get Password From OS X Key Chain logger.info("Retrieving password for %s" % passwordDomain) process = Subprocess.Popen(["security", "find-internet-password", "-s", passwordDomain, "-w"], stdout = Subprocess.PIPE, stderr = Subprocess.PIPE) stdout, stderr = process.communicate() password = stdout.rstrip().decode('utf-8') # Strip Newline Character & Convert Bytecode to UTF-8 # Exit if Unable to Retrieve Password if len(password) < 1: logger.error("Unable to retrieve password. Exiting.") exit() # Log User Agent logger.info("Useragent set - %s" % userAgent) # Log Posting Data to API logger.info("Posting data to API") # Initialize Secure Web Session & Login to Incentive Website with Requests.session() as session: # Set Request Headers headers = { "User-Agent" : userAgent } # Initial Login - Set Session Cookies response = session.get(protocol + "://" + username + ":" + password + "@" + url, headers = headers) logger.info("Login %s status - %d" % (protocol.upper(), response.status_code)) # Submit Trip Data & Capture Response (Session Cookies Handled Internally by Requests.session) response = session.post(protocol + "://" + username + ":" + password + "@" + url, data = tripDetails) logger.info("Form submit %s status - %d" % (protocol.upper(), response.status_code)) # Get DOM From Response logger.info("DOM retrieved (%0.2fKB)" % (len(response.content) / 1024)) htmlDOM = html.fromstring(response.content) # Get Notification notification = htmlDOM.xpath('//p[@class="notification"]/text()') notificationDetails = [Rgx.sub(r"[\:\-]", "", string).strip() for string in notification if len(string.strip()) > 0] for detail in notificationDetails: logger.info("%s" % detail) # Get Success success = htmlDOM.xpath('//span[@class="success"]/text()') successDetails = [Rgx.sub(r"[\:\-]", "", string).strip() for string in success if len(string.strip()) > 0] for detail in successDetails: logger.info("%s" % detail) # If Successfully Logged if len(successDetails) > 0: # Write Timestamp of Last Successful Log Attempt to Config & Reset Override to False with open(cwd + "config/config.json", "w") as file: config["last_success"] = currentDatetime.timestamp() config["override"] = False config = OrderedDict(((key, value) for key, value in sorted(config.items()))) JSON.dump(config, file, indent = "\t") else: # Reset Override to False - Enforces User Override on Each Override Attempt with open(cwd + "config/config.json", "w") as file: config["override"] = False config = OrderedDict(((key, value) for key, value in sorted(config.items()))) JSON.dump(config, file, indent = "\t") logger.info("- Exiting -----------------------------------") exit() else: # Log No Network Connection & Exit if len(network) == 1 or len(network["SSID"]) == 0: logger.warning("No network connection") logger.info("- Exiting -----------------------------------") exit() # Log Invalid Network & Exit else: logger.warning("Invalid network - %s" % network["SSID"]) logger.info("- Exiting -----------------------------------") exit() # Pass - Tool Already Ran Within Delay Period else: logger.warning("%d hour delay period active" % (delay / 3600)) logger.info("Delay period ends in %s" % str((Datetime.datetime.fromtimestamp(lastSuccess) + Datetime.timedelta(hours = config["hours_delay"])) - currentDatetime).split(".")[0]) logger.info("See config.json to change or temporarily override delay period") logger.info("- Exiting -----------------------------------") exit() else: pass
var geheimPopupEl = null; var geheimPopupTarget = null; function geheimPopup(target, settings) { geheimPopupEl = document.getElementById("geheim-popup"); geheimPopupTarget = target; geheimPopupEl.style.display = "inline"; var existingKeys = document.querySelector("#geheim-popup #keys"); // Clear existing keys while (existingKeys.firstChild) { existingKeys.removeChild(existingKeys.firstChild); } // Show existing keys settings.methods.sort(function(a, b){if (a.name < b.name){return -1;}else if (a.name > b.name){return 1;}else{return 0;}}).forEach(function (method) { var methodEl = document.createElement("li"); methodEl.className = "method"; methodEl.innerHTML = method.name; existingKeys.appendChild(methodEl); settings.keys.filter(k => k.methodid == method.id).sort(function(a, b){if (a.name < b.name){return -1;}else if (a.name > b.name){return 1;}else{return 0;}}).forEach(function (key) { var keyEl = document.createElement("li"); keyEl.className = "key"; keyEl.innerHTML = key.name; keyEl.setAttribute("geheimdialog", true); keyEl.setAttribute("methodid", key.methodid); keyEl.setAttribute("keyid", key.id); existingKeys.appendChild(keyEl); }); }); } window.addEventListener("click", function(event) { var el = event.target; // Dialog events if (el.getAttribute("geheimdialog")) { geheimPopupEl.style.display = "none"; geheimPopupTarget.methodid = el.getAttribute("methodid"); geheimPopupTarget.keyid = el.getAttribute("keyid"); //el.value = el.originalValue; el.value = el.value; geheimPopupTarget.setAttribute("geheim", true); } if (el.getAttribute("geheimaddkey")) { window.postMessage({type: "FROM_PAGE", text: "AddKey"}, "*"); } if (el.getAttribute("geheimsettings")) { window.postMessage({type: "FROM_PAGE", text: "OpenSettings"}, "*"); } if (el.getAttribute("geheimcancel")) { geheimPopupEl.style.display = "none"; } if (el.id == "geheim-popup") { geheimPopupEl.style.display = "none"; } }); document.onkeydown = function(event) { if (event.keyCode == 27) // ESC key { geheimPopupEl.style.display = "none"; } };
gfrom pipeline import pipeline nlp = pipeline("e2e-qg", model="valhalla/t5-base-e2e-qg") qg = pipeline("e2e-qg") qg2 = pipeline("multitask-qa-qg") print("preload finished.")
/** * yox.js v1.0.0-alpha.90 * (c) 2017-2019 musicode * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, global.Yox = factory()); }(this, function () { 'use strict'; var SYNTAX_IF = '#if'; var SYNTAX_ELSE = 'else'; var SYNTAX_ELSE_IF = 'else if'; var SYNTAX_EACH = '#each'; var SYNTAX_PARTIAL = '#partial'; var SYNTAX_IMPORT = '>'; var SYNTAX_SPREAD = '...'; var SYNTAX_COMMENT = /^!\s/; var SLOT_DATA_PREFIX = '$slot_'; var SLOT_NAME_DEFAULT = 'children'; var HINT_STRING = 1; var HINT_NUMBER = 2; var HINT_BOOLEAN = 3; var DIRECTIVE_ON = 'on'; var DIRECTIVE_LAZY = 'lazy'; var DIRECTIVE_MODEL = 'model'; var DIRECTIVE_EVENT = 'event'; var DIRECTIVE_BINDING = 'binding'; var DIRECTIVE_CUSTOM = 'o'; var MODIFER_NATIVE = 'native'; var MODEL_PROP_DEFAULT = 'value'; var NAMESPACE_HOOK = '.hook'; var HOOK_BEFORE_CREATE = 'beforeCreate'; var HOOK_AFTER_CREATE = 'afterCreate'; var HOOK_BEFORE_MOUNT = 'beforeMount'; var HOOK_AFTER_MOUNT = 'afterMount'; var HOOK_BEFORE_UPDATE = 'beforeUpdate'; var HOOK_AFTER_UPDATE = 'afterUpdate'; var HOOK_BEFORE_DESTROY = 'beforeDestroy'; var HOOK_AFTER_DESTROY = 'afterDestroy'; /** * 为了压缩,定义的常量 */ var TRUE = true; var FALSE = false; var NULL = null; var UNDEFINED = void 0; var MINUS_ONE = -1; var RAW_TRUE = 'true'; var RAW_FALSE = 'false'; var RAW_NULL = 'null'; var RAW_UNDEFINED = 'undefined'; var RAW_KEY = 'key'; var RAW_REF = 'ref'; var RAW_SLOT = 'slot'; var RAW_NAME = 'name'; var RAW_FILTER = 'filter'; var RAW_PARTIAL = 'partial'; var RAW_COMPONENT = 'component'; var RAW_DIRECTIVE = 'directive'; var RAW_TRANSITION = 'transition'; var RAW_THIS = 'this'; var RAW_VALUE = 'value'; var RAW_LENGTH = 'length'; var RAW_FUNCTION = 'function'; var RAW_TEMPLATE = 'template'; var RAW_WILDCARD = '*'; var RAW_DOT = '.'; var KEYPATH_PARENT = '..'; var KEYPATH_CURRENT = RAW_THIS; /** * Single instance for window in browser */ var WINDOW = typeof window !== RAW_UNDEFINED ? window : UNDEFINED; /** * Single instance for document in browser */ var DOCUMENT = typeof document !== RAW_UNDEFINED ? document : UNDEFINED; /** * Single instance for global in nodejs or browser */ var GLOBAL = typeof global !== RAW_UNDEFINED ? global : WINDOW; /** * tap 事件 * * 非常有用的抽象事件,比如 pc 端是 click 事件,移动端是 touchend 事件 * * 这样只需 on-tap="handler" 就可以完美兼容各端 * * 框架未实现此事件,通过 Yox.dom.addSpecialEvent 提供给外部扩展 * */ var EVENT_TAP = 'tap'; /** * 点击事件 */ var EVENT_CLICK = 'click'; /** * 输入事件 */ var EVENT_INPUT = 'input'; /** * 变化事件 */ var EVENT_CHANGE = 'change'; /** * 唯一内置的特殊事件:model */ var EVENT_MODEL = 'model'; /** * Single instance for noop function */ var EMPTY_FUNCTION = function () { /** yox */ }; /** * 空对象,很多地方会用到,比如 `a || EMPTY_OBJECT` 确保是个对象 */ var EMPTY_OBJECT = Object.freeze({}); /** * 空数组 */ var EMPTY_ARRAY = Object.freeze([]); /** * 空字符串 */ var EMPTY_STRING = ''; function isDef (target) { return target !== UNDEFINED; } function isUndef (target) { return target === UNDEFINED; } /** * Check if value is a function. * * @param value * @return */ function func(value) { return typeof value === RAW_FUNCTION; } /** * Check if value is an array. * * @param value * @return */ function array(value) { return Array.isArray(value); } /** * Check if value is an object. * * @param value * @return */ function object(value) { // 低版本 IE 会把 null 当作 object return value !== NULL && typeof value === 'object'; } /** * Check if value is a string. * * @param value * @return */ function string(value) { return typeof value === 'string'; } /** * Check if value is a number. * * @param value * @return */ function number(value) { return typeof value === 'number'; } /** * Check if value is boolean. * * @param value * @return */ function boolean(value) { return typeof value === 'boolean'; } /** * Check if value is numeric. * * @param value * @return */ function numeric(value) { return number(value) || (string(value) && !isNaN(parseFloat(value)) && isFinite(value)); } var is = /*#__PURE__*/Object.freeze({ func: func, array: array, object: object, string: string, number: number, boolean: boolean, numeric: numeric }); /** * 任性地执行一个函数,不管它有没有、是不是 * * @param fn 调用的函数 * @param context 执行函数时的 this 指向 * @param args 调用函数的参数,多参数时传入数组 * @return 调用函数的返回值 */ function execute (fn, context, args) { if (func(fn)) { return array(args) ? fn.apply(context, args) : isDef(context) ? fn.call(context, args) : isDef(args) ? fn(args) : fn(); } } var CustomEvent = /** @class */ (function () { /** * 构造函数 * * 可以传事件名称,也可以传原生事件对象 */ function CustomEvent(type, originalEvent) { // 这里不设置命名空间 // 因为有没有命名空间取决于 Emitter 的构造函数有没有传 true // CustomEvent 自己无法决定 this.type = type; this.phase = CustomEvent.PHASE_CURRENT; if (originalEvent) { this.originalEvent = originalEvent; } } /** * 阻止事件的默认行为 */ CustomEvent.prototype.preventDefault = function () { var instance = this; if (!instance.isPrevented) { var originalEvent = instance.originalEvent; if (originalEvent) { originalEvent.preventDefault(); } instance.isPrevented = TRUE; } return instance; }; /** * 停止事件广播 */ CustomEvent.prototype.stopPropagation = function () { var instance = this; if (!instance.isStoped) { var originalEvent = instance.originalEvent; if (originalEvent) { originalEvent.stopPropagation(); } instance.isStoped = TRUE; } return instance; }; CustomEvent.prototype.prevent = function () { return this.preventDefault(); }; CustomEvent.prototype.stop = function () { return this.stopPropagation(); }; CustomEvent.PHASE_CURRENT = 0; CustomEvent.PHASE_UPWARD = 1; CustomEvent.PHASE_DOWNWARD = MINUS_ONE; return CustomEvent; }()); /** * 遍历数组 * * @param array * @param callback 返回 false 可停止遍历 * @param reversed 是否逆序遍历 */ function each(array, callback, reversed) { var length = array.length; if (length) { if (reversed) { for (var i = length - 1; i >= 0; i--) { if (callback(array[i], i) === FALSE) { break; } } } else { for (var i = 0; i < length; i++) { if (callback(array[i], i) === FALSE) { break; } } } } } function nativePush(array, item) { array[array.length] = item; } function nativeUnshift(array, item) { array.unshift(item); } /** * 添加 * * @param array * @param value * @param action */ function addItem(array$1, value, action) { if (array(value)) { each(value, function (item) { action(array$1, item); }); } else { action(array$1, value); } } /** * 往后加 * * @param array * @param target */ function push(array, target) { addItem(array, target, nativePush); } /** * 往前加 * * @param array * @param target */ function unshift(array, target) { addItem(array, target, nativeUnshift); } /** * 数组项在数组中的位置 * * @param array 数组 * @param target 数组项 * @param strict 是否全等判断,默认是全等 * @return 如果未找到,返回 -1 */ function indexOf(array, target, strict) { var result = MINUS_ONE; each(array, function (item, index) { if (strict === FALSE ? item == target : item === target) { result = index; return FALSE; } }); return result; } /** * 获取数组最后一项 * * @param array 数组 * @return */ function last(array) { var length = array.length; if (length > 0) { return array[length - 1]; } } /** * 弹出数组最后一项 * * 项目里用的太多,仅用于节省字符... * * @param array 数组 * @return 弹出的数组项 */ function pop(array) { var length = array.length; if (length > 0) { return array.pop(); } } /** * 删除数组项 * * @param array 数组 * @param item 待删除项 * @param strict 是否全等判断,默认是全等 * @return 删除的数量 */ function remove(array, target, strict) { var result = 0; each(array, function (item, index) { if (strict === FALSE ? item == target : item === target) { array.splice(index, 1); result++; } }, TRUE); return result; } /** * 数组是否包含 item * * @param array 数组 * @param target 可能包含的数组项 * @param strict 是否全等判断,默认是全等 * @return */ function has(array, target, strict) { return indexOf(array, target, strict) >= 0; } /** * 把类数组转成数组 * * @param array 类数组 * @return */ function toArray(array$1) { return array(array$1) ? array$1 : execute(EMPTY_ARRAY.slice, array$1); } /** * 把数组转成对象 * * @param array 数组 * @param key 数组项包含的字段名称,如果数组项是基本类型,可不传 * @param value * @return */ function toObject(array, key, value) { var result = {}; each(array, function (item) { result[key ? item[key] : item] = value || item; }); return result; } /** * 把数组合并成字符串 * * @param array * @param separator * @return */ function join(array, separator) { return array.join(separator); } /** * 用于判断长度大于 0 的数组 * * @param array * @return */ function falsy(array$1) { return !array(array$1) || !array$1.length; } var array$1 = /*#__PURE__*/Object.freeze({ each: each, push: push, unshift: unshift, indexOf: indexOf, last: last, pop: pop, remove: remove, has: has, toArray: toArray, toObject: toObject, join: join, falsy: falsy }); var camelizePattern = /-([a-z])/gi, hyphenatePattern = /\B([A-Z])/g, capitalizePattern = /^[a-z]/, camelizeCache = {}, hyphenateCache = {}, capitalizeCache = {}; /** * 连字符转成驼峰 * * @param str * @return 驼峰格式的字符串 */ function camelize(str) { if (!camelizeCache[str]) { camelizeCache[str] = str.replace(camelizePattern, function ($0, $1) { return upper($1); }); } return camelizeCache[str]; } /** * 驼峰转成连字符 * * @param str * @return 连字符格式的字符串 */ function hyphenate(str) { if (!hyphenateCache[str]) { hyphenateCache[str] = str.replace(hyphenatePattern, function ($0, $1) { return '-' + lower($1); }); } return hyphenateCache[str]; } /** * 首字母大写 * * @param str * @return */ function capitalize(str) { if (!capitalizeCache[str]) { capitalizeCache[str] = str.replace(capitalizePattern, upper); } return capitalizeCache[str]; } /** * 清除两侧空白符 * * @param str * @return 清除两侧空白符的字符串 */ function trim(str) { return falsy$1(str) ? EMPTY_STRING : str.trim(); } /** * 截取字符串 * * @param str * @param start * @param end * @return */ function slice(str, start, end) { return number(end) ? start === end ? EMPTY_STRING : str.slice(start, end) : str.slice(start); } /** * 获取子串的起始位置 * * @param str * @param part * @param start * @return */ function indexOf$1(str, part, start) { return str.indexOf(part, isDef(start) ? start : 0); } /** * 获取子串的起始位置 * * @param str * @param part * @param end * @return */ function lastIndexOf(str, part, end) { return str.lastIndexOf(part, isDef(end) ? end : str.length); } /** * str 是否以 part 开头 * * @param str * @param part * @return */ function startsWith(str, part) { return indexOf$1(str, part) === 0; } /** * str 是否以 part 结束 * * @param str * @param part * @return */ function endsWith(str, part) { var offset = str.length - part.length; return offset >= 0 && lastIndexOf(str, part) === offset; } /** * 获取某个位置的字符 */ function charAt(str, index) { return str.charAt(index || 0); } /** * 获取某个位置的字符编码 */ function codeAt(str, index) { return str.charCodeAt(index || 0); } /** * 大写格式 */ function upper(str) { return str.toUpperCase(); } /** * 小写格式 */ function lower(str) { return str.toLowerCase(); } /** * str 是否包含 part * * @param str * @param part * @return 是否包含 */ function has$1(str, part) { return indexOf$1(str, part) >= 0; } /** * 判断长度大于 0 的字符串 * * @param str * @return */ function falsy$1(str) { return !string(str) || !str.length; } var string$1 = /*#__PURE__*/Object.freeze({ camelize: camelize, hyphenate: hyphenate, capitalize: capitalize, trim: trim, slice: slice, indexOf: indexOf$1, lastIndexOf: lastIndexOf, startsWith: startsWith, endsWith: endsWith, charAt: charAt, codeAt: codeAt, upper: upper, lower: lower, has: has$1, falsy: falsy$1 }); var dotPattern = /\./g, asteriskPattern = /\*/g, doubleAsteriskPattern = /\*\*/g, splitCache = {}, patternCache = {}; /** * 判断 keypath 是否以 prefix 开头,如果是,返回匹配上的前缀长度,否则返回 -1 * * @param keypath * @param prefix * @return */ function match(keypath, prefix) { if (keypath === prefix) { return prefix.length; } prefix += RAW_DOT; return startsWith(keypath, prefix) ? prefix.length : MINUS_ONE; } /** * 遍历 keypath 的每个部分 * * @param keypath * @param callback 返回 false 可中断遍历 */ function each$1(keypath, callback) { // 判断字符串是因为 keypath 有可能是 toString // 而 splitCache.toString 是个函数 var list = isDef(splitCache[keypath]) ? splitCache[keypath] : (splitCache[keypath] = keypath.split(RAW_DOT)); for (var i = 0, lastIndex = list.length - 1; i <= lastIndex; i++) { if (callback(list[i], i === lastIndex) === FALSE) { break; } } } /** * 遍历 keypath 的每个部分 * * @param keypath1 * @param keypath2 */ function join$1(keypath1, keypath2) { return keypath1 && keypath2 ? keypath1 + RAW_DOT + keypath2 : keypath1 || keypath2; } /** * 是否模糊匹配 * * @param keypath */ function isFuzzy(keypath) { return has$1(keypath, RAW_WILDCARD); } /** * 模糊匹配 keypath * * @param keypath * @param pattern */ function matchFuzzy(keypath, pattern) { var cache = patternCache[pattern]; if (!cache) { var str = pattern .replace(dotPattern, '\\.') .replace(asteriskPattern, '(\\w+)') .replace(doubleAsteriskPattern, '([\.\\w]+?)'); cache = patternCache[pattern] = new RegExp("^" + str + "$"); } var result = keypath.match(cache); if (result) { return result[1]; } } /** * 全局 value holder,避免频繁的创建临时对象 */ var holder = { value: UNDEFINED }; /** * 获取对象的 key 的数组 * * @param object * @return */ function keys(object) { return Object.keys(object); } function sortKeyByAsc(a, b) { return a.length - b.length; } function sortKeyByDesc(a, b) { return b.length - a.length; } /** * 排序对象的 key * * @param object * @param desc 是否逆序,默认从小到大排序 * @return */ function sort(object, desc) { return keys(object).sort(desc ? sortKeyByDesc : sortKeyByAsc); } /** * 遍历对象 * * @param object * @param callback 返回 false 可停止遍历 */ function each$2(object, callback) { for (var key in object) { if (callback(object[key], key) === FALSE) { break; } } } /** * 清空对象所有的键值对 * * @param object */ function clear(object) { each$2(object, function (_, key) { delete object[key]; }); } /** * 扩展对象 * * @return */ function extend(original, object) { each$2(object, function (value, key) { original[key] = value; }); return original; } /** * 合并对象 * * @return */ function merge(object1, object2) { return object1 && object2 ? extend(extend({}, object1), object2) : object1 || object2; } /** * 拷贝对象 * * @param object * @param deep 是否需要深拷贝 * @return */ function copy(object$1, deep) { var result = object$1; if (array(object$1)) { if (deep) { result = []; each(object$1, function (item, index) { result[index] = copy(item, deep); }); } else { result = object$1.slice(); } } else if (object(object$1)) { result = {}; each$2(object$1, function (value, key) { result[key] = deep ? copy(value, deep) : value; }); } return result; } /** * 从对象中查找一个 keypath * * 返回值是空时,表示没找到值 * * @param object * @param keypath * @return */ function get(object, keypath) { each$1(keypath, function (key, isLast) { if (object != NULL) { // 先直接取值 var value = object[key], // 紧接着判断值是否存在 // 下面会处理计算属性的值,不能在它后面设置 hasValue hasValue = isDef(value); // 如果是计算属性,取计算属性的值 if (value && func(value.get)) { value = value.get(); } if (isLast) { if (hasValue) { holder.value = value; object = holder; } else { object = UNDEFINED; } } else { object = value; } } else { object = UNDEFINED; return FALSE; } }); return object; } /** * 为对象设置一个键值对 * * @param object * @param keypath * @param value * @param autofill 是否自动填充不存在的对象,默认自动填充 */ function set(object, keypath, value, autofill) { each$1(keypath, function (key, isLast) { if (isLast) { object[key] = value; } else if (object[key]) { object = object[key]; } else if (autofill) { object = object[key] = {}; } else { return FALSE; } }); } /** * 对象是否包含某个 key * * @param object * @param key * @return */ function has$2(object, key) { // 不用 hasOwnProperty,性能差 return isDef(object[key]); } /** * 是否是空对象 * * @param object * @return */ function falsy$2(object$1) { return !object(object$1) || array(object$1) || !keys(object$1).length; } var object$1 = /*#__PURE__*/Object.freeze({ keys: keys, sort: sort, each: each$2, clear: clear, extend: extend, merge: merge, copy: copy, get: get, set: set, has: has$2, falsy: falsy$2 }); function toString (target, defaultValue) { return target != NULL && target.toString ? target.toString() : isDef(defaultValue) ? defaultValue : EMPTY_STRING; } var DEBUG = 1; var INFO = 2; var WARN = 3; var ERROR = 4; var FATAL = 5; /** * 是否有原生的日志特性,没有必要单独实现 */ var nativeConsole = typeof console !== RAW_UNDEFINED ? console : NULL, /** * 当前是否是源码调试,如果开启了代码压缩,empty function 里的注释会被干掉 */ defaultLogLevel = /yox/.test(toString(EMPTY_FUNCTION)) ? DEBUG : WARN, /** * console 样式前缀 * ie 和 edge 不支持 console.log 样式 */ stylePrefix = WINDOW && /edge|msie|trident/i.test(WINDOW.navigator.userAgent) ? EMPTY_STRING : '%c', /** * 日志打印函数 */ printLog = nativeConsole ? stylePrefix ? function (tag, msg, style) { nativeConsole.log(stylePrefix + tag, style, msg); } : function (tag, msg) { nativeConsole.log(tag, msg); } : EMPTY_FUNCTION; /** * 全局调试开关 */ function getLogLevel() { if (GLOBAL) { var logLevel = GLOBAL['YOX_LOG_LEVEL']; if (logLevel >= DEBUG && logLevel <= FATAL) { return logLevel; } } return defaultLogLevel; } function getStyle(backgroundColor) { return "background-color:" + backgroundColor + ";border-radius:12px;color:#fff;font-size:10px;padding:3px 6px;"; } /** * 打印 debug 日志 * * @param msg */ function debug(msg, tag) { if (getLogLevel() <= DEBUG) { printLog(tag || 'Yox debug', msg, getStyle('#999')); } } /** * 打印 info 日志 * * @param msg */ function info(msg, tag) { if (getLogLevel() <= INFO) { printLog(tag || 'Yox info', msg, getStyle('#2db7f5')); } } /** * 打印 warn 日志 * * @param msg */ function warn(msg, tag) { if (getLogLevel() <= WARN) { printLog(tag || 'Yox warn', msg, getStyle('#f90')); } } /** * 打印 error 日志 * * @param msg */ function error(msg, tag) { if (getLogLevel() <= ERROR) { printLog(tag || 'Yox error', msg, getStyle('#ed4014')); } } /** * 致命错误,中断程序 * * @param msg */ function fatal(msg, tag) { if (getLogLevel() <= FATAL) { throw new Error("[" + (tag || 'Yox fatal') + "]: " + msg); } } var logger = /*#__PURE__*/Object.freeze({ DEBUG: DEBUG, INFO: INFO, WARN: WARN, ERROR: ERROR, FATAL: FATAL, debug: debug, info: info, warn: warn, error: error, fatal: fatal }); var Emitter = /** @class */ (function () { function Emitter(ns) { this.ns = ns || FALSE; this.listeners = {}; } /** * 发射事件 * * @param type 事件名称或命名空间 * @param args 事件处理函数的参数列表 * @param filter 自定义过滤器 */ Emitter.prototype.fire = function (type, args, filter) { var instance = this, namespace = string(type) ? instance.parse(type) : type, list = instance.listeners[namespace.type], isComplete = TRUE; if (list) { // 避免遍历过程中,数组发生变化,比如增删了 list = copy(list); // 判断是否是发射事件 // 如果 args 的第一个参数是 CustomEvent 类型,表示发射事件 // 因为事件处理函数的参数列表是 (event, data) var event_1 = args && args[0] instanceof CustomEvent ? args[0] : UNDEFINED; each(list, function (options) { // 命名空间不匹配 if (!matchNamespace(namespace.ns, options) // 在 fire 过程中被移除了 || !has(list, options) // 传了 filter,则用 filter 判断是否过滤此 options || (filter && !filter(namespace, args, options))) { return; } // 为 event 对象加上当前正在处理的 listener // 这样方便业务层移除事件绑定 // 比如 on('xx', function) 这样定义了匿名 listener // 在这个 listener 里面获取不到当前 listener 的引用 // 为了能引用到,有时候会先定义 var listener = function // 然后再 on('xx', listener) 这样其实是没有必要的 if (event_1) { event_1.listener = options.fn; } var result = execute(options.fn, options.ctx, args); if (event_1) { event_1.listener = UNDEFINED; } // 执行次数 options.num = options.num ? (options.num + 1) : 1; // 注册的 listener 可以指定最大执行次数 if (options.num === options.max) { instance.off(namespace, options.fn); } // 如果没有返回 false,而是调用了 event.stop 也算是返回 false if (event_1) { if (result === FALSE) { event_1.prevent().stop(); } else if (event_1.isStoped) { result = FALSE; } } if (result === FALSE) { return isComplete = FALSE; } }); } return isComplete; }; /** * 注册监听 * * @param type * @param listener */ Emitter.prototype.on = function (type, listener) { var instance = this, listeners = instance.listeners, options = func(listener) ? { fn: listener } : listener; if (object(options) && func(options.fn)) { var namespace = string(type) ? instance.parse(type) : type; options.ns = namespace.ns; push(listeners[namespace.type] || (listeners[namespace.type] = []), options); } else { fatal("emitter.on(type, listener) invoke failed\uFF1A\n\n\"listener\" is expected to be a Function or an EmitterOptions.\n"); } }; /** * 取消监听 * * @param type * @param listener */ Emitter.prototype.off = function (type, listener) { var instance = this, listeners = instance.listeners; if (type) { var namespace = string(type) ? instance.parse(type) : type, name = namespace.type, ns_1 = namespace.ns, matchListener_1 = createMatchListener(listener), each$1 = function (list, name) { each(list, function (options, index) { if (matchListener_1(options) && matchNamespace(ns_1, options)) { list.splice(index, 1); } }, TRUE); if (!list.length) { delete listeners[name]; } }; if (name) { if (listeners[name]) { each$1(listeners[name], name); } } else if (ns_1) { each$2(listeners, each$1); } // 在开发阶段进行警告,比如传了 listener 进来,listener 是个空值 // 但你不知道它是空值 { if (arguments.length > 1 && listener == NULL) { warn("emitter.off(type, listener) is invoked, but \"listener\" is " + listener + "."); } } } else { // 清空 instance.listeners = {}; // 在开发阶段进行警告,比如传了 type 进来,type 是个空值 // 但你不知道它是空值 { if (arguments.length > 0) { warn("emitter.off(type) is invoked, but \"type\" is " + type + "."); } } } }; /** * 是否已监听某个事件 * * @param type * @param listener */ Emitter.prototype.has = function (type, listener) { var instance = this, listeners = instance.listeners, namespace = string(type) ? instance.parse(type) : type, name = namespace.type, ns = namespace.ns, result = TRUE, matchListener = createMatchListener(listener), each$1 = function (list) { each(list, function (options) { if (matchListener(options) && matchNamespace(ns, options)) { return result = FALSE; } }); return result; }; if (name) { if (listeners[name]) { each$1(listeners[name]); } } else if (ns) { each$2(listeners, each$1); } return !result; }; /** * 把事件类型解析成命名空间格式 * * @param type */ Emitter.prototype.parse = function (type) { // 这里 ns 必须为字符串 // 用于区分 event 对象是否已完成命名空间的解析 var result = { type: type, ns: EMPTY_STRING }; // 是否开启命名空间 if (this.ns) { var index = indexOf$1(type, RAW_DOT); if (index >= 0) { result.type = slice(type, 0, index); result.ns = slice(type, index + 1); } } return result; }; return Emitter; }()); function matchTrue() { return TRUE; } /** * 外部会传入 Function 或 EmitterOptions 或 空 * * 这里根据传入值的不同类型,创建不同的判断函数 * * 如果传入的是 EmitterOptions,则全等判断 * * 如果传入的是 Function,则判断函数是否全等 * * 如果传入的是空,则直接返回 true * * @param listener */ function createMatchListener(listener) { return func(listener) ? function (options) { return listener === options.fn; } : matchTrue; } /** * 判断 options 是否能匹配命名空间 * * 如果 namespace 和 options.ns 都不为空,则需完全匹配 * * 如果他们两个其中任何一个为空,则不判断命名空间 * * @param namespace * @param options */ function matchNamespace(namespace, options) { var ns = options.ns; return ns && namespace ? ns === namespace : TRUE; } function isNative (target) { return func(target) && /native code/.test(toString(target)); } var nextTick; // IE (10+) 和 node if (typeof setImmediate === RAW_FUNCTION && isNative(setImmediate)) { nextTick = setImmediate; } // 用 MessageChannel 去做 setImmediate 的 polyfill // 原理是将新的 message 事件加入到原有的 dom events 之后 // 兼容性 IE10+ 和其他标准浏览器 if (typeof MessageChannel === RAW_FUNCTION && isNative(MessageChannel)) { nextTick = function (fn) { var channel = new MessageChannel(); channel.port1.onmessage = fn; channel.port2.postMessage(1); }; } else { nextTick = setTimeout; } var nextTick$1 = nextTick; var shared; var NextTask = /** @class */ (function () { function NextTask() { this.tasks = []; } /** * 全局单例 */ NextTask.shared = function () { return shared || (shared = new NextTask()); }; /** * 在队尾添加异步任务 */ NextTask.prototype.append = function (func, context) { var instance = this, tasks = instance.tasks; push(tasks, { fn: func, ctx: context }); if (tasks.length === 1) { nextTick$1(function () { instance.run(); }); } }; /** * 在队首添加异步任务 */ NextTask.prototype.prepend = function (func, context) { var instance = this, tasks = instance.tasks; unshift(tasks, { fn: func, ctx: context }); if (tasks.length === 1) { nextTick$1(function () { instance.run(); }); } }; /** * 清空异步队列 */ NextTask.prototype.clear = function () { this.tasks.length = 0; }; /** * 立即执行异步任务,并清空队列 */ NextTask.prototype.run = function () { var tasks = this.tasks; if (tasks.length) { this.tasks = []; each(tasks, function (task) { execute(task.fn, task.ctx); }); } }; return NextTask; }()); var guid = 0; function guid$1 () { return ++guid; } // vnode.data 内部使用的几个字段 var ID = '$id'; var VNODE = '$vnode'; var LOADING = '$loading'; var COMPONENT = '$component'; var LEAVING = '$leaving'; function update(api, vnode, oldVnode) { var node = vnode.node, nativeAttrs = vnode.nativeAttrs, oldNativeAttrs = oldVnode && oldVnode.nativeAttrs; if (nativeAttrs || oldNativeAttrs) { var newValue_1 = nativeAttrs || EMPTY_OBJECT, oldValue_1 = oldNativeAttrs || EMPTY_OBJECT; each$2(newValue_1, function (attr, name) { if (!oldValue_1[name] || attr.value !== oldValue_1[name].value) { api.attr(node, name, attr.value); } }); each$2(oldValue_1, function (_, name) { if (!newValue_1[name]) { api.removeAttr(node, name); } }); } } function update$1(api, vnode, oldVnode) { var node = vnode.node, nativeProps = vnode.nativeProps, oldNativeProps = oldVnode && oldVnode.nativeProps; if (nativeProps || oldNativeProps) { var newValue_1 = nativeProps || EMPTY_OBJECT, oldValue_1 = oldNativeProps || EMPTY_OBJECT; each$2(newValue_1, function (prop, name) { if (!oldValue_1[name] || prop.value !== oldValue_1[name].value) { api.prop(node, name, prop.value); } }); each$2(oldValue_1, function (prop, name) { if (!newValue_1[name]) { api.removeProp(node, name, prop.hint); } }); } } function update$2(vnode, oldVnode) { var data = vnode.data, directives = vnode.directives, oldDirectives = oldVnode && oldVnode.directives; if (directives || oldDirectives) { var node_1 = data[COMPONENT] || vnode.node, isKeypathChange_1 = oldVnode && vnode.keypath !== oldVnode.keypath, newValue_1 = directives || EMPTY_OBJECT, oldValue_1 = oldDirectives || EMPTY_OBJECT; each$2(newValue_1, function (directive, name) { var _a = directive.hooks, once = _a.once, bind = _a.bind, unbind = _a.unbind; if (!oldValue_1[name]) { bind(node_1, directive, vnode); } else if (once || directive.value !== oldValue_1[name].value || isKeypathChange_1) { if (unbind) { unbind(node_1, oldValue_1[name], oldVnode); } bind(node_1, directive, vnode); } }); each$2(oldValue_1, function (directive, name) { if (!newValue_1[name]) { var unbind = directive.hooks.unbind; if (unbind) { unbind(node_1, directive, oldVnode); } } }); } } function remove$1(vnode) { var directives = vnode.directives; if (directives) { var node_2 = vnode.data[COMPONENT] || vnode.node; each$2(directives, function (directive) { var unbind = directive.hooks.unbind; if (unbind) { unbind(node_2, directive, vnode); } }); } } function update$3(vnode, oldVnode) { var data = vnode.data, ref = vnode.ref, props = vnode.props, slots = vnode.slots, directives = vnode.directives, context = vnode.context, node; if (vnode.isComponent) { node = data[COMPONENT]; // 更新时才要 set // 因为初始化时,所有这些都经过构造函数完成了 if (oldVnode) { var model = directives && directives[DIRECTIVE_MODEL]; if (model) { if (!props) { props = {}; } props[node.$model] = model.value; } { if (props) { each$2(props, function (value, key) { node.checkProp(key, value); }); } } var result = merge(props, slots); if (result) { node.forceUpdate(result); } } } else { node = vnode.node; } if (ref) { var refs = context.$refs; if (refs) { refs[ref] = node; } } } function isPatchable(vnode, oldVnode) { return vnode.tag === oldVnode.tag && vnode.key === oldVnode.key; } function createKeyToIndex(vnodes, startIndex, endIndex) { var result, vnode, key; while (startIndex <= endIndex) { vnode = vnodes[startIndex]; if (vnode && (key = vnode.key)) { if (!result) { result = {}; } result[key] = startIndex; } startIndex++; } return result || EMPTY_OBJECT; } function insertBefore(api, parentNode, node, referenceNode) { if (referenceNode) { api.before(parentNode, node, referenceNode); } else { api.append(parentNode, node); } } function createComponent(vnode, options) { var child = (vnode.parent || vnode.context).createComponent(options, vnode); vnode.data[COMPONENT] = child; vnode.data[LOADING] = FALSE; update$3(vnode); update$2(vnode); return child; } function createData() { var data = {}; data[ID] = guid$1(); return data; } function createVnode(api, vnode) { var tag = vnode.tag, node = vnode.node, data = vnode.data, isComponent = vnode.isComponent, isComment = vnode.isComment, isText = vnode.isText, isStyle = vnode.isStyle, isOption = vnode.isOption, children = vnode.children, text = vnode.text, html = vnode.html, context = vnode.context; if (node && data) { return; } data = createData(); vnode.data = data; if (isText) { vnode.node = api.createText(text); return; } if (isComment) { vnode.node = api.createComment(text); return; } if (isComponent) { var componentOptions_1 = UNDEFINED; // 动态组件,tag 可能为空 if (tag) { context.loadComponent(tag, function (options) { if (has$2(data, LOADING)) { // 异步组件 if (data[LOADING]) { // 尝试使用最新的 vnode if (data[VNODE]) { vnode = data[VNODE]; // 用完就删掉 delete data[VNODE]; } enterVnode(vnode, createComponent(vnode, options)); } } // 同步组件 else { componentOptions_1 = options; } }); } // 不论是同步还是异步组件,都需要一个占位元素 vnode.node = api.createComment(RAW_COMPONENT); if (componentOptions_1) { createComponent(vnode, componentOptions_1); } else { data[LOADING] = TRUE; } } else { node = vnode.node = api.createElement(vnode.tag, vnode.isSvg); if (children) { addVnodes(api, node, children); } else if (text) { api.text(node, text, isStyle, isOption); } else if (html) { api.html(node, html, isStyle, isOption); } update(api, vnode); update$1(api, vnode); update$3(vnode); update$2(vnode); } } function addVnodes(api, parentNode, vnodes, startIndex, endIndex, before) { var vnode, start = startIndex || 0, end = isDef(endIndex) ? endIndex : vnodes.length - 1; while (start <= end) { vnode = vnodes[start]; createVnode(api, vnode); insertVnode(api, parentNode, vnode, before); start++; } } function insertVnode(api, parentNode, vnode, before) { var node = vnode.node, data = vnode.data, context = vnode.context, hasParent = api.parent(node); // 这里不调用 insertBefore,避免判断两次 if (before) { api.before(parentNode, node, before.node); } else { api.append(parentNode, node); } // 普通元素和组件的占位节点都会走到这里 // 但是占位节点不用 enter,而是等组件加载回来之后再调 enter if (!hasParent) { var enter = UNDEFINED; if (vnode.isComponent) { var component_1 = data[COMPONENT]; if (component_1) { enter = function () { enterVnode(vnode, component_1); }; } } else if (!vnode.isStatic && !vnode.isText && !vnode.isComment) { enter = function () { enterVnode(vnode); }; } if (enter) { // 执行到这时,组件还没有挂载到 DOM 树 // 如果此时直接触发 enter,外部还需要做多余的工作,比如 setTimeout // 索性这里直接等挂载到 DOM 数之后再触发 // 注意:YoxInterface 没有声明 $observer,因为不想让外部访问, // 但是这里要用一次,所以加了 as any context.$observer.nextTask.prepend(enter); } } } function removeVnodes(api, parentNode, vnodes, startIndex, endIndex) { var vnode, start = startIndex || 0, end = isDef(endIndex) ? endIndex : vnodes.length - 1; while (start <= end) { vnode = vnodes[start]; if (vnode) { removeVnode(api, parentNode, vnode); } start++; } } function removeVnode(api, parentNode, vnode) { var node = vnode.node; if (vnode.isStatic || vnode.isText || vnode.isComment) { api.remove(parentNode, node); } else { var done = function () { destroyVnode(api, vnode); api.remove(parentNode, node); }, component_2; if (vnode.isComponent) { component_2 = vnode.data[COMPONENT]; // 异步组件,还没加载成功就被删除了 if (!component_2) { done(); return; } } leaveVnode(vnode, component_2, done); } } function destroyVnode(api, vnode) { /** * 如果一个子组件的模板是这样写的: * * <div> * {{#if visible}} * <slot name="children"/> * {{/if}} * </div> * * 当 visible 从 true 变为 false 时,不能销毁 slot 导入的任何 vnode * 不论是组件或是元素,都不能销毁,只能简单的 remove, * 否则子组件下一次展现它们时,会出问题 */ var data = vnode.data, children = vnode.children, parent = vnode.parent, slot = vnode.slot; // 销毁插槽组件 // 如果宿主组件正在销毁,$vnode 属性会在调 destroy() 之前被删除 // 这里表示的是宿主组件还没被销毁 // 如果宿主组件被销毁了,则它的一切都要进行销毁 if (slot && parent && parent.$vnode) { // 如果更新时,父组件没有传入该 slot,则子组件需要销毁该 slot var slots = parent.get(slot); // slots 要么没有,要么是数组,不可能是别的 if (slots && has(slots, vnode)) { return; } } if (vnode.isComponent) { var component_3 = data[COMPONENT]; if (component_3) { remove$1(vnode); component_3.destroy(); } else { [ data[LOADING] = FALSE ]; } } else { remove$1(vnode); if (children) { each(children, function (child) { destroyVnode(api, child); }); } } } /** * vnode 触发 enter hook 时,外部一般会做一些淡入动画 */ function enterVnode(vnode, component) { // 如果组件根元素和组件本身都写了 transition // 优先用外面定义的 // 因为这明确是在覆盖配置 var data = vnode.data, transition = vnode.transition; if (component && !transition) { // 再看组件根元素是否有 transition transition = component.$vnode.transition; } execute(data[LEAVING]); if (transition) { var enter = transition.enter; if (enter) { enter(vnode.node); return; } } } /** * vnode 触发 leave hook 时,外部一般会做一些淡出动画 * 动画结束后才能移除节点,否则无法产生动画 * 这里由外部调用 done 来通知内部动画结束 */ function leaveVnode(vnode, component, done) { // 如果组件根元素和组件本身都写了 transition // 优先用外面定义的 // 因为这明确是在覆盖配置 var data = vnode.data, transition = vnode.transition; if (component && !transition) { // 再看组件根元素是否有 transition transition = component.$vnode.transition; } if (transition) { var leave = transition.leave; if (leave) { leave(vnode.node, data[LEAVING] = function () { if (data[LEAVING]) { done(); data[LEAVING] = UNDEFINED; } }); return; } } // 如果没有淡出动画,直接结束 done(); } function updateChildren(api, parentNode, children, oldChildren) { var startIndex = 0, endIndex = children.length - 1, startVnode = children[startIndex], endVnode = children[endIndex], oldStartIndex = 0, oldEndIndex = oldChildren.length - 1, oldStartVnode = oldChildren[oldStartIndex], oldEndVnode = oldChildren[oldEndIndex], oldKeyToIndex, oldIndex; while (oldStartIndex <= oldEndIndex && startIndex <= endIndex) { // 下面有设为 UNDEFINED 的逻辑 if (!startVnode) { startVnode = children[++startIndex]; } else if (!endVnode) { endVnode = children[--endIndex]; } else if (!oldStartVnode) { oldStartVnode = oldChildren[++oldStartIndex]; } else if (!oldEndVnode) { oldEndVnode = oldChildren[--oldEndIndex]; } // 从头到尾比较,位置相同且值得 patch else if (isPatchable(startVnode, oldStartVnode)) { patch(api, startVnode, oldStartVnode); startVnode = children[++startIndex]; oldStartVnode = oldChildren[++oldStartIndex]; } // 从尾到头比较,位置相同且值得 patch else if (isPatchable(endVnode, oldEndVnode)) { patch(api, endVnode, oldEndVnode); endVnode = children[--endIndex]; oldEndVnode = oldChildren[--oldEndIndex]; } // 比较完两侧的节点,剩下就是 位置发生改变的节点 和 全新的节点 // 当 endVnode 和 oldStartVnode 值得 patch // 说明元素被移到右边了 else if (isPatchable(endVnode, oldStartVnode)) { patch(api, endVnode, oldStartVnode); insertBefore(api, parentNode, oldStartVnode.node, api.next(oldEndVnode.node)); endVnode = children[--endIndex]; oldStartVnode = oldChildren[++oldStartIndex]; } // 当 oldEndVnode 和 startVnode 值得 patch // 说明元素被移到左边了 else if (isPatchable(startVnode, oldEndVnode)) { patch(api, startVnode, oldEndVnode); insertBefore(api, parentNode, oldEndVnode.node, oldStartVnode.node); startVnode = children[++startIndex]; oldEndVnode = oldChildren[--oldEndIndex]; } // 尝试同级元素的 key else { if (!oldKeyToIndex) { oldKeyToIndex = createKeyToIndex(oldChildren, oldStartIndex, oldEndIndex); } // 新节点之前的位置 oldIndex = startVnode.key ? oldKeyToIndex[startVnode.key] : UNDEFINED; // 移动元素 if (isDef(oldIndex)) { patch(api, startVnode, oldChildren[oldIndex]); oldChildren[oldIndex] = UNDEFINED; } // 新元素 else { createVnode(api, startVnode); } insertVnode(api, parentNode, startVnode, oldStartVnode); startVnode = children[++startIndex]; } } if (oldStartIndex > oldEndIndex) { addVnodes(api, parentNode, children, startIndex, endIndex, children[endIndex + 1]); } else if (startIndex > endIndex) { removeVnodes(api, parentNode, oldChildren, oldStartIndex, oldEndIndex); } } function patch(api, vnode, oldVnode) { if (vnode === oldVnode) { return; } var node = oldVnode.node, data = oldVnode.data; // 如果不能 patch,则删除重建 if (!isPatchable(vnode, oldVnode)) { // 同步加载的组件,初始化时不会传入占位节点 // 它内部会自动生成一个注释节点,当它的根 vnode 和注释节点对比时,必然无法 patch // 于是走进此分支,为新组件创建一个 DOM 节点,然后继续 createComponent 后面的流程 var parentNode = api.parent(node); createVnode(api, vnode); if (parentNode) { insertVnode(api, parentNode, vnode, oldVnode); removeVnode(api, parentNode, oldVnode); } return; } vnode.node = node; vnode.data = data; // 组件正在异步加载,更新为最新的 vnode // 当异步加载完成时才能用上最新的 vnode if (oldVnode.isComponent && data[LOADING]) { data[VNODE] = vnode; return; } // 两棵静态子树就别折腾了 if (vnode.isStatic && oldVnode.isStatic) { return; } update(api, vnode, oldVnode); update$1(api, vnode, oldVnode); update$3(vnode, oldVnode); update$2(vnode, oldVnode); var text = vnode.text, html = vnode.html, children = vnode.children, isStyle = vnode.isStyle, isOption = vnode.isOption, oldText = oldVnode.text, oldHtml = oldVnode.html, oldChildren = oldVnode.children; if (string(text)) { if (text !== oldText) { api.text(node, text, isStyle, isOption); } } else if (string(html)) { if (html !== oldHtml) { api.html(node, html, isStyle, isOption); } } // 两个都有需要 diff else if (children && oldChildren) { if (children !== oldChildren) { updateChildren(api, node, children, oldChildren); } } // 有新的没旧的 - 新增节点 else if (children) { if (string(oldText) || string(oldHtml)) { api.text(node, EMPTY_STRING, isStyle); } addVnodes(api, node, children); } // 有旧的没新的 - 删除节点 else if (oldChildren) { removeVnodes(api, node, oldChildren); } // 有旧的 text 没有新的 text else if (string(oldText) || string(oldHtml)) { api.text(node, EMPTY_STRING, isStyle); } } function create(api, node, context, keypath) { return { tag: api.tag(node), data: createData(), node: node, context: context, keypath: keypath }; } function destroy(api, vnode, isRemove) { if (isRemove) { var parentNode = api.parent(vnode.node); if (parentNode) { removeVnode(api, parentNode, vnode); } else { fatal("The vnode can't be destroyed without a parent node."); } } else { destroyVnode(api, vnode); } } /** * 元素 节点 */ var ELEMENT = 1; /** * 属性 节点 */ var ATTRIBUTE = 2; /** * 指令 节点 */ var DIRECTIVE = 3; /** * 属性 节点 */ var PROPERTY = 4; /** * 文本 节点 */ var TEXT = 5; /** * if 节点 */ var IF = 6; /** * else if 节点 */ var ELSE_IF = 7; /** * else 节点 */ var ELSE = 8; /** * each 节点 */ var EACH = 9; /** * partial 节点 */ var PARTIAL = 10; /** * import 节点 */ var IMPORT = 11; /** * 表达式 节点 */ var EXPRESSION = 12; /** * 延展操作 节点 */ var SPREAD = 13; // 特殊标签 var specialTags = {}; // 特殊属性 var specialAttrs = {}; // 名称 -> 类型的映射 var name2Type = {}; specialTags[RAW_SLOT] = specialTags[RAW_TEMPLATE] = specialAttrs[RAW_KEY] = specialAttrs[RAW_REF] = specialAttrs[RAW_SLOT] = TRUE; name2Type['if'] = IF; name2Type['each'] = EACH; name2Type['partial'] = PARTIAL; var helper = /*#__PURE__*/Object.freeze({ specialTags: specialTags, specialAttrs: specialAttrs, name2Type: name2Type }); function createAttribute(name) { return { type: ATTRIBUTE, isStatic: TRUE, name: name }; } function createDirective(name, ns, modifier) { return { type: DIRECTIVE, ns: ns, name: name, key: join$1(ns, name), modifier: modifier }; } function createProperty(name, hint, value, expr, children) { return { type: PROPERTY, isStatic: TRUE, name: name, hint: hint, value: value, expr: expr, children: children }; } function createEach(from, to, equal, index) { return { type: EACH, from: from, to: to, equal: equal, index: index, isComplex: TRUE }; } function createElement(tag, isSvg, isStyle, isComponent) { return { type: ELEMENT, tag: tag, isSvg: isSvg, isStyle: isStyle, // 只有 <option> 没有 value 属性时才为 true isOption: FALSE, isComponent: isComponent, isStatic: !isComponent && tag !== RAW_SLOT }; } function createElse() { return { type: ELSE }; } function createElseIf(expr) { return { type: ELSE_IF, expr: expr }; } function createExpression(expr, safe) { return { type: EXPRESSION, expr: expr, safe: safe, isLeaf: TRUE }; } function createIf(expr) { return { type: IF, expr: expr }; } function createImport(name) { return { type: IMPORT, name: name, isComplex: TRUE, isLeaf: TRUE }; } function createPartial(name) { return { type: PARTIAL, name: name, isComplex: TRUE }; } function createSpread(expr, binding) { return { type: SPREAD, expr: expr, binding: binding, isLeaf: TRUE }; } function createText(text) { return { type: TEXT, text: text, isStatic: TRUE, isLeaf: TRUE }; } // 首字母大写,或中间包含 - var componentNamePattern = /^[$A-Z]|-/, // HTML 实体(中间最多 6 位,没见过更长的) htmlEntityPattern = /&[#\w\d]{2,6};/, // 常见的自闭合标签 selfClosingTagNames = 'area,base,embed,track,source,param,input,col,img,br,hr'.split(','), // 常见的 svg 标签 svgTagNames = 'svg,g,defs,desc,metadata,symbol,use,image,path,rect,circle,line,ellipse,polyline,polygon,text,tspan,tref,textpath,marker,pattern,clippath,mask,filter,cursor,view,animate,font,font-face,glyph,missing-glyph,foreignObject'.split(','), // 常见的字符串类型的属性 // 注意:autocomplete,autocapitalize 不是布尔类型 stringProperyNames = 'id,class,name,value,for,accesskey,title,style,src,type,href,target,alt,placeholder,preload,poster,wrap,accept,pattern,dir,autocomplete,autocapitalize'.split(','), // 常见的数字类型的属性 numberProperyNames = 'min,minlength,max,maxlength,step,width,height,size,rows,cols,tabindex'.split(','), // 常见的布尔类型的属性 booleanProperyNames = 'disabled,checked,required,multiple,readonly,autofocus,autoplay,controls,loop,muted,novalidate,draggable,hidden,spellcheck'.split(','), // 某些属性 attribute name 和 property name 不同 attr2Prop = {}; // 列举几个常见的 attr2Prop['for'] = 'htmlFor'; attr2Prop['class'] = 'className'; attr2Prop['accesskey'] = 'accessKey'; attr2Prop['style'] = 'style.cssText'; attr2Prop['novalidate'] = 'noValidate'; attr2Prop['readonly'] = 'readOnly'; attr2Prop['tabindex'] = 'tabIndex'; attr2Prop['minlength'] = 'minLength'; attr2Prop['maxlength'] = 'maxLength'; function isSelfClosing(tagName) { return has(selfClosingTagNames, tagName); } function createAttribute$1(element, name) { // 组件用驼峰格式 if (element.isComponent) { return createAttribute(camelize(name)); } // 原生 dom 属性 else { // 把 attr 优化成 prop var lowerName = lower(name); // <slot> 、<template> 或 svg 中的属性不用识别为 property if (specialTags[element.tag] || element.isSvg) { return createAttribute(name); } // 尝试识别成 property else if (has(stringProperyNames, lowerName)) { return createProperty(attr2Prop[lowerName] || lowerName, HINT_STRING); } else if (has(numberProperyNames, lowerName)) { return createProperty(attr2Prop[lowerName] || lowerName, HINT_NUMBER); } else if (has(booleanProperyNames, lowerName)) { return createProperty(attr2Prop[lowerName] || lowerName, HINT_BOOLEAN); } // 没辙,还是个 attribute return createAttribute(name); } } function getAttributeDefaultValue(element, name) { // 比如 <Dog isLive> if (element.isComponent) { return TRUE; } // <div data-name checked> else { return startsWith(name, 'data-') ? EMPTY_STRING : name; } } function createElement$1(tagName) { var isSvg = has(svgTagNames, tagName), isComponent = FALSE; // 是 svg 就不可能是组件 // 加这个判断的原因是,svg 某些标签含有 连字符 和 大写字母,比较蛋疼 if (!isSvg && componentNamePattern.test(tagName)) { isComponent = TRUE; } return createElement(tagName, isSvg, tagName === 'style', isComponent); } function compatElement(element) { var tag = element.tag, attrs = element.attrs, hasType = FALSE, hasValue = FALSE; if (attrs) { each(attrs, function (attr) { var name = attr.type === PROPERTY ? attr.name : UNDEFINED; if (name === 'type') { hasType = TRUE; } else if (name === RAW_VALUE) { hasValue = TRUE; } }); } // 补全 style 标签的 type // style 如果没有 type 则加一个 type="text/css" // 因为低版本 IE 没这个属性,没法正常渲染样式 if (element.isStyle && !hasType) { push(element.attrs || (element.attrs = []), createProperty('type', HINT_STRING, 'text/css')); } // 低版本 IE 需要给 option 标签强制加 value else if (tag === 'option' && !hasValue) { element.isOption = TRUE; } } function setElementText(element, text) { if (htmlEntityPattern.test(text)) { element.html = text; return TRUE; } } function toNumber (target, defaultValue) { return numeric(target) ? +target : isDef(defaultValue) ? defaultValue : 0; } /** * 字面量 */ var LITERAL = 1; /** * 标识符 */ var IDENTIFIER = 2; /** * 对象属性或数组下标 */ var MEMBER = 3; /** * 一元表达式,如 - a */ var UNARY = 4; /** * 二元表达式,如 a + b */ var BINARY = 5; /** * 三元表达式,如 a ? b : c */ var TERNARY = 6; /** * 数组表达式,如 [ 1, 2, 3 ] */ var ARRAY = 7; /** * 对象表达式,如 { name: 'yox' } */ var OBJECT = 8; /** * 函数调用表达式,如 a() */ var CALL = 9; function createArray(nodes, raw) { return { type: ARRAY, raw: raw, nodes: nodes }; } function createBinary(left, operator, right, raw) { return { type: BINARY, raw: raw, left: left, operator: operator, right: right }; } function createCall(name, args, raw) { return { type: CALL, raw: raw, name: name, args: args }; } function createIdentifierInner(raw, name, lookup, offset) { return { type: IDENTIFIER, raw: raw, name: name, lookup: lookup, offset: offset }; } function createMemberInner(raw, lead, keypath, nodes, lookup, offset) { return { type: MEMBER, raw: raw, lead: lead, keypath: keypath, nodes: nodes, lookup: lookup, offset: offset }; } function createIdentifier(raw, name, isProp) { var lookup = TRUE, offset = 0; if (name === KEYPATH_CURRENT || name === KEYPATH_PARENT) { lookup = FALSE; if (name === KEYPATH_PARENT) { offset = 1; } name = EMPTY_STRING; } // 对象属性需要区分 a.b 和 a[b] // 如果不借用 Literal 无法实现这个判断 // 同理,如果用了这种方式,就无法区分 a.b 和 a['b'],但是无所谓,这两种表示法本就一个意思 return isProp ? createLiteral(name, raw) : createIdentifierInner(raw, name, lookup, offset); } function createLiteral(value, raw) { return { type: LITERAL, raw: raw, value: value }; } function createObject(keys, values, raw) { return { type: OBJECT, raw: raw, keys: keys, values: values }; } function createTernary(test, yes, no, raw) { return { type: TERNARY, raw: raw, test: test, yes: yes, no: no }; } function createUnary(operator, node, raw) { return { type: UNARY, raw: raw, operator: operator, node: node }; } /** * 通过判断 nodes 来决定是否需要创建 Member * * 创建 Member 至少需要 nodes 有两个元素 * * nodes 元素类型没有限制,可以是 Identifier、Literal、Call,或是别的完整表达式 * * @param raw * @param nodes */ function createMemberIfNeeded(raw, nodes) { var firstNode = nodes.shift(), length = nodes.length, lookup = TRUE, offset = 0; // member 要求至少两个节点 if (length > 0) { // 处理剩下的 nodes // 这里要做两手准备: // 1. 如果全是 literal 节点,则编译时 join // 2. 如果不全是 literal 节点,则运行时 join var isLiteral_1 = TRUE, staticNodes_1 = [], runtimeNodes_1 = []; each(nodes, function (node) { if (node.type === LITERAL) { var literal = node; if (literal.raw === KEYPATH_PARENT) { offset += 1; return; } if (literal.raw !== KEYPATH_CURRENT) { push(staticNodes_1, toString(literal.value)); } } else { isLiteral_1 = FALSE; } push(runtimeNodes_1, node); }); // lookup 要求第一位元素是 Identifier,且它的 lookup 是 true 才为 true // 其他情况都为 false,如 "11".length 第一位元素是 Literal,不存在向上寻找的需求 // 优化 1:计算 keypath // // 计算 keypath 的唯一方式是,第一位元素是 Identifier,后面都是 Literal // 否则就表示中间包含动态元素,这会导致无法计算静态路径 // 如 a.b.c 可以算出 staticKeypath,而 a[b].c 则不行,因为 b 是动态的 // 优化 2:计算 offset 并智能转成 Identifier // // 比如 xx 这样的表达式,应优化成 offset = 2,并转成 Identifier // 处理第一个节点 if (firstNode.type === IDENTIFIER) { var identifier = firstNode; lookup = identifier.lookup; offset += identifier.offset; var name = identifier.name; // 不是 KEYPATH_THIS 或 KEYPATH_PARENT if (name) { unshift(staticNodes_1, name); } // a.b.c if (isLiteral_1) { // 转成 Identifier name = join(staticNodes_1, RAW_DOT); firstNode = createIdentifierInner(name, name, lookup, offset); } // a[b] else { firstNode = createMemberInner(raw, firstNode, UNDEFINED, runtimeNodes_1, lookup, offset); } } else { // "xxx".length // format().a.b if (isLiteral_1) { firstNode = createMemberInner(raw, firstNode, join(staticNodes_1, RAW_DOT), UNDEFINED, lookup, offset); } // "xxx"[length] // format()[a] else { firstNode = createMemberInner(raw, firstNode, UNDEFINED, runtimeNodes_1, lookup, offset); } } } return firstNode; } var unary = { '+': TRUE, '-': TRUE, '~': TRUE, '!': TRUE, '!!': TRUE }; // 参考 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence var binary = { '*': 14, '/': 14, '%': 14, '+': 13, '-': 13, '<<': 12, '>>': 12, '>>>': 12, '<': 11, '<=': 11, '>': 11, '>=': 11, '==': 10, '!=': 10, '===': 10, '!==': 10, '&': 9, '^': 8, '|': 7, '&&': 6, '||': 5 }; function compile(content) { if (!cache[content]) { var parser = new Parser(content); cache[content] = parser.scanTernary(CODE_EOF); } return cache[content]; } var Parser = /** @class */ (function () { function Parser(content) { var instance = this, length = content.length; instance.index = MINUS_ONE; instance.end = length; instance.code = CODE_EOF; instance.content = content; instance.go(); } /** * 移动一个字符 */ Parser.prototype.go = function (step) { var instance = this, index = instance.index, end = instance.end; index += step || 1; if (index >= 0 && index < end) { instance.code = codeAt(instance.content, index); instance.index = index; } else { instance.code = CODE_EOF; instance.index = index < 0 ? MINUS_ONE : end; } }; /** * 跳过空白符 */ Parser.prototype.skip = function (step) { var instance = this, reversed = step && step < 0; // 如果表达式是 " xyz ",到达结尾后,如果希望 skip(-1) 回到最后一个非空白符 // 必须先判断最后一个字符是空白符,否则碰到 "xyz" 这样结尾不是空白符的,其实不应该回退 if (instance.code === CODE_EOF) { var oldIndex = instance.index; instance.go(step); // 如果跳一位之后不是空白符,还原,然后返回 if (!isWhitespace(instance.code)) { instance.go(oldIndex - instance.index); return; } } // 逆向时,只有位置真的发生过变化才需要在停止时正向移动一位 // 比如 (a) 如果调用 skip 前位于 ),调用 skip(-1) ,结果应该是原地不动 // 为了解决这个问题,应该首先判断当前是不是空白符,如果不是,直接返回 else if (!isWhitespace(instance.code)) { return; } // 如果是正向的,停在第一个非空白符左侧 // 如果是逆向的,停在第一个非空白符右侧 while (TRUE) { if (isWhitespace(instance.code)) { instance.go(step); } else { if (reversed) { instance.go(); } break; } } }; /** * 判断当前字符 */ Parser.prototype.is = function (code) { return this.code === code; }; /** * 截取一段字符串 */ Parser.prototype.pick = function (startIndex, endIndex) { return slice(this.content, startIndex, isDef(endIndex) ? endIndex : this.index); }; /** * 尝试解析下一个 token */ Parser.prototype.scanToken = function () { var instance = this, code = instance.code, index = instance.index; if (isIdentifierStart(code)) { return instance.scanTail(index, [ instance.scanIdentifier(index) ]); } if (isDigit(code)) { return instance.scanNumber(index); } switch (code) { case CODE_EOF: return; // 'x' "x" case CODE_SQUOTE: case CODE_DQUOTE: return instance.scanTail(index, [ instance.scanString(index, code) ]); // .1 ./ ../ case CODE_DOT: instance.go(); return isDigit(instance.code) ? instance.scanNumber(index) : instance.scanPath(index); // (xx) case CODE_OPAREN: instance.go(); return instance.scanTernary(CODE_CPAREN); // [xx, xx] case CODE_OBRACK: return instance.scanTail(index, [ createArray(instance.scanTuple(index, CODE_CBRACK), instance.pick(index)) ]); // { a: 'x', b: 'x' } case CODE_OBRACE: return instance.scanObject(index); } // 因为 scanOperator 会导致 index 发生变化,只能放在最后尝试 var operator = instance.scanOperator(index); if (operator && unary[operator]) { var node = instance.scanTernary(); if (node) { if (node.type === LITERAL) { var value = node.value; if (number(value)) { // 类似 ' -1 ' 这样的右侧有空格,需要撤回来 instance.skip(MINUS_ONE); return createLiteral(-value, instance.pick(index)); } } // 类似 ' -a ' 这样的右侧有空格,需要撤回来 instance.skip(MINUS_ONE); return createUnary(operator, node, instance.pick(index)); } { // 一元运算只有操作符没有表达式? instance.fatal(index, "Expression expected."); } } }; /** * 扫描数字 * * 支持整数和小数 * * @param startIndex * @return */ Parser.prototype.scanNumber = function (startIndex) { var instance = this; while (isNumber(instance.code)) { instance.go(); } var raw = instance.pick(startIndex); // 尝试转型,如果转型失败,则确定是个错误的数字 if (numeric(raw)) { return createLiteral(+raw, raw); } { instance.fatal(startIndex, "Number expected."); } }; /** * 扫描字符串 * * 支持反斜线转义引号 * * @param startIndex * @param endCode */ Parser.prototype.scanString = function (startIndex, endCode) { var instance = this; loop: while (TRUE) { // 这句有两个作用: // 1. 跳过开始的引号 // 2. 驱动 index 前进 instance.go(); switch (instance.code) { // \" \' case CODE_BACKSLASH: instance.go(); break; case endCode: instance.go(); break loop; case CODE_EOF: { // 到头了,字符串还没解析完呢? instance.fatal(startIndex, 'Unexpected end of text.'); } break loop; } } // new Function 处理字符转义 var raw = instance.pick(startIndex); return createLiteral(new Function("return " + raw)(), raw); }; /** * 扫描对象字面量 * * @param startIndex */ Parser.prototype.scanObject = function (startIndex) { var instance = this, keys = [], values = [], isKey = TRUE, node; // 跳过 { instance.go(); loop: while (TRUE) { switch (instance.code) { case CODE_CBRACE: instance.go(); { // 对象的 keys 和 values 的长度不一致 if (keys.length !== values.length) { instance.fatal(startIndex, 'The number of keys and values must be equal.'); } } break loop; case CODE_EOF: { // 到头了,对象还没解析完呢? instance.fatal(startIndex, 'Unexpected end of text.'); } break loop; // : case CODE_COLON: instance.go(); isKey = FALSE; break; // , case CODE_COMMA: instance.go(); isKey = TRUE; break; default: // 解析 key 的时候,node 可以为空,如 { } 或 { name: 'xx', } // 解析 value 的时候,node 不能为空 node = instance.scanTernary(); if (isKey) { if (node) { // 处理 { key : value } key 后面的空格 instance.skip(); if (node.type === IDENTIFIER) { push(keys, node.name); } else if (node.type === LITERAL) { push(keys, node.value); } else { { // 对象的 key 必须是字面量或标识符 instance.fatal(startIndex, 'The key of an object must be a literal or identifier.'); } break loop; } } } else if (node) { // 处理 { key : value } value 后面的空格 instance.skip(); push(values, node); } // 类似这样 { key: } else { { // 对象的值没找到 instance.fatal(startIndex, "The value of the object was not found."); } break loop; } } } return createObject(keys, values, instance.pick(startIndex)); }; /** * 扫描元组,即 `a, b, c` 这种格式,可以是参数列表,也可以是数组 * * @param startIndex * @param endCode 元组的结束字符编码 */ Parser.prototype.scanTuple = function (startIndex, endCode) { var instance = this, nodes = [], node; // 跳过开始字符,如 [ 和 ( instance.go(); loop: while (TRUE) { switch (instance.code) { case endCode: instance.go(); break loop; case CODE_EOF: { // 到头了,tuple 还没解析完呢? instance.fatal(startIndex, 'Unexpected end of text.'); } break loop; case CODE_COMMA: instance.go(); break; default: // 1. ( ) // 2. (1, 2, ) // 这三个例子都会出现 scanTernary 为空的情况 // 但是不用报错 node = instance.scanTernary(); if (node) { // 为了解决 1 , 2 , 3 这样的写法 // 当解析出值后,先跳过后面的空格 instance.skip(); push(nodes, node); } } } return nodes; }; /** * 扫描路径,如 `./` 和 `../` * * 路径必须位于开头,如 ./../ 或 ,不存在 a/../b/../c 这样的情况,因为路径是用来切换或指定 context 的 * * @param startIndex * @param prevNode */ Parser.prototype.scanPath = function (startIndex) { var instance = this, nodes = [], name; // 进入此函数时,已确定前一个 code 是 CODE_DOT // 此时只需判断接下来是 ./ 还是 / 就行了 while (TRUE) { // 要么是 current 要么是 parent name = KEYPATH_CURRENT; // ../ if (instance.is(CODE_DOT)) { instance.go(); name = KEYPATH_PARENT; } push(nodes, createIdentifier(name, name, nodes.length > 0)); // 如果以 / 结尾,则命中 ./ 或 ../ if (instance.is(CODE_SLASH)) { instance.go(); // 没写错,这里不必强调 isIdentifierStart,数字开头也可以吧 if (isIdentifierPart(instance.code)) { push(nodes, instance.scanIdentifier(instance.index, TRUE)); return instance.scanTail(startIndex, nodes); } else if (instance.is(CODE_DOT)) { // 先跳过第一个 . instance.go(); // 继续循环 } else { // 类似 ./ 或 ../ 这样后面不跟标识符是想干嘛?报错可好? { instance.fatal(startIndex, last(nodes).raw + "/ must be followed by an identifier."); } break; } } // 类似 . 或 ..,可能就是想读取层级对象 // 此处不用关心后面跟的具体是什么字符,那是其他函数的事情,就算报错也让别的函数去报 // 此处也不用关心延展操作符,即 ...object,因为表达式引擎管不了这事,它没法把对象变成 attr1=value1 attr2=value2 的格式 // 这应该是模板引擎该做的事 else { break; } } }; /** * 扫描变量 */ Parser.prototype.scanTail = function (startIndex, nodes) { var instance = this, node; /** * 标识符后面紧着的字符,可以是 ( . [,此外还存在各种组合,感受一下: * * a.b.c().length * a[b].c()() * a[b][c]()[d](e, f, g).length * [].length */ loop: while (TRUE) { switch (instance.code) { // a(x) case CODE_OPAREN: nodes = [ createCall(createMemberIfNeeded(instance.pick(startIndex), nodes), instance.scanTuple(instance.index, CODE_CPAREN), instance.pick(startIndex)) ]; break; // a.x case CODE_DOT: instance.go(); // 接下来的字符,可能是数字,也可能是标识符,如果不是就报错 if (isIdentifierPart(instance.code)) { // 无需识别关键字 push(nodes, instance.scanIdentifier(instance.index, TRUE)); break; } else { { // . 后面跟的都是啥玩意啊 instance.fatal(startIndex, 'Identifier or number expected.'); } break loop; } // a[] case CODE_OBRACK: // 过掉 [ instance.go(); node = instance.scanTernary(CODE_CBRACK); if (node) { push(nodes, node); break; } else { // [] 内部不能为空 { instance.fatal(startIndex, "[] is not allowed."); } break loop; } default: break loop; } } return createMemberIfNeeded(instance.pick(startIndex), nodes); }; /** * 扫描标识符 * * @param startIndex * @param isProp 是否是对象的属性 * @return */ Parser.prototype.scanIdentifier = function (startIndex, isProp) { var instance = this; while (isIdentifierPart(instance.code)) { instance.go(); } var raw = instance.pick(startIndex); return !isProp && raw in keywordLiterals ? createLiteral(keywordLiterals[raw], raw) : createIdentifier(raw, raw, isProp); }; /** * 扫描运算符 * * @param startIndex */ Parser.prototype.scanOperator = function (startIndex) { var instance = this; switch (instance.code) { // /、%、~、^ case CODE_DIVIDE: case CODE_MODULO: case CODE_WAVE: case CODE_XOR: instance.go(); break; // * case CODE_MULTIPLY: instance.go(); break; // + case CODE_PLUS: instance.go(); { // ++ if (instance.is(CODE_PLUS)) { instance.fatal(startIndex, '++ is not supported.'); } } break; // - case CODE_MINUS: instance.go(); { // -- if (instance.is(CODE_MINUS)) { instance.fatal(startIndex, '-- is not supported.'); } } break; // !、!!、!=、!== case CODE_NOT: instance.go(); if (instance.is(CODE_NOT)) { instance.go(); } else if (instance.is(CODE_EQUAL)) { instance.go(); if (instance.is(CODE_EQUAL)) { instance.go(); } } break; // &、&& case CODE_AND: instance.go(); if (instance.is(CODE_AND)) { instance.go(); } break; // |、|| case CODE_OR: instance.go(); if (instance.is(CODE_OR)) { instance.go(); } break; // ==、=== case CODE_EQUAL: instance.go(); if (instance.is(CODE_EQUAL)) { instance.go(); if (instance.is(CODE_EQUAL)) { instance.go(); } } // 一个等号要报错 else { instance.fatal(startIndex, 'Assignment statements are not supported.'); } break; // <、<=、<< case CODE_LESS: instance.go(); if (instance.is(CODE_EQUAL) || instance.is(CODE_LESS)) { instance.go(); } break; // >、>=、>>、>>> case CODE_GREAT: instance.go(); if (instance.is(CODE_EQUAL)) { instance.go(); } else if (instance.is(CODE_GREAT)) { instance.go(); if (instance.is(CODE_GREAT)) { instance.go(); } } break; } if (instance.index > startIndex) { return instance.pick(startIndex); } }; /** * 扫描二元运算 */ Parser.prototype.scanBinary = function (startIndex) { // 二元运算,如 a + b * c / d,这里涉及运算符的优先级 // 算法参考 https://en.wikipedia.org/wiki/Shunting-yard_algorithm var instance = this, // 格式为 [ index1, node1, index2, node2, ... ] output = [], token, index, operator, operatorPrecedence, lastOperator, lastOperatorPrecedence; while (TRUE) { instance.skip(); push(output, instance.index); token = instance.scanToken(); if (token) { push(output, token); push(output, instance.index); instance.skip(); operator = instance.scanOperator(instance.index); // 必须是二元运算符,一元不行 if (operator && (operatorPrecedence = binary[operator])) { // 比较前一个运算符 index = output.length - 4; // 如果前一个运算符的优先级 >= 现在这个,则新建 Binary // 如 a + b * c / d,当从左到右读取到 / 时,发现和前一个 * 优先级相同,则把 b * c 取出用于创建 Binary if ((lastOperator = output[index]) && (lastOperatorPrecedence = binary[lastOperator]) && lastOperatorPrecedence >= operatorPrecedence) { output.splice(index - 2, 5, createBinary(output[index - 2], lastOperator, output[index + 2], instance.pick(output[index - 3], output[index + 3]))); } push(output, operator); continue; } else { operator = UNDEFINED; } } // 比如不支持的表达式,a++ 之类的 else { if (operator) { instance.fatal(startIndex, 'Invalid syntax.'); } } // 没匹配到 token 或 operator 则跳出循环 break; } // 类似 a + b * c 这种走到这会有 11 个 // 此时需要从后往前遍历,因为确定后面的优先级肯定大于前面的 while (TRUE) { // 最少的情况是 a + b,它有 7 个元素 if (output.length >= 7) { index = output.length - 4; output.splice(index - 2, 5, createBinary(output[index - 2], output[index], output[index + 2], instance.pick(output[index - 3], output[index + 3]))); } else { return output[1]; } } }; /** * 扫描三元运算 * * @param endCode */ Parser.prototype.scanTernary = function (endCode) { /** * https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Operator_Precedence * * ?: 运算符的优先级几乎是最低的,比它低的只有四种: 赋值、yield、延展、逗号 * 我们不支持这四种,因此可认为 ?: 优先级最低 */ var instance = this; instance.skip(); var index = instance.index, test = instance.scanBinary(index), yes, no; if (instance.is(CODE_QUESTION)) { // 跳过 ? instance.go(); yes = instance.scanBinary(index); if (instance.is(CODE_COLON)) { // 跳过 : instance.go(); no = instance.scanBinary(index); } if (test && yes && no) { // 类似 ' a ? 1 : 0 ' 这样的右侧有空格,需要撤回来 instance.skip(MINUS_ONE); test = createTernary(test, yes, no, instance.pick(index)); } else { // 三元表达式语法错误 instance.fatal(index, "Invalid ternary syntax."); } } // 过掉结束字符 if (isDef(endCode)) { instance.skip(); if (instance.is(endCode)) { instance.go(); } // 没匹配到结束字符要报错 else { instance.fatal(index, "\"" + String.fromCharCode(endCode) + "\" expected, \"" + String.fromCharCode(instance.code) + "\" actually."); } } return test; }; Parser.prototype.fatal = function (start, message) { { fatal("Error compiling expression\n\n" + this.content + "\n\nmessage: " + message + "\n"); } }; return Parser; }()); var cache = {}, CODE_EOF = 0, // CODE_DOT = 46, // . CODE_COMMA = 44, // , CODE_SLASH = 47, // / CODE_BACKSLASH = 92, // \ CODE_SQUOTE = 39, // ' CODE_DQUOTE = 34, // " CODE_OPAREN = 40, // ( CODE_CPAREN = 41, // ) CODE_OBRACK = 91, // [ CODE_CBRACK = 93, // ] CODE_OBRACE = 123, // { CODE_CBRACE = 125, // } CODE_QUESTION = 63, // ? CODE_COLON = 58, // : CODE_PLUS = 43, // + CODE_MINUS = 45, // - CODE_MULTIPLY = 42, // * CODE_DIVIDE = 47, // / CODE_MODULO = 37, // % CODE_WAVE = 126, // ~ CODE_AND = 38, // & CODE_OR = 124, // | CODE_XOR = 94, // ^ CODE_NOT = 33, // ! CODE_LESS = 60, // < CODE_EQUAL = 61, // = CODE_GREAT = 62, // > /** * 区分关键字和普通变量 * 举个例子:a === true * 从解析器的角度来说,a 和 true 是一样的 token */ keywordLiterals = {}; keywordLiterals[RAW_TRUE] = TRUE; keywordLiterals[RAW_FALSE] = FALSE; keywordLiterals[RAW_NULL] = NULL; keywordLiterals[RAW_UNDEFINED] = UNDEFINED; /** * 是否是空白符,用下面的代码在浏览器测试一下 * * ``` * for (var i = 0; i < 200; i++) { * console.log(i, String.fromCharCode(i)) * } * ``` * * 从 0 到 32 全是空白符,100 往上分布比较散且较少用,唯一需要注意的是 160 * * 160 表示 non-breaking space * http://www.adamkoch.com/2009/07/25/white-space-and-character-160/ */ function isWhitespace(code) { return (code > 0 && code < 33) || code === 160; } /** * 是否是数字 */ function isDigit(code) { return code > 47 && code < 58; // 0...9 } /** * 是否是数字 */ function isNumber(code) { return isDigit(code) || code === CODE_DOT; } /** * 变量开始字符必须是 字母、下划线、$ */ function isIdentifierStart(code) { return code === 36 // $ || code === 95 // _ || (code > 96 && code < 123) // a...z || (code > 64 && code < 91); // A...Z } /** * 变量剩余的字符必须是 字母、下划线、$、数字 */ function isIdentifierPart(code) { return isIdentifierStart(code) || isDigit(code); } // 当前不位于 block 之间 var BLOCK_MODE_NONE = 1, // {{ x }} BLOCK_MODE_SAFE = 2, // {{{ x }}} BLOCK_MODE_UNSAFE = 3, // 缓存编译正则 patternCache$1 = {}, // 指令分隔符,如 on-click 和 lazy-click directiveSeparator = '-', // 没有命名空间的事件 eventPattern = /^[_$a-z]([\w]+)?$/i, // 有命名空间的事件 eventNamespacePattern = /^[_$a-z]([\w]+)?\.[_$a-z]([\w]+)?$/i, // 换行符 // 比较神奇是,有时候你明明看不到换行符,却真的存在一个,那就是 \r breaklinePattern = /^\s*[\n\r]\s*|\s*[\n\r]\s*$/g, // 区间遍历 rangePattern = /\s*(=>|->)\s*/, // 标签 tagPattern = /<(\/)?([$a-z][-a-z0-9]*)/i, // 注释 commentPattern = /<!--[\s\S]*?-->/g, // 开始注释 openCommentPattern = /^([\s\S]*?)<!--/, // 结束注释 closeCommentPattern = /-->([\s\S]*?)$/, // 属性的 name // 支持 on-click.namespace="" 或 on-get-out="" 或 xml:xx="" attributePattern = /^\s*([-.:\w]+)(['"])?(?:=(['"]))?/, // 自闭合标签 selfClosingTagPattern = /^\s*(\/)?>/; /** * 截取前缀之后的字符串 */ function slicePrefix(str, prefix) { return trim(slice(str, prefix.length)); } function compile$1(content) { var nodeList = [], nodeStack = [], // 持有 if/elseif/else 节点 ifStack = [], currentElement, currentAttribute, length = content.length, // 当前处理的位置 index = 0, // 下一段开始的位置 nextIndex = 0, // 开始定界符的位置,表示的是 {{ 的右侧位置 openBlockIndex = 0, // 结束定界符的位置,表示的是 }} 的左侧位置 closeBlockIndex = 0, // 当前正在处理或即将处理的 block 类型 blockMode = BLOCK_MODE_NONE, // mustache 注释可能出现嵌套插值的情况 blockStack = [], indexList = [], code, startQuote, fatal$1 = function (msg) { { fatal("Error compiling template\n\n" + content + "\n\nmessage: " + msg); } }, /** * 常见的两种情况: * * <div> * <input>1 * </div> * * <div> * <input> * </div> */ popSelfClosingElementIfNeeded = function (popingTagName) { var lastNode = last(nodeStack); if (lastNode && lastNode.type === ELEMENT) { var element = lastNode; if (element.tag !== popingTagName && isSelfClosing(element.tag)) { popStack(element.type, element.tag); } } }, popStack = function (type, tagName) { var node = pop(nodeStack); if (node && node.type === type) { var children = node.children, // 优化单个子节点 child = children && children.length === 1 && children[0], isElement = type === ELEMENT, isAttribute = type === ATTRIBUTE, isProperty = type === PROPERTY, isDirective = type === DIRECTIVE; var currentBranch = last(nodeStack); if (currentBranch) { if (currentBranch.isStatic && !node.isStatic) { currentBranch.isStatic = FALSE; } if (!currentBranch.isComplex) { if (node.isComplex || isElement) { currentBranch.isComplex = TRUE; } // <div {{#if xx}} xx{{/if}}> else if (currentElement && currentElement !== currentBranch && (isAttribute || isProperty || isDirective)) { currentBranch.isComplex = TRUE; } } } { if (isElement) { var element = node; if (tagName && element.tag !== tagName) { fatal$1("End tag is \"" + tagName + "\"\uFF0Cbut start tag is \"" + element.tag + "\"."); } } } // 除了 helper.specialAttrs 里指定的特殊属性,attrs 里的任何节点都不能单独拎出来赋给 element // 因为 attrs 可能存在 if,所以每个 attr 最终都不一定会存在 if (child) { switch (child.type) { case TEXT: // 属性的值如果是纯文本,直接获取文本值 // 减少渲染时的遍历 if (isElement) { processElementSingleText(node, child); } else if (isAttribute) { processAttributeSingleText(node, child); } else if (isProperty) { processPropertySingleText(node, child); } else if (isDirective) { processDirectiveSingleText(node, child); } break; case EXPRESSION: if (isElement) { processElementSingleExpression(node, child); } else if (isAttribute) { processAttributeSingleExpression(node, child); } else if (isProperty) { processPropertySingleExpression(node, child); } else if (isDirective) { processDirectiveSingleExpression(node, child); } break; } } // 大于 1 个子节点,即有插值或 if 写法 else if (children) { if (isDirective) { processDirectiveMultiChildren(); } // 元素层级 else if (!currentElement) { removeComment(children); if (!children.length) { node.children = UNDEFINED; } } } // 0 个子节点 else if (currentElement) { if (isAttribute) { processAttributeEmptyChildren(currentElement, node); } else if (isProperty) { processPropertyEmptyChildren(currentElement, node); } else if (isDirective) { processDirectiveEmptyChildren(currentElement, node); } } if (type === EACH) { checkEach(node); } else if (type === PARTIAL) { checkPartial(node); } else if (isElement) { checkElement(node); } else if (currentElement) { if (isAttribute) { if (isSpecialAttr(currentElement, node)) { bindSpecialAttr(currentElement, node); } } else if (isDirective) { checkDirective(currentElement, node); } } return node; } // 出栈节点类型不匹配 { fatal$1("The poping node type is not as expected."); } }, removeComment = function (children) { // 类似 <!-- xx {{name}} yy {{age}} zz --> 这样的注释里包含插值 // 按照目前的解析逻辑,是根据定界符进行模板分拆 // 一旦出现插值,children 长度必然大于 1 var openIndex = MINUS_ONE, openText = EMPTY_STRING, closeIndex = MINUS_ONE, closeText = EMPTY_STRING; each(children, function (child, index) { if (child.type === TEXT) { if (closeIndex >= 0) { openText = child.text; // 处理 <!-- <!-- 这样有多个的情况 while (openCommentPattern.test(openText)) { openText = RegExp.$1; openIndex = index; } if (openIndex >= 0) { // openIndex 肯定小于 closeIndex,因为完整的注释在解析过程中会被干掉 // 只有包含插值的注释才会走进这里 // 现在要确定开始和结束的文本节点,是否包含正常文本 if (openText) { children[openIndex].text = openText; openIndex++; } if (closeText) { children[closeIndex].text = closeText; closeIndex--; } children.splice(openIndex, closeIndex - openIndex + 1); openIndex = closeIndex = MINUS_ONE; } } else { closeText = child.text; // 处理 --> --> 这样有多个的情况 while (closeCommentPattern.test(closeText)) { closeText = RegExp.$1; closeIndex = index; } } } }, TRUE); }, processDirectiveMultiChildren = function () { // 不支持 on-click="1{{xx}}2" 或是 on-click="1{{#if x}}x{{else}}y{{/if}}2" // 1. 很难做性能优化 // 2. 全局搜索不到事件名,不利于代码维护 // 3. 不利于编译成静态函数 { fatal$1("{{ and }} are not allowed in directive."); } }, processElementSingleText = function (element, child) { // processElementSingleText 和 processElementSingleExpression // 不把元素子节点智能转换为 textContent property // 因为子节点还有 <div>1{{a}}{{b}}</div> 这样的情况 // 还是在序列化的时候统一处理比较好 // 唯独需要在这特殊处理的是 html 实体 // 但这只是 WEB 平台的特殊逻辑,所以丢给 platform 处理 if (setElementText(element, child.text)) { element.children = UNDEFINED; } }, processElementSingleExpression = function (element, child) { if (!element.isComponent && !element.slot && !child.safe) { element.html = child.expr; element.children = UNDEFINED; } }, processPropertyEmptyChildren = function (element, prop) { if (prop.hint === HINT_BOOLEAN) { prop.value = TRUE; } else { // string 或 number 类型的属性,如果不写值,直接忽略 replaceChild(prop); } }, processPropertySingleText = function (prop, child) { var text = child.text; if (prop.hint === HINT_NUMBER) { prop.value = toNumber(text); } else if (prop.hint === HINT_BOOLEAN) { prop.value = text === RAW_TRUE || text === prop.name; } else { prop.value = text; } prop.children = UNDEFINED; }, processPropertySingleExpression = function (prop, child) { var expr = child.expr; prop.expr = expr; prop.children = UNDEFINED; // 对于有静态路径的表达式,可转为单向绑定指令,可实现精确更新视图,如下 // <div class="{{className}}"> if (expr.type === IDENTIFIER) { prop.binding = TRUE; } }, processAttributeEmptyChildren = function (element, attr) { if (isSpecialAttr(element, attr)) { { fatal$1("The value of \"" + attr.name + "\" is empty."); } } else { attr.value = getAttributeDefaultValue(element, attr.name); } }, processAttributeSingleText = function (attr, child) { attr.value = child.text; attr.children = UNDEFINED; }, processAttributeSingleExpression = function (attr, child) { var expr = child.expr; attr.expr = expr; attr.children = UNDEFINED; // 对于有静态路径的表达式,可转为单向绑定指令,可实现精确更新视图,如下 // <div class="{{className}}"> if (expr.type === IDENTIFIER) { attr.binding = TRUE; } }, processDirectiveEmptyChildren = function (element, directive) { directive.value = TRUE; }, processDirectiveSingleText = function (directive, child) { var text = child.text, // model="xx" model="this.x" 值只能是标识符或 Member isModel = directive.ns === DIRECTIVE_MODEL, // lazy 的值必须是大于 0 的数字 isLazy = directive.ns === DIRECTIVE_LAZY, // 校验事件名称 // 且命名空间不能用 native isEvent = directive.ns === DIRECTIVE_EVENT, // 自定义指令运行不合法的表达式 isCustom = directive.ns === DIRECTIVE_CUSTOM, // 指令的值是纯文本,可以预编译表达式,提升性能 expr, error; try { expr = compile(text); } catch (e) { error = e; } if (expr) { { var raw = expr.raw; if (isLazy) { if (expr.type !== LITERAL || !number(expr.value) || expr.value <= 0) { fatal$1("The value of lazy must be a number greater than 0."); } } // 如果指令表达式是函数调用,则只能调用方法(难道还有别的可以调用的吗?) else if (expr.type === CALL) { if (expr.name.type !== IDENTIFIER) { fatal$1('The method name that appear on directive must be an identifier.'); } } // 上面检测过方法调用,接下来事件指令只需要判断是否以下两种格式: // on-click="name" 或 on-click="name.namespace" else if (isEvent) { if (eventPattern.test(raw) || eventNamespacePattern.test(raw)) { // native 有特殊用处,不能给业务层用 if (eventNamespacePattern.test(raw) && raw.split(RAW_DOT)[1] === MODIFER_NATIVE) { fatal$1("The event namespace \"" + MODIFER_NATIVE + "\" is not permitted."); } // <Button on-click="click"> 这种写法没有意义 if (currentElement && currentElement.isComponent && directive.name === raw) { fatal$1("The event name listened and fired can't be the same."); } } // 事件转换名称只能是 [name] 或 [name.namespace] 格式 else { fatal$1('The event name and namespace must be an identifier.'); } } if (isModel && expr.type !== IDENTIFIER) { fatal$1("The value of the model must be an identifier."); } } directive.expr = expr; directive.value = expr.type === LITERAL ? expr.value : text; } else { { if (!isCustom) { throw error; } } directive.value = text; } directive.children = UNDEFINED; }, processDirectiveSingleExpression = function (directive, child) { { fatal$1("{{ and }} are not allowed in a directive value."); } }, checkCondition = function (condition) { var currentNode = condition, prevNode, hasChildren, hasNext; while (TRUE) { if (currentNode.children) { if (!hasNext) { if (currentNode.next) { delete currentNode.next; } } hasChildren = hasNext = TRUE; } prevNode = currentNode.prev; if (prevNode) { // prev 仅仅用在 checkCondition 函数中 // 用完就可以删掉了 delete currentNode.prev; currentNode = prevNode; } else { break; } } // 每个条件都是空内容,则删掉整个 if if (!hasChildren) { replaceChild(currentNode); } }, checkEach = function (each) { // 没内容就干掉 if (!each.children) { replaceChild(each); } }, checkPartial = function (partial) { // 没内容就干掉 if (!partial.children) { replaceChild(partial); } }, checkElement = function (element) { var tag = element.tag, slot = element.slot, isTemplate = tag === RAW_TEMPLATE; { if (isTemplate) { if (element.key) { fatal$1("The \"key\" is not supported in <template>."); } else if (element.ref) { fatal$1("The \"ref\" is not supported in <template>."); } else if (element.attrs) { fatal$1("The attributes and directives are not supported in <template>."); } else if (!slot) { fatal$1("The \"slot\" is required in <template>."); } } } // 没有子节点,则意味着这个插槽没任何意义 if (isTemplate && slot && !element.children) { replaceChild(element); } // <slot /> 如果没写 name,自动加上默认名称 else if (tag === RAW_SLOT && !element.name) { element.name = SLOT_NAME_DEFAULT; } else { compatElement(element); } }, checkDirective = function (element, directive) { { // model 不能写在 if 里,影响节点的静态结构 if (directive.ns === DIRECTIVE_MODEL) { if (last(nodeStack) !== element) { fatal$1("The \"model\" can't be used in an if block."); } } } }, bindSpecialAttr = function (element, attr) { var name = attr.name, value = attr.value, // 这三个属性值要求是字符串 isStringValueRequired = name === RAW_NAME || name === RAW_SLOT; { // 因为要拎出来给 element,所以不能用 if if (last(nodeStack) !== element) { fatal$1("The \"" + name + "\" can't be used in an if block."); } // 对于所有特殊属性来说,空字符串是肯定不行的,没有任何意义 if (value === EMPTY_STRING) { fatal$1("The value of \"" + name + "\" is empty."); } else if (isStringValueRequired && falsy$1(value)) { fatal$1("The value of \"" + name + "\" can only be a string literal."); } } element[name] = isStringValueRequired ? value : attr; replaceChild(attr); }, isSpecialAttr = function (element, attr) { return specialAttrs[attr.name] || element.tag === RAW_SLOT && attr.name === RAW_NAME; }, replaceChild = function (oldNode, newNode) { var currentBranch = last(nodeStack), isAttr, list, index; if (currentBranch) { isAttr = currentElement && currentElement === currentBranch; list = isAttr ? currentBranch.attrs : currentBranch.children; } else { list = nodeList; } if (list) { index = indexOf(list, oldNode); if (index >= 0) { if (newNode) { list[index] = newNode; } else { list.splice(index, 1); if (currentBranch && !list.length) { if (isAttr) { delete currentBranch.attrs; } else { currentBranch.children = UNDEFINED; } } } } } }, addChild = function (node) { /** * <div> * <input> * <div></div> * </div> * * <div> * <input>xxx * </div> */ if (!currentElement) { popSelfClosingElementIfNeeded(); } var type = node.type, currentBranch = last(nodeStack); // else 系列只是 if 的递进节点,不需要加入 nodeList if (type === ELSE || type === ELSE_IF) { var lastNode = pop(ifStack); if (lastNode) { // 方便 checkCondition 逆向遍历 node.prev = lastNode; // lastNode 只能是 if 或 else if 节点 if (lastNode.type === ELSE_IF || lastNode.type === IF) { lastNode.next = node; popStack(lastNode.type); push(ifStack, node); } else if (type === ELSE_IF) { { fatal$1('The "else" block must not be followed by an "else if" block.'); } } else { fatal$1("The \"else\" block can't appear more than once in a conditional statement."); } } else { fatal$1('The "if" block is required.'); } } else { if (currentBranch) { push( // 这里不能写 currentElement && !currentAttribute,举个例子 // // <div id="x" {{#if}} name="xx" alt="xx" {{/if}} // // 当 name 属性结束后,条件满足,但此时已不是元素属性层级了 currentElement && currentBranch.type === ELEMENT ? currentElement.attrs || (currentElement.attrs = []) : currentBranch.children || (currentBranch.children = []), node); } else { push(nodeList, node); } if (type === IF) { // 只要是 if 节点,并且和 element 同级,就加上 stub // 方便 virtual dom 进行对比 // 这个跟 virtual dom 的实现原理密切相关,不加 stub 会有问题 if (!currentElement) { node.stub = TRUE; } push(ifStack, node); } } if (node.isLeaf) { // 当前树枝节点如果是静态的,一旦加入了一个非静态子节点,改变当前树枝节点的 isStatic // 这里不处理树枝节点的进栈,因为当树枝节点出栈时,还有一次处理机会,那时它的 isStatic 已确定下来,不会再变 if (currentBranch) { if (currentBranch.isStatic && !node.isStatic) { currentBranch.isStatic = FALSE; } // 当前树枝节点是简单节点,一旦加入了一个复杂子节点,当前树枝节点变为复杂节点 if (!currentBranch.isComplex && node.isComplex) { currentBranch.isComplex = TRUE; } } } else { push(nodeStack, node); } }, addTextChild = function (text) { // [注意] // 这里不能随便删掉 // 因为收集组件的子节点会受影响,举个例子: // <Component> // // </Component> // 按现在的逻辑,这样的组件是没有子节点的,因为在这里过滤掉了,因此该组件没有 slot // 如果这里放开了,组件就会有一个 slot // trim 文本开始和结束位置的换行符 text = text.replace(breaklinePattern, EMPTY_STRING); if (text) { addChild(createText(text)); } }, htmlParsers = [ function (content) { if (!currentElement) { var match = content.match(tagPattern); // 必须以 <tag 开头才能继续 // 如果 <tag 前面有别的字符,会走进第四个 parser if (match && match.index === 0) { var tag = match[2]; if (match[1] === '/') { /** * 处理可能存在的自闭合元素,如下 * * <div> * <input> * </div> */ popSelfClosingElementIfNeeded(tag); popStack(ELEMENT, tag); } else { /** * template 只能写在组件的第一级,如下: * * <Component> * <template slot="xx"> * 111 * </template> * </Component> */ { if (tag === RAW_TEMPLATE) { var lastNode = last(nodeStack); if (!lastNode || !lastNode.isComponent) { fatal$1('<template> can only be used within an component children.'); } } } var node = createElement$1(tag); addChild(node); currentElement = node; } return match[0]; } } }, // 处理标签的 > 或 />,不论开始还是结束标签 function (content) { var match = content.match(selfClosingTagPattern); if (match) { // 处理开始标签的 > 或 /> if (currentElement && !currentAttribute) { // 自闭合标签 if (match[1] === '/') { popStack(currentElement.type, currentElement.tag); } currentElement = UNDEFINED; } // 处理结束标签的 > return match[0]; } }, // 处理 attribute directive 的 name 部分 function (content) { // 当前在 element 层级 if (currentElement && !currentAttribute) { var match = content.match(attributePattern); if (match) { // <div class="11 name="xxx"></div> // 这里会匹配上 xxx",match[2] 就是那个引号 { if (match[2]) { fatal$1("The previous attribute is not end."); } } var node = void 0, name = match[1]; if (name === DIRECTIVE_MODEL || name === RAW_TRANSITION) { node = createDirective(EMPTY_STRING, name); } // 这里要用 on- 判断前缀,否则 on 太容易重名了 else if (startsWith(name, DIRECTIVE_ON + directiveSeparator)) { var event = slicePrefix(name, DIRECTIVE_ON + directiveSeparator); { if (!event) { fatal$1('The event name is required.'); } } var _a = camelize(event).split(RAW_DOT), directiveName = _a[0], diectiveModifier = _a[1]; node = createDirective(directiveName, DIRECTIVE_EVENT, diectiveModifier); } // 当一个元素绑定了多个事件时,可分别指定每个事件的 lazy // 当只有一个事件时,可简写成 lazy // <div on-click="xx" lazy-click else if (startsWith(name, DIRECTIVE_LAZY)) { var lazy = slicePrefix(name, DIRECTIVE_LAZY); if (startsWith(lazy, directiveSeparator)) { lazy = slicePrefix(lazy, directiveSeparator); } node = createDirective(lazy ? camelize(lazy) : EMPTY_STRING, DIRECTIVE_LAZY); } // 这里要用 o- 判断前缀,否则 o 太容易重名了 else if (startsWith(name, DIRECTIVE_CUSTOM + directiveSeparator)) { var custom = slicePrefix(name, DIRECTIVE_CUSTOM + directiveSeparator); { if (!custom) { fatal$1('The directive name is required.'); } } var _b = camelize(custom).split(RAW_DOT), directiveName = _b[0], diectiveModifier = _b[1]; node = createDirective(directiveName, DIRECTIVE_CUSTOM, diectiveModifier); } else { node = createAttribute$1(currentElement, name); } addChild(node); // 这里先记下,下一个 handler 要匹配结束引号 startQuote = match[3]; // 有属性值才需要设置 currentAttribute,便于后续收集属性值 if (startQuote) { currentAttribute = node; } else { popStack(node.type); } return match[0]; } } }, function (content) { var text, match; // 处理 attribute directive 的 value 部分 if (currentAttribute && startQuote) { match = content.match(patternCache$1[startQuote] || (patternCache$1[startQuote] = new RegExp(startQuote))); // 有结束引号 if (match) { text = slice(content, 0, match.index); addTextChild(text); text += startQuote; // attribute directive 结束了 // 此时如果一个值都没收集到,需设置一个空字符串 // 否则无法区分 <div a b=""> 中的 a 和 b if (!currentAttribute.children) { addChild(createText(EMPTY_STRING)); } popStack(currentAttribute.type); currentAttribute = UNDEFINED; } // 没有结束引号,整段匹配 // 如 id="1{{x}}2" 中的 1 else if (blockMode !== BLOCK_MODE_NONE) { text = content; addTextChild(text); } // 没找到结束引号 else { fatal$1("Unterminated quoted string in \"" + currentAttribute.name + "\"."); } } // 如果不加判断,类似 <div {{...obj}}> 这样写,会把空格当做一个属性 // 收集文本只有两处:属性值、元素内容 // 属性值通过上面的 if 处理过了,这里只需要处理元素内容 else if (!currentElement) { // 获取 <tag 前面的字符 match = content.match(tagPattern); // 元素层级的注释都要删掉 if (match) { text = slice(content, 0, match.index); if (text) { addTextChild(text.replace(commentPattern, EMPTY_STRING)); } } else { text = content; addTextChild(text.replace(commentPattern, EMPTY_STRING)); } } else { { if (trim(content)) { fatal$1("Invalid character is found in <" + currentElement.tag + "> attribute level."); } } text = content; } return text; } ], blockParsers = [ // {{#each xx:index}} function (source) { if (startsWith(source, SYNTAX_EACH)) { { if (currentElement) { fatal$1(currentAttribute ? "The \"each\" block can't be appear in an attribute value." : "The \"each\" block can't be appear in attribute level."); } } source = slicePrefix(source, SYNTAX_EACH); var terms = source.replace(/\s+/g, EMPTY_STRING).split(':'); if (terms[0]) { var literal = trim(terms[0]), index_1 = trim(terms[1]), match = literal.match(rangePattern); if (match) { var parts = literal.split(rangePattern), from = compile(parts[0]), to = compile(parts[2]); if (from && to) { return createEach(from, to, trim(match[1]) === '=>', index_1); } } else { var expr = compile(literal); if (expr) { return createEach(expr, UNDEFINED, FALSE, index_1); } } } { fatal$1("Invalid each"); } } }, // {{#import name}} function (source) { if (startsWith(source, SYNTAX_IMPORT)) { source = slicePrefix(source, SYNTAX_IMPORT); if (source) { if (!currentElement) { return createImport(source); } else { fatal$1(currentAttribute ? "The \"import\" block can't be appear in an attribute value." : "The \"import\" block can't be appear in attribute level."); } } { fatal$1("Invalid import"); } } }, // {{#partial name}} function (source) { if (startsWith(source, SYNTAX_PARTIAL)) { source = slicePrefix(source, SYNTAX_PARTIAL); if (source) { if (!currentElement) { return createPartial(source); } else { fatal$1(currentAttribute ? "The \"partial\" block can't be appear in an attribute value." : "The \"partial\" block can't be appear in attribute level."); } } { fatal$1("Invalid partial"); } } }, // {{#if expr}} function (source) { if (startsWith(source, SYNTAX_IF)) { source = slicePrefix(source, SYNTAX_IF); var expr = compile(source); if (expr) { return createIf(expr); } { fatal$1("Invalid if"); } } }, // {{else if expr}} function (source) { if (startsWith(source, SYNTAX_ELSE_IF)) { source = slicePrefix(source, SYNTAX_ELSE_IF); var expr = compile(source); if (expr) { return createElseIf(expr); } { fatal$1("Invalid else if"); } } }, // {{else}} function (source) { if (startsWith(source, SYNTAX_ELSE)) { source = slicePrefix(source, SYNTAX_ELSE); if (!trim(source)) { return createElse(); } { fatal$1("The \"else\" must not be followed by anything."); } } }, // {{...obj}} function (source) { if (startsWith(source, SYNTAX_SPREAD)) { source = slicePrefix(source, SYNTAX_SPREAD); var expr = compile(source); if (expr) { if (currentElement && currentElement.isComponent) { return createSpread(expr, expr.type === IDENTIFIER); } else { fatal$1("The spread can only be used by a component."); } } { fatal$1("Invalid spread"); } } }, // {{expr}} function (source) { if (!SYNTAX_COMMENT.test(source)) { source = trim(source); var expr = compile(source); if (expr) { return createExpression(expr, blockMode === BLOCK_MODE_SAFE); } { fatal$1("Invalid expression"); } } } ], parseHtml = function (code) { while (code) { each(htmlParsers, function (parse) { var match = parse(code); if (match) { code = slice(code, match.length); return FALSE; } }); } }, parseBlock = function (code) { if (charAt(code) === '/') { /** * 处理可能存在的自闭合元素,如下 * * {{#if xx}} * <input> * {{/if}} */ popSelfClosingElementIfNeeded(); var name = slice(code, 1); var type = name2Type[name], isCondition = FALSE; if (type === IF) { var node_1 = pop(ifStack); if (node_1) { type = node_1.type; isCondition = TRUE; } else { fatal$1("The \"if\" block is closing, but it does't opened."); } } var node = popStack(type); if (node && isCondition) { checkCondition(node); } } else { // 开始下一个 block 或表达式 each(blockParsers, function (parse) { var node = parse(code); if (node) { addChild(node); return FALSE; } }); } }, closeBlock = function () { // 确定开始和结束定界符能否配对成功,即 {{ 对 }},{{{ 对 }}} // 这里不能动 openBlockIndex 和 closeBlockIndex,因为等下要用他俩 slice index = closeBlockIndex + 2; // 这里要用 <=,因为很可能到头了 if (index <= length) { if (index < length && charAt(content, index) === '}') { if (blockMode === BLOCK_MODE_UNSAFE) { nextIndex = index + 1; } else { fatal$1("{{ and }}} is not a pair."); } } else { if (blockMode === BLOCK_MODE_SAFE) { nextIndex = index; } else { fatal$1("{{{ and }} is not a pair."); } } pop(blockStack); // }} 左侧的位置 addIndex(closeBlockIndex); openBlockIndex = indexOf$1(content, '{{', nextIndex); closeBlockIndex = indexOf$1(content, '}}', nextIndex); // 如果碰到连续的结束定界符,继续 close if (closeBlockIndex >= nextIndex && (openBlockIndex < 0 || closeBlockIndex < openBlockIndex)) { return closeBlock(); } } else { // 到头了 return TRUE; } }, addIndex = function (index) { if (!blockStack.length) { push(indexList, index); } }; // 因为存在 mustache 注释内包含插值的情况 // 这里把流程设计为先标记切片的位置,标记过程中丢弃无效的 block // 最后处理有效的 block while (TRUE) { addIndex(nextIndex); openBlockIndex = indexOf$1(content, '{{', nextIndex); if (openBlockIndex >= nextIndex) { blockMode = BLOCK_MODE_SAFE; // {{ 左侧的位置 addIndex(openBlockIndex); // 跳过 {{ openBlockIndex += 2; // {{ 后面总得有内容吧 if (openBlockIndex < length) { if (charAt(content, openBlockIndex) === '{') { blockMode = BLOCK_MODE_UNSAFE; openBlockIndex++; } // {{ 右侧的位置 addIndex(openBlockIndex); // block 是否安全 addIndex(blockMode); // 打开一个 block 就入栈一个 push(blockStack, TRUE); if (openBlockIndex < length) { closeBlockIndex = indexOf$1(content, '}}', openBlockIndex); if (closeBlockIndex >= openBlockIndex) { // 注释可以嵌套,如 {{! {{xx}} {{! {{xx}} }} }} nextIndex = indexOf$1(content, '{{', openBlockIndex); if (nextIndex < 0 || closeBlockIndex < nextIndex) { if (closeBlock()) { break; } } } else { fatal$1('The end delimiter is not found.'); } } else { // {{{ 后面没字符串了? fatal$1('Unterminated template literal.'); } } else { // {{ 后面没字符串了? fatal$1('Unterminated template literal.'); } } else { break; } } for (var i = 0, length_1 = indexList.length; i < length_1; i += 5) { index = indexList[i]; // {{ 左侧的位置 openBlockIndex = indexList[i + 1]; if (openBlockIndex) { parseHtml(slice(content, index, openBlockIndex)); } // {{ 右侧的位置 openBlockIndex = indexList[i + 2]; blockMode = indexList[i + 3]; closeBlockIndex = indexList[i + 4]; if (closeBlockIndex) { code = trim(slice(content, openBlockIndex, closeBlockIndex)); // 不用处理 {{ }} 和 {{{ }}} 这种空 block if (code) { parseBlock(code); } } else { blockMode = BLOCK_MODE_NONE; parseHtml(slice(content, index)); } } if (nodeStack.length) { /** * 处理可能存在的自闭合元素,如下 * * <input> */ popSelfClosingElementIfNeeded(); { if (nodeStack.length) { fatal$1('Some nodes is still in the stack.'); } } } if (nodeList.length > 0) { removeComment(nodeList); } return nodeList; } var UNDEFINED$1 = 'z'; var TRUE$1 = '!0'; var FALSE$1 = '!1'; var COMMA = ','; var COLON = ':'; var PLUS = '+'; var AND = '&&'; var QUESTION = '?'; var NOT = '!'; var EMPTY = '""'; var RETURN = 'return '; /** * 目的是 保证调用参数顺序稳定,减少运行时判断 */ function trimArgs(list) { var args = [], removable = TRUE; each(list, function (arg) { if (isDef(arg)) { removable = FALSE; unshift(args, arg); } else if (!removable) { unshift(args, UNDEFINED$1); } }, TRUE); return args; } function toObject$1(fields) { return "{" + join(fields, COMMA) + "}"; } function toArray$1(items) { return "[" + join(items, COMMA) + "]"; } function toCall(name, args) { return name + "(" + join(trimArgs(args), COMMA) + ")"; } function toString$1(value) { return JSON.stringify(value); } function toFunction(args, code) { return RAW_FUNCTION + "(" + args + "){var " + UNDEFINED$1 + "=void 0;" + RETURN + code + "}"; } var generator = /*#__PURE__*/Object.freeze({ UNDEFINED: UNDEFINED$1, TRUE: TRUE$1, FALSE: FALSE$1, COMMA: COMMA, COLON: COLON, PLUS: PLUS, AND: AND, QUESTION: QUESTION, NOT: NOT, EMPTY: EMPTY, RETURN: RETURN, toObject: toObject$1, toArray: toArray$1, toCall: toCall, toString: toString$1, toFunction: toFunction }); function generate(node, renderIdentifier, renderMemberKeypath, renderMemberLiteral, renderCall, holder, depIgnore, stack, inner) { var value, isSpecialNode = FALSE, generateChildNode = function (node) { return generate(node, renderIdentifier, renderMemberKeypath, renderMemberLiteral, renderCall, holder, depIgnore, stack, TRUE); }; switch (node.type) { case LITERAL: value = toString$1(node.value); break; case UNARY: value = node.operator + generateChildNode(node.node); break; case BINARY: value = generateChildNode(node.left) + node.operator + generateChildNode(node.right); break; case TERNARY: value = generateChildNode(node.test) + QUESTION + generateChildNode(node.yes) + COLON + generateChildNode(node.no); break; case ARRAY: var items = node.nodes.map(generateChildNode); value = toArray$1(items); break; case OBJECT: var fields_1 = []; each(node.keys, function (key, index) { push(fields_1, toString$1(key) + COLON + generateChildNode(node.values[index])); }); value = toObject$1(fields_1); break; case IDENTIFIER: isSpecialNode = TRUE; var identifier = node; value = toCall(renderIdentifier, [ toString$1(identifier.name), identifier.lookup ? TRUE$1 : UNDEFINED, identifier.offset > 0 ? toString$1(identifier.offset) : UNDEFINED, holder ? TRUE$1 : UNDEFINED, depIgnore ? TRUE$1 : UNDEFINED, stack ? stack : UNDEFINED ]); break; case MEMBER: isSpecialNode = TRUE; var _a = node, lead = _a.lead, keypath = _a.keypath, nodes = _a.nodes, lookup = _a.lookup, offset = _a.offset, stringifyNodes = nodes ? nodes.map(generateChildNode) : []; if (lead.type === IDENTIFIER) { // 只能是 a[b] 的形式,因为 a.b 已经在解析时转换成 Identifier 了 value = toCall(renderIdentifier, [ toCall(renderMemberKeypath, [ toString$1(lead.name), toArray$1(stringifyNodes) ]), lookup ? TRUE$1 : UNDEFINED, offset > 0 ? toString$1(offset) : UNDEFINED, holder ? TRUE$1 : UNDEFINED, depIgnore ? TRUE$1 : UNDEFINED, stack ? stack : UNDEFINED ]); } else if (nodes) { // "xx"[length] // format()[a][b] value = toCall(renderMemberLiteral, [ generateChildNode(lead), UNDEFINED, toArray$1(stringifyNodes), holder ? TRUE$1 : UNDEFINED ]); } else { // "xx".length // format().a.b value = toCall(renderMemberLiteral, [ generateChildNode(lead), toString$1(keypath), UNDEFINED, holder ? TRUE$1 : UNDEFINED ]); } break; default: isSpecialNode = TRUE; var args = node.args; value = toCall(renderCall, [ generateChildNode(node.name), args.length ? toArray$1(args.map(generateChildNode)) : UNDEFINED, holder ? TRUE$1 : UNDEFINED ]); break; } // 不需要 value holder if (!holder) { return value; } // 内部的临时值,且 holder 为 true if (inner) { return isSpecialNode ? value + RAW_DOT + RAW_VALUE : value; } // 最外层的值,且 holder 为 true return isSpecialNode ? value : toObject$1([RAW_VALUE + COLON + value]); } /** * 这里的难点在于处理 Element 的 children,举个例子: * * ['1', _x(expr), _l(expr, index, generate), _x(expr) ? ['1', _x(expr), _l(expr, index, generate)] : y] * * children 用数组表示,其中表达式求出的值可能是任意类型,比如数组或对象,我们无法控制表达式的值最终会是什么类型 * * 像 each 或 import 这样的语法,内部其实会产生一个 vnode 数组,这里就出现了两个难点: * * 1. 如何区分 each 或其他语法产生的数组和表达式求值的数组 * 2. 如何避免频繁的创建数组 * * 我能想到的解决方案是,根据当前节点类型,如果是元素,则确保 children 的每一项的值序列化后都是函数调用的形式 * * 这样能确保是从左到右依次执行,也就便于在内部创建一个公共数组,执行一个函数就收集一个值,而不管那个值到底是什么类型 * */ // 是否要执行 join 操作 var joinStack = [], // 是否正在收集子节点 collectStack = [], nodeGenerator = {}, RENDER_EXPRESSION_IDENTIFIER = 'a', RENDER_EXPRESSION_MEMBER_KEYPATH = 'b', RENDER_EXPRESSION_MEMBER_LITERAL = 'c', RENDER_EXPRESSION_CALL = 'd', RENDER_TEXT_VNODE = 'e', RENDER_ATTRIBUTE_VNODE = 'f', RENDER_PROPERTY_VNODE = 'g', RENDER_LAZY_VNODE = 'h', RENDER_TRANSITION_VNODE = 'i', RENDER_BINDING_VNODE = 'j', RENDER_MODEL_VNODE = 'k', RENDER_EVENT_METHOD_VNODE = 'l', RENDER_EVENT_NAME_VNODE = 'm', RENDER_DIRECTIVE_VNODE = 'n', RENDER_SPREAD_VNODE = 'o', RENDER_ELEMENT_VNODE = 'p', RENDER_SLOT = 'q', RENDER_PARTIAL = 'r', RENDER_IMPORT = 's', RENDER_EACH = 't', RENDER_RANGE = 'u', RENDER_EQUAL_RANGE = 'v', TO_STRING = 'w', ARG_STACK = 'x'; // 序列化代码的参数列表 var codeArgs, // 表达式求值是否要求返回字符串类型 isStringRequired; function renderExpression(expr, holder, depIgnore, stack) { return generate(expr, RENDER_EXPRESSION_IDENTIFIER, RENDER_EXPRESSION_MEMBER_KEYPATH, RENDER_EXPRESSION_MEMBER_LITERAL, RENDER_EXPRESSION_CALL, holder, depIgnore, stack); } function stringifyObject(obj) { var fields = []; each$2(obj, function (value, key) { if (isDef(value)) { push(fields, toString$1(key) + COLON + value); } }); return toObject$1(fields); } function stringifyFunction(result, arg) { return RAW_FUNCTION + "(" + (arg || EMPTY_STRING) + "){" + (result || EMPTY_STRING) + "}"; } function stringifyGroup(code) { return "(" + code + ")"; } function stringifyExpression(expr, toString) { var value = renderExpression(expr); return toString ? toCall(TO_STRING, [ value ]) : value; } function stringifyExpressionVnode(expr, toString) { return toCall(RENDER_TEXT_VNODE, [ stringifyExpression(expr, toString) ]); } function stringifyExpressionArg(expr) { return renderExpression(expr, FALSE, FALSE, ARG_STACK); } function stringifyValue(value, expr, children) { if (isDef(value)) { return toString$1(value); } // 只有一个表达式时,保持原始类型 if (expr) { return stringifyExpression(expr); } // 多个值拼接时,要求是字符串 if (children) { isStringRequired = children.length > 1; return stringifyChildren(children); } } function stringifyChildren(children, isComplex) { // 如果是复杂节点的 children,则每个 child 的序列化都是函数调用的形式 // 因此最后可以拼接为 fn1(), fn2(), fn3() 这样依次调用,而不用再多此一举的使用数组,因为在 renderer 里也用不上这个数组 // children 大于一个时,才有 join 的可能,单个值 jion 啥啊... var isJoin = children.length > 1 && !isComplex; push(joinStack, isJoin); var value = join(children.map(function (child) { return nodeGenerator[child.type](child); }), isJoin ? PLUS : COMMA); pop(joinStack); return value; } function stringifyConditionChildren(children, isComplex) { if (children) { var result = stringifyChildren(children, isComplex); return children.length > 1 && isComplex ? stringifyGroup(result) : result; } } function stringifyIf(node, stub) { var children = node.children, isComplex = node.isComplex, next = node.next, test = stringifyExpression(node.expr), yes = stringifyConditionChildren(children, isComplex), no, result; if (next) { no = next.type === ELSE ? stringifyConditionChildren(next.children, next.isComplex) : stringifyIf(next, stub); } // 到达最后一个条件,发现第一个 if 语句带有 stub,需创建一个注释标签占位 else if (stub) { no = renderElement(stringifyObject({ isComment: TRUE$1, text: EMPTY })); } if (isDef(yes) || isDef(no)) { var isJoin = last(joinStack); if (isJoin) { if (isUndef(yes)) { yes = EMPTY; } if (isUndef(no)) { no = EMPTY; } } if (isUndef(no)) { result = test + AND + yes; } else if (isUndef(yes)) { result = NOT + test + AND + no; } else { result = test + QUESTION + yes + COLON + no; } // 如果是连接操作,因为 ?: 优先级最低,因此要加 () return isJoin ? stringifyGroup(result) : result; } return EMPTY; } function renderElement(data, tag, attrs, childs, slots) { return toCall(RENDER_ELEMENT_VNODE, [data, tag, attrs, childs, slots]); } function getComponentSlots(children) { var result = {}, slots = {}, addSlot = function (name, nodes) { if (!falsy(nodes)) { name = SLOT_DATA_PREFIX + name; push(slots[name] || (slots[name] = []), nodes); } }; each(children, function (child) { // 找到具名 slot if (child.type === ELEMENT) { var element = child; if (element.slot) { addSlot(element.slot, element.tag === RAW_TEMPLATE ? element.children : [element]); return; } } // 匿名 slot,名称统一为 children addSlot(SLOT_NAME_DEFAULT, [child]); }); each$2(slots, function (children, name) { // 强制为复杂节点,因为 slot 的子节点不能用字符串拼接的方式来渲染 result[name] = stringifyFunction(stringifyChildren(children, TRUE)); }); if (!falsy$2(result)) { return stringifyObject(result); } } nodeGenerator[ELEMENT] = function (node) { var tag = node.tag, isComponent = node.isComponent, isSvg = node.isSvg, isStyle = node.isStyle, isOption = node.isOption, isStatic = node.isStatic, isComplex = node.isComplex, name = node.name, ref = node.ref, key = node.key, html = node.html, attrs = node.attrs, children = node.children, data = {}, outputTag, outputAttrs = [], outputChilds, outputSlots; if (tag === RAW_SLOT) { var args = [toString$1(SLOT_DATA_PREFIX + name)]; if (children) { push(args, stringifyFunction(stringifyChildren(children, TRUE))); } return toCall(RENDER_SLOT, args); } push(collectStack, FALSE); if (attrs) { each(attrs, function (attr) { push(outputAttrs, nodeGenerator[attr.type](attr)); }); } // 如果以 $ 开头,表示动态组件 if (codeAt(tag) === 36) { outputTag = toString$1(slice(tag, 1)); } else { data.tag = toString$1(tag); } if (isSvg) { data.isSvg = TRUE$1; } if (isStyle) { data.isStyle = TRUE$1; } if (isOption) { data.isOption = TRUE$1; } if (isStatic) { data.isStatic = TRUE$1; } if (ref) { data.ref = stringifyValue(ref.value, ref.expr, ref.children); } if (key) { data.key = stringifyValue(key.value, key.expr, key.children); } if (html) { data.html = string(html) ? toString$1(html) : stringifyExpression(html, TRUE); } if (isComponent) { data.isComponent = TRUE$1; if (children) { collectStack[collectStack.length - 1] = TRUE; outputSlots = getComponentSlots(children); } } else if (children) { isStringRequired = TRUE; collectStack[collectStack.length - 1] = isComplex; outputChilds = stringifyChildren(children, isComplex); if (isComplex) { outputChilds = stringifyFunction(outputChilds); } else { data.text = outputChilds; outputChilds = UNDEFINED; } } pop(collectStack); return renderElement(stringifyObject(data), outputTag, falsy(outputAttrs) ? UNDEFINED : stringifyFunction(join(outputAttrs, COMMA)), outputChilds, outputSlots); }; nodeGenerator[ATTRIBUTE] = function (node) { var value = node.binding ? toCall(RENDER_BINDING_VNODE, [ toString$1(node.name), renderExpression(node.expr, TRUE, TRUE) ]) : stringifyValue(node.value, node.expr, node.children); return toCall(RENDER_ATTRIBUTE_VNODE, [ toString$1(node.name), value ]); }; nodeGenerator[PROPERTY] = function (node) { var value = node.binding ? toCall(RENDER_BINDING_VNODE, [ toString$1(node.name), renderExpression(node.expr, TRUE, TRUE), toString$1(node.hint) ]) : stringifyValue(node.value, node.expr, node.children); return toCall(RENDER_PROPERTY_VNODE, [ toString$1(node.name), toString$1(node.hint), value ]); }; nodeGenerator[DIRECTIVE] = function (node) { var ns = node.ns, name = node.name, key = node.key, value = node.value, expr = node.expr, modifier = node.modifier; if (ns === DIRECTIVE_LAZY) { return toCall(RENDER_LAZY_VNODE, [ toString$1(name), toString$1(value) ]); } // <div transition="name"> if (ns === RAW_TRANSITION) { return toCall(RENDER_TRANSITION_VNODE, [ toString$1(value) ]); } // <input model="id"> if (ns === DIRECTIVE_MODEL) { return toCall(RENDER_MODEL_VNODE, [ renderExpression(expr, TRUE, TRUE) ]); } var renderName = RENDER_DIRECTIVE_VNODE, args = [ toString$1(name), toString$1(key), toString$1(modifier), toString$1(value) ]; // 尽可能把表达式编译成函数,这样对外界最友好 // // 众所周知,事件指令会编译成函数,对于自定义指令来说,也要尽可能编译成函数 // // 比如 o-tap="method()" 或 o-log="{'id': '11'}" // 前者会编译成 handler(调用方法),后者会编译成 getter(取值) if (expr) { // 如果表达式明确是在调用方法,则序列化成 method + args 的形式 if (expr.type === CALL) { if (ns === DIRECTIVE_EVENT) { renderName = RENDER_EVENT_METHOD_VNODE; } // compiler 保证了函数调用的 name 是标识符 push(args, toString$1(expr.name.name)); // 为了实现运行时动态收集参数,这里序列化成函数 if (!falsy(expr.args)) { // args 函数在触发事件时调用,调用时会传入它的作用域,因此这里要加一个参数 push(args, stringifyFunction(RETURN + toArray$1(expr.args.map(stringifyExpressionArg)), ARG_STACK)); } } // 不是调用方法,就是事件转换 else if (ns === DIRECTIVE_EVENT) { renderName = RENDER_EVENT_NAME_VNODE; push(args, toString$1(expr.raw)); } else if (ns === DIRECTIVE_CUSTOM) { // 取值函数 // getter 函数在触发事件时调用,调用时会传入它的作用域,因此这里要加一个参数 if (expr.type !== LITERAL) { push(args, UNDEFINED); // method push(args, UNDEFINED); // args push(args, stringifyFunction(RETURN + stringifyExpressionArg(expr), ARG_STACK)); } } } return toCall(renderName, args); }; nodeGenerator[SPREAD] = function (node) { return toCall(RENDER_SPREAD_VNODE, [ renderExpression(node.expr, TRUE, node.binding) ]); }; nodeGenerator[TEXT] = function (node) { var result = toString$1(node.text); if (last(collectStack) && !last(joinStack)) { return toCall(RENDER_TEXT_VNODE, [ result ]); } return result; }; nodeGenerator[EXPRESSION] = function (node) { // 强制保留 isStringRequired 参数,减少运行时判断参数是否存在 // 因为还有 stack 参数呢,各种判断真的很累 if (last(collectStack) && !last(joinStack)) { return stringifyExpressionVnode(node.expr, isStringRequired); } return stringifyExpression(node.expr, isStringRequired); }; nodeGenerator[IF] = function (node) { return stringifyIf(node, node.stub); }; nodeGenerator[EACH] = function (node) { // compiler 保证了 children 一定有值 var children = stringifyFunction(stringifyChildren(node.children, node.isComplex)); // 遍历区间 if (node.to) { if (node.equal) { return toCall(RENDER_EQUAL_RANGE, [ children, renderExpression(node.from), renderExpression(node.to), node.index ? toString$1(node.index) : UNDEFINED ]); } return toCall(RENDER_RANGE, [ children, renderExpression(node.from), renderExpression(node.to), node.index ? toString$1(node.index) : UNDEFINED ]); } // 遍历数组和对象 return toCall(RENDER_EACH, [ children, renderExpression(node.from, TRUE), node.index ? toString$1(node.index) : UNDEFINED ]); }; nodeGenerator[PARTIAL] = function (node) { return toCall(RENDER_PARTIAL, [ toString$1(node.name), // compiler 保证了 children 一定有值 stringifyFunction(stringifyChildren(node.children, node.isComplex)) ]); }; nodeGenerator[IMPORT] = function (node) { return toCall(RENDER_IMPORT, [ toString$1(node.name) ]); }; function generate$1(node) { if (!codeArgs) { codeArgs = join([ RENDER_EXPRESSION_IDENTIFIER, RENDER_EXPRESSION_MEMBER_KEYPATH, RENDER_EXPRESSION_MEMBER_LITERAL, RENDER_EXPRESSION_CALL, RENDER_TEXT_VNODE, RENDER_ATTRIBUTE_VNODE, RENDER_PROPERTY_VNODE, RENDER_LAZY_VNODE, RENDER_TRANSITION_VNODE, RENDER_BINDING_VNODE, RENDER_MODEL_VNODE, RENDER_EVENT_METHOD_VNODE, RENDER_EVENT_NAME_VNODE, RENDER_DIRECTIVE_VNODE, RENDER_SPREAD_VNODE, RENDER_ELEMENT_VNODE, RENDER_SLOT, RENDER_PARTIAL, RENDER_IMPORT, RENDER_EACH, RENDER_RANGE, RENDER_EQUAL_RANGE, TO_STRING ], COMMA); } return toFunction(codeArgs, nodeGenerator[node.type](node)); } function setPair(target, name, key, value) { var data = target[name] || (target[name] = {}); data[key] = value; } var KEY_DIRECTIVES = 'directives'; function render(context, observer, template, filters, partials, directives, transitions) { var $scope = { $keypath: EMPTY_STRING }, $stack = [$scope], $vnode, vnodeStack = [], localPartials = {}, findValue = function (stack, index, key, lookup, depIgnore, defaultKeypath) { var scope = stack[index], keypath = join$1(scope.$keypath, key), value = stack, holder$1 = holder; // 如果最后还是取不到值,用回最初的 keypath if (isUndef(defaultKeypath)) { defaultKeypath = keypath; } // 如果取的是 scope 上直接有的数据,如 $keypath if (isDef(scope[key])) { value = scope[key]; } // 如果取的是数组项,则要更进一步 else if (isDef(scope.$item)) { scope = scope.$item; // 到这里 scope 可能为空 // 比如 new Array(10) 然后遍历这个数组,每一项肯定是空 // 取 this if (key === EMPTY_STRING) { value = scope; } // 取 this.xx else if (scope != NULL && isDef(scope[key])) { value = scope[key]; } } if (value === stack) { // 正常取数据 value = observer.get(keypath, stack, depIgnore); if (value === stack) { if (lookup && index > 0) { { debug("The data \"" + keypath + "\" can't be found in the current context, start looking up."); } return findValue(stack, index - 1, key, lookup, depIgnore, defaultKeypath); } // 到头了,最后尝试过滤器 var result = get(filters, key); if (result) { holder$1 = result; holder$1.keypath = key; } else { holder$1.value = UNDEFINED; holder$1.keypath = defaultKeypath; } return holder$1; } } holder$1.value = value; holder$1.keypath = keypath; return holder$1; }, createEventListener = function (type) { return function (event, data) { // 事件名称相同的情况,只可能是监听 DOM 事件,比如写一个 Button 组件 // <button on-click="click"> 纯粹的封装了一个原生 click 事件 if (type !== event.type) { event = new CustomEvent(type, event); } context.fire(event, data); }; }, createMethodListener = function (name, args, stack) { return function (event, data) { var method = context[name]; if (event instanceof CustomEvent) { var result = UNDEFINED; if (args) { var scope = last(stack); if (scope) { scope.$event = event; scope.$data = data; result = execute(method, context, args(stack)); scope.$event = scope.$data = UNDEFINED; } } else { result = execute(method, context, data ? [event, data] : event); } return result; } else { execute(method, context, args ? args(stack) : UNDEFINED); } }; }, createGetter = function (getter, stack) { return function () { return getter(stack); }; }, renderTextVnode = function (text) { var vnodeList = last(vnodeStack); if (vnodeList) { var lastVnode = last(vnodeList); if (lastVnode && lastVnode.isText) { lastVnode.text += text; } else { var textVnode = { isText: TRUE, text: text, context: context, keypath: $scope.$keypath }; push(vnodeList, textVnode); } } }, renderAttributeVnode = function (name, value) { if ($vnode.isComponent) { setPair($vnode, 'props', name, value); } else { setPair($vnode, 'nativeAttrs', name, { name: name, value: value }); } }, renderPropertyVnode = function (name, hint, value) { setPair($vnode, 'nativeProps', name, { name: name, value: value, hint: hint }); }, renderLazyVnode = function (name, value) { setPair($vnode, 'lazy', name, value); }, renderTransitionVnode = function (name) { $vnode.transition = transitions[name]; { if (!$vnode.transition) { fatal("The transition \"" + name + "\" can't be found."); } } }, renderBindingVnode = function (name, holder, hint) { var key = join$1(DIRECTIVE_BINDING, name); setPair($vnode, KEY_DIRECTIVES, key, { ns: DIRECTIVE_BINDING, name: name, key: key, modifier: holder.keypath, hooks: directives[DIRECTIVE_BINDING], hint: hint }); return holder.value; }, renderModelVnode = function (holder) { setPair($vnode, KEY_DIRECTIVES, DIRECTIVE_MODEL, { ns: DIRECTIVE_MODEL, name: EMPTY_STRING, key: DIRECTIVE_MODEL, value: holder.value, modifier: holder.keypath, hooks: directives[DIRECTIVE_MODEL] }); }, renderEventMethodVnode = function (name, key, modifier, value, method, args) { setPair($vnode, KEY_DIRECTIVES, key, { ns: DIRECTIVE_EVENT, name: name, key: key, value: value, modifier: modifier, hooks: directives[DIRECTIVE_EVENT], handler: createMethodListener(method, args, $stack) }); }, renderEventNameVnode = function (name, key, modifier, value, event) { setPair($vnode, KEY_DIRECTIVES, key, { ns: DIRECTIVE_EVENT, name: name, key: key, value: value, modifier: modifier, hooks: directives[DIRECTIVE_EVENT], handler: createEventListener(event) }); }, renderDirectiveVnode = function (name, key, modifier, value, method, args, getter) { var hooks = directives[name]; { if (!hooks) { fatal("The directive " + name + " can't be found."); } } setPair($vnode, KEY_DIRECTIVES, key, { ns: DIRECTIVE_CUSTOM, name: name, key: key, value: value, hooks: hooks, modifier: modifier, getter: getter ? createGetter(getter, $stack) : UNDEFINED, handler: method ? createMethodListener(method, args, $stack) : UNDEFINED }); }, renderSpreadVnode = function (holder) { var value = holder.value, keypath = holder.keypath; // 如果为 null 或 undefined,则不需要 warn if (value != NULL) { // 数组也算一种对象,要排除掉 if (object(value) && !array(value)) { each$2(value, function (value, key) { setPair($vnode, 'props', key, value); }); if (keypath) { var key = join$1(DIRECTIVE_BINDING, keypath); setPair($vnode, KEY_DIRECTIVES, key, { ns: DIRECTIVE_BINDING, name: EMPTY_STRING, key: key, modifier: join$1(keypath, RAW_WILDCARD), hooks: directives[DIRECTIVE_BINDING] }); } } } }, renderElementVnode = function (vnode, tag, attrs, childs, slots) { if (tag) { var componentName = observer.get(tag); { if (!componentName) { warn("The dynamic component \"" + tag + "\" can't be found."); } } vnode.tag = componentName; } if (attrs) { $vnode = vnode; attrs(); $vnode = UNDEFINED; } // childs 和 slots 不可能同时存在 if (childs) { vnodeStack.push(vnode.children = []); childs(); pop(vnodeStack); } else if (slots) { var renderSlots_1 = {}; each$2(slots, function (slot, name) { vnodeStack.push([]); slot(); var vnodes = pop(vnodeStack); renderSlots_1[name] = vnodes.length ? vnodes : UNDEFINED; }); vnode.slots = renderSlots_1; } vnode.context = context; vnode.keypath = $scope.$keypath; var vnodeList = last(vnodeStack); if (vnodeList) { push(vnodeList, vnode); } return vnode; }, renderExpressionIdentifier = function (name, lookup, offset, holder, depIgnore, stack) { var myStack = stack || $stack, result = findValue(myStack, myStack.length - ((offset || 0) + 1), name, lookup, depIgnore); return holder ? result : result.value; }, renderExpressionMemberKeypath = function (identifier, runtimeKeypath) { unshift(runtimeKeypath, identifier); return join(runtimeKeypath, RAW_DOT); }, renderExpressionMemberLiteral = function (value, staticKeypath, runtimeKeypath, holder$1) { if (isDef(runtimeKeypath)) { staticKeypath = join(runtimeKeypath, RAW_DOT); } var match = get(value, staticKeypath); holder.keypath = UNDEFINED; holder.value = match ? match.value : UNDEFINED; return holder$1 ? holder : holder.value; }, renderExpressionCall = function (fn, args, holder$1) { holder.keypath = UNDEFINED; // 当 holder 为 true, args 为空时,args 会传入 false holder.value = execute(fn, context, args || UNDEFINED); return holder$1 ? holder : holder.value; }, // <slot name="xx"/> renderSlot = function (name, defaultRender) { var vnodeList = last(vnodeStack), vnodes = context.get(name); if (vnodeList) { if (vnodes) { each(vnodes, function (vnode) { push(vnodeList, vnode); vnode.slot = name; vnode.parent = context; }); } else if (defaultRender) { defaultRender(); } } }, // {{#partial name}} // xx // {{/partial}} renderPartial = function (name, render) { localPartials[name] = render; }, // {{> name}} renderImport = function (name) { if (localPartials[name]) { localPartials[name](); } else { var partial = partials[name]; if (partial) { partial(renderExpressionIdentifier, renderExpressionMemberKeypath, renderExpressionMemberLiteral, renderExpressionCall, renderTextVnode, renderAttributeVnode, renderPropertyVnode, renderLazyVnode, renderTransitionVnode, renderBindingVnode, renderModelVnode, renderEventMethodVnode, renderEventNameVnode, renderDirectiveVnode, renderSpreadVnode, renderElementVnode, renderSlot, renderPartial, renderImport, renderEach, renderRange, renderEqualRange, toString); } else { fatal("The partial \"" + name + "\" can't be found."); } } }, eachHandler = function (generate, item, key, keypath, index, length) { var lastScope = $scope, lastStack = $stack; // each 会改变 keypath $scope = { $keypath: keypath }; $stack = lastStack.concat($scope); // 避免模板里频繁读取 list.length if (isDef(length)) { $scope.$length = length; } // 业务层是否写了 expr:index if (index) { $scope[index] = key; } // 无法通过 context.get($keypath + key) 读取到数据的场景 // 必须把 item 写到 scope if (!keypath) { $scope.$item = item; } generate(); $scope = lastScope; $stack = lastStack; }, renderEach = function (generate, holder, index) { var keypath = holder.keypath, value = holder.value; if (array(value)) { for (var i = 0, length = value.length; i < length; i++) { eachHandler(generate, value[i], i, keypath ? join$1(keypath, EMPTY_STRING + i) : EMPTY_STRING, index, length); } } else if (object(value)) { for (var key in value) { eachHandler(generate, value[key], key, keypath ? join$1(keypath, key) : EMPTY_STRING, index); } } }, renderRange = function (generate, from, to, index) { var count = 0; if (from < to) { for (var i = from; i < to; i++) { eachHandler(generate, i, count++, EMPTY_STRING, index); } } else { for (var i = from; i > to; i--) { eachHandler(generate, i, count++, EMPTY_STRING, index); } } }, renderEqualRange = function (generate, from, to, index) { var count = 0; if (from < to) { for (var i = from; i <= to; i++) { eachHandler(generate, i, count++, EMPTY_STRING, index); } } else { for (var i = from; i >= to; i--) { eachHandler(generate, i, count++, EMPTY_STRING, index); } } }; return template(renderExpressionIdentifier, renderExpressionMemberKeypath, renderExpressionMemberLiteral, renderExpressionCall, renderTextVnode, renderAttributeVnode, renderPropertyVnode, renderLazyVnode, renderTransitionVnode, renderBindingVnode, renderModelVnode, renderEventMethodVnode, renderEventNameVnode, renderDirectiveVnode, renderSpreadVnode, renderElementVnode, renderSlot, renderPartial, renderImport, renderEach, renderRange, renderEqualRange, toString); } // 这里先写 IE9 支持的接口 var innerText = 'textContent', innerHTML = 'innerHTML', findElement = function (selector) { var node = DOCUMENT.querySelector(selector); if (node) { return node; } }, addEventListener = function (node, type, listener) { node.addEventListener(type, listener, FALSE); }, removeEventListener = function (node, type, listener) { node.removeEventListener(type, listener, FALSE); }, // IE9 不支持 classList addElementClass = function (node, className) { node.classList.add(className); }, removeElementClass = function (node, className) { node.classList.remove(className); }, createEvent = function (event, node) { return event; }; { if (DOCUMENT) { // 此时 document.body 不一定有值,比如 script 放在 head 里 if (!DOCUMENT.documentElement.classList) { addElementClass = function (node, className) { var classes = node.className.split(CHAR_WHITESPACE); if (!has(classes, className)) { push(classes, className); node.className = join(classes, CHAR_WHITESPACE); } }; removeElementClass = function (node, className) { var classes = node.className.split(CHAR_WHITESPACE); if (remove(classes, className)) { node.className = join(classes, CHAR_WHITESPACE); } }; } } } var CHAR_WHITESPACE = ' ', /** * 绑定在 HTML 元素上的事件发射器 */ EMITTER = '$emitter', /** * 跟输入事件配套使用的事件 */ COMPOSITION_START = 'compositionstart', /** * 跟输入事件配套使用的事件 */ COMPOSITION_END = 'compositionend', domain = 'http://www.w3.org/', namespaces = { svg: domain + '2000/svg' }, specialEvents = {}; specialEvents[EVENT_MODEL] = { on: function (node, listener) { var locked = FALSE; on(node, COMPOSITION_START, listener[COMPOSITION_START] = function () { locked = TRUE; }); on(node, COMPOSITION_END, listener[COMPOSITION_END] = function (event) { locked = FALSE; listener(event); }); addEventListener(node, EVENT_INPUT, listener[EVENT_INPUT] = function (event) { if (!locked) { listener(event); } }); }, off: function (node, listener) { off(node, COMPOSITION_START, listener[COMPOSITION_START]); off(node, COMPOSITION_END, listener[COMPOSITION_END]); removeEventListener(node, EVENT_INPUT, listener[EVENT_INPUT]); listener[COMPOSITION_START] = listener[COMPOSITION_END] = listener[EVENT_INPUT] = UNDEFINED; } }; function createElement$2(tag, isSvg) { return isSvg ? DOCUMENT.createElementNS(namespaces.svg, tag) : DOCUMENT.createElement(tag); } function createText$1(text) { return DOCUMENT.createTextNode(text); } function createComment(text) { return DOCUMENT.createComment(text); } function prop(node, name, value) { if (isDef(value)) { set(node, name, value, FALSE); } else { var holder = get(node, name); if (holder) { return holder.value; } } } function removeProp(node, name, hint) { set(node, name, hint === HINT_BOOLEAN ? FALSE : EMPTY_STRING, FALSE); } function attr(node, name, value) { if (isDef(value)) { node.setAttribute(name, value); } else { // value 还可能是 null var value_1 = node.getAttribute(name); if (value_1 != NULL) { return value_1; } } } function removeAttr(node, name) { node.removeAttribute(name); } function before(parentNode, node, beforeNode) { parentNode.insertBefore(node, beforeNode); } function append(parentNode, node) { parentNode.appendChild(node); } function replace(parentNode, node, oldNode) { parentNode.replaceChild(node, oldNode); } function remove$2(parentNode, node) { parentNode.removeChild(node); } function parent(node) { var parentNode = node.parentNode; if (parentNode) { return parentNode; } } function next(node) { var nextSibling = node.nextSibling; if (nextSibling) { return nextSibling; } } var find = findElement; function tag(node) { if (node.nodeType === 1) { return lower(node.tagName); } } function text(node, text, isStyle, isOption) { if (isDef(text)) { { node[innerText] = text; } } else { return node[innerText]; } } function html(node, html, isStyle, isOption) { if (isDef(html)) { { node[innerHTML] = html; } } else { return node[innerHTML]; } } var addClass = addElementClass; var removeClass = removeElementClass; function on(node, type, listener, context) { var emitter = node[EMITTER] || (node[EMITTER] = new Emitter()), nativeListeners = emitter.nativeListeners || (emitter.nativeListeners = {}); // 一个元素,相同的事件,只注册一个 native listener if (!nativeListeners[type]) { // 特殊事件 var special = specialEvents[type], // 唯一的原生监听器 nativeListener = function (event) { var customEvent = event instanceof CustomEvent ? event : new CustomEvent(event.type, createEvent(event, node)); if (customEvent.type !== type) { customEvent.type = type; } emitter.fire(type, [customEvent]); }; nativeListeners[type] = nativeListener; if (special) { special.on(node, nativeListener); } else { addEventListener(node, type, nativeListener); } } emitter.on(type, { fn: listener, ctx: context }); } function off(node, type, listener) { var emitter = node[EMITTER], listeners = emitter.listeners, nativeListeners = emitter.nativeListeners; // emitter 会根据 type 和 listener 参数进行适当的删除 emitter.off(type, listener); // 如果注册的 type 事件都解绑了,则去掉原生监听器 if (nativeListeners && !emitter.has(type)) { var special = specialEvents[type], nativeListener = nativeListeners[type]; if (special) { special.off(node, nativeListener); } else { removeEventListener(node, type, nativeListener); } delete nativeListeners[type]; } if (falsy$2(listeners)) { node[EMITTER] = UNDEFINED; } } function addSpecialEvent(type, hooks) { { if (specialEvents[type]) { fatal("The special event \"" + type + "\" is existed."); } info("The special event \"" + type + "\" is added successfully."); } specialEvents[type] = hooks; } var domApi = /*#__PURE__*/Object.freeze({ createElement: createElement$2, createText: createText$1, createComment: createComment, prop: prop, removeProp: removeProp, attr: attr, removeAttr: removeAttr, before: before, append: append, replace: replace, remove: remove$2, parent: parent, next: next, find: find, tag: tag, text: text, html: html, addClass: addClass, removeClass: removeClass, on: on, off: off, addSpecialEvent: addSpecialEvent }); /** * 计算属性 * * 可配置 cache、deps、get、set 等 */ var Computed = /** @class */ (function () { function Computed(keypath, sync, cache, deps, observer, getter, setter) { var instance = this; instance.keypath = keypath; instance.cache = cache; instance.deps = deps; instance.context = observer.context; instance.observer = observer; instance.getter = getter; instance.setter = setter; instance.unique = {}; instance.watcher = function ($0, $1, $2) { // 计算属性的依赖变了会走进这里 var oldValue = instance.value, newValue = instance.get(TRUE); if (newValue !== oldValue) { observer.diff(keypath, newValue, oldValue); } }; instance.watcherOptions = { sync: sync, watcher: instance.watcher }; if (instance.fixed = !falsy(deps)) { each(deps, function (dep) { observer.watch(dep, instance.watcherOptions); }); } } /** * 读取计算属性的值 * * @param force 是否强制刷新缓存 */ Computed.prototype.get = function (force) { var instance = this, getter = instance.getter, context = instance.context; // 禁用缓存 if (!instance.cache) { instance.value = execute(getter, context); } // 减少取值频率,尤其是处理复杂的计算规则 else if (force || !has$2(instance, RAW_VALUE)) { // 如果写死了依赖,则不需要收集依赖 if (instance.fixed) { instance.value = execute(getter, context); } else { // 清空上次收集的依赖 instance.unbind(); // 开始收集新的依赖 var lastComputed = Computed.current; Computed.current = instance; instance.value = execute(getter, context); // 绑定新的依赖 instance.bind(); Computed.current = lastComputed; } } return instance.value; }; Computed.prototype.set = function (value) { var _a = this, setter = _a.setter, context = _a.context; if (setter) { setter.call(context, value); } }; /** * 添加依赖 * * 这里只是为了保证依赖唯一,最后由 bind() 实现绑定 * * @param dep */ Computed.prototype.add = function (dep) { this.unique[dep] = TRUE; }; /** * 绑定依赖 */ Computed.prototype.bind = function () { var _a = this, unique = _a.unique, deps = _a.deps, observer = _a.observer, watcherOptions = _a.watcherOptions; each$2(unique, function (_, dep) { push(deps, dep); observer.watch(dep, watcherOptions); }); // 用完重置 // 方便下次收集依赖 this.unique = {}; }; /** * 解绑依赖 */ Computed.prototype.unbind = function () { var _a = this, deps = _a.deps, observer = _a.observer, watcher = _a.watcher; each(deps, function (dep) { observer.unwatch(dep, watcher); }, TRUE); deps.length = 0; }; return Computed; }()); /** * 从 keypath 数组中选择和 keypath 最匹配的那一个 * * @param sorted 经过排序的 keypath 数组 * @param keypath */ function matchBest (sorted, keypath) { var result; each(sorted, function (prefix) { var length = match(keypath, prefix); if (length >= 0) { result = { name: prefix, prop: slice(keypath, length) }; return FALSE; } }); return result; } function readValue (source, keypath) { if (source == NULL || keypath === EMPTY_STRING) { return source; } var result = get(source, keypath); if (result) { return result.value; } } /** * 对比新旧数组 * * @param newValue * @param oldValue * @param callback */ function diffString (newValue, oldValue, callback) { var newIsString = string(newValue), oldIsString = string(oldValue); if (newIsString || oldIsString) { callback(RAW_LENGTH, newIsString ? newValue.length : UNDEFINED, oldIsString ? oldValue.length : UNDEFINED); return TRUE; } } /** * 对比新旧数组 * * @param newValue * @param oldValue * @param callback */ function diffArray (newValue, oldValue, callback) { var newIsArray = array(newValue), oldIsArray = array(oldValue); if (newIsArray || oldIsArray) { var newLength = newIsArray ? newValue.length : UNDEFINED, oldLength = oldIsArray ? oldValue.length : UNDEFINED; callback(RAW_LENGTH, newLength, oldLength); for (var i = 0, length = Math.max(newLength || 0, oldLength || 0); i < length; i++) { callback('' + i, newValue ? newValue[i] : UNDEFINED, oldValue ? oldValue[i] : UNDEFINED); } return TRUE; } } /** * 对比新旧对象 * * @param newValue * @param oldValue * @param callback */ function diffObject (newValue, oldValue, callback) { var newIsObject = object(newValue), oldIsObject = object(oldValue); if (newIsObject || oldIsObject) { newValue = newIsObject ? newValue : EMPTY_OBJECT; oldValue = oldIsObject ? oldValue : EMPTY_OBJECT; if (newIsObject) { each$2(newValue, function (value, key) { if (value !== oldValue[key]) { callback(key, value, oldValue[key]); } }); } if (oldIsObject) { each$2(oldValue, function (value, key) { if (value !== newValue[key]) { callback(key, newValue[key], value); } }); } } } function diffRecursion(keypath, newValue, oldValue, watchFuzzyKeypaths, callback) { var diff = function (subKeypath, subNewValue, subOldValue) { if (subNewValue !== subOldValue) { var newKeypath_1 = join$1(keypath, subKeypath); each(watchFuzzyKeypaths, function (fuzzyKeypath) { if (isDef(matchFuzzy(newKeypath_1, fuzzyKeypath))) { callback(fuzzyKeypath, newKeypath_1, subNewValue, subOldValue); } }); diffRecursion(newKeypath_1, subNewValue, subOldValue, watchFuzzyKeypaths, callback); } }; diffString(newValue, oldValue, diff) || diffArray(newValue, oldValue, diff) || diffObject(newValue, oldValue, diff); } function diffWatcher (keypath, newValue, oldValue, watcher, isRecursive, callback) { var fuzzyKeypaths; // 遍历监听的 keypath,如果未被监听,则无需触发任何事件 each$2(watcher, function (_, watchKeypath) { // 模糊监听,如 users.*.name if (isFuzzy(watchKeypath)) { // 如果当前修改的是 users.0 整个对象 // users.0 和 users.*.name 无法匹配 // 此时要知道设置 users.0 到底会不会改变 users.*.name 需要靠递归了 // 如果匹配,则无需递归 if (isDef(matchFuzzy(keypath, watchKeypath))) { callback(watchKeypath, keypath, newValue, oldValue); } else if (isRecursive) { if (fuzzyKeypaths) { push(fuzzyKeypaths, watchKeypath); } else { fuzzyKeypaths = [watchKeypath]; } } return; } // 不是模糊匹配,直接靠前缀匹配 // 比如监听的是 users.0.name,此时修改 users.0,则直接读出子属性值,判断是否相等 var length = match(watchKeypath, keypath); if (length >= 0) { var subKeypath = slice(watchKeypath, length), subNewValue = readValue(newValue, subKeypath), subOldValue = readValue(oldValue, subKeypath); if (subNewValue !== subOldValue) { callback(watchKeypath, watchKeypath, subNewValue, subOldValue); } } }); // 存在模糊匹配的需求 // 必须对数据进行递归 // 性能确实会慢一些,但是很好用啊,几乎可以监听所有的数据 if (fuzzyKeypaths) { diffRecursion(keypath, newValue, oldValue, fuzzyKeypaths, callback); } } /** * 触发异步变化时,用此函数过滤下,哪些 listener 应该执行 * * @param item * @param data */ function filterWatcher (_, args, options) { if (options.count && args) { // 采用计数器的原因是,同一个 options 可能执行多次 // 比如监听 user.*,如果同批次修改了 user.name 和 user.age // 这个监听器会调用多次,如果第一次执行就把 count 干掉了,第二次就无法执行了 options.count--; // 新旧值不相等 return args[0] !== args[1]; } } // 避免频繁创建对象 var optionsHolder = { watcher: EMPTY_FUNCTION }; /** * 格式化 watch options * * @param options */ function formatWatcherOptions (options, immediate) { if (func(options)) { optionsHolder.watcher = options; optionsHolder.immediate = immediate === TRUE; return optionsHolder; } if (options && options.watcher) { return options; } { fatal("watcher should be a function or object."); } } /** * 观察者有两种观察模式: * * 1. 同步监听 * 2. 异步监听 * * 对于`计算属性`这种需要实时变化的对象,即它的依赖变了,它需要立即跟着变,否则会出现不一致的问题 * 这种属于同步监听 * * 对于外部调用 observer.watch('keypath', listener),属于异步监听,它只关心是否变了,而不关心是否是立即触发的 */ var Observer = /** @class */ (function () { function Observer(data, context) { var instance = this; instance.data = data || {}; instance.context = context || instance; instance.nextTask = new NextTask(); instance.syncEmitter = new Emitter(); instance.asyncEmitter = new Emitter(); instance.asyncChanges = {}; } /** * 获取数据 * * @param keypath * @param defaultValue * @param depIgnore * @return */ Observer.prototype.get = function (keypath, defaultValue, depIgnore) { var instance = this, currentComputed = Computed.current, data = instance.data, computed = instance.computed, reversedComputedKeys = instance.reversedComputedKeys; // 传入 '' 获取整个 data if (keypath === EMPTY_STRING) { return data; } // 调用 get 时,外面想要获取依赖必须设置是谁在收集依赖 // 如果没设置,则跳过依赖收集 if (currentComputed && !depIgnore) { currentComputed.add(keypath); } var result, target; if (computed) { target = computed[keypath]; if (target) { return target.get(); } if (reversedComputedKeys) { var match = matchBest(reversedComputedKeys, keypath); if (match && match.prop) { result = get(computed[match.name].get(), match.prop); } } } if (!result) { result = get(data, keypath); } return result ? result.value : defaultValue; }; /** * 更新数据 * * @param keypath * @param value */ Observer.prototype.set = function (keypath, value) { var instance = this, data = instance.data, computed = instance.computed, reversedComputedKeys = instance.reversedComputedKeys, setValue = function (newValue, keypath) { var oldValue = instance.get(keypath); if (newValue === oldValue) { return; } var target; if (computed) { target = computed[keypath]; if (target) { target.set(newValue); } if (reversedComputedKeys) { var match = matchBest(reversedComputedKeys, keypath); if (match && match.prop) { target = computed[match.name]; if (target) { var targetValue = target.get(); if (object(targetValue)) { set(targetValue, match.prop, newValue); } } } } } if (!target) { set(data, keypath, newValue); } instance.diff(keypath, newValue, oldValue); }; if (string(keypath)) { setValue(value, keypath); } else if (object(keypath)) { each$2(keypath, setValue); } }; /** * 同步调用的 diff,用于触发 syncEmitter,以及唤醒 asyncEmitter * * @param keypath * @param newValue * @param oldValue */ Observer.prototype.diff = function (keypath, newValue, oldValue) { var instance = this, syncEmitter = instance.syncEmitter, asyncEmitter = instance.asyncEmitter, asyncChanges = instance.asyncChanges, /** * 我们认为 $ 开头的变量是不可递归的 * 比如浏览器中常见的 $0 表示当前选中元素 * DOM 元素是不能递归的 */ isRecursive = codeAt(keypath) !== 36; diffWatcher(keypath, newValue, oldValue, syncEmitter.listeners, isRecursive, function (watchKeypath, keypath, newValue, oldValue) { syncEmitter.fire(watchKeypath, [newValue, oldValue, keypath]); }); /** * 此处有坑,举个例子 * * observer.watch('a', function () {}) * * observer.set('a', 1) * * observer.watch('a', function () {}) * * 这里,第一个 watcher 应该触发,但第二个不应该,因为它绑定监听时,值已经是最新的了 */ diffWatcher(keypath, newValue, oldValue, asyncEmitter.listeners, isRecursive, function (watchKeypath, keypath, newValue, oldValue) { each(asyncEmitter.listeners[watchKeypath], function (item) { item.count++; }); var keypaths = (asyncChanges[keypath] || (asyncChanges[keypath] = { value: oldValue, keypaths: [] })).keypaths; if (!has(keypaths, watchKeypath)) { push(keypaths, watchKeypath); } if (!instance.pending) { instance.pending = TRUE; instance.nextTask.append(function () { if (instance.pending) { instance.pending = UNDEFINED; instance.diffAsync(); } }); } }); }; /** * 异步触发的 diff */ Observer.prototype.diffAsync = function () { var instance = this, asyncEmitter = instance.asyncEmitter, asyncChanges = instance.asyncChanges; instance.asyncChanges = {}; each$2(asyncChanges, function (change, keypath) { var args = [instance.get(keypath), change.value, keypath]; // 不能在这判断新旧值是否相同,相同就不 fire // 因为前面标记了 count,在这中断会导致 count 无法清除 each(change.keypaths, function (watchKeypath) { asyncEmitter.fire(watchKeypath, args, filterWatcher); }); }); }; /** * 添加计算属性 * * @param keypath * @param computed */ Observer.prototype.addComputed = function (keypath, options) { var cache = TRUE, sync = TRUE, deps = [], getter, setter; if (func(options)) { getter = options; } else if (object(options)) { var computedOptions = options; if (boolean(computedOptions.cache)) { cache = computedOptions.cache; } if (boolean(computedOptions.sync)) { sync = computedOptions.sync; } // 因为可能会修改 deps,所以这里创建一个新的 deps,避免影响外部传入的 deps if (array(computedOptions.deps)) { deps = copy(computedOptions.deps); } if (func(computedOptions.get)) { getter = computedOptions.get; } if (func(computedOptions.set)) { setter = computedOptions.set; } } if (getter) { var instance = this, computed = new Computed(keypath, sync, cache, deps, instance, getter, setter); if (!instance.computed) { instance.computed = {}; } instance.computed[keypath] = computed; instance.reversedComputedKeys = sort(instance.computed, TRUE); return computed; } }; /** * 移除计算属性 * * @param keypath */ Observer.prototype.removeComputed = function (keypath) { var instance = this, computed = instance.computed; if (computed && has$2(computed, keypath)) { delete computed[keypath]; instance.reversedComputedKeys = sort(computed, TRUE); } }; /** * 监听数据变化 * * @param keypath * @param watcher * @param immediate */ Observer.prototype.watch = function (keypath, watcher, immediate) { var instance = this, context = instance.context, syncEmitter = instance.syncEmitter, asyncEmitter = instance.asyncEmitter, bind = function (keypath, options) { var emitter = options.sync ? syncEmitter : asyncEmitter, // formatWatcherOptions 保证了 options.watcher 一定存在 listener = { fn: options.watcher, ctx: context, count: 0 }; if (options.once) { listener.max = 1; } emitter.on(keypath, listener); if (options.immediate) { execute(options.watcher, context, [ instance.get(keypath), UNDEFINED, keypath ]); } }; if (string(keypath)) { bind(keypath, formatWatcherOptions(watcher, immediate)); return; } each$2(keypath, function (options, keypath) { bind(keypath, formatWatcherOptions(options)); }); }; /** * 取消监听数据变化 * * @param keypath * @param watcher */ Observer.prototype.unwatch = function (keypath, watcher) { this.syncEmitter.off(keypath, watcher); this.asyncEmitter.off(keypath, watcher); }; /** * 取反 keypath 对应的数据 * * 不管 keypath 对应的数据是什么类型,操作后都是布尔型 * * @param keypath * @return 取反后的布尔值 */ Observer.prototype.toggle = function (keypath) { var value = !this.get(keypath); this.set(keypath, value); return value; }; /** * 递增 keypath 对应的数据 * * 注意,最好是整型的加法,如果涉及浮点型,不保证计算正确 * * @param keypath 值必须能转型成数字,如果不能,则默认从 0 开始递增 * @param step 步进值,默认是 1 * @param max 可以递增到的最大值,默认不限制 */ Observer.prototype.increase = function (keypath, step, max) { var value = toNumber(this.get(keypath), 0) + (step || 1); if (!number(max) || value <= max) { this.set(keypath, value); return value; } }; /** * 递减 keypath 对应的数据 * * 注意,最好是整型的减法,如果涉及浮点型,不保证计算正确 * * @param keypath 值必须能转型成数字,如果不能,则默认从 0 开始递减 * @param step 步进值,默认是 1 * @param min 可以递减到的最小值,默认不限制 */ Observer.prototype.decrease = function (keypath, step, min) { var value = toNumber(this.get(keypath), 0) - (step || 1); if (!number(min) || value >= min) { this.set(keypath, value); return value; } }; /** * 在数组指定位置插入元素 * * @param keypath * @param item * @param index */ Observer.prototype.insert = function (keypath, item, index) { var list = this.get(keypath); list = !array(list) ? [] : copy(list); var length = list.length; if (index === TRUE || index === length) { list.push(item); } else if (index === FALSE || index === 0) { list.unshift(item); } else if (index > 0 && index < length) { list.splice(index, 0, item); } else { return; } this.set(keypath, list); return TRUE; }; /** * 在数组尾部添加元素 * * @param keypath * @param item */ Observer.prototype.append = function (keypath, item) { return this.insert(keypath, item, TRUE); }; /** * 在数组首部添加元素 * * @param keypath * @param item */ Observer.prototype.prepend = function (keypath, item) { return this.insert(keypath, item, FALSE); }; /** * 通过索引移除数组中的元素 * * @param keypath * @param index */ Observer.prototype.removeAt = function (keypath, index) { var list = this.get(keypath); if (array(list) && index >= 0 && index < list.length) { list = copy(list); list.splice(index, 1); this.set(keypath, list); return TRUE; } }; /** * 直接移除数组中的元素 * * @param keypath * @param item */ Observer.prototype.remove = function (keypath, item) { var list = this.get(keypath); if (array(list)) { list = copy(list); if (remove(list, item)) { this.set(keypath, list); return TRUE; } } }; /** * 拷贝任意数据,支持深拷贝 * * @param data * @param deep */ Observer.prototype.copy = function (data, deep) { return copy(data, deep); }; /** * 销毁 */ Observer.prototype.destroy = function () { var instance = this; instance.syncEmitter.off(); instance.asyncEmitter.off(); instance.nextTask.clear(); clear(instance); }; return Observer; }()); /** * 节流调用 * * @param fn 需要节制调用的函数 * @param delay 调用的时间间隔,单位毫秒 * @param immediate 是否立即触发 * @return 节流函数 */ function debounce (fn, delay, immediate) { var timer; return function () { if (!timer) { var args_1 = toArray(arguments); if (immediate) { execute(fn, UNDEFINED, args_1); } timer = setTimeout(function () { timer = UNDEFINED; if (!immediate) { execute(fn, UNDEFINED, args_1); } }, delay); } }; } function bind(node, directive, vnode) { var key = directive.key, name = directive.name, modifier = directive.modifier, handler = directive.handler, lazy = vnode.lazy; if (!handler) { return; } if (lazy) { var value = lazy[name] || lazy[EMPTY_STRING]; if (value === TRUE) { name = EVENT_CHANGE; } else if (value > 0) { handler = debounce(handler, value, // 避免连续多次点击,主要用于提交表单场景 // 移动端的 tap 事件可自行在业务层打补丁实现 name === EVENT_CLICK || name === EVENT_TAP); } } var element; if (vnode.isComponent) { var component_1 = node; if (modifier === MODIFER_NATIVE) { element = component_1.$el; on(element, name, handler); vnode.data[key] = function () { off(element, name, handler); }; } else { // 还原命名空间 if (modifier) { name += RAW_DOT + modifier; } component_1.on(name, handler); vnode.data[key] = function () { component_1.off(name, handler); }; } } else { element = node; on(element, name, handler); vnode.data[key] = function () { off(element, name, handler); }; } } function unbind(node, directive, vnode) { execute(vnode.data[directive.key]); } var event = /*#__PURE__*/Object.freeze({ bind: bind, unbind: unbind }); function debounceIfNeeded(fn, lazy) { // 应用 lazy return lazy && lazy !== TRUE ? debounce(fn, lazy) : fn; } var inputControl = { set: function (node, value) { node.value = toString(value); }, sync: function (node, keypath, context) { context.set(keypath, node.value); }, name: RAW_VALUE }, radioControl = { set: function (node, value) { node.checked = node.value === toString(value); }, sync: function (node, keypath, context) { if (node.checked) { context.set(keypath, node.value); } }, name: 'checked' }, checkboxControl = { set: function (node, value) { node.checked = array(value) ? has(value, node.value, FALSE) : !!value; }, sync: function (node, keypath, context) { var value = context.get(keypath); if (array(value)) { if (node.checked) { context.append(keypath, node.value); } else { context.removeAt(keypath, indexOf(value, node.value, FALSE)); } } else { context.set(keypath, node.checked); } }, name: 'checked' }, selectControl = { set: function (node, value) { each(toArray(node.options), node.multiple ? function (option) { option.selected = has(value, option.value, FALSE); } : function (option, index) { if (option.value == value) { node.selectedIndex = index; return FALSE; } }); }, sync: function (node, keypath, context) { var options = node.options; if (node.multiple) { var values_1 = []; each(toArray(options), function (option) { if (option.selected) { push(values_1, option.value); } }); context.set(keypath, values_1); } else { context.set(keypath, options[node.selectedIndex].value); } }, name: RAW_VALUE }; var once = TRUE; function bind$1(node, directive, vnode) { var context = vnode.context, lazy = vnode.lazy, isComponent = vnode.isComponent, dataBinding = directive.modifier, lazyValue = lazy && (lazy[DIRECTIVE_MODEL] || lazy[EMPTY_STRING]), set, unbind; if (isComponent) { var component_1 = node, viewBinding_1 = component_1.$model, viewSyncing_1 = debounceIfNeeded(function (newValue) { context.set(dataBinding, newValue); }, lazyValue); set = function (newValue) { if (set) { component_1.set(viewBinding_1, newValue); } }; unbind = function () { component_1.unwatch(viewBinding_1, viewSyncing_1); }; component_1.watch(viewBinding_1, viewSyncing_1); } else { var element_1 = node, control_1 = vnode.tag === 'select' ? selectControl : inputControl, // checkbox,radio,select 监听的是 change 事件 eventName_1 = EVENT_CHANGE; if (control_1 === inputControl) { var type = node.type; if (type === 'radio') { control_1 = radioControl; } else if (type === 'checkbox') { control_1 = checkboxControl; } // 如果是输入框,则切换成 model 事件 // model 事件是个 yox-dom 实现的特殊事件 // 不会在输入法组合文字过程中得到触发事件 else if (lazyValue !== TRUE) { eventName_1 = EVENT_MODEL; } } set = function (newValue) { if (set) { control_1.set(element_1, newValue); } }; var sync_1 = debounceIfNeeded(function () { control_1.sync(element_1, dataBinding, context); }, lazyValue); unbind = function () { off(element_1, eventName_1, sync_1); }; on(element_1, eventName_1, sync_1); control_1.set(element_1, directive.value); } // 监听数据,修改界面 context.watch(dataBinding, set); vnode.data[directive.key] = function () { context.unwatch(dataBinding, set); set = UNDEFINED; unbind(); }; } function unbind$1(node, directive, vnode) { execute(vnode.data[directive.key]); } var model = /*#__PURE__*/Object.freeze({ once: once, bind: bind$1, unbind: unbind$1 }); var once$1 = TRUE; function bind$2(node, directive, vnode) { // binding 可能是模糊匹配 // 比如延展属性 {{...obj}},这里 binding 会是 `obj.*` var binding = directive.modifier, // 提前判断好是否是模糊匹配,避免 watcher 频繁执行判断逻辑 isFuzzy$1 = isFuzzy(binding), watcher = function (newValue, _, keypath) { if (watcher) { var name = isFuzzy$1 ? matchFuzzy(keypath, binding) : directive.name; if (vnode.isComponent) { var component = node; component.checkProp(name, newValue); component.set(name, newValue); } else { var element = node; if (isDef(directive.hint)) { prop(element, name, newValue); } else { attr(element, name, newValue); } } } }; vnode.context.watch(binding, watcher); vnode.data[directive.key] = function () { vnode.context.unwatch(binding, watcher); watcher = UNDEFINED; }; } function unbind$2(node, directive, vnode) { execute(vnode.data[directive.key]); } var binding = /*#__PURE__*/Object.freeze({ once: once$1, bind: bind$2, unbind: unbind$2 }); var globalDirectives = {}, globalTransitions = {}, globalComponents = {}, globalPartials = {}, globalFilters = {}, compileCache = {}, TEMPLATE_COMPUTED = '$$', selectorPattern = /^[#.][-\w+]+$/; var Yox = /** @class */ (function () { function Yox(options) { var instance = this, $options = options || EMPTY_OBJECT; // 为了冒泡 HOOK_BEFORE_CREATE 事件,必须第一时间创建 emitter // 监听各种事件 // 支持命名空间 instance.$emitter = new Emitter(TRUE); if ($options.events) { instance.on($options.events); } { // 当前组件的直接父组件 if ($options.parent) { instance.$parent = $options.parent; } // 建立好父子连接后,立即触发钩子 execute($options[HOOK_BEFORE_CREATE], instance, $options); // 冒泡 before create 事件 instance.fire(HOOK_BEFORE_CREATE + NAMESPACE_HOOK, $options); } var data = $options.data, props = $options.props, vnode = $options.vnode, propTypes = $options.propTypes, computed = $options.computed, methods = $options.methods, watchers = $options.watchers, extensions = $options.extensions; instance.$options = $options; if (extensions) { extend(instance, extensions); } // 数据源,默认值仅在创建组件时启用 var source = props ? copy(props) : {}; { if (propTypes) { each$2(propTypes, function (rule, key) { var value = source[key]; { checkProp(key, value, rule); } if (isUndef(value)) { value = rule.value; if (isDef(value)) { source[key] = rule.type === RAW_FUNCTION ? value : func(value) ? value() : value; } } }); } } // 先放 props // 当 data 是函数时,可以通过 this.get() 获取到外部数据 var observer = instance.$observer = new Observer(source, instance); if (computed) { each$2(computed, function (options, keypath) { observer.addComputed(keypath, options); }); } // 后放 data { if (vnode && object(data)) { warn("The \"data\" option of child component should be a function which return an object."); } } var extend$1 = func(data) ? execute(data, instance, options) : data; if (object(extend$1)) { each$2(extend$1, function (value, key) { { if (has$2(source, key)) { warn("The data \"" + key + "\" is already used as a prop."); } } source[key] = value; }); } if (methods) { each$2(methods, function (method, name) { { if (instance[name]) { fatal("The method \"" + name + "\" is conflicted with built-in methods."); } } instance[name] = method; }); } { var placeholder = UNDEFINED, el = $options.el, root = $options.root, model_1 = $options.model, context = $options.context, replace = $options.replace, template = $options.template, transitions = $options.transitions, components = $options.components, directives = $options.directives, partials = $options.partials, filters = $options.filters, slots = $options.slots; if (model_1) { instance.$model = model_1; } // 把 slots 放进数据里,方便 get if (slots) { extend(source, slots); } // 检查 template if (string(template)) { // 传了选择器,则取对应元素的 html if (selectorPattern.test(template)) { placeholder = find(template); if (placeholder) { template = html(placeholder); placeholder = UNDEFINED; } else { fatal("The selector \"" + template + "\" can't match an element."); } } } // 检查 el if (el) { if (string(el)) { var selector = el; if (selectorPattern.test(selector)) { placeholder = find(selector); { if (!placeholder) { fatal("The selector \"" + selector + "\" can't match an element."); } } } else { fatal("The \"el\" option should be a selector."); } } else { placeholder = el; } if (!replace) { append(placeholder, placeholder = createComment(EMPTY_STRING)); } } // 根组件 if (root) { instance.$root = root; } // 当前组件是被哪个组件渲染出来的 // 因为有 slot 机制,$context 不一定等于 $parent if (context) { instance.$context = context; } setFlexibleOptions(instance, RAW_TRANSITION, transitions); setFlexibleOptions(instance, RAW_COMPONENT, components); setFlexibleOptions(instance, RAW_DIRECTIVE, directives); setFlexibleOptions(instance, RAW_PARTIAL, partials); setFlexibleOptions(instance, RAW_FILTER, filters); // 当存在模板和计算属性时 // 因为这里把模板当做一种特殊的计算属性 // 因此模板这个计算属性的优先级应该最高 if (template) { // 拷贝一份,避免影响外部定义的 watchers var newWatchers = watchers ? copy(watchers) : {}; newWatchers[TEMPLATE_COMPUTED] = { // 模板一旦变化,立即刷新 sync: TRUE, watcher: function (vnode) { instance.update(vnode, instance.$vnode); } }; // 当模板的依赖变了,则重新创建 virtual dom observer.addComputed(TEMPLATE_COMPUTED, { // 当模板依赖变化时,异步通知模板更新 sync: FALSE, get: function () { return instance.render(); } }); afterCreateHook(instance, newWatchers); // 编译模板 // 在开发阶段,template 是原始的 html 模板 // 在产品阶段,template 是编译后的渲染函数 // 当然,具体是什么需要外部自己控制 instance.$template = string(template) ? Yox.compile(template) : template; if (!vnode) { { if (!placeholder) { fatal('The "el" option is required for root component.'); } } vnode = create(domApi, placeholder, instance, EMPTY_STRING); } instance.update(instance.get(TEMPLATE_COMPUTED), vnode); return; } else { if (placeholder || vnode) { fatal('The "template" option is required.'); } } } afterCreateHook(instance, watchers); } /** * 安装插件 * * 插件必须暴露 install 方法 */ Yox.use = function (plugin) { plugin.install(Yox); }; /** * 定义组件对象 */ Yox.define = function (options) { return options; }; /** * 因为组件采用的是异步更新机制,为了在更新之后进行一些操作,可使用 nextTick */ Yox.nextTick = function (task, context) { NextTask.shared().append(task, context); }; /** * 编译模板,暴露出来是为了打包阶段的模板预编译 */ Yox.compile = function (template, stringify) { { // 需要编译的都是模板源文件,一旦经过预编译,就成了 render 函数,不会再走进 Yox.compile if (!compileCache[template]) { var nodes = compile$1(template); { if (nodes.length !== 1) { fatal("The \"template\" option should have just one root element."); } } compileCache[template] = generate$1(nodes[0]); } template = compileCache[template]; return stringify ? template : new Function("return " + template)(); } }; /** * 注册全局指令 */ Yox.directive = function (name, directive) { { if (string(name) && !directive) { return getResource(globalDirectives, name); } setResource(globalDirectives, name, directive); } }; /** * 注册全局过渡动画 */ Yox.transition = function (name, transition) { { if (string(name) && !transition) { return getResource(globalTransitions, name); } setResource(globalTransitions, name, transition); } }; /** * 注册全局组件 */ Yox.component = function (name, component) { { if (string(name) && !component) { return getResource(globalComponents, name); } setResource(globalComponents, name, component); } }; /** * 注册全局子模板 */ Yox.partial = function (name, partial) { { if (string(name) && !partial) { return getResource(globalPartials, name); } setResource(globalPartials, name, partial, Yox.compile); } }; /** * 注册全局过滤器 */ Yox.filter = function (name, filter) { { if (string(name) && !filter) { return getResource(globalFilters, name); } setResource(globalFilters, name, filter); } }; /** * 取值 */ Yox.prototype.get = function (keypath, defaultValue) { return this.$observer.get(keypath, defaultValue); }; /** * 设值 */ Yox.prototype.set = function (keypath, value) { // 组件经常有各种异步改值,为了避免组件销毁后依然调用 set // 这里判断一下,至于其他方法的异步调用就算了,业务自己控制吧 var $observer = this.$observer; if ($observer) { $observer.set(keypath, value); } }; /** * 监听事件,支持链式调用 */ Yox.prototype.on = function (type, listener) { addEvents(this, type, listener); return this; }; /** * 监听一次事件,支持链式调用 */ Yox.prototype.once = function (type, listener) { addEvents(this, type, listener, TRUE); return this; }; /** * 取消监听事件,支持链式调用 */ Yox.prototype.off = function (type, listener) { this.$emitter.off(type, listener); return this; }; /** * 发射事件 */ Yox.prototype.fire = function (type, data, downward) { // 外部为了使用方便,fire(type) 或 fire(type, data) 就行了 // 内部为了保持格式统一 // 需要转成 Event,这样还能知道 target 是哪个组件 var instance = this, $emitter = instance.$emitter, $parent = instance.$parent, $children = instance.$children, event = type instanceof CustomEvent ? type : new CustomEvent(type), args = [event], isComplete; // 创建完 CustomEvent,如果没有人为操作 // 它的 ns 为 undefined // 这里先解析出命名空间,避免每次 fire 都要解析 if (isUndef(event.ns)) { var namespace = $emitter.parse(event.type); event.type = namespace.type; event.ns = namespace.ns; } // 告诉外部是谁发出的事件 if (!event.target) { event.target = instance; } // 比如 fire('name', true) 直接向下发事件 if (object(data)) { push(args, data); } else if (data === TRUE) { downward = TRUE; } // 如果手动 fire 带上了事件命名空间 // 则命名空间不能是 native,因为 native 有特殊用处 { if (event.ns === MODIFER_NATIVE) { error("The namespace \"" + MODIFER_NATIVE + "\" is not permitted."); } } isComplete = $emitter.fire(event, args); if (isComplete) { if (downward) { if ($children) { event.phase = CustomEvent.PHASE_DOWNWARD; each($children, function (child) { return isComplete = child.fire(event, data, TRUE); }); } } else if ($parent) { event.phase = CustomEvent.PHASE_UPWARD; isComplete = $parent.fire(event, data); } } return isComplete; }; /** * 监听数据变化,支持链式调用 */ Yox.prototype.watch = function (keypath, watcher, immediate) { this.$observer.watch(keypath, watcher, immediate); return this; }; /** * 取消监听数据变化,支持链式调用 */ Yox.prototype.unwatch = function (keypath, watcher) { this.$observer.unwatch(keypath, watcher); return this; }; /** * 加载组件,组件可以是同步或异步,最后会调用 callback * * @param name 组件名称 * @param callback 组件加载成功后的回调 */ Yox.prototype.loadComponent = function (name, callback) { { if (!loadComponent(this.$components, name, callback)) { { if (!loadComponent(globalComponents, name, callback)) { error("The component \"" + name + "\" is not found."); } } } } }; /** * 创建子组件 * * @param options 组件配置 * @param vnode 虚拟节点 */ Yox.prototype.createComponent = function (options, vnode) { { var instance = this; options = copy(options); options.root = instance.$root || instance; options.parent = instance; options.context = vnode.context; options.vnode = vnode; options.replace = TRUE; var props = vnode.props, slots = vnode.slots, directives = vnode.directives, model_2 = directives && directives[DIRECTIVE_MODEL]; if (model_2) { if (!props) { props = {}; } var key = options.model || MODEL_PROP_DEFAULT; props[key] = model_2.value; options.model = key; } if (props) { options.props = props; } if (slots) { options.slots = slots; } var child = new Yox(options); push(instance.$children || (instance.$children = []), child); var node = child.$el; if (node) { vnode.node = node; } else { fatal("The root element of component \"" + vnode.tag + "\" is not found."); } return child; } }; /** * 注册当前组件级别的指令 */ Yox.prototype.directive = function (name, directive) { { var instance = this, $directives = instance.$directives; if (string(name) && !directive) { return getResource($directives, name, Yox.directive); } setResource($directives || (instance.$directives = {}), name, directive); } }; /** * 注册当前组件级别的过渡动画 */ Yox.prototype.transition = function (name, transition) { { var instance = this, $transitions = instance.$transitions; if (string(name) && !transition) { return getResource($transitions, name, Yox.transition); } setResource($transitions || (instance.$transitions = {}), name, transition); } }; /** * 注册当前组件级别的组件 */ Yox.prototype.component = function (name, component) { { var instance = this, $components = instance.$components; if (string(name) && !component) { return getResource($components, name, Yox.component); } setResource($components || (instance.$components = {}), name, component); } }; /** * 注册当前组件级别的子模板 */ Yox.prototype.partial = function (name, partial) { { var instance = this, $partials = instance.$partials; if (string(name) && !partial) { return getResource($partials, name, Yox.partial); } setResource($partials || (instance.$partials = {}), name, partial, Yox.compile); } }; /** * 注册当前组件级别的过滤器 */ Yox.prototype.filter = function (name, filter) { { var instance = this, $filters = instance.$filters; if (string(name) && !filter) { return getResource($filters, name, Yox.filter); } setResource($filters || (instance.$filters = {}), name, filter); } }; /** * 对于某些特殊场景,修改了数据,但是模板的依赖中并没有这一项 * 而你非常确定需要更新模板,强制刷新正是你需要的 */ Yox.prototype.forceUpdate = function (data) { { var instance = this, $vnode = instance.$vnode, $observer = instance.$observer, computed = $observer.computed; if ($vnode && computed) { var template = computed[TEMPLATE_COMPUTED], oldValue = template.get(); if (data) { instance.set(data); } // 当前可能正在进行下一轮更新 $observer.nextTask.run(); // 没有更新模板,强制刷新 if (!data && oldValue === template.get()) { instance.update(template.get(TRUE), $vnode); } } } }; /** * 把模板抽象语法树渲染成 virtual dom */ Yox.prototype.render = function () { { var instance = this; return render(instance, instance.$observer, instance.$template, merge(instance.$filters, globalFilters), merge(instance.$partials, globalPartials), merge(instance.$directives, globalDirectives), merge(instance.$transitions, globalTransitions)); } }; /** * 更新 virtual dom * * @param vnode * @param oldVnode */ Yox.prototype.update = function (vnode, oldVnode) { { var instance_1 = this, $vnode = instance_1.$vnode, $options_1 = instance_1.$options, afterHook_1; // 每次渲染重置 refs // 在渲染过程中收集最新的 ref // 这样可避免更新时,新的 ref,在前面创建,老的 ref 却在后面删除的情况 instance_1.$refs = {}; if ($vnode) { execute($options_1[HOOK_BEFORE_UPDATE], instance_1); instance_1.fire(HOOK_BEFORE_UPDATE + NAMESPACE_HOOK); patch(domApi, vnode, oldVnode); afterHook_1 = HOOK_AFTER_UPDATE; } else { execute($options_1[HOOK_BEFORE_MOUNT], instance_1); instance_1.fire(HOOK_BEFORE_MOUNT + NAMESPACE_HOOK); patch(domApi, vnode, oldVnode); instance_1.$el = vnode.node; afterHook_1 = HOOK_AFTER_MOUNT; } instance_1.$vnode = vnode; // 跟 nextTask 保持一个节奏 // 这样可以预留一些优化的余地 Yox.nextTick(function () { if (instance_1.$vnode) { execute($options_1[afterHook_1], instance_1); instance_1.fire(afterHook_1 + NAMESPACE_HOOK); } }); } }; /** * 校验组件参数 * * @param props */ Yox.prototype.checkProp = function (key, value) { { var propTypes = this.$options.propTypes; if (propTypes) { var rule = propTypes[key]; if (rule) { checkProp(key, value, rule); } } } }; /** * 销毁组件 */ Yox.prototype.destroy = function () { var instance = this, $parent = instance.$parent, $options = instance.$options, $emitter = instance.$emitter, $observer = instance.$observer; { execute($options[HOOK_BEFORE_DESTROY], instance); instance.fire(HOOK_BEFORE_DESTROY + NAMESPACE_HOOK); var $vnode = instance.$vnode; if ($parent && $parent.$children) { remove($parent.$children, instance); } if ($vnode) { // virtual dom 通过判断 parent.$vnode 知道宿主组件是否正在销毁 instance.$vnode = UNDEFINED; destroy(domApi, $vnode, !$parent); } } $observer.destroy(); { execute($options[HOOK_AFTER_DESTROY], instance); instance.fire(HOOK_AFTER_DESTROY + NAMESPACE_HOOK); } // 发完 after destroy 事件再解绑所有事件 $emitter.off(); clear(instance); }; /** * 因为组件采用的是异步更新机制,为了在更新之后进行一些操作,可使用 nextTick */ Yox.prototype.nextTick = function (task) { this.$observer.nextTask.append(task, this); }; /** * 取反 keypath 对应的数据 * * 不管 keypath 对应的数据是什么类型,操作后都是布尔型 */ Yox.prototype.toggle = function (keypath) { return this.$observer.toggle(keypath); }; /** * 递增 keypath 对应的数据 * * 注意,最好是整型的加法,如果涉及浮点型,不保证计算正确 * * @param keypath 值必须能转型成数字,如果不能,则默认从 0 开始递增 * @param step 步进值,默认是 1 * @param max 可以递增到的最大值,默认不限制 */ Yox.prototype.increase = function (keypath, step, max) { return this.$observer.increase(keypath, step, max); }; /** * 递减 keypath 对应的数据 * * 注意,最好是整型的减法,如果涉及浮点型,不保证计算正确 * * @param keypath 值必须能转型成数字,如果不能,则默认从 0 开始递减 * @param step 步进值,默认是 1 * @param min 可以递减到的最小值,默认不限制 */ Yox.prototype.decrease = function (keypath, step, min) { return this.$observer.decrease(keypath, step, min); }; /** * 在数组指定位置插入元素 * * @param keypath * @param item * @param index */ Yox.prototype.insert = function (keypath, item, index) { return this.$observer.insert(keypath, item, index); }; /** * 在数组尾部添加元素 * * @param keypath * @param item */ Yox.prototype.append = function (keypath, item) { return this.$observer.append(keypath, item); }; /** * 在数组首部添加元素 * * @param keypath * @param item */ Yox.prototype.prepend = function (keypath, item) { return this.$observer.prepend(keypath, item); }; /** * 通过索引移除数组中的元素 * * @param keypath * @param index */ Yox.prototype.removeAt = function (keypath, index) { return this.$observer.removeAt(keypath, index); }; /** * 直接移除数组中的元素 * * @param keypath * @param item */ Yox.prototype.remove = function (keypath, item) { return this.$observer.remove(keypath, item); }; /** * 拷贝任意数据,支持深拷贝 * * @param data * @param deep */ Yox.prototype.copy = function (data, deep) { return this.$observer.copy(data, deep); }; /** * core 版本 */ Yox.version = "1.0.0-alpha.90"; /** * 方便外部共用的通用逻辑,特别是写插件,减少重复代码 */ Yox.is = is; Yox.dom = domApi; Yox.array = array$1; Yox.object = object$1; Yox.string = string$1; Yox.logger = logger; Yox.Event = CustomEvent; Yox.Emitter = Emitter; return Yox; }()); var toString$2 = Object.prototype.toString; function matchType(value, type) { return type === 'numeric' ? numeric(value) : lower(toString$2.call(value)) === "[object " + type + "]"; } function checkProp(key, value, rule) { // 传了数据 if (isDef(value)) { var type = rule.type; // 如果不写 type 或 type 不是 字符串 或 数组 // 就当做此规则无效,和没写一样 if (type) { // 自定义函数判断是否匹配类型 // 自己打印警告信息吧 if (func(type)) { type(key, value); } else { var matched_1 = FALSE; // type: 'string' if (!falsy$1(type)) { matched_1 = matchType(value, type); } // type: ['string', 'number'] else if (!falsy(type)) { each(type, function (item) { if (matchType(value, item)) { matched_1 = TRUE; return FALSE; } }); } if (!matched_1) { warn("The type of prop \"" + key + "\" expected to be \"" + type + "\", but is \"" + value + "\"."); } } } else { warn("The prop \"" + key + "\" in propTypes has no type."); } } // 没传值但此项是必传项 else if (rule.required) { warn("The prop \"" + key + "\" is marked as required, but its value is not found."); } } function afterCreateHook(instance, watchers) { if (watchers) { instance.watch(watchers); } { execute(instance.$options[HOOK_AFTER_CREATE], instance); instance.fire(HOOK_AFTER_CREATE + NAMESPACE_HOOK); } } function setFlexibleOptions(instance, key, value) { if (func(value)) { instance[key](execute(value, instance)); } else if (object(value)) { instance[key](value); } } function addEvent(instance, type, listener, once) { var options = { fn: listener, ctx: instance }; if (once) { options.max = 1; } // YoxInterface 没有声明 $emitter,因为不想让外部访问, // 但是这里要用一次,所以加了 as any instance.$emitter.on(type, options); } function addEvents(instance, type, listener, once) { if (string(type)) { addEvent(instance, type, listener, once); } else { each$2(type, function (value, key) { addEvent(instance, key, value, once); }); } } function loadComponent(registry, name, callback) { if (registry && registry[name]) { var component = registry[name]; // 注册的是异步加载函数 if (func(component)) { registry[name] = [callback]; var componentCallback = function (result) { var queue = registry[name], options = result['default'] || result; registry[name] = options; each(queue, function (callback) { callback(options); }); }, promise = component(componentCallback); if (promise) { promise.then(componentCallback); } } // 正在加载中 else if (array(component)) { push(component, callback); } // 不是异步加载函数,直接同步返回 else { callback(component); } return TRUE; } } function getResource(registry, name, lookup) { if (registry && registry[name]) { return registry[name]; } else if (lookup) { return lookup(name); } } function setResource(registry, name, value, formatValue) { if (string(name)) { registry[name] = formatValue ? formatValue(value) : value; } else { each$2(name, function (value, key) { registry[key] = formatValue ? formatValue(value) : value; }); } } { // 全局注册内置指令 Yox.directive({ event: event, model: model, binding: binding }); // 全局注册内置过滤器 Yox.filter({ hasSlot: function (name) { // 不鼓励在过滤器使用 this // 因此过滤器没有 this 的类型声明 // 这个内置过滤器是不得不用 this return isDef(this.get(SLOT_DATA_PREFIX + name)); } }); } return Yox; })); //# sourceMappingURL=yox.js.map
import json import sqlite3 import sys import unicodedata import re import pickle import os import logging from urllib.parse import unquote from tqdm import tqdm # input: input_file = sys.argv[1] db_path = sys.argv[2] # output output_file = sys.argv[3] EDGE_XY = re.compile(r'<a href="(.*?)">(.*?)</a>') def get_edges(sentence): # ret = EDGE_XY.findall(sentence) ret = EDGE_XY.findall(sentence + '</a>') return [(unquote(x), y) for x, y in ret] def normalize(text): """Resolve different type of unicode encodings.""" return unicodedata.normalize('NFD', text) class DocDB(object): """Sqlite backed document storage. Implements get_doc_text(doc_id). """ def __init__(self, db_path): self.path = db_path self.connection = sqlite3.connect(self.path, check_same_thread=False) def __enter__(self): return self def __exit__(self, *args): self.close() def path(self): """Return the path to the file that backs this database.""" return self.path def close(self): """Close the connection to the database.""" self.connection.close() def get_doc_ids(self): """Fetch all ids of docs stored in the db.""" cursor = self.connection.cursor() cursor.execute("SELECT id FROM documents") results = [r[0] for r in cursor.fetchall()] cursor.close() return results def _get_doc_key(self, doc_id, key): """Fetch the raw text of the doc for 'doc_id'.""" cursor = self.connection.cursor() cursor.execute( "SELECT {} FROM documents WHERE id = ?".format(key), (normalize(doc_id),) ) result = cursor.fetchone() cursor.close() return result if result is None else result[0] def get_doc_text(self, doc_id): """Fetch the raw text of the doc for 'doc_id'.""" return self._get_doc_key(doc_id, 'text') def get_doc_sent_num(self, doc_id): return int(self._get_doc_key(doc_id, 'sent_num')) def get_doc_text_with_links(self, doc_id): return self._get_doc_key(doc_id, 'text_with_links') def get_doc_ner(self, doc_id): return self._get_doc_key(doc_id, 'text_ner') def get_doc_url(self, doc_id): return self._get_doc_key(doc_id, 'url') def get_doc_title(self, doc_id): return self._get_doc_key(doc_id, 'title') def get_doc_id_title_all(self): cursor = self.connection.cursor() cursor.execute("SELECT id, title FROM documents") results = cursor.fetchall() cursor.close() return results doc_db = DocDB(db_path) # 1. map title to ID # title_to_id = {} # doc_ids = doc_db.get_doc_ids() # # for doc_id in doc_ids: # title = doc_db.get_doc_title(doc_id) # # if title not in title_to_id: # title_to_id[title] = doc_id print("Map title to ID...") title_to_id = {} doc_id_title_all = doc_db.get_doc_id_title_all() print("Total id/title pairs: " + str(len(doc_id_title_all))) for doc_id, title in doc_id_title_all: title_to_id[title] = doc_id # 2. extract hyperlink and NER print("Extract hyperlink and NER...") input_data = json.load(open(input_file, 'r')) output_data = {} for data in input_data: context = dict(data['context']) for title in context.keys(): if title not in title_to_id: print("{} not exist in DB".format(title)) else: doc_id = title_to_id[title] text_with_links = pickle.loads(doc_db.get_doc_text_with_links(doc_id)) text_ner = pickle.loads(doc_db.get_doc_ner(doc_id)) hyperlink_titles, hyperlink_spans = [], [] hyperlink_paras = [] for i, sentence in enumerate(text_with_links): _lt, _ls, _lp = [], [], [] t = get_edges(sentence) if len(t) > 0: for link_title, mention_entity in t: if link_title in title_to_id: _lt.append(link_title) _ls.append(mention_entity) doc_text = pickle.loads(doc_db.get_doc_text(title_to_id[link_title])) _lp.append(doc_text) hyperlink_titles.append(_lt) hyperlink_spans.append(_ls) hyperlink_paras.append(_lp) output_data[title] = {'hyperlink_titles': hyperlink_titles, 'hyperlink_paras': hyperlink_paras, 'hyperlink_spans': hyperlink_spans, 'text_ner': text_ner} print(f"Dump to {output_file}") json.dump(output_data, open(output_file, 'w'))
from Instrucciones.TablaSimbolos.Instruccion import Instruccion class Undefined(Instruccion): def __init__(self, tipo, valor, strGram, linea, columna): Instruccion.__init__(self, None, linea, columna, strGram) self.tipo = tipo self.valor = valor def ejecutar(self, tabla, arbol): super().ejecutar(tabla, arbol) if self.valor != None: self.valor = self.tipo + self.valor return self.valor def traducir(self, tabla, controlador, arbol): codigo = 'Undefined.Undefined("' + self.tipo + '", ' if self.valor is None: codigo += 'None' else: codigo += '"' + self.valor + '"' codigo += ', "' + self.strGram + '", ' + str(self.linea) + ', ' + str(self.columna) + ')' return codigo
/** * RESTFul API 시작하기 * @author Geunhyeok LEE */ const path = require('path') const colors = require('colors') const express = require('express') const bodyParser = require('body-parser') const paddingNumber = (number, length) => { const sNumber = number.toString(); if (sNumber.length >= length) { return sNumber; } else { let padding = ''; for (let i = 0; i < length - sNumber.length; i++) { padding += '0'; } return padding + sNumber; } }; // 에러 로그 레벨에 따른 출력 색상 const LEVEL_COLORS = { info: colors.green, debug: colors.blue, success: colors.green, warning: colors.yellow, danger: colors.red, error: colors.red, critical: colors.magenta } /** * 현재 시점의 날짜, 시간 문자열을 반환합니다 */ const timestamp = () => { const d = new Date() const yyyy = d.getFullYear() const MM = paddingNumber(d.getMonth() + 1, 2) const dd = paddingNumber(d.getDate(), 2) const hh = paddingNumber(d.getHours(), 2) const mm = paddingNumber(d.getMinutes(), 2) const ss = paddingNumber(d.getSeconds(), 2) const aaa = paddingNumber(d.getMilliseconds(), 3) return `${yyyy}-${MM}-${dd} ${hh}:${mm}:${ss}.${aaa}` } // 해당 레벨의 로그를 출력합니다 const printLog = (level, ...msg) => { console.log( `[${timestamp()}]`.gray, `${LEVEL_COLORS[level](level.toUpperCase())}`, '-', ...msg ) } const logger = { info (...msg) { printLog('info', ...msg) }, debug (...msg) { printLog('debug', ...msg) }, success (...msg) { printLog('success', ...msg) }, warning (...msg) { printLog('warning', ...msg) }, danger (...msg) { printLog('danger', ...msg) }, error (...msg) { printLog('error', ...msg) }, critical (...msg) { printLog('critical', ...msg) } } module.exports = (app, router) => { router.use(bodyParser.json()) router.use(bodyParser.urlencoded({ extended: false })) router.use('*', (_req, res, next) => { const afterResponse = () => { res.removeListener('finish', afterResponse) res.removeListener('close', afterResponse) const url = res.req.originalUrl const method = res.req.method let sStatusCode = res.statusCode.toString() let logType = logger.info switch (sStatusCode.charAt(0)) { case '2': sStatusCode = sStatusCode.green break case '3': sStatusCode = sStatusCode.yellow break case '4': case '5': sStatusCode = sStatusCode.red logType = logger.error break } if (url.includes('/api')) { logType(`${method} ${sStatusCode} ${' API '.bgBlue.white} ${url}`) } else { logType(`${method} ${sStatusCode} ${url}`) } } res.on('finish', afterResponse) res.on('close', afterResponse) next() }) router.use(express.static(path.join(__dirname, 'web'))) }
"""profiles_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from profles_api import urls urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('profles_api.urls')) ]
import axios from 'axios'; import authHeader from './auth-header'; import storage from '../utils/storage'; class Auth { login = (email, password) => { return axios .post(`${process.env.REACT_APP_BACKEND_URL}/auth/login`, { email: email, password: password }) .then(response => { if (response.data.code === 200) { storage.setStorage('token', response.data.data.token); storage.setStorage('role', response.data.data.role); } return response.data; }).catch(error => { return error; }) } register = (email, password, setAdvanced, first_name, last_name) => { return axios .post(`${process.env.REACT_APP_BACKEND_URL}/auth/register`, { email: email, password: password, setAdvanced: setAdvanced, first_name: first_name, last_name: last_name }) .then(response => { return response.data; }).catch(error => { return error; }) } validate = (token) => { return axios .post(`${process.env.REACT_APP_BACKEND_URL}/auth/verify`, { }, {headers: authHeader(token)}) .then(response => { return response.data; }).catch(error => { return error; }) } forgot = (email) => { return axios .post(`${process.env.REACT_APP_BACKEND_URL}/auth/forgot`, { email: email }) .then(response => { return response.data; }).catch(error => { return error; }) } reset_password = (password, token) => { return axios .post(`${process.env.REACT_APP_BACKEND_URL}/auth/reset_password`, { password: password }, {headers: authHeader(token)}) .then(response => { return response.data; }).catch(error => { return error; }) } validateToken = () => { return axios .get(`${process.env.REACT_APP_BACKEND_URL}/user/validate_token`, {headers: authHeader(storage.getStorage('token'))}) .then(response => { return response.data; }).catch(error => { return error; }) } } export default new Auth();
/*! * Chart.js v2.9.2 * https://www.chartjs.org * (c) 2019 Chart.js Contributors * Released under the MIT License */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(function() { try { return require('moment'); } catch(e) { } }()) : typeof define === 'function' && define.amd ? define(['require'], function(require) { return factory(function() { try { return require('moment'); } catch(e) { } }()); }) : (global = global || self, global.Chart = factory(global.moment)); }(this, (function (moment) { 'use strict'; moment = moment && moment.hasOwnProperty('default') ? moment['default'] : moment; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } function getCjsExportFromNamespace (n) { return n && n['default'] || n; } var colorName = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; var conversions = createCommonjsModule(function (module) { /* MIT license */ // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) var reverseKeywords = {}; for (var key in colorName) { if (colorName.hasOwnProperty(key)) { reverseKeywords[colorName[key]] = key; } } var convert = module.exports = { rgb: {channels: 3, labels: 'rgb'}, hsl: {channels: 3, labels: 'hsl'}, hsv: {channels: 3, labels: 'hsv'}, hwb: {channels: 3, labels: 'hwb'}, cmyk: {channels: 4, labels: 'cmyk'}, xyz: {channels: 3, labels: 'xyz'}, lab: {channels: 3, labels: 'lab'}, lch: {channels: 3, labels: 'lch'}, hex: {channels: 1, labels: ['hex']}, keyword: {channels: 1, labels: ['keyword']}, ansi16: {channels: 1, labels: ['ansi16']}, ansi256: {channels: 1, labels: ['ansi256']}, hcg: {channels: 3, labels: ['h', 'c', 'g']}, apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, gray: {channels: 1, labels: ['gray']} }; // hide .channels and .labels properties for (var model in convert) { if (convert.hasOwnProperty(model)) { if (!('channels' in convert[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert[model])) { throw new Error('missing channel labels property: ' + model); } if (convert[model].labels.length !== convert[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } var channels = convert[model].channels; var labels = convert[model].labels; delete convert[model].channels; delete convert[model].labels; Object.defineProperty(convert[model], 'channels', {value: channels}); Object.defineProperty(convert[model], 'labels', {value: labels}); } } convert.rgb.hsl = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var min = Math.min(r, g, b); var max = Math.max(r, g, b); var delta = max - min; var h; var s; var l; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert.rgb.hsv = function (rgb) { var rdif; var gdif; var bdif; var h; var s; var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var v = Math.max(r, g, b); var diff = v - Math.min(r, g, b); var diffc = function (c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = (1 / 3) + rdif - bdif; } else if (b === v) { h = (2 / 3) + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [ h * 360, s * 100, v * 100 ]; }; convert.rgb.hwb = function (rgb) { var r = rgb[0]; var g = rgb[1]; var b = rgb[2]; var h = convert.rgb.hsl(rgb)[0]; var w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert.rgb.cmyk = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var c; var m; var y; var k; k = Math.min(1 - r, 1 - g, 1 - b); c = (1 - r - k) / (1 - k) || 0; m = (1 - g - k) / (1 - k) || 0; y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; /** * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance * */ function comparativeDistance(x, y) { return ( Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2) ); } convert.rgb.keyword = function (rgb) { var reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } var currentClosestDistance = Infinity; var currentClosestKeyword; for (var keyword in colorName) { if (colorName.hasOwnProperty(keyword)) { var value = colorName[keyword]; // Compute comparative distance var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } } return currentClosestKeyword; }; convert.keyword.rgb = function (keyword) { return colorName[keyword]; }; convert.rgb.xyz = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; // assume sRGB r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); return [x * 100, y * 100, z * 100]; }; convert.rgb.lab = function (rgb) { var xyz = convert.rgb.xyz(rgb); var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); l = (116 * y) - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.hsl.rgb = function (hsl) { var h = hsl[0] / 360; var s = hsl[1] / 100; var l = hsl[2] / 100; var t1; var t2; var t3; var rgb; var val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } t1 = 2 * l - t2; rgb = [0, 0, 0]; for (var i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert.hsl.hsv = function (hsl) { var h = hsl[0]; var s = hsl[1] / 100; var l = hsl[2] / 100; var smin = s; var lmin = Math.max(l, 0.01); var sv; var v; l *= 2; s *= (l <= 1) ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; v = (l + s) / 2; sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); return [h, sv * 100, v * 100]; }; convert.hsv.rgb = function (hsv) { var h = hsv[0] / 60; var s = hsv[1] / 100; var v = hsv[2] / 100; var hi = Math.floor(h) % 6; var f = h - Math.floor(h); var p = 255 * v * (1 - s); var q = 255 * v * (1 - (s * f)); var t = 255 * v * (1 - (s * (1 - f))); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert.hsv.hsl = function (hsv) { var h = hsv[0]; var s = hsv[1] / 100; var v = hsv[2] / 100; var vmin = Math.max(v, 0.01); var lmin; var sl; var l; l = (2 - s) * v; lmin = (2 - s) * vmin; sl = s * vmin; sl /= (lmin <= 1) ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert.hwb.rgb = function (hwb) { var h = hwb[0] / 360; var wh = hwb[1] / 100; var bl = hwb[2] / 100; var ratio = wh + bl; var i; var v; var f; var n; // wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } i = Math.floor(6 * h); v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } n = wh + f * (v - wh); // linear interpolation var r; var g; var b; switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } return [r * 255, g * 255, b * 255]; }; convert.cmyk.rgb = function (cmyk) { var c = cmyk[0] / 100; var m = cmyk[1] / 100; var y = cmyk[2] / 100; var k = cmyk[3] / 100; var r; var g; var b; r = 1 - Math.min(1, c * (1 - k) + k); g = 1 - Math.min(1, m * (1 - k) + k); b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert.xyz.rgb = function (xyz) { var x = xyz[0] / 100; var y = xyz[1] / 100; var z = xyz[2] / 100; var r; var g; var b; r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); // assume sRGB r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) : r * 12.92; g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) : g * 12.92; b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert.xyz.lab = function (xyz) { var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); l = (116 * y) - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.lab.xyz = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var x; var y; var z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; var y2 = Math.pow(y, 3); var x2 = Math.pow(x, 3); var z2 = Math.pow(z, 3); y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert.lab.lch = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var hr; var h; var c; hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert.lch.lab = function (lch) { var l = lch[0]; var c = lch[1]; var h = lch[2]; var a; var b; var hr; hr = h / 360 * 2 * Math.PI; a = c * Math.cos(hr); b = c * Math.sin(hr); return [l, a, b]; }; convert.rgb.ansi16 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } var ansi = 30 + ((Math.round(b / 255) << 2) | (Math.round(g / 255) << 1) | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert.hsv.ansi16 = function (args) { // optimization here; we already know the value and don't need to get // it converted for us. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); }; convert.rgb.ansi256 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; // we use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round(((r - 8) / 247) * 24) + 232; } var ansi = 16 + (36 * Math.round(r / 255 * 5)) + (6 * Math.round(g / 255 * 5)) + Math.round(b / 255 * 5); return ansi; }; convert.ansi16.rgb = function (args) { var color = args % 10; // handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } var mult = (~~(args > 50) + 1) * 0.5; var r = ((color & 1) * mult) * 255; var g = (((color >> 1) & 1) * mult) * 255; var b = (((color >> 2) & 1) * mult) * 255; return [r, g, b]; }; convert.ansi256.rgb = function (args) { // handle greyscale if (args >= 232) { var c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; var rem; var r = Math.floor(args / 36) / 5 * 255; var g = Math.floor((rem = args % 36) / 6) / 5 * 255; var b = (rem % 6) / 5 * 255; return [r, g, b]; }; convert.rgb.hex = function (args) { var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.hex.rgb = function (args) { var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } var colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(function (char) { return char + char; }).join(''); } var integer = parseInt(colorString, 16); var r = (integer >> 16) & 0xFF; var g = (integer >> 8) & 0xFF; var b = integer & 0xFF; return [r, g, b]; }; convert.rgb.hcg = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var max = Math.max(Math.max(r, g), b); var min = Math.min(Math.min(r, g), b); var chroma = (max - min); var grayscale; var hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = ((g - b) / chroma) % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma + 4; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert.hsl.hcg = function (hsl) { var s = hsl[1] / 100; var l = hsl[2] / 100; var c = 1; var f = 0; if (l < 0.5) { c = 2.0 * s * l; } else { c = 2.0 * s * (1.0 - l); } if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert.hsv.hcg = function (hsv) { var s = hsv[1] / 100; var v = hsv[2] / 100; var c = s * v; var f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert.hcg.rgb = function (hcg) { var h = hcg[0] / 360; var c = hcg[1] / 100; var g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } var pure = [0, 0, 0]; var hi = (h % 1) * 6; var v = hi % 1; var w = 1 - v; var mg = 0; switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } mg = (1.0 - c) * g; return [ (c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255 ]; }; convert.hcg.hsv = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); var f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert.hcg.hsl = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var l = g * (1.0 - c) + 0.5 * c; var s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert.hcg.hwb = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert.hwb.hcg = function (hwb) { var w = hwb[1] / 100; var b = hwb[2] / 100; var v = 1 - b; var c = v - w; var g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert.apple.rgb = function (apple) { return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; }; convert.rgb.apple = function (rgb) { return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; }; convert.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert.gray.hsl = convert.gray.hsv = function (args) { return [0, 0, args[0]]; }; convert.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert.gray.hex = function (gray) { var val = Math.round(gray[0] / 100 * 255) & 0xFF; var integer = (val << 16) + (val << 8) + val; var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.rgb.gray = function (rgb) { var val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; }); var conversions_1 = conversions.rgb; var conversions_2 = conversions.hsl; var conversions_3 = conversions.hsv; var conversions_4 = conversions.hwb; var conversions_5 = conversions.cmyk; var conversions_6 = conversions.xyz; var conversions_7 = conversions.lab; var conversions_8 = conversions.lch; var conversions_9 = conversions.hex; var conversions_10 = conversions.keyword; var conversions_11 = conversions.ansi16; var conversions_12 = conversions.ansi256; var conversions_13 = conversions.hcg; var conversions_14 = conversions.apple; var conversions_15 = conversions.gray; /* this function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph() { var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 var models = Object.keys(conversions); for (var len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS(fromModel) { var graph = buildGraph(); var queue = [fromModel]; // unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { var current = queue.pop(); var adjacents = Object.keys(conversions[current]); for (var len = adjacents.length, i = 0; i < len; i++) { var adjacent = adjacents[i]; var node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion(toModel, graph) { var path = [graph[toModel].parent, toModel]; var fn = conversions[graph[toModel].parent][toModel]; var cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link(conversions[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } var route = function (fromModel) { var graph = deriveBFS(fromModel); var conversion = {}; var models = Object.keys(graph); for (var len = models.length, i = 0; i < len; i++) { var toModel = models[i]; var node = graph[toModel]; if (node.parent === null) { // no possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion(toModel, graph); } return conversion; }; var convert = {}; var models = Object.keys(conversions); function wrapRaw(fn) { var wrappedFn = function (args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } return fn(args); }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded(fn) { var wrappedFn = function (args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } var result = fn(args); // we're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (var len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models.forEach(function (fromModel) { convert[fromModel] = {}; Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); var routes = route(fromModel); var routeModels = Object.keys(routes); routeModels.forEach(function (toModel) { var fn = routes[toModel]; convert[fromModel][toModel] = wrapRounded(fn); convert[fromModel][toModel].raw = wrapRaw(fn); }); }); var colorConvert = convert; var colorName$1 = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; /* MIT license */ var colorString = { getRgba: getRgba, getHsla: getHsla, getRgb: getRgb, getHsl: getHsl, getHwb: getHwb, getAlpha: getAlpha, hexString: hexString, rgbString: rgbString, rgbaString: rgbaString, percentString: percentString, percentaString: percentaString, hslString: hslString, hslaString: hslaString, hwbString: hwbString, keyword: keyword }; function getRgba(string) { if (!string) { return; } var abbr = /^#([a-fA-F0-9]{3,4})$/i, hex = /^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i, rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i, per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i, keyword = /(\w+)/; var rgb = [0, 0, 0], a = 1, match = string.match(abbr), hexAlpha = ""; if (match) { match = match[1]; hexAlpha = match[3]; for (var i = 0; i < rgb.length; i++) { rgb[i] = parseInt(match[i] + match[i], 16); } if (hexAlpha) { a = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100; } } else if (match = string.match(hex)) { hexAlpha = match[2]; match = match[1]; for (var i = 0; i < rgb.length; i++) { rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16); } if (hexAlpha) { a = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100; } } else if (match = string.match(rgba)) { for (var i = 0; i < rgb.length; i++) { rgb[i] = parseInt(match[i + 1]); } a = parseFloat(match[4]); } else if (match = string.match(per)) { for (var i = 0; i < rgb.length; i++) { rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55); } a = parseFloat(match[4]); } else if (match = string.match(keyword)) { if (match[1] == "transparent") { return [0, 0, 0, 0]; } rgb = colorName$1[match[1]]; if (!rgb) { return; } } for (var i = 0; i < rgb.length; i++) { rgb[i] = scale(rgb[i], 0, 255); } if (!a && a != 0) { a = 1; } else { a = scale(a, 0, 1); } rgb[3] = a; return rgb; } function getHsla(string) { if (!string) { return; } var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/; var match = string.match(hsl); if (match) { var alpha = parseFloat(match[4]); var h = scale(parseInt(match[1]), 0, 360), s = scale(parseFloat(match[2]), 0, 100), l = scale(parseFloat(match[3]), 0, 100), a = scale(isNaN(alpha) ? 1 : alpha, 0, 1); return [h, s, l, a]; } } function getHwb(string) { if (!string) { return; } var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/; var match = string.match(hwb); if (match) { var alpha = parseFloat(match[4]); var h = scale(parseInt(match[1]), 0, 360), w = scale(parseFloat(match[2]), 0, 100), b = scale(parseFloat(match[3]), 0, 100), a = scale(isNaN(alpha) ? 1 : alpha, 0, 1); return [h, w, b, a]; } } function getRgb(string) { var rgba = getRgba(string); return rgba && rgba.slice(0, 3); } function getHsl(string) { var hsla = getHsla(string); return hsla && hsla.slice(0, 3); } function getAlpha(string) { var vals = getRgba(string); if (vals) { return vals[3]; } else if (vals = getHsla(string)) { return vals[3]; } else if (vals = getHwb(string)) { return vals[3]; } } // generators function hexString(rgba, a) { var a = (a !== undefined && rgba.length === 3) ? a : rgba[3]; return "#" + hexDouble(rgba[0]) + hexDouble(rgba[1]) + hexDouble(rgba[2]) + ( (a >= 0 && a < 1) ? hexDouble(Math.round(a * 255)) : "" ); } function rgbString(rgba, alpha) { if (alpha < 1 || (rgba[3] && rgba[3] < 1)) { return rgbaString(rgba, alpha); } return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")"; } function rgbaString(rgba, alpha) { if (alpha === undefined) { alpha = (rgba[3] !== undefined ? rgba[3] : 1); } return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ", " + alpha + ")"; } function percentString(rgba, alpha) { if (alpha < 1 || (rgba[3] && rgba[3] < 1)) { return percentaString(rgba, alpha); } var r = Math.round(rgba[0]/255 * 100), g = Math.round(rgba[1]/255 * 100), b = Math.round(rgba[2]/255 * 100); return "rgb(" + r + "%, " + g + "%, " + b + "%)"; } function percentaString(rgba, alpha) { var r = Math.round(rgba[0]/255 * 100), g = Math.round(rgba[1]/255 * 100), b = Math.round(rgba[2]/255 * 100); return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")"; } function hslString(hsla, alpha) { if (alpha < 1 || (hsla[3] && hsla[3] < 1)) { return hslaString(hsla, alpha); } return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)"; } function hslaString(hsla, alpha) { if (alpha === undefined) { alpha = (hsla[3] !== undefined ? hsla[3] : 1); } return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, " + alpha + ")"; } // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax // (hwb have alpha optional & 1 is default value) function hwbString(hwb, alpha) { if (alpha === undefined) { alpha = (hwb[3] !== undefined ? hwb[3] : 1); } return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%" + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")"; } function keyword(rgb) { return reverseNames[rgb.slice(0, 3)]; } // helpers function scale(num, min, max) { return Math.min(Math.max(min, num), max); } function hexDouble(num) { var str = num.toString(16).toUpperCase(); return (str.length < 2) ? "0" + str : str; } //create a list of reverse color names var reverseNames = {}; for (var name in colorName$1) { reverseNames[colorName$1[name]] = name; } /* MIT license */ var Color = function (obj) { if (obj instanceof Color) { return obj; } if (!(this instanceof Color)) { return new Color(obj); } this.valid = false; this.values = { rgb: [0, 0, 0], hsl: [0, 0, 0], hsv: [0, 0, 0], hwb: [0, 0, 0], cmyk: [0, 0, 0, 0], alpha: 1 }; // parse Color() argument var vals; if (typeof obj === 'string') { vals = colorString.getRgba(obj); if (vals) { this.setValues('rgb', vals); } else if (vals = colorString.getHsla(obj)) { this.setValues('hsl', vals); } else if (vals = colorString.getHwb(obj)) { this.setValues('hwb', vals); } } else if (typeof obj === 'object') { vals = obj; if (vals.r !== undefined || vals.red !== undefined) { this.setValues('rgb', vals); } else if (vals.l !== undefined || vals.lightness !== undefined) { this.setValues('hsl', vals); } else if (vals.v !== undefined || vals.value !== undefined) { this.setValues('hsv', vals); } else if (vals.w !== undefined || vals.whiteness !== undefined) { this.setValues('hwb', vals); } else if (vals.c !== undefined || vals.cyan !== undefined) { this.setValues('cmyk', vals); } } }; Color.prototype = { isValid: function () { return this.valid; }, rgb: function () { return this.setSpace('rgb', arguments); }, hsl: function () { return this.setSpace('hsl', arguments); }, hsv: function () { return this.setSpace('hsv', arguments); }, hwb: function () { return this.setSpace('hwb', arguments); }, cmyk: function () { return this.setSpace('cmyk', arguments); }, rgbArray: function () { return this.values.rgb; }, hslArray: function () { return this.values.hsl; }, hsvArray: function () { return this.values.hsv; }, hwbArray: function () { var values = this.values; if (values.alpha !== 1) { return values.hwb.concat([values.alpha]); } return values.hwb; }, cmykArray: function () { return this.values.cmyk; }, rgbaArray: function () { var values = this.values; return values.rgb.concat([values.alpha]); }, hslaArray: function () { var values = this.values; return values.hsl.concat([values.alpha]); }, alpha: function (val) { if (val === undefined) { return this.values.alpha; } this.setValues('alpha', val); return this; }, red: function (val) { return this.setChannel('rgb', 0, val); }, green: function (val) { return this.setChannel('rgb', 1, val); }, blue: function (val) { return this.setChannel('rgb', 2, val); }, hue: function (val) { if (val) { val %= 360; val = val < 0 ? 360 + val : val; } return this.setChannel('hsl', 0, val); }, saturation: function (val) { return this.setChannel('hsl', 1, val); }, lightness: function (val) { return this.setChannel('hsl', 2, val); }, saturationv: function (val) { return this.setChannel('hsv', 1, val); }, whiteness: function (val) { return this.setChannel('hwb', 1, val); }, blackness: function (val) { return this.setChannel('hwb', 2, val); }, value: function (val) { return this.setChannel('hsv', 2, val); }, cyan: function (val) { return this.setChannel('cmyk', 0, val); }, magenta: function (val) { return this.setChannel('cmyk', 1, val); }, yellow: function (val) { return this.setChannel('cmyk', 2, val); }, black: function (val) { return this.setChannel('cmyk', 3, val); }, hexString: function () { return colorString.hexString(this.values.rgb); }, rgbString: function () { return colorString.rgbString(this.values.rgb, this.values.alpha); }, rgbaString: function () { return colorString.rgbaString(this.values.rgb, this.values.alpha); }, percentString: function () { return colorString.percentString(this.values.rgb, this.values.alpha); }, hslString: function () { return colorString.hslString(this.values.hsl, this.values.alpha); }, hslaString: function () { return colorString.hslaString(this.values.hsl, this.values.alpha); }, hwbString: function () { return colorString.hwbString(this.values.hwb, this.values.alpha); }, keyword: function () { return colorString.keyword(this.values.rgb, this.values.alpha); }, rgbNumber: function () { var rgb = this.values.rgb; return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2]; }, luminosity: function () { // http://www.w3.org/TR/WCAG20/#relativeluminancedef var rgb = this.values.rgb; var lum = []; for (var i = 0; i < rgb.length; i++) { var chan = rgb[i] / 255; lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4); } return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2]; }, contrast: function (color2) { // http://www.w3.org/TR/WCAG20/#contrast-ratiodef var lum1 = this.luminosity(); var lum2 = color2.luminosity(); if (lum1 > lum2) { return (lum1 + 0.05) / (lum2 + 0.05); } return (lum2 + 0.05) / (lum1 + 0.05); }, level: function (color2) { var contrastRatio = this.contrast(color2); if (contrastRatio >= 7.1) { return 'AAA'; } return (contrastRatio >= 4.5) ? 'AA' : ''; }, dark: function () { // YIQ equation from http://24ways.org/2010/calculating-color-contrast var rgb = this.values.rgb; var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000; return yiq < 128; }, light: function () { return !this.dark(); }, negate: function () { var rgb = []; for (var i = 0; i < 3; i++) { rgb[i] = 255 - this.values.rgb[i]; } this.setValues('rgb', rgb); return this; }, lighten: function (ratio) { var hsl = this.values.hsl; hsl[2] += hsl[2] * ratio; this.setValues('hsl', hsl); return this; }, darken: function (ratio) { var hsl = this.values.hsl; hsl[2] -= hsl[2] * ratio; this.setValues('hsl', hsl); return this; }, saturate: function (ratio) { var hsl = this.values.hsl; hsl[1] += hsl[1] * ratio; this.setValues('hsl', hsl); return this; }, desaturate: function (ratio) { var hsl = this.values.hsl; hsl[1] -= hsl[1] * ratio; this.setValues('hsl', hsl); return this; }, whiten: function (ratio) { var hwb = this.values.hwb; hwb[1] += hwb[1] * ratio; this.setValues('hwb', hwb); return this; }, blacken: function (ratio) { var hwb = this.values.hwb; hwb[2] += hwb[2] * ratio; this.setValues('hwb', hwb); return this; }, greyscale: function () { var rgb = this.values.rgb; // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11; this.setValues('rgb', [val, val, val]); return this; }, clearer: function (ratio) { var alpha = this.values.alpha; this.setValues('alpha', alpha - (alpha * ratio)); return this; }, opaquer: function (ratio) { var alpha = this.values.alpha; this.setValues('alpha', alpha + (alpha * ratio)); return this; }, rotate: function (degrees) { var hsl = this.values.hsl; var hue = (hsl[0] + degrees) % 360; hsl[0] = hue < 0 ? 360 + hue : hue; this.setValues('hsl', hsl); return this; }, /** * Ported from sass implementation in C * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209 */ mix: function (mixinColor, weight) { var color1 = this; var color2 = mixinColor; var p = weight === undefined ? 0.5 : weight; var w = 2 * p - 1; var a = color1.alpha() - color2.alpha(); var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; var w2 = 1 - w1; return this .rgb( w1 * color1.red() + w2 * color2.red(), w1 * color1.green() + w2 * color2.green(), w1 * color1.blue() + w2 * color2.blue() ) .alpha(color1.alpha() * p + color2.alpha() * (1 - p)); }, toJSON: function () { return this.rgb(); }, clone: function () { // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify, // making the final build way to big to embed in Chart.js. So let's do it manually, // assuming that values to clone are 1 dimension arrays containing only numbers, // except 'alpha' which is a number. var result = new Color(); var source = this.values; var target = result.values; var value, type; for (var prop in source) { if (source.hasOwnProperty(prop)) { value = source[prop]; type = ({}).toString.call(value); if (type === '[object Array]') { target[prop] = value.slice(0); } else if (type === '[object Number]') { target[prop] = value; } else { console.error('unexpected color value:', value); } } } return result; } }; Color.prototype.spaces = { rgb: ['red', 'green', 'blue'], hsl: ['hue', 'saturation', 'lightness'], hsv: ['hue', 'saturation', 'value'], hwb: ['hue', 'whiteness', 'blackness'], cmyk: ['cyan', 'magenta', 'yellow', 'black'] }; Color.prototype.maxes = { rgb: [255, 255, 255], hsl: [360, 100, 100], hsv: [360, 100, 100], hwb: [360, 100, 100], cmyk: [100, 100, 100, 100] }; Color.prototype.getValues = function (space) { var values = this.values; var vals = {}; for (var i = 0; i < space.length; i++) { vals[space.charAt(i)] = values[space][i]; } if (values.alpha !== 1) { vals.a = values.alpha; } // {r: 255, g: 255, b: 255, a: 0.4} return vals; }; Color.prototype.setValues = function (space, vals) { var values = this.values; var spaces = this.spaces; var maxes = this.maxes; var alpha = 1; var i; this.valid = true; if (space === 'alpha') { alpha = vals; } else if (vals.length) { // [10, 10, 10] values[space] = vals.slice(0, space.length); alpha = vals[space.length]; } else if (vals[space.charAt(0)] !== undefined) { // {r: 10, g: 10, b: 10} for (i = 0; i < space.length; i++) { values[space][i] = vals[space.charAt(i)]; } alpha = vals.a; } else if (vals[spaces[space][0]] !== undefined) { // {red: 10, green: 10, blue: 10} var chans = spaces[space]; for (i = 0; i < space.length; i++) { values[space][i] = vals[chans[i]]; } alpha = vals.alpha; } values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha))); if (space === 'alpha') { return false; } var capped; // cap values of the space prior converting all values for (i = 0; i < space.length; i++) { capped = Math.max(0, Math.min(maxes[space][i], values[space][i])); values[space][i] = Math.round(capped); } // convert to all the other color spaces for (var sname in spaces) { if (sname !== space) { values[sname] = colorConvert[space][sname](values[space]); } } return true; }; Color.prototype.setSpace = function (space, args) { var vals = args[0]; if (vals === undefined) { // color.rgb() return this.getValues(space); } // color.rgb(10, 10, 10) if (typeof vals === 'number') { vals = Array.prototype.slice.call(args); } this.setValues(space, vals); return this; }; Color.prototype.setChannel = function (space, index, val) { var svalues = this.values[space]; if (val === undefined) { // color.red() return svalues[index]; } else if (val === svalues[index]) { // color.red(color.red()) return this; } // color.red(100) svalues[index] = val; this.setValues(space, svalues); return this; }; if (typeof window !== 'undefined') { window.Color = Color; } var chartjsColor = Color; /** * @namespace Chart.helpers */ var helpers = { /** * An empty function that can be used, for example, for optional callback. */ noop: function() {}, /** * Returns a unique id, sequentially generated from a global variable. * @returns {number} * @function */ uid: (function() { var id = 0; return function() { return id++; }; }()), /** * Returns true if `value` is neither null nor undefined, else returns false. * @param {*} value - The value to test. * @returns {boolean} * @since 2.7.0 */ isNullOrUndef: function(value) { return value === null || typeof value === 'undefined'; }, /** * Returns true if `value` is an array (including typed arrays), else returns false. * @param {*} value - The value to test. * @returns {boolean} * @function */ isArray: function(value) { if (Array.isArray && Array.isArray(value)) { return true; } var type = Object.prototype.toString.call(value); if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') { return true; } return false; }, /** * Returns true if `value` is an object (excluding null), else returns false. * @param {*} value - The value to test. * @returns {boolean} * @since 2.7.0 */ isObject: function(value) { return value !== null && Object.prototype.toString.call(value) === '[object Object]'; }, /** * Returns true if `value` is a finite number, else returns false * @param {*} value - The value to test. * @returns {boolean} */ isFinite: function(value) { return (typeof value === 'number' || value instanceof Number) && isFinite(value); }, /** * Returns `value` if defined, else returns `defaultValue`. * @param {*} value - The value to return if defined. * @param {*} defaultValue - The value to return if `value` is undefined. * @returns {*} */ valueOrDefault: function(value, defaultValue) { return typeof value === 'undefined' ? defaultValue : value; }, /** * Returns value at the given `index` in array if defined, else returns `defaultValue`. * @param {Array} value - The array to lookup for value at `index`. * @param {number} index - The index in `value` to lookup for value. * @param {*} defaultValue - The value to return if `value[index]` is undefined. * @returns {*} */ valueAtIndexOrDefault: function(value, index, defaultValue) { return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue); }, /** * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the * value returned by `fn`. If `fn` is not a function, this method returns undefined. * @param {function} fn - The function to call. * @param {Array|undefined|null} args - The arguments with which `fn` should be called. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`. * @returns {*} */ callback: function(fn, args, thisArg) { if (fn && typeof fn.call === 'function') { return fn.apply(thisArg, args); } }, /** * Note(SB) for performance sake, this method should only be used when loopable type * is unknown or in none intensive code (not called often and small loopable). Else * it's preferable to use a regular for() loop and save extra function calls. * @param {object|Array} loopable - The object or array to be iterated. * @param {function} fn - The function to call for each item. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`. * @param {boolean} [reverse] - If true, iterates backward on the loopable. */ each: function(loopable, fn, thisArg, reverse) { var i, len, keys; if (helpers.isArray(loopable)) { len = loopable.length; if (reverse) { for (i = len - 1; i >= 0; i--) { fn.call(thisArg, loopable[i], i); } } else { for (i = 0; i < len; i++) { fn.call(thisArg, loopable[i], i); } } } else if (helpers.isObject(loopable)) { keys = Object.keys(loopable); len = keys.length; for (i = 0; i < len; i++) { fn.call(thisArg, loopable[keys[i]], keys[i]); } } }, /** * Returns true if the `a0` and `a1` arrays have the same content, else returns false. * @see https://stackoverflow.com/a/14853974 * @param {Array} a0 - The array to compare * @param {Array} a1 - The array to compare * @returns {boolean} */ arrayEquals: function(a0, a1) { var i, ilen, v0, v1; if (!a0 || !a1 || a0.length !== a1.length) { return false; } for (i = 0, ilen = a0.length; i < ilen; ++i) { v0 = a0[i]; v1 = a1[i]; if (v0 instanceof Array && v1 instanceof Array) { if (!helpers.arrayEquals(v0, v1)) { return false; } } else if (v0 !== v1) { // NOTE: two different object instances will never be equal: {x:20} != {x:20} return false; } } return true; }, /** * Returns a deep copy of `source` without keeping references on objects and arrays. * @param {*} source - The value to clone. * @returns {*} */ clone: function(source) { if (helpers.isArray(source)) { return source.map(helpers.clone); } if (helpers.isObject(source)) { var target = {}; var keys = Object.keys(source); var klen = keys.length; var k = 0; for (; k < klen; ++k) { target[keys[k]] = helpers.clone(source[keys[k]]); } return target; } return source; }, /** * The default merger when Chart.helpers.merge is called without merger option. * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback. * @private */ _merger: function(key, target, source, options) { var tval = target[key]; var sval = source[key]; if (helpers.isObject(tval) && helpers.isObject(sval)) { helpers.merge(tval, sval, options); } else { target[key] = helpers.clone(sval); } }, /** * Merges source[key] in target[key] only if target[key] is undefined. * @private */ _mergerIf: function(key, target, source) { var tval = target[key]; var sval = source[key]; if (helpers.isObject(tval) && helpers.isObject(sval)) { helpers.mergeIf(tval, sval); } else if (!target.hasOwnProperty(key)) { target[key] = helpers.clone(sval); } }, /** * Recursively deep copies `source` properties into `target` with the given `options`. * IMPORTANT: `target` is not cloned and will be updated with `source` properties. * @param {object} target - The target object in which all sources are merged into. * @param {object|object[]} source - Object(s) to merge into `target`. * @param {object} [options] - Merging options: * @param {function} [options.merger] - The merge method (key, target, source, options) * @returns {object} The `target` object. */ merge: function(target, source, options) { var sources = helpers.isArray(source) ? source : [source]; var ilen = sources.length; var merge, i, keys, klen, k; if (!helpers.isObject(target)) { return target; } options = options || {}; merge = options.merger || helpers._merger; for (i = 0; i < ilen; ++i) { source = sources[i]; if (!helpers.isObject(source)) { continue; } keys = Object.keys(source); for (k = 0, klen = keys.length; k < klen; ++k) { merge(keys[k], target, source, options); } } return target; }, /** * Recursively deep copies `source` properties into `target` *only* if not defined in target. * IMPORTANT: `target` is not cloned and will be updated with `source` properties. * @param {object} target - The target object in which all sources are merged into. * @param {object|object[]} source - Object(s) to merge into `target`. * @returns {object} The `target` object. */ mergeIf: function(target, source) { return helpers.merge(target, source, {merger: helpers._mergerIf}); }, /** * Applies the contents of two or more objects together into the first object. * @param {object} target - The target object in which all objects are merged into. * @param {object} arg1 - Object containing additional properties to merge in target. * @param {object} argN - Additional objects containing properties to merge in target. * @returns {object} The `target` object. */ extend: Object.assign || function(target) { return helpers.merge(target, [].slice.call(arguments, 1), { merger: function(key, dst, src) { dst[key] = src[key]; } }); }, /** * Basic javascript inheritance based on the model created in Backbone.js */ inherits: function(extensions) { var me = this; var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() { return me.apply(this, arguments); }; var Surrogate = function() { this.constructor = ChartElement; }; Surrogate.prototype = me.prototype; ChartElement.prototype = new Surrogate(); ChartElement.extend = helpers.inherits; if (extensions) { helpers.extend(ChartElement.prototype, extensions); } ChartElement.__super__ = me.prototype; return ChartElement; }, _deprecated: function(scope, value, previous, current) { if (value !== undefined) { console.warn(scope + ': "' + previous + '" is deprecated. Please use "' + current + '" instead'); } } }; var helpers_core = helpers; // DEPRECATIONS /** * Provided for backward compatibility, use Chart.helpers.callback instead. * @function Chart.helpers.callCallback * @deprecated since version 2.6.0 * @todo remove at version 3 * @private */ helpers.callCallback = helpers.callback; /** * Provided for backward compatibility, use Array.prototype.indexOf instead. * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+ * @function Chart.helpers.indexOf * @deprecated since version 2.7.0 * @todo remove at version 3 * @private */ helpers.indexOf = function(array, item, fromIndex) { return Array.prototype.indexOf.call(array, item, fromIndex); }; /** * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead. * @function Chart.helpers.getValueOrDefault * @deprecated since version 2.7.0 * @todo remove at version 3 * @private */ helpers.getValueOrDefault = helpers.valueOrDefault; /** * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead. * @function Chart.helpers.getValueAtIndexOrDefault * @deprecated since version 2.7.0 * @todo remove at version 3 * @private */ helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault; /** * Easing functions adapted from Robert Penner's easing equations. * @namespace Chart.helpers.easingEffects * @see http://www.robertpenner.com/easing/ */ var effects = { linear: function(t) { return t; }, easeInQuad: function(t) { return t * t; }, easeOutQuad: function(t) { return -t * (t - 2); }, easeInOutQuad: function(t) { if ((t /= 0.5) < 1) { return 0.5 * t * t; } return -0.5 * ((--t) * (t - 2) - 1); }, easeInCubic: function(t) { return t * t * t; }, easeOutCubic: function(t) { return (t = t - 1) * t * t + 1; }, easeInOutCubic: function(t) { if ((t /= 0.5) < 1) { return 0.5 * t * t * t; } return 0.5 * ((t -= 2) * t * t + 2); }, easeInQuart: function(t) { return t * t * t * t; }, easeOutQuart: function(t) { return -((t = t - 1) * t * t * t - 1); }, easeInOutQuart: function(t) { if ((t /= 0.5) < 1) { return 0.5 * t * t * t * t; } return -0.5 * ((t -= 2) * t * t * t - 2); }, easeInQuint: function(t) { return t * t * t * t * t; }, easeOutQuint: function(t) { return (t = t - 1) * t * t * t * t + 1; }, easeInOutQuint: function(t) { if ((t /= 0.5) < 1) { return 0.5 * t * t * t * t * t; } return 0.5 * ((t -= 2) * t * t * t * t + 2); }, easeInSine: function(t) { return -Math.cos(t * (Math.PI / 2)) + 1; }, easeOutSine: function(t) { return Math.sin(t * (Math.PI / 2)); }, easeInOutSine: function(t) { return -0.5 * (Math.cos(Math.PI * t) - 1); }, easeInExpo: function(t) { return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1)); }, easeOutExpo: function(t) { return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1; }, easeInOutExpo: function(t) { if (t === 0) { return 0; } if (t === 1) { return 1; } if ((t /= 0.5) < 1) { return 0.5 * Math.pow(2, 10 * (t - 1)); } return 0.5 * (-Math.pow(2, -10 * --t) + 2); }, easeInCirc: function(t) { if (t >= 1) { return t; } return -(Math.sqrt(1 - t * t) - 1); }, easeOutCirc: function(t) { return Math.sqrt(1 - (t = t - 1) * t); }, easeInOutCirc: function(t) { if ((t /= 0.5) < 1) { return -0.5 * (Math.sqrt(1 - t * t) - 1); } return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1); }, easeInElastic: function(t) { var s = 1.70158; var p = 0; var a = 1; if (t === 0) { return 0; } if (t === 1) { return 1; } if (!p) { p = 0.3; } if (a < 1) { a = 1; s = p / 4; } else { s = p / (2 * Math.PI) * Math.asin(1 / a); } return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p)); }, easeOutElastic: function(t) { var s = 1.70158; var p = 0; var a = 1; if (t === 0) { return 0; } if (t === 1) { return 1; } if (!p) { p = 0.3; } if (a < 1) { a = 1; s = p / 4; } else { s = p / (2 * Math.PI) * Math.asin(1 / a); } return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1; }, easeInOutElastic: function(t) { var s = 1.70158; var p = 0; var a = 1; if (t === 0) { return 0; } if ((t /= 0.5) === 2) { return 1; } if (!p) { p = 0.45; } if (a < 1) { a = 1; s = p / 4; } else { s = p / (2 * Math.PI) * Math.asin(1 / a); } if (t < 1) { return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p)); } return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1; }, easeInBack: function(t) { var s = 1.70158; return t * t * ((s + 1) * t - s); }, easeOutBack: function(t) { var s = 1.70158; return (t = t - 1) * t * ((s + 1) * t + s) + 1; }, easeInOutBack: function(t) { var s = 1.70158; if ((t /= 0.5) < 1) { return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s)); } return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2); }, easeInBounce: function(t) { return 1 - effects.easeOutBounce(1 - t); }, easeOutBounce: function(t) { if (t < (1 / 2.75)) { return 7.5625 * t * t; } if (t < (2 / 2.75)) { return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75; } if (t < (2.5 / 2.75)) { return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375; } return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375; }, easeInOutBounce: function(t) { if (t < 0.5) { return effects.easeInBounce(t * 2) * 0.5; } return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5; } }; var helpers_easing = { effects: effects }; // DEPRECATIONS /** * Provided for backward compatibility, use Chart.helpers.easing.effects instead. * @function Chart.helpers.easingEffects * @deprecated since version 2.7.0 * @todo remove at version 3 * @private */ helpers_core.easingEffects = effects; var PI = Math.PI; var RAD_PER_DEG = PI / 180; var DOUBLE_PI = PI * 2; var HALF_PI = PI / 2; var QUARTER_PI = PI / 4; var TWO_THIRDS_PI = PI * 2 / 3; /** * @namespace Chart.helpers.canvas */ var exports$1 = { /** * Clears the entire canvas associated to the given `chart`. * @param {Chart} chart - The chart for which to clear the canvas. */ clear: function(chart) { chart.ctx.clearRect(0, 0, chart.width, chart.height); }, /** * Creates a "path" for a rectangle with rounded corners at position (x, y) with a * given size (width, height) and the same `radius` for all corners. * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context. * @param {number} x - The x axis of the coordinate for the rectangle starting point. * @param {number} y - The y axis of the coordinate for the rectangle starting point. * @param {number} width - The rectangle's width. * @param {number} height - The rectangle's height. * @param {number} radius - The rounded amount (in pixels) for the four corners. * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object? */ roundedRect: function(ctx, x, y, width, height, radius) { if (radius) { var r = Math.min(radius, height / 2, width / 2); var left = x + r; var top = y + r; var right = x + width - r; var bottom = y + height - r; ctx.moveTo(x, top); if (left < right && top < bottom) { ctx.arc(left, top, r, -PI, -HALF_PI); ctx.arc(right, top, r, -HALF_PI, 0); ctx.arc(right, bottom, r, 0, HALF_PI); ctx.arc(left, bottom, r, HALF_PI, PI); } else if (left < right) { ctx.moveTo(left, y); ctx.arc(right, top, r, -HALF_PI, HALF_PI); ctx.arc(left, top, r, HALF_PI, PI + HALF_PI); } else if (top < bottom) { ctx.arc(left, top, r, -PI, 0); ctx.arc(left, bottom, r, 0, PI); } else { ctx.arc(left, top, r, -PI, PI); } ctx.closePath(); ctx.moveTo(x, y); } else { ctx.rect(x, y, width, height); } }, drawPoint: function(ctx, style, radius, x, y, rotation) { var type, xOffset, yOffset, size, cornerRadius; var rad = (rotation || 0) * RAD_PER_DEG; if (style && typeof style === 'object') { type = style.toString(); if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') { ctx.save(); ctx.translate(x, y); ctx.rotate(rad); ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height); ctx.restore(); return; } } if (isNaN(radius) || radius <= 0) { return; } ctx.beginPath(); switch (style) { // Default includes circle default: ctx.arc(x, y, radius, 0, DOUBLE_PI); ctx.closePath(); break; case 'triangle': ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); rad += TWO_THIRDS_PI; ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); rad += TWO_THIRDS_PI; ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); ctx.closePath(); break; case 'rectRounded': // NOTE: the rounded rect implementation changed to use `arc` instead of // `quadraticCurveTo` since it generates better results when rect is // almost a circle. 0.516 (instead of 0.5) produces results with visually // closer proportion to the previous impl and it is inscribed in the // circle with `radius`. For more details, see the following PRs: // https://github.com/chartjs/Chart.js/issues/5597 // https://github.com/chartjs/Chart.js/issues/5858 cornerRadius = radius * 0.516; size = radius - cornerRadius; xOffset = Math.cos(rad + QUARTER_PI) * size; yOffset = Math.sin(rad + QUARTER_PI) * size; ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI); ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad); ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI); ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI); ctx.closePath(); break; case 'rect': if (!rotation) { size = Math.SQRT1_2 * radius; ctx.rect(x - size, y - size, 2 * size, 2 * size); break; } rad += QUARTER_PI; /* falls through */ case 'rectRot': xOffset = Math.cos(rad) * radius; yOffset = Math.sin(rad) * radius; ctx.moveTo(x - xOffset, y - yOffset); ctx.lineTo(x + yOffset, y - xOffset); ctx.lineTo(x + xOffset, y + yOffset); ctx.lineTo(x - yOffset, y + xOffset); ctx.closePath(); break; case 'crossRot': rad += QUARTER_PI; /* falls through */ case 'cross': xOffset = Math.cos(rad) * radius; yOffset = Math.sin(rad) * radius; ctx.moveTo(x - xOffset, y - yOffset); ctx.lineTo(x + xOffset, y + yOffset); ctx.moveTo(x + yOffset, y - xOffset); ctx.lineTo(x - yOffset, y + xOffset); break; case 'star': xOffset = Math.cos(rad) * radius; yOffset = Math.sin(rad) * radius; ctx.moveTo(x - xOffset, y - yOffset); ctx.lineTo(x + xOffset, y + yOffset); ctx.moveTo(x + yOffset, y - xOffset); ctx.lineTo(x - yOffset, y + xOffset); rad += QUARTER_PI; xOffset = Math.cos(rad) * radius; yOffset = Math.sin(rad) * radius; ctx.moveTo(x - xOffset, y - yOffset); ctx.lineTo(x + xOffset, y + yOffset); ctx.moveTo(x + yOffset, y - xOffset); ctx.lineTo(x - yOffset, y + xOffset); break; case 'line': xOffset = Math.cos(rad) * radius; yOffset = Math.sin(rad) * radius; ctx.moveTo(x - xOffset, y - yOffset); ctx.lineTo(x + xOffset, y + yOffset); break; case 'dash': ctx.moveTo(x, y); ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius); break; } ctx.fill(); ctx.stroke(); }, /** * Returns true if the point is inside the rectangle * @param {object} point - The point to test * @param {object} area - The rectangle * @returns {boolean} * @private */ _isPointInArea: function(point, area) { var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error. return point.x > area.left - epsilon && point.x < area.right + epsilon && point.y > area.top - epsilon && point.y < area.bottom + epsilon; }, clipArea: function(ctx, area) { ctx.save(); ctx.beginPath(); ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top); ctx.clip(); }, unclipArea: function(ctx) { ctx.restore(); }, lineTo: function(ctx, previous, target, flip) { var stepped = target.steppedLine; if (stepped) { if (stepped === 'middle') { var midpoint = (previous.x + target.x) / 2.0; ctx.lineTo(midpoint, flip ? target.y : previous.y); ctx.lineTo(midpoint, flip ? previous.y : target.y); } else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) { ctx.lineTo(previous.x, target.y); } else { ctx.lineTo(target.x, previous.y); } ctx.lineTo(target.x, target.y); return; } if (!target.tension) { ctx.lineTo(target.x, target.y); return; } ctx.bezierCurveTo( flip ? previous.controlPointPreviousX : previous.controlPointNextX, flip ? previous.controlPointPreviousY : previous.controlPointNextY, flip ? target.controlPointNextX : target.controlPointPreviousX, flip ? target.controlPointNextY : target.controlPointPreviousY, target.x, target.y); } }; var helpers_canvas = exports$1; // DEPRECATIONS /** * Provided for backward compatibility, use Chart.helpers.canvas.clear instead. * @namespace Chart.helpers.clear * @deprecated since version 2.7.0 * @todo remove at version 3 * @private */ helpers_core.clear = exports$1.clear; /** * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead. * @namespace Chart.helpers.drawRoundedRectangle * @deprecated since version 2.7.0 * @todo remove at version 3 * @private */ helpers_core.drawRoundedRectangle = function(ctx) { ctx.beginPath(); exports$1.roundedRect.apply(exports$1, arguments); }; var defaults = { /** * @private */ _set: function(scope, values) { return helpers_core.merge(this[scope] || (this[scope] = {}), values); } }; // TODO(v3): remove 'global' from namespace. all default are global and // there's inconsistency around which options are under 'global' defaults._set('global', { defaultColor: 'rgba(0,0,0,0.1)', defaultFontColor: '#666', defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", defaultFontSize: 12, defaultFontStyle: 'normal', defaultLineHeight: 1.2, showLines: true }); var core_defaults = defaults; var valueOrDefault = helpers_core.valueOrDefault; /** * Converts the given font object into a CSS font string. * @param {object} font - A font object. * @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font * @private */ function toFontString(font) { if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) { return null; } return (font.style ? font.style + ' ' : '') + (font.weight ? font.weight + ' ' : '') + font.size + 'px ' + font.family; } /** * @alias Chart.helpers.options * @namespace */ var helpers_options = { /** * Converts the given line height `value` in pixels for a specific font `size`. * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em'). * @param {number} size - The font size (in pixels) used to resolve relative `value`. * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height * @since 2.7.0 */ toLineHeight: function(value, size) { var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/); if (!matches || matches[1] === 'normal') { return size * 1.2; } value = +matches[2]; switch (matches[3]) { case 'px': return value; case '%': value /= 100; break; } return size * value; }, /** * Converts the given value into a padding object with pre-computed width/height. * @param {number|object} value - If a number, set the value to all TRBL component, * else, if and object, use defined properties and sets undefined ones to 0. * @returns {object} The padding values (top, right, bottom, left, width, height) * @since 2.7.0 */ toPadding: function(value) { var t, r, b, l; if (helpers_core.isObject(value)) { t = +value.top || 0; r = +value.right || 0; b = +value.bottom || 0; l = +value.left || 0; } else { t = r = b = l = +value || 0; } return { top: t, right: r, bottom: b, left: l, height: t + b, width: l + r }; }, /** * Parses font options and returns the font object. * @param {object} options - A object that contains font options to be parsed. * @return {object} The font object. * @todo Support font.* options and renamed to toFont(). * @private */ _parseFont: function(options) { var globalDefaults = core_defaults.global; var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize); var font = { family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily), lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size), size: size, style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle), weight: null, string: '' }; font.string = toFontString(font); return font; }, /** * Evaluates the given `inputs` sequentially and returns the first defined value. * @param {Array} inputs - An array of values, falling back to the last value. * @param {object} [context] - If defined and the current value is a function, the value * is called with `context` as first argument and the result becomes the new input. * @param {number} [index] - If defined and the current value is an array, the value * at `index` become the new input. * @param {object} [info] - object to return information about resolution in * @param {boolean} [info.cacheable] - Will be set to `false` if option is not cacheable. * @since 2.7.0 */ resolve: function(inputs, context, index, info) { var cacheable = true; var i, ilen, value; for (i = 0, ilen = inputs.length; i < ilen; ++i) { value = inputs[i]; if (value === undefined) { continue; } if (context !== undefined && typeof value === 'function') { value = value(context); cacheable = false; } if (index !== undefined && helpers_core.isArray(value)) { value = value[index]; cacheable = false; } if (value !== undefined) { if (info && !cacheable) { info.cacheable = false; } return value; } } } }; /** * @alias Chart.helpers.math * @namespace */ var exports$2 = { /** * Returns an array of factors sorted from 1 to sqrt(value) * @private */ _factorize: function(value) { var result = []; var sqrt = Math.sqrt(value); var i; for (i = 1; i < sqrt; i++) { if (value % i === 0) { result.push(i); result.push(value / i); } } if (sqrt === (sqrt | 0)) { // if value is a square number result.push(sqrt); } result.sort(function(a, b) { return a - b; }).pop(); return result; }, log10: Math.log10 || function(x) { var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10. // Check for whole powers of 10, // which due to floating point rounding error should be corrected. var powerOf10 = Math.round(exponent); var isPowerOf10 = x === Math.pow(10, powerOf10); return isPowerOf10 ? powerOf10 : exponent; } }; var helpers_math = exports$2; // DEPRECATIONS /** * Provided for backward compatibility, use Chart.helpers.math.log10 instead. * @namespace Chart.helpers.log10 * @deprecated since version 2.9.0 * @todo remove at version 3 * @private */ helpers_core.log10 = exports$2.log10; var getRtlAdapter = function(rectX, width) { return { x: function(x) { return rectX + rectX + width - x; }, setWidth: function(w) { width = w; }, textAlign: function(align) { if (align === 'center') { return align; } return align === 'right' ? 'left' : 'right'; }, xPlus: function(x, value) { return x - value; }, leftForLtr: function(x, itemWidth) { return x - itemWidth; }, }; }; var getLtrAdapter = function() { return { x: function(x) { return x; }, setWidth: function(w) { // eslint-disable-line no-unused-vars }, textAlign: function(align) { return align; }, xPlus: function(x, value) { return x + value; }, leftForLtr: function(x, _itemWidth) { // eslint-disable-line no-unused-vars return x; }, }; }; var getAdapter = function(rtl, rectX, width) { return rtl ? getRtlAdapter(rectX, width) : getLtrAdapter(); }; var overrideTextDirection = function(ctx, direction) { var style, original; if (direction === 'ltr' || direction === 'rtl') { style = ctx.canvas.style; original = [ style.getPropertyValue('direction'), style.getPropertyPriority('direction'), ]; style.setProperty('direction', direction, 'important'); ctx.prevTextDirection = original; } }; var restoreTextDirection = function(ctx) { var original = ctx.prevTextDirection; if (original !== undefined) { delete ctx.prevTextDirection; ctx.canvas.style.setProperty('direction', original[0], original[1]); } }; var helpers_rtl = { getRtlAdapter: getAdapter, overrideTextDirection: overrideTextDirection, restoreTextDirection: restoreTextDirection, }; var helpers$1 = helpers_core; var easing = helpers_easing; var canvas = helpers_canvas; var options = helpers_options; var math = helpers_math; var rtl = helpers_rtl; helpers$1.easing = easing; helpers$1.canvas = canvas; helpers$1.options = options; helpers$1.math = math; helpers$1.rtl = rtl; function interpolate(start, view, model, ease) { var keys = Object.keys(model); var i, ilen, key, actual, origin, target, type, c0, c1; for (i = 0, ilen = keys.length; i < ilen; ++i) { key = keys[i]; target = model[key]; // if a value is added to the model after pivot() has been called, the view // doesn't contain it, so let's initialize the view to the target value. if (!view.hasOwnProperty(key)) { view[key] = target; } actual = view[key]; if (actual === target || key[0] === '_') { continue; } if (!start.hasOwnProperty(key)) { start[key] = actual; } origin = start[key]; type = typeof target; if (type === typeof origin) { if (type === 'string') { c0 = chartjsColor(origin); if (c0.valid) { c1 = chartjsColor(target); if (c1.valid) { view[key] = c1.mix(c0, ease).rgbString(); continue; } } } else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) { view[key] = origin + (target - origin) * ease; continue; } } view[key] = target; } } var Element = function(configuration) { helpers$1.extend(this, configuration); this.initialize.apply(this, arguments); }; helpers$1.extend(Element.prototype, { _type: undefined, initialize: function() { this.hidden = false; }, pivot: function() { var me = this; if (!me._view) { me._view = helpers$1.extend({}, me._model); } me._start = {}; return me; }, transition: function(ease) { var me = this; var model = me._model; var start = me._start; var view = me._view; // No animation -> No Transition if (!model || ease === 1) { me._view = helpers$1.extend({}, model); me._start = null; return me; } if (!view) { view = me._view = {}; } if (!start) { start = me._start = {}; } interpolate(start, view, model, ease); return me; }, tooltipPosition: function() { return { x: this._model.x, y: this._model.y }; }, hasValue: function() { return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y); } }); Element.extend = helpers$1.inherits; var core_element = Element; var exports$3 = core_element.extend({ chart: null, // the animation associated chart instance currentStep: 0, // the current animation step numSteps: 60, // default number of steps easing: '', // the easing to use for this animation render: null, // render function used by the animation service onAnimationProgress: null, // user specified callback to fire on each step of the animation onAnimationComplete: null, // user specified callback to fire when the animation finishes }); var core_animation = exports$3; // DEPRECATIONS /** * Provided for backward compatibility, use Chart.Animation instead * @prop Chart.Animation#animationObject * @deprecated since version 2.6.0 * @todo remove at version 3 */ Object.defineProperty(exports$3.prototype, 'animationObject', { get: function() { return this; } }); /** * Provided for backward compatibility, use Chart.Animation#chart instead * @prop Chart.Animation#chartInstance * @deprecated since version 2.6.0 * @todo remove at version 3 */ Object.defineProperty(exports$3.prototype, 'chartInstance', { get: function() { return this.chart; }, set: function(value) { this.chart = value; } }); core_defaults._set('global', { animation: { duration: 1000, easing: 'easeOutQuart', onProgress: helpers$1.noop, onComplete: helpers$1.noop } }); var core_animations = { animations: [], request: null, /** * @param {Chart} chart - The chart to animate. * @param {Chart.Animation} animation - The animation that we will animate. * @param {number} duration - The animation duration in ms. * @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions */ addAnimation: function(chart, animation, duration, lazy) { var animations = this.animations; var i, ilen; animation.chart = chart; animation.startTime = Date.now(); animation.duration = duration; if (!lazy) { chart.animating = true; } for (i = 0, ilen = animations.length; i < ilen; ++i) { if (animations[i].chart === chart) { animations[i] = animation; return; } } animations.push(animation); // If there are no animations queued, manually kickstart a digest, for lack of a better word if (animations.length === 1) { this.requestAnimationFrame(); } }, cancelAnimation: function(chart) { var index = helpers$1.findIndex(this.animations, function(animation) { return animation.chart === chart; }); if (index !== -1) { this.animations.splice(index, 1); chart.animating = false; } }, requestAnimationFrame: function() { var me = this; if (me.request === null) { // Skip animation frame requests until the active one is executed. // This can happen when processing mouse events, e.g. 'mousemove' // and 'mouseout' events will trigger multiple renders. me.request = helpers$1.requestAnimFrame.call(window, function() { me.request = null; me.startDigest(); }); } }, /** * @private */ startDigest: function() { var me = this; me.advance(); // Do we have more stuff to animate? if (me.animations.length > 0) { me.requestAnimationFrame(); } }, /** * @private */ advance: function() { var animations = this.animations; var animation, chart, numSteps, nextStep; var i = 0; // 1 animation per chart, so we are looping charts here while (i < animations.length) { animation = animations[i]; chart = animation.chart; numSteps = animation.numSteps; // Make sure that currentStep starts at 1 // https://github.com/chartjs/Chart.js/issues/6104 nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1; animation.currentStep = Math.min(nextStep, numSteps); helpers$1.callback(animation.render, [chart, animation], chart); helpers$1.callback(animation.onAnimationProgress, [animation], chart); if (animation.currentStep >= numSteps) { helpers$1.callback(animation.onAnimationComplete, [animation], chart); chart.animating = false; animations.splice(i, 1); } else { ++i; } } } }; var resolve = helpers$1.options.resolve; var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift']; /** * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice', * 'unshift') and notify the listener AFTER the array has been altered. Listeners are * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments. */ function listenArrayEvents(array, listener) { if (array._chartjs) { array._chartjs.listeners.push(listener); return; } Object.defineProperty(array, '_chartjs', { configurable: true, enumerable: false, value: { listeners: [listener] } }); arrayEvents.forEach(function(key) { var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1); var base = array[key]; Object.defineProperty(array, key, { configurable: true, enumerable: false, value: function() { var args = Array.prototype.slice.call(arguments); var res = base.apply(this, args); helpers$1.each(array._chartjs.listeners, function(object) { if (typeof object[method] === 'function') { object[method].apply(object, args); } }); return res; } }); }); } /** * Removes the given array event listener and cleanup extra attached properties (such as * the _chartjs stub and overridden methods) if array doesn't have any more listeners. */ function unlistenArrayEvents(array, listener) { var stub = array._chartjs; if (!stub) { return; } var listeners = stub.listeners; var index = listeners.indexOf(listener); if (index !== -1) { listeners.splice(index, 1); } if (listeners.length > 0) { return; } arrayEvents.forEach(function(key) { delete array[key]; }); delete array._chartjs; } // Base class for all dataset controllers (line, bar, etc) var DatasetController = function(chart, datasetIndex) { this.initialize(chart, datasetIndex); }; helpers$1.extend(DatasetController.prototype, { /** * Element type used to generate a meta dataset (e.g. Chart.element.Line). * @type {Chart.core.element} */ datasetElementType: null, /** * Element type used to generate a meta data (e.g. Chart.element.Point). * @type {Chart.core.element} */ dataElementType: null, /** * Dataset element option keys to be resolved in _resolveDatasetElementOptions. * A derived controller may override this to resolve controller-specific options. * The keys defined here are for backward compatibility for legend styles. * @private */ _datasetElementOptions: [ 'backgroundColor', 'borderCapStyle', 'borderColor', 'borderDash', 'borderDashOffset', 'borderJoinStyle', 'borderWidth' ], /** * Data element option keys to be resolved in _resolveDataElementOptions. * A derived controller may override this to resolve controller-specific options. * The keys defined here are for backward compatibility for legend styles. * @private */ _dataElementOptions: [ 'backgroundColor', 'borderColor', 'borderWidth', 'pointStyle' ], initialize: function(chart, datasetIndex) { var me = this; me.chart = chart; me.index = datasetIndex; me.linkScales(); me.addElements(); me._type = me.getMeta().type; }, updateIndex: function(datasetIndex) { this.index = datasetIndex; }, linkScales: function() { var me = this; var meta = me.getMeta(); var chart = me.chart; var scales = chart.scales; var dataset = me.getDataset(); var scalesOpts = chart.options.scales; if (meta.xAxisID === null || !(meta.xAxisID in scales) || dataset.xAxisID) { meta.xAxisID = dataset.xAxisID || scalesOpts.xAxes[0].id; } if (meta.yAxisID === null || !(meta.yAxisID in scales) || dataset.yAxisID) { meta.yAxisID = dataset.yAxisID || scalesOpts.yAxes[0].id; } }, getDataset: function() { return this.chart.data.datasets[this.index]; }, getMeta: function() { return this.chart.getDatasetMeta(this.index); }, getScaleForId: function(scaleID) { return this.chart.scales[scaleID]; }, /** * @private */ _getValueScaleId: function() { return this.getMeta().yAxisID; }, /** * @private */ _getIndexScaleId: function() { return this.getMeta().xAxisID; }, /** * @private */ _getValueScale: function() { return this.getScaleForId(this._getValueScaleId()); }, /** * @private */ _getIndexScale: function() { return this.getScaleForId(this._getIndexScaleId()); }, reset: function() { this._update(true); }, /** * @private */ destroy: function() { if (this._data) { unlistenArrayEvents(this._data, this); } }, createMetaDataset: function() { var me = this; var type = me.datasetElementType; return type && new type({ _chart: me.chart, _datasetIndex: me.index }); }, createMetaData: function(index) { var me = this; var type = me.dataElementType; return type && new type({ _chart: me.chart, _datasetIndex: me.index, _index: index }); }, addElements: function() { var me = this; var meta = me.getMeta(); var data = me.getDataset().data || []; var metaData = meta.data; var i, ilen; for (i = 0, ilen = data.length; i < ilen; ++i) { metaData[i] = metaData[i] || me.createMetaData(i); } meta.dataset = meta.dataset || me.createMetaDataset(); }, addElementAndReset: function(index) { var element = this.createMetaData(index); this.getMeta().data.splice(index, 0, element); this.updateElement(element, index, true); }, buildOrUpdateElements: function() { var me = this; var dataset = me.getDataset(); var data = dataset.data || (dataset.data = []); // In order to correctly handle data addition/deletion animation (an thus simulate // real-time charts), we need to monitor these data modifications and synchronize // the internal meta data accordingly. if (me._data !== data) { if (me._data) { // This case happens when the user replaced the data array instance. unlistenArrayEvents(me._data, me); } if (data && Object.isExtensible(data)) { listenArrayEvents(data, me); } me._data = data; } // Re-sync meta data in case the user replaced the data array or if we missed // any updates and so make sure that we handle number of datapoints changing. me.resyncElements(); }, /** * Returns the merged user-supplied and default dataset-level options * @private */ _configure: function() { var me = this; me._config = helpers$1.merge({}, [ me.chart.options.datasets[me._type], me.getDataset(), ], { merger: function(key, target, source) { if (key !== '_meta' && key !== 'data') { helpers$1._merger(key, target, source); } } }); }, _update: function(reset) { var me = this; me._configure(); me._cachedDataOpts = null; me.update(reset); }, update: helpers$1.noop, transition: function(easingValue) { var meta = this.getMeta(); var elements = meta.data || []; var ilen = elements.length; var i = 0; for (; i < ilen; ++i) { elements[i].transition(easingValue); } if (meta.dataset) { meta.dataset.transition(easingValue); } }, draw: function() { var meta = this.getMeta(); var elements = meta.data || []; var ilen = elements.length; var i = 0; if (meta.dataset) { meta.dataset.draw(); } for (; i < ilen; ++i) { elements[i].draw(); } }, /** * Returns a set of predefined style properties that should be used to represent the dataset * or the data if the index is specified * @param {number} index - data index * @return {IStyleInterface} style object */ getStyle: function(index) { var me = this; var meta = me.getMeta(); var dataset = meta.dataset; var style; me._configure(); if (dataset && index === undefined) { style = me._resolveDatasetElementOptions(dataset || {}); } else { index = index || 0; style = me._resolveDataElementOptions(meta.data[index] || {}, index); } if (style.fill === false || style.fill === null) { style.backgroundColor = 'rgba(0,0,0,0)'; } return style; }, /** * @private */ _resolveDatasetElementOptions: function(element, hover) { var me = this; var chart = me.chart; var datasetOpts = me._config; var custom = element.custom || {}; var options = chart.options.elements[me.datasetElementType.prototype._type] || {}; var elementOptions = me._datasetElementOptions; var values = {}; var i, ilen, key, readKey; // Scriptable options var context = { chart: chart, dataset: me.getDataset(), datasetIndex: me.index, hover: hover }; for (i = 0, ilen = elementOptions.length; i < ilen; ++i) { key = elementOptions[i]; readKey = hover ? 'hover' + key.charAt(0).toUpperCase() + key.slice(1) : key; values[key] = resolve([ custom[readKey], datasetOpts[readKey], options[readKey] ], context); } return values; }, /** * @private */ _resolveDataElementOptions: function(element, index) { var me = this; var custom = element && element.custom; var cached = me._cachedDataOpts; if (cached && !custom) { return cached; } var chart = me.chart; var datasetOpts = me._config; var options = chart.options.elements[me.dataElementType.prototype._type] || {}; var elementOptions = me._dataElementOptions; var values = {}; // Scriptable options var context = { chart: chart, dataIndex: index, dataset: me.getDataset(), datasetIndex: me.index }; // `resolve` sets cacheable to `false` if any option is indexed or scripted var info = {cacheable: !custom}; var keys, i, ilen, key; custom = custom || {}; if (helpers$1.isArray(elementOptions)) { for (i = 0, ilen = elementOptions.length; i < ilen; ++i) { key = elementOptions[i]; values[key] = resolve([ custom[key], datasetOpts[key], options[key] ], context, index, info); } } else { keys = Object.keys(elementOptions); for (i = 0, ilen = keys.length; i < ilen; ++i) { key = keys[i]; values[key] = resolve([ custom[key], datasetOpts[elementOptions[key]], datasetOpts[key], options[key] ], context, index, info); } } if (info.cacheable) { me._cachedDataOpts = Object.freeze(values); } return values; }, removeHoverStyle: function(element) { helpers$1.merge(element._model, element.$previousStyle || {}); delete element.$previousStyle; }, setHoverStyle: function(element) { var dataset = this.chart.data.datasets[element._datasetIndex]; var index = element._index; var custom = element.custom || {}; var model = element._model; var getHoverColor = helpers$1.getHoverColor; element.$previousStyle = { backgroundColor: model.backgroundColor, borderColor: model.borderColor, borderWidth: model.borderWidth }; model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index); model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index); model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index); }, /** * @private */ _removeDatasetHoverStyle: function() { var element = this.getMeta().dataset; if (element) { this.removeHoverStyle(element); } }, /** * @private */ _setDatasetHoverStyle: function() { var element = this.getMeta().dataset; var prev = {}; var i, ilen, key, keys, hoverOptions, model; if (!element) { return; } model = element._model; hoverOptions = this._resolveDatasetElementOptions(element, true); keys = Object.keys(hoverOptions); for (i = 0, ilen = keys.length; i < ilen; ++i) { key = keys[i]; prev[key] = model[key]; model[key] = hoverOptions[key]; } element.$previousStyle = prev; }, /** * @private */ resyncElements: function() { var me = this; var meta = me.getMeta(); var data = me.getDataset().data; var numMeta = meta.data.length; var numData = data.length; if (numData < numMeta) { meta.data.splice(numData, numMeta - numData); } else if (numData > numMeta) { me.insertElements(numMeta, numData - numMeta); } }, /** * @private */ insertElements: function(start, count) { for (var i = 0; i < count; ++i) { this.addElementAndReset(start + i); } }, /** * @private */ onDataPush: function() { var count = arguments.length; this.insertElements(this.getDataset().data.length - count, count); }, /** * @private */ onDataPop: function() { this.getMeta().data.pop(); }, /** * @private */ onDataShift: function() { this.getMeta().data.shift(); }, /** * @private */ onDataSplice: function(start, count) { this.getMeta().data.splice(start, count); this.insertElements(start, arguments.length - 2); }, /** * @private */ onDataUnshift: function() { this.insertElements(0, arguments.length); } }); DatasetController.extend = helpers$1.inherits; var core_datasetController = DatasetController; var TAU = Math.PI * 2; core_defaults._set('global', { elements: { arc: { backgroundColor: core_defaults.global.defaultColor, borderColor: '#fff', borderWidth: 2, borderAlign: 'center' } } }); function clipArc(ctx, arc) { var startAngle = arc.startAngle; var endAngle = arc.endAngle; var pixelMargin = arc.pixelMargin; var angleMargin = pixelMargin / arc.outerRadius; var x = arc.x; var y = arc.y; // Draw an inner border by cliping the arc and drawing a double-width border // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders ctx.beginPath(); ctx.arc(x, y, arc.outerRadius, startAngle - angleMargin, endAngle + angleMargin); if (arc.innerRadius > pixelMargin) { angleMargin = pixelMargin / arc.innerRadius; ctx.arc(x, y, arc.innerRadius - pixelMargin, endAngle + angleMargin, startAngle - angleMargin, true); } else { ctx.arc(x, y, pixelMargin, endAngle + Math.PI / 2, startAngle - Math.PI / 2); } ctx.closePath(); ctx.clip(); } function drawFullCircleBorders(ctx, vm, arc, inner) { var endAngle = arc.endAngle; var i; if (inner) { arc.endAngle = arc.startAngle + TAU; clipArc(ctx, arc); arc.endAngle = endAngle; if (arc.endAngle === arc.startAngle && arc.fullCircles) { arc.endAngle += TAU; arc.fullCircles--; } } ctx.beginPath(); ctx.arc(arc.x, arc.y, arc.innerRadius, arc.startAngle + TAU, arc.startAngle, true); for (i = 0; i < arc.fullCircles; ++i) { ctx.stroke(); } ctx.beginPath(); ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.startAngle + TAU); for (i = 0; i < arc.fullCircles; ++i) { ctx.stroke(); } } function drawBorder(ctx, vm, arc) { var inner = vm.borderAlign === 'inner'; if (inner) { ctx.lineWidth = vm.borderWidth * 2; ctx.lineJoin = 'round'; } else { ctx.lineWidth = vm.borderWidth; ctx.lineJoin = 'bevel'; } if (arc.fullCircles) { drawFullCircleBorders(ctx, vm, arc, inner); } if (inner) { clipArc(ctx, arc); } ctx.beginPath(); ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.endAngle); ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true); ctx.closePath(); ctx.stroke(); } var element_arc = core_element.extend({ _type: 'arc', inLabelRange: function(mouseX) { var vm = this._view; if (vm) { return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2)); } return false; }, inRange: function(chartX, chartY) { var vm = this._view; if (vm) { var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY}); var angle = pointRelativePosition.angle; var distance = pointRelativePosition.distance; // Sanitise angle range var startAngle = vm.startAngle; var endAngle = vm.endAngle; while (endAngle < startAngle) { endAngle += TAU; } while (angle > endAngle) { angle -= TAU; } while (angle < startAngle) { angle += TAU; } // Check if within the range of the open/close angle var betweenAngles = (angle >= startAngle && angle <= endAngle); var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius); return (betweenAngles && withinRadius); } return false; }, getCenterPoint: function() { var vm = this._view; var halfAngle = (vm.startAngle + vm.endAngle) / 2; var halfRadius = (vm.innerRadius + vm.outerRadius) / 2; return { x: vm.x + Math.cos(halfAngle) * halfRadius, y: vm.y + Math.sin(halfAngle) * halfRadius }; }, getArea: function() { var vm = this._view; return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2)); }, tooltipPosition: function() { var vm = this._view; var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2); var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius; return { x: vm.x + (Math.cos(centreAngle) * rangeFromCentre), y: vm.y + (Math.sin(centreAngle) * rangeFromCentre) }; }, draw: function() { var ctx = this._chart.ctx; var vm = this._view; var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0; var arc = { x: vm.x, y: vm.y, innerRadius: vm.innerRadius, outerRadius: Math.max(vm.outerRadius - pixelMargin, 0), pixelMargin: pixelMargin, startAngle: vm.startAngle, endAngle: vm.endAngle, fullCircles: Math.floor(vm.circumference / TAU) }; var i; ctx.save(); ctx.fillStyle = vm.backgroundColor; ctx.strokeStyle = vm.borderColor; if (arc.fullCircles) { arc.endAngle = arc.startAngle + TAU; ctx.beginPath(); ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle); ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true); ctx.closePath(); for (i = 0; i < arc.fullCircles; ++i) { ctx.fill(); } arc.endAngle = arc.startAngle + vm.circumference % TAU; } ctx.beginPath(); ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle); ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true); ctx.closePath(); ctx.fill(); if (vm.borderWidth) { drawBorder(ctx, vm, arc); } ctx.restore(); } }); var valueOrDefault$1 = helpers$1.valueOrDefault; var defaultColor = core_defaults.global.defaultColor; core_defaults._set('global', { elements: { line: { tension: 0.4, backgroundColor: defaultColor, borderWidth: 3, borderColor: defaultColor, borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', capBezierPoints: true, fill: true, // do we fill in the area between the line and its base axis } } }); var element_line = core_element.extend({ _type: 'line', draw: function() { var me = this; var vm = me._view; var ctx = me._chart.ctx; var spanGaps = vm.spanGaps; var points = me._children.slice(); // clone array var globalDefaults = core_defaults.global; var globalOptionLineElements = globalDefaults.elements.line; var lastDrawnIndex = -1; var closePath = me._loop; var index, previous, currentVM; if (!points.length) { return; } if (me._loop) { for (index = 0; index < points.length; ++index) { previous = helpers$1.previousItem(points, index); // If the line has an open path, shift the point array if (!points[index]._view.skip && previous._view.skip) { points = points.slice(index).concat(points.slice(0, index)); closePath = spanGaps; break; } } // If the line has a close path, add the first point again if (closePath) { points.push(points[0]); } } ctx.save(); // Stroke Line Options ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle; // IE 9 and 10 do not support line dash if (ctx.setLineDash) { ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash); } ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset); ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle; ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth); ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor; // Stroke Line ctx.beginPath(); // First point moves to it's starting position no matter what currentVM = points[0]._view; if (!currentVM.skip) { ctx.moveTo(currentVM.x, currentVM.y); lastDrawnIndex = 0; } for (index = 1; index < points.length; ++index) { currentVM = points[index]._view; previous = lastDrawnIndex === -1 ? helpers$1.previousItem(points, index) : points[lastDrawnIndex]; if (!currentVM.skip) { if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) { // There was a gap and this is the first point after the gap ctx.moveTo(currentVM.x, currentVM.y); } else { // Line to next point helpers$1.canvas.lineTo(ctx, previous._view, currentVM); } lastDrawnIndex = index; } } if (closePath) { ctx.closePath(); } ctx.stroke(); ctx.restore(); } }); var valueOrDefault$2 = helpers$1.valueOrDefault; var defaultColor$1 = core_defaults.global.defaultColor; core_defaults._set('global', { elements: { point: { radius: 3, pointStyle: 'circle', backgroundColor: defaultColor$1, borderColor: defaultColor$1, borderWidth: 1, // Hover hitRadius: 1, hoverRadius: 4, hoverBorderWidth: 1 } } }); function xRange(mouseX) { var vm = this._view; return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false; } function yRange(mouseY) { var vm = this._view; return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false; } var element_point = core_element.extend({ _type: 'point', inRange: function(mouseX, mouseY) { var vm = this._view; return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false; }, inLabelRange: xRange, inXRange: xRange, inYRange: yRange, getCenterPoint: function() { var vm = this._view; return { x: vm.x, y: vm.y }; }, getArea: function() { return Math.PI * Math.pow(this._view.radius, 2); }, tooltipPosition: function() { var vm = this._view; return { x: vm.x, y: vm.y, padding: vm.radius + vm.borderWidth }; }, draw: function(chartArea) { var vm = this._view; var ctx = this._chart.ctx; var pointStyle = vm.pointStyle; var rotation = vm.rotation; var radius = vm.radius; var x = vm.x; var y = vm.y; var globalDefaults = core_defaults.global; var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow if (vm.skip) { return; } // Clipping for Points. if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) { ctx.strokeStyle = vm.borderColor || defaultColor; ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth); ctx.fillStyle = vm.backgroundColor || defaultColor; helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation); } } }); var defaultColor$2 = core_defaults.global.defaultColor; core_defaults._set('global', { elements: { rectangle: { backgroundColor: defaultColor$2, borderColor: defaultColor$2, borderSkipped: 'bottom', borderWidth: 0 } } }); function isVertical(vm) { return vm && vm.width !== undefined; } /** * Helper function to get the bounds of the bar regardless of the orientation * @param bar {Chart.Element.Rectangle} the bar * @return {Bounds} bounds of the bar * @private */ function getBarBounds(vm) { var x1, x2, y1, y2, half; if (isVertical(vm)) { half = vm.width / 2; x1 = vm.x - half; x2 = vm.x + half; y1 = Math.min(vm.y, vm.base); y2 = Math.max(vm.y, vm.base); } else { half = vm.height / 2; x1 = Math.min(vm.x, vm.base); x2 = Math.max(vm.x, vm.base); y1 = vm.y - half; y2 = vm.y + half; } return { left: x1, top: y1, right: x2, bottom: y2 }; } function swap(orig, v1, v2) { return orig === v1 ? v2 : orig === v2 ? v1 : orig; } function parseBorderSkipped(vm) { var edge = vm.borderSkipped; var res = {}; if (!edge) { return res; } if (vm.horizontal) { if (vm.base > vm.x) { edge = swap(edge, 'left', 'right'); } } else if (vm.base < vm.y) { edge = swap(edge, 'bottom', 'top'); } res[edge] = true; return res; } function parseBorderWidth(vm, maxW, maxH) { var value = vm.borderWidth; var skip = parseBorderSkipped(vm); var t, r, b, l; if (helpers$1.isObject(value)) { t = +value.top || 0; r = +value.right || 0; b = +value.bottom || 0; l = +value.left || 0; } else { t = r = b = l = +value || 0; } return { t: skip.top || (t < 0) ? 0 : t > maxH ? maxH : t, r: skip.right || (r < 0) ? 0 : r > maxW ? maxW : r, b: skip.bottom || (b < 0) ? 0 : b > maxH ? maxH : b, l: skip.left || (l < 0) ? 0 : l > maxW ? maxW : l }; } function boundingRects(vm) { var bounds = getBarBounds(vm); var width = bounds.right - bounds.left; var height = bounds.bottom - bounds.top; var border = parseBorderWidth(vm, width / 2, height / 2); return { outer: { x: bounds.left, y: bounds.top, w: width, h: height }, inner: { x: bounds.left + border.l, y: bounds.top + border.t, w: width - border.l - border.r, h: height - border.t - border.b } }; } function inRange(vm, x, y) { var skipX = x === null; var skipY = y === null; var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm); return bounds && (skipX || x >= bounds.left && x <= bounds.right) && (skipY || y >= bounds.top && y <= bounds.bottom); } var element_rectangle = core_element.extend({ _type: 'rectangle', draw: function() { var ctx = this._chart.ctx; var vm = this._view; var rects = boundingRects(vm); var outer = rects.outer; var inner = rects.inner; ctx.fillStyle = vm.backgroundColor; ctx.fillRect(outer.x, outer.y, outer.w, outer.h); if (outer.w === inner.w && outer.h === inner.h) { return; } ctx.save(); ctx.beginPath(); ctx.rect(outer.x, outer.y, outer.w, outer.h); ctx.clip(); ctx.fillStyle = vm.borderColor; ctx.rect(inner.x, inner.y, inner.w, inner.h); ctx.fill('evenodd'); ctx.restore(); }, height: function() { var vm = this._view; return vm.base - vm.y; }, inRange: function(mouseX, mouseY) { return inRange(this._view, mouseX, mouseY); }, inLabelRange: function(mouseX, mouseY) { var vm = this._view; return isVertical(vm) ? inRange(vm, mouseX, null) : inRange(vm, null, mouseY); }, inXRange: function(mouseX) { return inRange(this._view, mouseX, null); }, inYRange: function(mouseY) { return inRange(this._view, null, mouseY); }, getCenterPoint: function() { var vm = this._view; var x, y; if (isVertical(vm)) { x = vm.x; y = (vm.y + vm.base) / 2; } else { x = (vm.x + vm.base) / 2; y = vm.y; } return {x: x, y: y}; }, getArea: function() { var vm = this._view; return isVertical(vm) ? vm.width * Math.abs(vm.y - vm.base) : vm.height * Math.abs(vm.x - vm.base); }, tooltipPosition: function() { var vm = this._view; return { x: vm.x, y: vm.y }; } }); var elements = {}; var Arc = element_arc; var Line = element_line; var Point = element_point; var Rectangle = element_rectangle; elements.Arc = Arc; elements.Line = Line; elements.Point = Point; elements.Rectangle = Rectangle; var deprecated = helpers$1._deprecated; var valueOrDefault$3 = helpers$1.valueOrDefault; core_defaults._set('bar', { hover: { mode: 'label' }, scales: { xAxes: [{ type: 'category', offset: true, gridLines: { offsetGridLines: true } }], yAxes: [{ type: 'linear' }] } }); core_defaults._set('global', { datasets: { bar: { categoryPercentage: 0.8, barPercentage: 0.9 } } }); /** * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap. * @private */ function computeMinSampleSize(scale, pixels) { var min = scale._length; var prev, curr, i, ilen; for (i = 1, ilen = pixels.length; i < ilen; ++i) { min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1])); } for (i = 0, ilen = scale.getTicks().length; i < ilen; ++i) { curr = scale.getPixelForTick(i); min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min; prev = curr; } return min; } /** * Computes an "ideal" categories based on the absolute bar thickness or, if undefined or null, * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This * mode currently always generates bars equally sized (until we introduce scriptable options?). * @private */ function computeFitCategoryTraits(index, ruler, options) { var thickness = options.barThickness; var count = ruler.stackCount; var curr = ruler.pixels[index]; var min = helpers$1.isNullOrUndef(thickness) ? computeMinSampleSize(ruler.scale, ruler.pixels) : -1; var size, ratio; if (helpers$1.isNullOrUndef(thickness)) { size = min * options.categoryPercentage; ratio = options.barPercentage; } else { // When bar thickness is enforced, categories and bar percentages are ignored. // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%') // and deprecate barPercentage since this value is ignored when thickness is absolute. size = thickness * count; ratio = 1; } return { chunk: size / count, ratio: ratio, start: curr - (size / 2) }; } /** * Computes an "optimal" categories that globally arranges bars side by side (no gap when * percentage options are 1), based on the previous and following categories. This mode * generates bars with different widths when data are not evenly spaced. * @private */ function computeFlexCategoryTraits(index, ruler, options) { var pixels = ruler.pixels; var curr = pixels[index]; var prev = index > 0 ? pixels[index - 1] : null; var next = index < pixels.length - 1 ? pixels[index + 1] : null; var percent = options.categoryPercentage; var start, size; if (prev === null) { // first data: its size is double based on the next point or, // if it's also the last data, we use the scale size. prev = curr - (next === null ? ruler.end - ruler.start : next - curr); } if (next === null) { // last data: its size is also double based on the previous point. next = curr + curr - prev; } start = curr - (curr - Math.min(prev, next)) / 2 * percent; size = Math.abs(next - prev) / 2 * percent; return { chunk: size / ruler.stackCount, ratio: options.barPercentage, start: start }; } var controller_bar = core_datasetController.extend({ dataElementType: elements.Rectangle, /** * @private */ _dataElementOptions: [ 'backgroundColor', 'borderColor', 'borderSkipped', 'borderWidth', 'barPercentage', 'barThickness', 'categoryPercentage', 'maxBarThickness', 'minBarLength' ], initialize: function() { var me = this; var meta, scaleOpts; core_datasetController.prototype.initialize.apply(me, arguments); meta = me.getMeta(); meta.stack = me.getDataset().stack; meta.bar = true; scaleOpts = me._getIndexScale().options; deprecated('bar chart', scaleOpts.barPercentage, 'scales.[x/y]Axes.barPercentage', 'dataset.barPercentage'); deprecated('bar chart', scaleOpts.barThickness, 'scales.[x/y]Axes.barThickness', 'dataset.barThickness'); deprecated('bar chart', scaleOpts.categoryPercentage, 'scales.[x/y]Axes.categoryPercentage', 'dataset.categoryPercentage'); deprecated('bar chart', me._getValueScale().options.minBarLength, 'scales.[x/y]Axes.minBarLength', 'dataset.minBarLength'); deprecated('bar chart', scaleOpts.maxBarThickness, 'scales.[x/y]Axes.maxBarThickness', 'dataset.maxBarThickness'); }, update: function(reset) { var me = this; var rects = me.getMeta().data; var i, ilen; me._ruler = me.getRuler(); for (i = 0, ilen = rects.length; i < ilen; ++i) { me.updateElement(rects[i], i, reset); } }, updateElement: function(rectangle, index, reset) { var me = this; var meta = me.getMeta(); var dataset = me.getDataset(); var options = me._resolveDataElementOptions(rectangle, index); rectangle._xScale = me.getScaleForId(meta.xAxisID); rectangle._yScale = me.getScaleForId(meta.yAxisID); rectangle._datasetIndex = me.index; rectangle._index = index; rectangle._model = { backgroundColor: options.backgroundColor, borderColor: options.borderColor, borderSkipped: options.borderSkipped, borderWidth: options.borderWidth, datasetLabel: dataset.label, label: me.chart.data.labels[index] }; if (helpers$1.isArray(dataset.data[index])) { rectangle._model.borderSkipped = null; } me._updateElementGeometry(rectangle, index, reset, options); rectangle.pivot(); }, /** * @private */ _updateElementGeometry: function(rectangle, index, reset, options) { var me = this; var model = rectangle._model; var vscale = me._getValueScale(); var base = vscale.getBasePixel(); var horizontal = vscale.isHorizontal(); var ruler = me._ruler || me.getRuler(); var vpixels = me.calculateBarValuePixels(me.index, index, options); var ipixels = me.calculateBarIndexPixels(me.index, index, ruler, options); model.horizontal = horizontal; model.base = reset ? base : vpixels.base; model.x = horizontal ? reset ? base : vpixels.head : ipixels.center; model.y = horizontal ? ipixels.center : reset ? base : vpixels.head; model.height = horizontal ? ipixels.size : undefined; model.width = horizontal ? undefined : ipixels.size; }, /** * Returns the stacks based on groups and bar visibility. * @param {number} [last] - The dataset index * @returns {string[]} The list of stack IDs * @private */ _getStacks: function(last) { var me = this; var scale = me._getIndexScale(); var metasets = scale._getMatchingVisibleMetas(me._type); var stacked = scale.options.stacked; var ilen = metasets.length; var stacks = []; var i, meta; for (i = 0; i < ilen; ++i) { meta = metasets[i]; // stacked | meta.stack // | found | not found | undefined // false | x | x | x // true | | x | // undefined | | x | x if (stacked === false || stacks.indexOf(meta.stack) === -1 || (stacked === undefined && meta.stack === undefined)) { stacks.push(meta.stack); } if (meta.index === last) { break; } } return stacks; }, /** * Returns the effective number of stacks based on groups and bar visibility. * @private */ getStackCount: function() { return this._getStacks().length; }, /** * Returns the stack index for the given dataset based on groups and bar visibility. * @param {number} [datasetIndex] - The dataset index * @param {string} [name] - The stack name to find * @returns {number} The stack index * @private */ getStackIndex: function(datasetIndex, name) { var stacks = this._getStacks(datasetIndex); var index = (name !== undefined) ? stacks.indexOf(name) : -1; // indexOf returns -1 if element is not present return (index === -1) ? stacks.length - 1 : index; }, /** * @private */ getRuler: function() { var me = this; var scale = me._getIndexScale(); var pixels = []; var i, ilen; for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) { pixels.push(scale.getPixelForValue(null, i, me.index)); } return { pixels: pixels, start: scale._startPixel, end: scale._endPixel, stackCount: me.getStackCount(), scale: scale }; }, /** * Note: pixel values are not clamped to the scale area. * @private */ calculateBarValuePixels: function(datasetIndex, index, options) { var me = this; var chart = me.chart; var scale = me._getValueScale(); var isHorizontal = scale.isHorizontal(); var datasets = chart.data.datasets; var metasets = scale._getMatchingVisibleMetas(me._type); var value = scale._parseValue(datasets[datasetIndex].data[index]); var minBarLength = options.minBarLength; var stacked = scale.options.stacked; var stack = me.getMeta().stack; var start = value.start === undefined ? 0 : value.max >= 0 && value.min >= 0 ? value.min : value.max; var length = value.start === undefined ? value.end : value.max >= 0 && value.min >= 0 ? value.max - value.min : value.min - value.max; var ilen = metasets.length; var i, imeta, ivalue, base, head, size, stackLength; if (stacked || (stacked === undefined && stack !== undefined)) { for (i = 0; i < ilen; ++i) { imeta = metasets[i]; if (imeta.index === datasetIndex) { break; } if (imeta.stack === stack) { stackLength = scale._parseValue(datasets[imeta.index].data[index]); ivalue = stackLength.start === undefined ? stackLength.end : stackLength.min >= 0 && stackLength.max >= 0 ? stackLength.max : stackLength.min; if ((value.min < 0 && ivalue < 0) || (value.max >= 0 && ivalue > 0)) { start += ivalue; } } } } base = scale.getPixelForValue(start); head = scale.getPixelForValue(start + length); size = head - base; if (minBarLength !== undefined && Math.abs(size) < minBarLength) { size = minBarLength; if (length >= 0 && !isHorizontal || length < 0 && isHorizontal) { head = base - minBarLength; } else { head = base + minBarLength; } } return { size: size, base: base, head: head, center: head + size / 2 }; }, /** * @private */ calculateBarIndexPixels: function(datasetIndex, index, ruler, options) { var me = this; var range = options.barThickness === 'flex' ? computeFlexCategoryTraits(index, ruler, options) : computeFitCategoryTraits(index, ruler, options); var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack); var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2); var size = Math.min( valueOrDefault$3(options.maxBarThickness, Infinity), range.chunk * range.ratio); return { base: center - size / 2, head: center + size / 2, center: center, size: size }; }, draw: function() { var me = this; var chart = me.chart; var scale = me._getValueScale(); var rects = me.getMeta().data; var dataset = me.getDataset(); var ilen = rects.length; var i = 0; helpers$1.canvas.clipArea(chart.ctx, chart.chartArea); for (; i < ilen; ++i) { var val = scale._parseValue(dataset.data[i]); if (!isNaN(val.min) && !isNaN(val.max)) { rects[i].draw(); } } helpers$1.canvas.unclipArea(chart.ctx); }, /** * @private */ _resolveDataElementOptions: function() { var me = this; var values = helpers$1.extend({}, core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments)); var indexOpts = me._getIndexScale().options; var valueOpts = me._getValueScale().options; values.barPercentage = valueOrDefault$3(indexOpts.barPercentage, values.barPercentage); values.barThickness = valueOrDefault$3(indexOpts.barThickness, values.barThickness); values.categoryPercentage = valueOrDefault$3(indexOpts.categoryPercentage, values.categoryPercentage); values.maxBarThickness = valueOrDefault$3(indexOpts.maxBarThickness, values.maxBarThickness); values.minBarLength = valueOrDefault$3(valueOpts.minBarLength, values.minBarLength); return values; } }); var valueOrDefault$4 = helpers$1.valueOrDefault; var resolve$1 = helpers$1.options.resolve; core_defaults._set('bubble', { hover: { mode: 'single' }, scales: { xAxes: [{ type: 'linear', // bubble should probably use a linear scale by default position: 'bottom', id: 'x-axis-0' // need an ID so datasets can reference the scale }], yAxes: [{ type: 'linear', position: 'left', id: 'y-axis-0' }] }, tooltips: { callbacks: { title: function() { // Title doesn't make sense for scatter since we format the data as a point return ''; }, label: function(item, data) { var datasetLabel = data.datasets[item.datasetIndex].label || ''; var dataPoint = data.datasets[item.datasetIndex].data[item.index]; return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')'; } } } }); var controller_bubble = core_datasetController.extend({ /** * @protected */ dataElementType: elements.Point, /** * @private */ _dataElementOptions: [ 'backgroundColor', 'borderColor', 'borderWidth', 'hoverBackgroundColor', 'hoverBorderColor', 'hoverBorderWidth', 'hoverRadius', 'hitRadius', 'pointStyle', 'rotation' ], /** * @protected */ update: function(reset) { var me = this; var meta = me.getMeta(); var points = meta.data; // Update Points helpers$1.each(points, function(point, index) { me.updateElement(point, index, reset); }); }, /** * @protected */ updateElement: function(point, index, reset) { var me = this; var meta = me.getMeta(); var custom = point.custom || {}; var xScale = me.getScaleForId(meta.xAxisID); var yScale = me.getScaleForId(meta.yAxisID); var options = me._resolveDataElementOptions(point, index); var data = me.getDataset().data[index]; var dsIndex = me.index; var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex); var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex); point._xScale = xScale; point._yScale = yScale; point._options = options; point._datasetIndex = dsIndex; point._index = index; point._model = { backgroundColor: options.backgroundColor, borderColor: options.borderColor, borderWidth: options.borderWidth, hitRadius: options.hitRadius, pointStyle: options.pointStyle, rotation: options.rotation, radius: reset ? 0 : options.radius, skip: custom.skip || isNaN(x) || isNaN(y), x: x, y: y, }; point.pivot(); }, /** * @protected */ setHoverStyle: function(point) { var model = point._model; var options = point._options; var getHoverColor = helpers$1.getHoverColor; point.$previousStyle = { backgroundColor: model.backgroundColor, borderColor: model.borderColor, borderWidth: model.borderWidth, radius: model.radius }; model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor)); model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor)); model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth); model.radius = options.radius + options.hoverRadius; }, /** * @private */ _resolveDataElementOptions: function(point, index) { var me = this; var chart = me.chart; var dataset = me.getDataset(); var custom = point.custom || {}; var data = dataset.data[index] || {}; var values = core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments); // Scriptable options var context = { chart: chart, dataIndex: index, dataset: dataset, datasetIndex: me.index }; // In case values were cached (and thus frozen), we need to clone the values if (me._cachedDataOpts === values) { values = helpers$1.extend({}, values); } // Custom radius resolution values.radius = resolve$1([ custom.radius, data.r, me._config.radius, chart.options.elements.point.radius ], context, index); return values; } }); var valueOrDefault$5 = helpers$1.valueOrDefault; var PI$1 = Math.PI; var DOUBLE_PI$1 = PI$1 * 2; var HALF_PI$1 = PI$1 / 2; core_defaults._set('doughnut', { animation: { // Boolean - Whether we animate the rotation of the Doughnut animateRotate: true, // Boolean - Whether we animate scaling the Doughnut from the centre animateScale: false }, hover: { mode: 'single' }, legendCallback: function(chart) { var list = document.createElement('ul'); var data = chart.data; var datasets = data.datasets; var labels = data.labels; var i, ilen, listItem, listItemSpan; list.setAttribute('class', chart.id + '-legend'); if (datasets.length) { for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) { listItem = list.appendChild(document.createElement('li')); listItemSpan = listItem.appendChild(document.createElement('span')); listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i]; if (labels[i]) { listItem.appendChild(document.createTextNode(labels[i])); } } } return list.outerHTML; }, legend: { labels: { generateLabels: function(chart) { var data = chart.data; if (data.labels.length && data.datasets.length) { return data.labels.map(function(label, i) { var meta = chart.getDatasetMeta(0); var style = meta.controller.getStyle(i); return { text: label, fillStyle: style.backgroundColor, strokeStyle: style.borderColor, lineWidth: style.borderWidth, hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden, // Extra data used for toggling the correct item index: i }; }); } return []; } }, onClick: function(e, legendItem) { var index = legendItem.index; var chart = this.chart; var i, ilen, meta; for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) { meta = chart.getDatasetMeta(i); // toggle visibility of index if exists if (meta.data[index]) { meta.data[index].hidden = !meta.data[index].hidden; } } chart.update(); } }, // The percentage of the chart that we cut out of the middle. cutoutPercentage: 50, // The rotation of the chart, where the first data arc begins. rotation: -HALF_PI$1, // The total circumference of the chart. circumference: DOUBLE_PI$1, // Need to override these to give a nice default tooltips: { callbacks: { title: function() { return ''; }, label: function(tooltipItem, data) { var dataLabel = data.labels[tooltipItem.index]; var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]; if (helpers$1.isArray(dataLabel)) { // show value on first line of multiline label // need to clone because we are changing the value dataLabel = dataLabel.slice(); dataLabel[0] += value; } else { dataLabel += value; } return dataLabel; } } } }); var controller_doughnut = core_datasetController.extend({ dataElementType: elements.Arc, linkScales: helpers$1.noop, /** * @private */ _dataElementOptions: [ 'backgroundColor', 'borderColor', 'borderWidth', 'borderAlign', 'hoverBackgroundColor', 'hoverBorderColor', 'hoverBorderWidth', ], // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly getRingIndex: function(datasetIndex) { var ringIndex = 0; for (var j = 0; j < datasetIndex; ++j) { if (this.chart.isDatasetVisible(j)) { ++ringIndex; } } return ringIndex; }, update: function(reset) { var me = this; var chart = me.chart; var chartArea = chart.chartArea; var opts = chart.options; var ratioX = 1; var ratioY = 1; var offsetX = 0; var offsetY = 0; var meta = me.getMeta(); var arcs = meta.data; var cutout = opts.cutoutPercentage / 100 || 0; var circumference = opts.circumference; var chartWeight = me._getRingWeight(me.index); var maxWidth, maxHeight, i, ilen; // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc if (circumference < DOUBLE_PI$1) { var startAngle = opts.rotation % DOUBLE_PI$1; startAngle += startAngle >= PI$1 ? -DOUBLE_PI$1 : startAngle < -PI$1 ? DOUBLE_PI$1 : 0; var endAngle = startAngle + circumference; var startX = Math.cos(startAngle); var startY = Math.sin(startAngle); var endX = Math.cos(endAngle); var endY = Math.sin(endAngle); var contains0 = (startAngle <= 0 && endAngle >= 0) || endAngle >= DOUBLE_PI$1; var contains90 = (startAngle <= HALF_PI$1 && endAngle >= HALF_PI$1) || endAngle >= DOUBLE_PI$1 + HALF_PI$1; var contains180 = startAngle === -PI$1 || endAngle >= PI$1; var contains270 = (startAngle <= -HALF_PI$1 && endAngle >= -HALF_PI$1) || endAngle >= PI$1 + HALF_PI$1; var minX = contains180 ? -1 : Math.min(startX, startX * cutout, endX, endX * cutout); var minY = contains270 ? -1 : Math.min(startY, startY * cutout, endY, endY * cutout); var maxX = contains0 ? 1 : Math.max(startX, startX * cutout, endX, endX * cutout); var maxY = contains90 ? 1 : Math.max(startY, startY * cutout, endY, endY * cutout); ratioX = (maxX - minX) / 2; ratioY = (maxY - minY) / 2; offsetX = -(maxX + minX) / 2; offsetY = -(maxY + minY) / 2; } for (i = 0, ilen = arcs.length; i < ilen; ++i) { arcs[i]._options = me._resolveDataElementOptions(arcs[i], i); } chart.borderWidth = me.getMaxBorderWidth(); maxWidth = (chartArea.right - chartArea.left - chart.borderWidth) / ratioX; maxHeight = (chartArea.bottom - chartArea.top - chart.borderWidth) / ratioY; chart.outerRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0); chart.innerRadius = Math.max(chart.outerRadius * cutout, 0); chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1); chart.offsetX = offsetX * chart.outerRadius; chart.offsetY = offsetY * chart.outerRadius; meta.total = me.calculateTotal(); me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index); me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0); for (i = 0, ilen = arcs.length; i < ilen; ++i) { me.updateElement(arcs[i], i, reset); } }, updateElement: function(arc, index, reset) { var me = this; var chart = me.chart; var chartArea = chart.chartArea; var opts = chart.options; var animationOpts = opts.animation; var centerX = (chartArea.left + chartArea.right) / 2; var centerY = (chartArea.top + chartArea.bottom) / 2; var startAngle = opts.rotation; // non reset case handled later var endAngle = opts.rotation; // non reset case handled later var dataset = me.getDataset(); var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / DOUBLE_PI$1); var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius; var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius; var options = arc._options || {}; helpers$1.extend(arc, { // Utility _datasetIndex: me.index, _index: index, // Desired view properties _model: { backgroundColor: options.backgroundColor, borderColor: options.borderColor, borderWidth: options.borderWidth, borderAlign: options.borderAlign, x: centerX + chart.offsetX, y: centerY + chart.offsetY, startAngle: startAngle, endAngle: endAngle, circumference: circumference, outerRadius: outerRadius, innerRadius: innerRadius, label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index]) } }); var model = arc._model; // Set correct angles if not resetting if (!reset || !animationOpts.animateRotate) { if (index === 0) { model.startAngle = opts.rotation; } else { model.startAngle = me.getMeta().data[index - 1]._model.endAngle; } model.endAngle = model.startAngle + model.circumference; } arc.pivot(); }, calculateTotal: function() { var dataset = this.getDataset(); var meta = this.getMeta(); var total = 0; var value; helpers$1.each(meta.data, function(element, index) { value = dataset.data[index]; if (!isNaN(value) && !element.hidden) { total += Math.abs(value); } }); /* if (total === 0) { total = NaN; }*/ return total; }, calculateCircumference: function(value) { var total = this.getMeta().total; if (total > 0 && !isNaN(value)) { return DOUBLE_PI$1 * (Math.abs(value) / total); } return 0; }, // gets the max border or hover width to properly scale pie charts getMaxBorderWidth: function(arcs) { var me = this; var max = 0; var chart = me.chart; var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth; if (!arcs) { // Find the outmost visible dataset for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) { if (chart.isDatasetVisible(i)) { meta = chart.getDatasetMeta(i); arcs = meta.data; if (i !== me.index) { controller = meta.controller; } break; } } } if (!arcs) { return 0; } for (i = 0, ilen = arcs.length; i < ilen; ++i) { arc = arcs[i]; if (controller) { controller._configure(); options = controller._resolveDataElementOptions(arc, i); } else { options = arc._options; } if (options.borderAlign !== 'inner') { borderWidth = options.borderWidth; hoverWidth = options.hoverBorderWidth; max = borderWidth > max ? borderWidth : max; max = hoverWidth > max ? hoverWidth : max; } } return max; }, /** * @protected */ setHoverStyle: function(arc) { var model = arc._model; var options = arc._options; var getHoverColor = helpers$1.getHoverColor; arc.$previousStyle = { backgroundColor: model.backgroundColor, borderColor: model.borderColor, borderWidth: model.borderWidth, }; model.backgroundColor = valueOrDefault$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor)); model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor)); model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth); }, /** * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly * @private */ _getRingWeightOffset: function(datasetIndex) { var ringWeightOffset = 0; for (var i = 0; i < datasetIndex; ++i) { if (this.chart.isDatasetVisible(i)) { ringWeightOffset += this._getRingWeight(i); } } return ringWeightOffset; }, /** * @private */ _getRingWeight: function(dataSetIndex) { return Math.max(valueOrDefault$5(this.chart.data.datasets[dataSetIndex].weight, 1), 0); }, /** * Returns the sum of all visibile data set weights. This value can be 0. * @private */ _getVisibleDatasetWeightTotal: function() { return this._getRingWeightOffset(this.chart.data.datasets.length); } }); core_defaults._set('horizontalBar', { hover: { mode: 'index', axis: 'y' }, scales: { xAxes: [{ type: 'linear', position: 'bottom' }], yAxes: [{ type: 'category', position: 'left', offset: true, gridLines: { offsetGridLines: true } }] }, elements: { rectangle: { borderSkipped: 'left' } }, tooltips: { mode: 'index', axis: 'y' } }); core_defaults._set('global', { datasets: { horizontalBar: { categoryPercentage: 0.8, barPercentage: 0.9 } } }); var controller_horizontalBar = controller_bar.extend({ /** * @private */ _getValueScaleId: function() { return this.getMeta().xAxisID; }, /** * @private */ _getIndexScaleId: function() { return this.getMeta().yAxisID; } }); var valueOrDefault$6 = helpers$1.valueOrDefault; var resolve$2 = helpers$1.options.resolve; var isPointInArea = helpers$1.canvas._isPointInArea; core_defaults._set('line', { showLines: true, spanGaps: false, hover: { mode: 'label' }, scales: { xAxes: [{ type: 'category', id: 'x-axis-0' }], yAxes: [{ type: 'linear', id: 'y-axis-0' }] } }); function scaleClip(scale, halfBorderWidth) { var tickOpts = scale && scale.options.ticks || {}; var reverse = tickOpts.reverse; var min = tickOpts.min === undefined ? halfBorderWidth : 0; var max = tickOpts.max === undefined ? halfBorderWidth : 0; return { start: reverse ? max : min, end: reverse ? min : max }; } function defaultClip(xScale, yScale, borderWidth) { var halfBorderWidth = borderWidth / 2; var x = scaleClip(xScale, halfBorderWidth); var y = scaleClip(yScale, halfBorderWidth); return { top: y.end, right: x.end, bottom: y.start, left: x.start }; } function toClip(value) { var t, r, b, l; if (helpers$1.isObject(value)) { t = value.top; r = value.right; b = value.bottom; l = value.left; } else { t = r = b = l = value; } return { top: t, right: r, bottom: b, left: l }; } var controller_line = core_datasetController.extend({ datasetElementType: elements.Line, dataElementType: elements.Point, /** * @private */ _datasetElementOptions: [ 'backgroundColor', 'borderCapStyle', 'borderColor', 'borderDash', 'borderDashOffset', 'borderJoinStyle', 'borderWidth', 'cubicInterpolationMode', 'fill' ], /** * @private */ _dataElementOptions: { backgroundColor: 'pointBackgroundColor', borderColor: 'pointBorderColor', borderWidth: 'pointBorderWidth', hitRadius: 'pointHitRadius', hoverBackgroundColor: 'pointHoverBackgroundColor', hoverBorderColor: 'pointHoverBorderColor', hoverBorderWidth: 'pointHoverBorderWidth', hoverRadius: 'pointHoverRadius', pointStyle: 'pointStyle', radius: 'pointRadius', rotation: 'pointRotation' }, update: function(reset) { var me = this; var meta = me.getMeta(); var line = meta.dataset; var points = meta.data || []; var options = me.chart.options; var config = me._config; var showLine = me._showLine = valueOrDefault$6(config.showLine, options.showLines); var i, ilen; me._xScale = me.getScaleForId(meta.xAxisID); me._yScale = me.getScaleForId(meta.yAxisID); // Update Line if (showLine) { // Compatibility: If the properties are defined with only the old name, use those values if (config.tension !== undefined && config.lineTension === undefined) { config.lineTension = config.tension; } // Utility line._scale = me._yScale; line._datasetIndex = me.index; // Data line._children = points; // Model line._model = me._resolveDatasetElementOptions(line); line.pivot(); } // Update Points for (i = 0, ilen = points.length; i < ilen; ++i) { me.updateElement(points[i], i, reset); } if (showLine && line._model.tension !== 0) { me.updateBezierControlPoints(); } // Now pivot the point for animation for (i = 0, ilen = points.length; i < ilen; ++i) { points[i].pivot(); } }, updateElement: function(point, index, reset) { var me = this; var meta = me.getMeta(); var custom = point.custom || {}; var dataset = me.getDataset(); var datasetIndex = me.index; var value = dataset.data[index]; var xScale = me._xScale; var yScale = me._yScale; var lineModel = meta.dataset._model; var x, y; var options = me._resolveDataElementOptions(point, index); x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex); y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex); // Utility point._xScale = xScale; point._yScale = yScale; point._options = options; point._datasetIndex = datasetIndex; point._index = index; // Desired view properties point._model = { x: x, y: y, skip: custom.skip || isNaN(x) || isNaN(y), // Appearance radius: options.radius, pointStyle: options.pointStyle, rotation: options.rotation, backgroundColor: options.backgroundColor, borderColor: options.borderColor, borderWidth: options.borderWidth, tension: valueOrDefault$6(custom.tension, lineModel ? lineModel.tension : 0), steppedLine: lineModel ? lineModel.steppedLine : false, // Tooltip hitRadius: options.hitRadius }; }, /** * @private */ _resolveDatasetElementOptions: function(element) { var me = this; var config = me._config; var custom = element.custom || {}; var options = me.chart.options; var lineOptions = options.elements.line; var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments); // The default behavior of lines is to break at null values, according // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158 // This option gives lines the ability to span gaps values.spanGaps = valueOrDefault$6(config.spanGaps, options.spanGaps); values.tension = valueOrDefault$6(config.lineTension, lineOptions.tension); values.steppedLine = resolve$2([custom.steppedLine, config.steppedLine, lineOptions.stepped]); values.clip = toClip(valueOrDefault$6(config.clip, defaultClip(me._xScale, me._yScale, values.borderWidth))); return values; }, calculatePointY: function(value, index, datasetIndex) { var me = this; var chart = me.chart; var yScale = me._yScale; var sumPos = 0; var sumNeg = 0; var i, ds, dsMeta, stackedRightValue, rightValue, metasets, ilen; if (yScale.options.stacked) { rightValue = +yScale.getRightValue(value); metasets = chart._getSortedVisibleDatasetMetas(); ilen = metasets.length; for (i = 0; i < ilen; ++i) { dsMeta = metasets[i]; if (dsMeta.index === datasetIndex) { break; } ds = chart.data.datasets[dsMeta.index]; if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id) { stackedRightValue = +yScale.getRightValue(ds.data[index]); if (stackedRightValue < 0) { sumNeg += stackedRightValue || 0; } else { sumPos += stackedRightValue || 0; } } } if (rightValue < 0) { return yScale.getPixelForValue(sumNeg + rightValue); } return yScale.getPixelForValue(sumPos + rightValue); } return yScale.getPixelForValue(value); }, updateBezierControlPoints: function() { var me = this; var chart = me.chart; var meta = me.getMeta(); var lineModel = meta.dataset._model; var area = chart.chartArea; var points = meta.data || []; var i, ilen, model, controlPoints; // Only consider points that are drawn in case the spanGaps option is used if (lineModel.spanGaps) { points = points.filter(function(pt) { return !pt._model.skip; }); } function capControlPoint(pt, min, max) { return Math.max(Math.min(pt, max), min); } if (lineModel.cubicInterpolationMode === 'monotone') { helpers$1.splineCurveMonotone(points); } else { for (i = 0, ilen = points.length; i < ilen; ++i) { model = points[i]._model; controlPoints = helpers$1.splineCurve( helpers$1.previousItem(points, i)._model, model, helpers$1.nextItem(points, i)._model, lineModel.tension ); model.controlPointPreviousX = controlPoints.previous.x; model.controlPointPreviousY = controlPoints.previous.y; model.controlPointNextX = controlPoints.next.x; model.controlPointNextY = controlPoints.next.y; } } if (chart.options.elements.line.capBezierPoints) { for (i = 0, ilen = points.length; i < ilen; ++i) { model = points[i]._model; if (isPointInArea(model, area)) { if (i > 0 && isPointInArea(points[i - 1]._model, area)) { model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right); model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom); } if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) { model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right); model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom); } } } } }, draw: function() { var me = this; var chart = me.chart; var meta = me.getMeta(); var points = meta.data || []; var area = chart.chartArea; var canvas = chart.canvas; var i = 0; var ilen = points.length; var clip; if (me._showLine) { clip = meta.dataset._model.clip; helpers$1.canvas.clipArea(chart.ctx, { left: clip.left === false ? 0 : area.left - clip.left, right: clip.right === false ? canvas.width : area.right + clip.right, top: clip.top === false ? 0 : area.top - clip.top, bottom: clip.bottom === false ? canvas.height : area.bottom + clip.bottom }); meta.dataset.draw(); helpers$1.canvas.unclipArea(chart.ctx); } // Draw the points for (; i < ilen; ++i) { points[i].draw(area); } }, /** * @protected */ setHoverStyle: function(point) { var model = point._model; var options = point._options; var getHoverColor = helpers$1.getHoverColor; point.$previousStyle = { backgroundColor: model.backgroundColor, borderColor: model.borderColor, borderWidth: model.borderWidth, radius: model.radius }; model.backgroundColor = valueOrDefault$6(options.hoverBackgroundColor, getHoverColor(options.backgroundColor)); model.borderColor = valueOrDefault$6(options.hoverBorderColor, getHoverColor(options.borderColor)); model.borderWidth = valueOrDefault$6(options.hoverBorderWidth, options.borderWidth); model.radius = valueOrDefault$6(options.hoverRadius, options.radius); }, }); var resolve$3 = helpers$1.options.resolve; core_defaults._set('polarArea', { scale: { type: 'radialLinear', angleLines: { display: false }, gridLines: { circular: true }, pointLabels: { display: false }, ticks: { beginAtZero: true } }, // Boolean - Whether to animate the rotation of the chart animation: { animateRotate: true, animateScale: true }, startAngle: -0.5 * Math.PI, legendCallback: function(chart) { var list = document.createElement('ul'); var data = chart.data; var datasets = data.datasets; var labels = data.labels; var i, ilen, listItem, listItemSpan; list.setAttribute('class', chart.id + '-legend'); if (datasets.length) { for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) { listItem = list.appendChild(document.createElement('li')); listItemSpan = listItem.appendChild(document.createElement('span')); listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i]; if (labels[i]) { listItem.appendChild(document.createTextNode(labels[i])); } } } return list.outerHTML; }, legend: { labels: { generateLabels: function(chart) { var data = chart.data; if (data.labels.length && data.datasets.length) { return data.labels.map(function(label, i) { var meta = chart.getDatasetMeta(0); var style = meta.controller.getStyle(i); return { text: label, fillStyle: style.backgroundColor, strokeStyle: style.borderColor, lineWidth: style.borderWidth, hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden, // Extra data used for toggling the correct item index: i }; }); } return []; } }, onClick: function(e, legendItem) { var index = legendItem.index; var chart = this.chart; var i, ilen, meta; for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) { meta = chart.getDatasetMeta(i); meta.data[index].hidden = !meta.data[index].hidden; } chart.update(); } }, // Need to override these to give a nice default tooltips: { callbacks: { title: function() { return ''; }, label: function(item, data) { return data.labels[item.index] + ': ' + item.yLabel; } } } }); var controller_polarArea = core_datasetController.extend({ dataElementType: elements.Arc, linkScales: helpers$1.noop, /** * @private */ _dataElementOptions: [ 'backgroundColor', 'borderColor', 'borderWidth', 'borderAlign', 'hoverBackgroundColor', 'hoverBorderColor', 'hoverBorderWidth', ], /** * @private */ _getIndexScaleId: function() { return this.chart.scale.id; }, /** * @private */ _getValueScaleId: function() { return this.chart.scale.id; }, update: function(reset) { var me = this; var dataset = me.getDataset(); var meta = me.getMeta(); var start = me.chart.options.startAngle || 0; var starts = me._starts = []; var angles = me._angles = []; var arcs = meta.data; var i, ilen, angle; me._updateRadius(); meta.count = me.countVisibleElements(); for (i = 0, ilen = dataset.data.length; i < ilen; i++) { starts[i] = start; angle = me._computeAngle(i); angles[i] = angle; start += angle; } for (i = 0, ilen = arcs.length; i < ilen; ++i) { arcs[i]._options = me._resolveDataElementOptions(arcs[i], i); me.updateElement(arcs[i], i, reset); } }, /** * @private */ _updateRadius: function() { var me = this; var chart = me.chart; var chartArea = chart.chartArea; var opts = chart.options; var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top); chart.outerRadius = Math.max(minSize / 2, 0); chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0); chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount(); me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index); me.innerRadius = me.outerRadius - chart.radiusLength; }, updateElement: function(arc, index, reset) { var me = this; var chart = me.chart; var dataset = me.getDataset(); var opts = chart.options; var animationOpts = opts.animation; var scale = chart.scale; var labels = chart.data.labels; var centerX = scale.xCenter; var centerY = scale.yCenter; // var negHalfPI = -0.5 * Math.PI; var datasetStartAngle = opts.startAngle; var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]); var startAngle = me._starts[index]; var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]); var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]); var options = arc._options || {}; helpers$1.extend(arc, { // Utility _datasetIndex: me.index, _index: index, _scale: scale, // Desired view properties _model: { backgroundColor: options.backgroundColor, borderColor: options.borderColor, borderWidth: options.borderWidth, borderAlign: options.borderAlign, x: centerX, y: centerY, innerRadius: 0, outerRadius: reset ? resetRadius : distance, startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle, endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle, label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index]) } }); arc.pivot(); }, countVisibleElements: function() { var dataset = this.getDataset(); var meta = this.getMeta(); var count = 0; helpers$1.each(meta.data, function(element, index) { if (!isNaN(dataset.data[index]) && !element.hidden) { count++; } }); return count; }, /** * @protected */ setHoverStyle: function(arc) { var model = arc._model; var options = arc._options; var getHoverColor = helpers$1.getHoverColor; var valueOrDefault = helpers$1.valueOrDefault; arc.$previousStyle = { backgroundColor: model.backgroundColor, borderColor: model.borderColor, borderWidth: model.borderWidth, }; model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor)); model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor)); model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth); }, /** * @private */ _computeAngle: function(index) { var me = this; var count = this.getMeta().count; var dataset = me.getDataset(); var meta = me.getMeta(); if (isNaN(dataset.data[index]) || meta.data[index].hidden) { return 0; } // Scriptable options var context = { chart: me.chart, dataIndex: index, dataset: dataset, datasetIndex: me.index }; return resolve$3([ me.chart.options.elements.arc.angle, (2 * Math.PI) / count ], context, index); } }); core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut)); core_defaults._set('pie', { cutoutPercentage: 0 }); // Pie charts are Doughnut chart with different defaults var controller_pie = controller_doughnut; var valueOrDefault$7 = helpers$1.valueOrDefault; core_defaults._set('radar', { spanGaps: false, scale: { type: 'radialLinear' }, elements: { line: { fill: 'start', tension: 0 // no bezier in radar } } }); var controller_radar = core_datasetController.extend({ datasetElementType: elements.Line, dataElementType: elements.Point, linkScales: helpers$1.noop, /** * @private */ _datasetElementOptions: [ 'backgroundColor', 'borderWidth', 'borderColor', 'borderCapStyle', 'borderDash', 'borderDashOffset', 'borderJoinStyle', 'fill' ], /** * @private */ _dataElementOptions: { backgroundColor: 'pointBackgroundColor', borderColor: 'pointBorderColor', borderWidth: 'pointBorderWidth', hitRadius: 'pointHitRadius', hoverBackgroundColor: 'pointHoverBackgroundColor', hoverBorderColor: 'pointHoverBorderColor', hoverBorderWidth: 'pointHoverBorderWidth', hoverRadius: 'pointHoverRadius', pointStyle: 'pointStyle', radius: 'pointRadius', rotation: 'pointRotation' }, /** * @private */ _getIndexScaleId: function() { return this.chart.scale.id; }, /** * @private */ _getValueScaleId: function() { return this.chart.scale.id; }, update: function(reset) { var me = this; var meta = me.getMeta(); var line = meta.dataset; var points = meta.data || []; var scale = me.chart.scale; var config = me._config; var i, ilen; // Compatibility: If the properties are defined with only the old name, use those values if (config.tension !== undefined && config.lineTension === undefined) { config.lineTension = config.tension; } // Utility line._scale = scale; line._datasetIndex = me.index; // Data line._children = points; line._loop = true; // Model line._model = me._resolveDatasetElementOptions(line); line.pivot(); // Update Points for (i = 0, ilen = points.length; i < ilen; ++i) { me.updateElement(points[i], i, reset); } // Update bezier control points me.updateBezierControlPoints(); // Now pivot the point for animation for (i = 0, ilen = points.length; i < ilen; ++i) { points[i].pivot(); } }, updateElement: function(point, index, reset) { var me = this; var custom = point.custom || {}; var dataset = me.getDataset(); var scale = me.chart.scale; var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]); var options = me._resolveDataElementOptions(point, index); var lineModel = me.getMeta().dataset._model; var x = reset ? scale.xCenter : pointPosition.x; var y = reset ? scale.yCenter : pointPosition.y; // Utility point._scale = scale; point._options = options; point._datasetIndex = me.index; point._index = index; // Desired view properties point._model = { x: x, // value not used in dataset scale, but we want a consistent API between scales y: y, skip: custom.skip || isNaN(x) || isNaN(y), // Appearance radius: options.radius, pointStyle: options.pointStyle, rotation: options.rotation, backgroundColor: options.backgroundColor, borderColor: options.borderColor, borderWidth: options.borderWidth, tension: valueOrDefault$7(custom.tension, lineModel ? lineModel.tension : 0), // Tooltip hitRadius: options.hitRadius }; }, /** * @private */ _resolveDatasetElementOptions: function() { var me = this; var config = me._config; var options = me.chart.options; var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments); values.spanGaps = valueOrDefault$7(config.spanGaps, options.spanGaps); values.tension = valueOrDefault$7(config.lineTension, options.elements.line.tension); return values; }, updateBezierControlPoints: function() { var me = this; var meta = me.getMeta(); var area = me.chart.chartArea; var points = meta.data || []; var i, ilen, model, controlPoints; // Only consider points that are drawn in case the spanGaps option is used if (meta.dataset._model.spanGaps) { points = points.filter(function(pt) { return !pt._model.skip; }); } function capControlPoint(pt, min, max) { return Math.max(Math.min(pt, max), min); } for (i = 0, ilen = points.length; i < ilen; ++i) { model = points[i]._model; controlPoints = helpers$1.splineCurve( helpers$1.previousItem(points, i, true)._model, model, helpers$1.nextItem(points, i, true)._model, model.tension ); // Prevent the bezier going outside of the bounds of the graph model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right); model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom); model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right); model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom); } }, setHoverStyle: function(point) { var model = point._model; var options = point._options; var getHoverColor = helpers$1.getHoverColor; point.$previousStyle = { backgroundColor: model.backgroundColor, borderColor: model.borderColor, borderWidth: model.borderWidth, radius: model.radius }; model.backgroundColor = valueOrDefault$7(options.hoverBackgroundColor, getHoverColor(options.backgroundColor)); model.borderColor = valueOrDefault$7(options.hoverBorderColor, getHoverColor(options.borderColor)); model.borderWidth = valueOrDefault$7(options.hoverBorderWidth, options.borderWidth); model.radius = valueOrDefault$7(options.hoverRadius, options.radius); } }); core_defaults._set('scatter', { hover: { mode: 'single' }, scales: { xAxes: [{ id: 'x-axis-1', // need an ID so datasets can reference the scale type: 'linear', // scatter should not use a categories axis position: 'bottom' }], yAxes: [{ id: 'y-axis-1', type: 'linear', position: 'left' }] }, tooltips: { callbacks: { title: function() { return ''; // doesn't make sense for scatter since data are formatted as a point }, label: function(item) { return '(' + item.xLabel + ', ' + item.yLabel + ')'; } } } }); core_defaults._set('global', { datasets: { scatter: { showLine: false } } }); // Scatter charts use line controllers var controller_scatter = controller_line; // NOTE export a map in which the key represents the controller type, not // the class, and so must be CamelCase in order to be correctly retrieved // by the controller in core.controller.js (`controllers[meta.type]`). var controllers = { bar: controller_bar, bubble: controller_bubble, doughnut: controller_doughnut, horizontalBar: controller_horizontalBar, line: controller_line, polarArea: controller_polarArea, pie: controller_pie, radar: controller_radar, scatter: controller_scatter }; /** * Helper function to get relative position for an event * @param {Event|IEvent} event - The event to get the position for * @param {Chart} chart - The chart * @returns {object} the event position */ function getRelativePosition(e, chart) { if (e.native) { return { x: e.x, y: e.y }; } return helpers$1.getRelativePosition(e, chart); } /** * Helper function to traverse all of the visible elements in the chart * @param {Chart} chart - the chart * @param {function} handler - the callback to execute for each visible item */ function parseVisibleItems(chart, handler) { var metasets = chart._getSortedVisibleDatasetMetas(); var metadata, i, j, ilen, jlen, element; for (i = 0, ilen = metasets.length; i < ilen; ++i) { metadata = metasets[i].data; for (j = 0, jlen = metadata.length; j < jlen; ++j) { element = metadata[j]; if (!element._view.skip) { handler(element); } } } } /** * Helper function to get the items that intersect the event position * @param {ChartElement[]} items - elements to filter * @param {object} position - the point to be nearest to * @return {ChartElement[]} the nearest items */ function getIntersectItems(chart, position) { var elements = []; parseVisibleItems(chart, function(element) { if (element.inRange(position.x, position.y)) { elements.push(element); } }); return elements; } /** * Helper function to get the items nearest to the event position considering all visible items in teh chart * @param {Chart} chart - the chart to look at elements from * @param {object} position - the point to be nearest to * @param {boolean} intersect - if true, only consider items that intersect the position * @param {function} distanceMetric - function to provide the distance between points * @return {ChartElement[]} the nearest items */ function getNearestItems(chart, position, intersect, distanceMetric) { var minDistance = Number.POSITIVE_INFINITY; var nearestItems = []; parseVisibleItems(chart, function(element) { if (intersect && !element.inRange(position.x, position.y)) { return; } var center = element.getCenterPoint(); var distance = distanceMetric(position, center); if (distance < minDistance) { nearestItems = [element]; minDistance = distance; } else if (distance === minDistance) { // Can have multiple items at the same distance in which case we sort by size nearestItems.push(element); } }); return nearestItems; } /** * Get a distance metric function for two points based on the * axis mode setting * @param {string} axis - the axis mode. x|y|xy */ function getDistanceMetricForAxis(axis) { var useX = axis.indexOf('x') !== -1; var useY = axis.indexOf('y') !== -1; return function(pt1, pt2) { var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0; var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0; return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); }; } function indexMode(chart, e, options) { var position = getRelativePosition(e, chart); // Default axis for index mode is 'x' to match old behaviour options.axis = options.axis || 'x'; var distanceMetric = getDistanceMetricForAxis(options.axis); var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric); var elements = []; if (!items.length) { return []; } chart._getSortedVisibleDatasetMetas().forEach(function(meta) { var element = meta.data[items[0]._index]; // don't count items that are skipped (null data) if (element && !element._view.skip) { elements.push(element); } }); return elements; } /** * @interface IInteractionOptions */ /** * If true, only consider items that intersect the point * @name IInterfaceOptions#boolean * @type Boolean */ /** * Contains interaction related functions * @namespace Chart.Interaction */ var core_interaction = { // Helper function for different modes modes: { single: function(chart, e) { var position = getRelativePosition(e, chart); var elements = []; parseVisibleItems(chart, function(element) { if (element.inRange(position.x, position.y)) { elements.push(element); return elements; } }); return elements.slice(0, 1); }, /** * @function Chart.Interaction.modes.label * @deprecated since version 2.4.0 * @todo remove at version 3 * @private */ label: indexMode, /** * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item * @function Chart.Interaction.modes.index * @since v2.4.0 * @param {Chart} chart - the chart we are returning items from * @param {Event} e - the event we are find things at * @param {IInteractionOptions} options - options to use during interaction * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned */ index: indexMode, /** * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something * If the options.intersect is false, we find the nearest item and return the items in that dataset * @function Chart.Interaction.modes.dataset * @param {Chart} chart - the chart we are returning items from * @param {Event} e - the event we are find things at * @param {IInteractionOptions} options - options to use during interaction * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned */ dataset: function(chart, e, options) { var position = getRelativePosition(e, chart); options.axis = options.axis || 'xy'; var distanceMetric = getDistanceMetricForAxis(options.axis); var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric); if (items.length > 0) { items = chart.getDatasetMeta(items[0]._datasetIndex).data; } return items; }, /** * @function Chart.Interaction.modes.x-axis * @deprecated since version 2.4.0. Use index mode and intersect == true * @todo remove at version 3 * @private */ 'x-axis': function(chart, e) { return indexMode(chart, e, {intersect: false}); }, /** * Point mode returns all elements that hit test based on the event position * of the event * @function Chart.Interaction.modes.intersect * @param {Chart} chart - the chart we are returning items from * @param {Event} e - the event we are find things at * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned */ point: function(chart, e) { var position = getRelativePosition(e, chart); return getIntersectItems(chart, position); }, /** * nearest mode returns the element closest to the point * @function Chart.Interaction.modes.intersect * @param {Chart} chart - the chart we are returning items from * @param {Event} e - the event we are find things at * @param {IInteractionOptions} options - options to use * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned */ nearest: function(chart, e, options) { var position = getRelativePosition(e, chart); options.axis = options.axis || 'xy'; var distanceMetric = getDistanceMetricForAxis(options.axis); return getNearestItems(chart, position, options.intersect, distanceMetric); }, /** * x mode returns the elements that hit-test at the current x coordinate * @function Chart.Interaction.modes.x * @param {Chart} chart - the chart we are returning items from * @param {Event} e - the event we are find things at * @param {IInteractionOptions} options - options to use * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned */ x: function(chart, e, options) { var position = getRelativePosition(e, chart); var items = []; var intersectsItem = false; parseVisibleItems(chart, function(element) { if (element.inXRange(position.x)) { items.push(element); } if (element.inRange(position.x, position.y)) { intersectsItem = true; } }); // If we want to trigger on an intersect and we don't have any items // that intersect the position, return nothing if (options.intersect && !intersectsItem) { items = []; } return items; }, /** * y mode returns the elements that hit-test at the current y coordinate * @function Chart.Interaction.modes.y * @param {Chart} chart - the chart we are returning items from * @param {Event} e - the event we are find things at * @param {IInteractionOptions} options - options to use * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned */ y: function(chart, e, options) { var position = getRelativePosition(e, chart); var items = []; var intersectsItem = false; parseVisibleItems(chart, function(element) { if (element.inYRange(position.y)) { items.push(element); } if (element.inRange(position.x, position.y)) { intersectsItem = true; } }); // If we want to trigger on an intersect and we don't have any items // that intersect the position, return nothing if (options.intersect && !intersectsItem) { items = []; } return items; } } }; var extend = helpers$1.extend; function filterByPosition(array, position) { return helpers$1.where(array, function(v) { return v.pos === position; }); } function sortByWeight(array, reverse) { return array.sort(function(a, b) { var v0 = reverse ? b : a; var v1 = reverse ? a : b; return v0.weight === v1.weight ? v0.index - v1.index : v0.weight - v1.weight; }); } function wrapBoxes(boxes) { var layoutBoxes = []; var i, ilen, box; for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) { box = boxes[i]; layoutBoxes.push({ index: i, box: box, pos: box.position, horizontal: box.isHorizontal(), weight: box.weight }); } return layoutBoxes; } function setLayoutDims(layouts, params) { var i, ilen, layout; for (i = 0, ilen = layouts.length; i < ilen; ++i) { layout = layouts[i]; // store width used instead of chartArea.w in fitBoxes layout.width = layout.horizontal ? layout.box.fullWidth && params.availableWidth : params.vBoxMaxWidth; // store height used instead of chartArea.h in fitBoxes layout.height = layout.horizontal && params.hBoxMaxHeight; } } function buildLayoutBoxes(boxes) { var layoutBoxes = wrapBoxes(boxes); var left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true); var right = sortByWeight(filterByPosition(layoutBoxes, 'right')); var top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true); var bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom')); return { leftAndTop: left.concat(top), rightAndBottom: right.concat(bottom), chartArea: filterByPosition(layoutBoxes, 'chartArea'), vertical: left.concat(right), horizontal: top.concat(bottom) }; } function getCombinedMax(maxPadding, chartArea, a, b) { return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]); } function updateDims(chartArea, params, layout) { var box = layout.box; var maxPadding = chartArea.maxPadding; var newWidth, newHeight; if (layout.size) { // this layout was already counted for, lets first reduce old size chartArea[layout.pos] -= layout.size; } layout.size = layout.horizontal ? box.height : box.width; chartArea[layout.pos] += layout.size; if (box.getPadding) { var boxPadding = box.getPadding(); maxPadding.top = Math.max(maxPadding.top, boxPadding.top); maxPadding.left = Math.max(maxPadding.left, boxPadding.left); maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom); maxPadding.right = Math.max(maxPadding.right, boxPadding.right); } newWidth = params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'); newHeight = params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'); if (newWidth !== chartArea.w || newHeight !== chartArea.h) { chartArea.w = newWidth; chartArea.h = newHeight; // return true if chart area changed in layout's direction return layout.horizontal ? newWidth !== chartArea.w : newHeight !== chartArea.h; } } function handleMaxPadding(chartArea) { var maxPadding = chartArea.maxPadding; function updatePos(pos) { var change = Math.max(maxPadding[pos] - chartArea[pos], 0); chartArea[pos] += change; return change; } chartArea.y += updatePos('top'); chartArea.x += updatePos('left'); updatePos('right'); updatePos('bottom'); } function getMargins(horizontal, chartArea) { var maxPadding = chartArea.maxPadding; function marginForPositions(positions) { var margin = {left: 0, top: 0, right: 0, bottom: 0}; positions.forEach(function(pos) { margin[pos] = Math.max(chartArea[pos], maxPadding[pos]); }); return margin; } return horizontal ? marginForPositions(['left', 'right']) : marginForPositions(['top', 'bottom']); } function fitBoxes(boxes, chartArea, params) { var refitBoxes = []; var i, ilen, layout, box, refit, changed; for (i = 0, ilen = boxes.length; i < ilen; ++i) { layout = boxes[i]; box = layout.box; box.update( layout.width || chartArea.w, layout.height || chartArea.h, getMargins(layout.horizontal, chartArea) ); if (updateDims(chartArea, params, layout)) { changed = true; if (refitBoxes.length) { // Dimensions changed and there were non full width boxes before this // -> we have to refit those refit = true; } } if (!box.fullWidth) { // fullWidth boxes don't need to be re-fitted in any case refitBoxes.push(layout); } } return refit ? fitBoxes(refitBoxes, chartArea, params) || changed : changed; } function placeBoxes(boxes, chartArea, params) { var userPadding = params.padding; var x = chartArea.x; var y = chartArea.y; var i, ilen, layout, box; for (i = 0, ilen = boxes.length; i < ilen; ++i) { layout = boxes[i]; box = layout.box; if (layout.horizontal) { box.left = box.fullWidth ? userPadding.left : chartArea.left; box.right = box.fullWidth ? params.outerWidth - userPadding.right : chartArea.left + chartArea.w; box.top = y; box.bottom = y + box.height; box.width = box.right - box.left; y = box.bottom; } else { box.left = x; box.right = x + box.width; box.top = chartArea.top; box.bottom = chartArea.top + chartArea.h; box.height = box.bottom - box.top; x = box.right; } } chartArea.x = x; chartArea.y = y; } core_defaults._set('global', { layout: { padding: { top: 0, right: 0, bottom: 0, left: 0 } } }); /** * @interface ILayoutItem * @prop {string} position - The position of the item in the chart layout. Possible values are * 'left', 'top', 'right', 'bottom', and 'chartArea' * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom) * @prop {function} update - Takes two parameters: width and height. Returns size of item * @prop {function} getPadding - Returns an object with padding on the edges * @prop {number} width - Width of item. Must be valid after update() * @prop {number} height - Height of item. Must be valid after update() * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update */ // The layout service is very self explanatory. It's responsible for the layout within a chart. // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need // It is this service's responsibility of carrying out that layout. var core_layouts = { defaults: {}, /** * Register a box to a chart. * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title. * @param {Chart} chart - the chart to use * @param {ILayoutItem} item - the item to add to be layed out */ addBox: function(chart, item) { if (!chart.boxes) { chart.boxes = []; } // initialize item with default values item.fullWidth = item.fullWidth || false; item.position = item.position || 'top'; item.weight = item.weight || 0; item._layers = item._layers || function() { return [{ z: 0, draw: function() { item.draw.apply(item, arguments); } }]; }; chart.boxes.push(item); }, /** * Remove a layoutItem from a chart * @param {Chart} chart - the chart to remove the box from * @param {ILayoutItem} layoutItem - the item to remove from the layout */ removeBox: function(chart, layoutItem) { var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1; if (index !== -1) { chart.boxes.splice(index, 1); } }, /** * Sets (or updates) options on the given `item`. * @param {Chart} chart - the chart in which the item lives (or will be added to) * @param {ILayoutItem} item - the item to configure with the given options * @param {object} options - the new item options. */ configure: function(chart, item, options) { var props = ['fullWidth', 'position', 'weight']; var ilen = props.length; var i = 0; var prop; for (; i < ilen; ++i) { prop = props[i]; if (options.hasOwnProperty(prop)) { item[prop] = options[prop]; } } }, /** * Fits boxes of the given chart into the given size by having each box measure itself * then running a fitting algorithm * @param {Chart} chart - the chart * @param {number} width - the width to fit into * @param {number} height - the height to fit into */ update: function(chart, width, height) { if (!chart) { return; } var layoutOptions = chart.options.layout || {}; var padding = helpers$1.options.toPadding(layoutOptions.padding); var availableWidth = width - padding.width; var availableHeight = height - padding.height; var boxes = buildLayoutBoxes(chart.boxes); var verticalBoxes = boxes.vertical; var horizontalBoxes = boxes.horizontal; // Essentially we now have any number of boxes on each of the 4 sides. // Our canvas looks like the following. // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and // B1 is the bottom axis // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays // These locations are single-box locations only, when trying to register a chartArea location that is already taken, // an error will be thrown. // // |----------------------------------------------------| // | T1 (Full Width) | // |----------------------------------------------------| // | | | T2 | | // | |----|-------------------------------------|----| // | | | C1 | | C2 | | // | | |----| |----| | // | | | | | // | L1 | L2 | ChartArea (C0) | R1 | // | | | | | // | | |----| |----| | // | | | C3 | | C4 | | // | |----|-------------------------------------|----| // | | | B1 | | // |----------------------------------------------------| // | B2 (Full Width) | // |----------------------------------------------------| // var params = Object.freeze({ outerWidth: width, outerHeight: height, padding: padding, availableWidth: availableWidth, vBoxMaxWidth: availableWidth / 2 / verticalBoxes.length, hBoxMaxHeight: availableHeight / 2 }); var chartArea = extend({ maxPadding: extend({}, padding), w: availableWidth, h: availableHeight, x: padding.left, y: padding.top }, padding); setLayoutDims(verticalBoxes.concat(horizontalBoxes), params); // First fit vertical boxes fitBoxes(verticalBoxes, chartArea, params); // Then fit horizontal boxes if (fitBoxes(horizontalBoxes, chartArea, params)) { // if the area changed, re-fit vertical boxes fitBoxes(verticalBoxes, chartArea, params); } handleMaxPadding(chartArea); // Finally place the boxes to correct coordinates placeBoxes(boxes.leftAndTop, chartArea, params); // Move to opposite side of chart chartArea.x += chartArea.w; chartArea.y += chartArea.h; placeBoxes(boxes.rightAndBottom, chartArea, params); chart.chartArea = { left: chartArea.left, top: chartArea.top, right: chartArea.left + chartArea.w, bottom: chartArea.top + chartArea.h }; // Finally update boxes in chartArea (radial scale for example) helpers$1.each(boxes.chartArea, function(layout) { var box = layout.box; extend(box, chart.chartArea); box.update(chartArea.w, chartArea.h); }); } }; /** * Platform fallback implementation (minimal). * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939 */ var platform_basic = { acquireContext: function(item) { if (item && item.canvas) { // Support for any object associated to a canvas (including a context2d) item = item.canvas; } return item && item.getContext('2d') || null; } }; var platform_dom = "/*\n * DOM element rendering detection\n * https://davidwalsh.name/detect-node-insertion\n */\n@keyframes chartjs-render-animation {\n\tfrom { opacity: 0.99; }\n\tto { opacity: 1; }\n}\n\n.chartjs-render-monitor {\n\tanimation: chartjs-render-animation 0.001s;\n}\n\n/*\n * DOM element resizing detection\n * https://github.com/marcj/css-element-queries\n */\n.chartjs-size-monitor,\n.chartjs-size-monitor-expand,\n.chartjs-size-monitor-shrink {\n\tposition: absolute;\n\tdirection: ltr;\n\tleft: 0;\n\ttop: 0;\n\tright: 0;\n\tbottom: 0;\n\toverflow: hidden;\n\tpointer-events: none;\n\tvisibility: hidden;\n\tz-index: -1;\n}\n\n.chartjs-size-monitor-expand > div {\n\tposition: absolute;\n\twidth: 1000000px;\n\theight: 1000000px;\n\tleft: 0;\n\ttop: 0;\n}\n\n.chartjs-size-monitor-shrink > div {\n\tposition: absolute;\n\twidth: 200%;\n\theight: 200%;\n\tleft: 0;\n\ttop: 0;\n}\n"; var platform_dom$1 = /*#__PURE__*/Object.freeze({ __proto__: null, 'default': platform_dom }); var stylesheet = getCjsExportFromNamespace(platform_dom$1); var EXPANDO_KEY = '$chartjs'; var CSS_PREFIX = 'chartjs-'; var CSS_SIZE_MONITOR = CSS_PREFIX + 'size-monitor'; var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor'; var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation'; var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart']; /** * DOM event types -> Chart.js event types. * Note: only events with different types are mapped. * @see https://developer.mozilla.org/en-US/docs/Web/Events */ var EVENT_TYPES = { touchstart: 'mousedown', touchmove: 'mousemove', touchend: 'mouseup', pointerenter: 'mouseenter', pointerdown: 'mousedown', pointermove: 'mousemove', pointerup: 'mouseup', pointerleave: 'mouseout', pointerout: 'mouseout' }; /** * The "used" size is the final value of a dimension property after all calculations have * been performed. This method uses the computed style of `element` but returns undefined * if the computed style is not expressed in pixels. That can happen in some cases where * `element` has a size relative to its parent and this last one is not yet displayed, * for example because of `display: none` on a parent node. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value * @returns {number} Size in pixels or undefined if unknown. */ function readUsedSize(element, property) { var value = helpers$1.getStyle(element, property); var matches = value && value.match(/^(\d+)(\.\d+)?px$/); return matches ? Number(matches[1]) : undefined; } /** * Initializes the canvas style and render size without modifying the canvas display size, * since responsiveness is handled by the controller.resize() method. The config is used * to determine the aspect ratio to apply in case no explicit height has been specified. */ function initCanvas(canvas, config) { var style = canvas.style; // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it // returns null or '' if no explicit value has been set to the canvas attribute. var renderHeight = canvas.getAttribute('height'); var renderWidth = canvas.getAttribute('width'); // Chart.js modifies some canvas values that we want to restore on destroy canvas[EXPANDO_KEY] = { initial: { height: renderHeight, width: renderWidth, style: { display: style.display, height: style.height, width: style.width } } }; // Force canvas to display as block to avoid extra space caused by inline // elements, which would interfere with the responsive resize process. // https://github.com/chartjs/Chart.js/issues/2538 style.display = style.display || 'block'; if (renderWidth === null || renderWidth === '') { var displayWidth = readUsedSize(canvas, 'width'); if (displayWidth !== undefined) { canvas.width = displayWidth; } } if (renderHeight === null || renderHeight === '') { if (canvas.style.height === '') { // If no explicit render height and style height, let's apply the aspect ratio, // which one can be specified by the user but also by charts as default option // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2. canvas.height = canvas.width / (config.options.aspectRatio || 2); } else { var displayHeight = readUsedSize(canvas, 'height'); if (displayWidth !== undefined) { canvas.height = displayHeight; } } } return canvas; } /** * Detects support for options object argument in addEventListener. * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support * @private */ var supportsEventListenerOptions = (function() { var supports = false; try { var options = Object.defineProperty({}, 'passive', { // eslint-disable-next-line getter-return get: function() { supports = true; } }); window.addEventListener('e', null, options); } catch (e) { // continue regardless of error } return supports; }()); // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events. // https://github.com/chartjs/Chart.js/issues/4287 var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false; function addListener(node, type, listener) { node.addEventListener(type, listener, eventListenerOptions); } function removeListener(node, type, listener) { node.removeEventListener(type, listener, eventListenerOptions); } function createEvent(type, chart, x, y, nativeEvent) { return { type: type, chart: chart, native: nativeEvent || null, x: x !== undefined ? x : null, y: y !== undefined ? y : null, }; } function fromNativeEvent(event, chart) { var type = EVENT_TYPES[event.type] || event.type; var pos = helpers$1.getRelativePosition(event, chart); return createEvent(type, chart, pos.x, pos.y, event); } function throttled(fn, thisArg) { var ticking = false; var args = []; return function() { args = Array.prototype.slice.call(arguments); thisArg = thisArg || this; if (!ticking) { ticking = true; helpers$1.requestAnimFrame.call(window, function() { ticking = false; fn.apply(thisArg, args); }); } }; } function createDiv(cls) { var el = document.createElement('div'); el.className = cls || ''; return el; } // Implementation based on https://github.com/marcj/css-element-queries function createResizer(handler) { var maxSize = 1000000; // NOTE(SB) Don't use innerHTML because it could be considered unsafe. // https://github.com/chartjs/Chart.js/issues/5902 var resizer = createDiv(CSS_SIZE_MONITOR); var expand = createDiv(CSS_SIZE_MONITOR + '-expand'); var shrink = createDiv(CSS_SIZE_MONITOR + '-shrink'); expand.appendChild(createDiv()); shrink.appendChild(createDiv()); resizer.appendChild(expand); resizer.appendChild(shrink); resizer._reset = function() { expand.scrollLeft = maxSize; expand.scrollTop = maxSize; shrink.scrollLeft = maxSize; shrink.scrollTop = maxSize; }; var onScroll = function() { resizer._reset(); handler(); }; addListener(expand, 'scroll', onScroll.bind(expand, 'expand')); addListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink')); return resizer; } // https://davidwalsh.name/detect-node-insertion function watchForRender(node, handler) { var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {}); var proxy = expando.renderProxy = function(e) { if (e.animationName === CSS_RENDER_ANIMATION) { handler(); } }; helpers$1.each(ANIMATION_START_EVENTS, function(type) { addListener(node, type, proxy); }); // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class // is removed then added back immediately (same animation frame?). Accessing the // `offsetParent` property will force a reflow and re-evaluate the CSS animation. // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics // https://github.com/chartjs/Chart.js/issues/4737 expando.reflow = !!node.offsetParent; node.classList.add(CSS_RENDER_MONITOR); } function unwatchForRender(node) { var expando = node[EXPANDO_KEY] || {}; var proxy = expando.renderProxy; if (proxy) { helpers$1.each(ANIMATION_START_EVENTS, function(type) { removeListener(node, type, proxy); }); delete expando.renderProxy; } node.classList.remove(CSS_RENDER_MONITOR); } function addResizeListener(node, listener, chart) { var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {}); // Let's keep track of this added resizer and thus avoid DOM query when removing it. var resizer = expando.resizer = createResizer(throttled(function() { if (expando.resizer) { var container = chart.options.maintainAspectRatio && node.parentNode; var w = container ? container.clientWidth : 0; listener(createEvent('resize', chart)); if (container && container.clientWidth < w && chart.canvas) { // If the container size shrank during chart resize, let's assume // scrollbar appeared. So we resize again with the scrollbar visible - // effectively making chart smaller and the scrollbar hidden again. // Because we are inside `throttled`, and currently `ticking`, scroll // events are ignored during this whole 2 resize process. // If we assumed wrong and something else happened, we are resizing // twice in a frame (potential performance issue) listener(createEvent('resize', chart)); } } })); // The resizer needs to be attached to the node parent, so we first need to be // sure that `node` is attached to the DOM before injecting the resizer element. watchForRender(node, function() { if (expando.resizer) { var container = node.parentNode; if (container && container !== resizer.parentNode) { container.insertBefore(resizer, container.firstChild); } // The container size might have changed, let's reset the resizer state. resizer._reset(); } }); } function removeResizeListener(node) { var expando = node[EXPANDO_KEY] || {}; var resizer = expando.resizer; delete expando.resizer; unwatchForRender(node); if (resizer && resizer.parentNode) { resizer.parentNode.removeChild(resizer); } } /** * Injects CSS styles inline if the styles are not already present. * @param {HTMLDocument|ShadowRoot} rootNode - the node to contain the <style>. * @param {string} css - the CSS to be injected. */ function injectCSS(rootNode, css) { // https://stackoverflow.com/q/3922139 var expando = rootNode[EXPANDO_KEY] || (rootNode[EXPANDO_KEY] = {}); if (!expando.containsStyles) { expando.containsStyles = true; css = '/* Chart.js */\n' + css; var style = document.createElement('style'); style.setAttribute('type', 'text/css'); style.appendChild(document.createTextNode(css)); rootNode.appendChild(style); } } var platform_dom$2 = { /** * When `true`, prevents the automatic injection of the stylesheet required to * correctly detect when the chart is added to the DOM and then resized. This * switch has been added to allow external stylesheet (`dist/Chart(.min)?.js`) * to be manually imported to make this library compatible with any CSP. * See https://github.com/chartjs/Chart.js/issues/5208 */ disableCSSInjection: false, /** * This property holds whether this platform is enabled for the current environment. * Currently used by platform.js to select the proper implementation. * @private */ _enabled: typeof window !== 'undefined' && typeof document !== 'undefined', /** * Initializes resources that depend on platform options. * @param {HTMLCanvasElement} canvas - The Canvas element. * @private */ _ensureLoaded: function(canvas) { if (!this.disableCSSInjection) { // If the canvas is in a shadow DOM, then the styles must also be inserted // into the same shadow DOM. // https://github.com/chartjs/Chart.js/issues/5763 var root = canvas.getRootNode ? canvas.getRootNode() : document; var targetNode = root.host ? root : document.head; injectCSS(targetNode, stylesheet); } }, acquireContext: function(item, config) { if (typeof item === 'string') { item = document.getElementById(item); } else if (item.length) { // Support for array based queries (such as jQuery) item = item[0]; } if (item && item.canvas) { // Support for any object associated to a canvas (including a context2d) item = item.canvas; } // To prevent canvas fingerprinting, some add-ons undefine the getContext // method, for example: https://github.com/kkapsner/CanvasBlocker // https://github.com/chartjs/Chart.js/issues/2807 var context = item && item.getContext && item.getContext('2d'); // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is // inside an iframe or when running in a protected environment. We could guess the // types from their toString() value but let's keep things flexible and assume it's // a sufficient condition if the item has a context2D which has item as `canvas`. // https://github.com/chartjs/Chart.js/issues/3887 // https://github.com/chartjs/Chart.js/issues/4102 // https://github.com/chartjs/Chart.js/issues/4152 if (context && context.canvas === item) { // Load platform resources on first chart creation, to make it possible to // import the library before setting platform options. this._ensureLoaded(item); initCanvas(item, config); return context; } return null; }, releaseContext: function(context) { var canvas = context.canvas; if (!canvas[EXPANDO_KEY]) { return; } var initial = canvas[EXPANDO_KEY].initial; ['height', 'width'].forEach(function(prop) { var value = initial[prop]; if (helpers$1.isNullOrUndef(value)) { canvas.removeAttribute(prop); } else { canvas.setAttribute(prop, value); } }); helpers$1.each(initial.style || {}, function(value, key) { canvas.style[key] = value; }); // The canvas render size might have been changed (and thus the state stack discarded), // we can't use save() and restore() to restore the initial state. So make sure that at // least the canvas context is reset to the default state by setting the canvas width. // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html // eslint-disable-next-line no-self-assign canvas.width = canvas.width; delete canvas[EXPANDO_KEY]; }, addEventListener: function(chart, type, listener) { var canvas = chart.canvas; if (type === 'resize') { // Note: the resize event is not supported on all browsers. addResizeListener(canvas, listener, chart); return; } var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {}); var proxies = expando.proxies || (expando.proxies = {}); var proxy = proxies[chart.id + '_' + type] = function(event) { listener(fromNativeEvent(event, chart)); }; addListener(canvas, type, proxy); }, removeEventListener: function(chart, type, listener) { var canvas = chart.canvas; if (type === 'resize') { // Note: the resize event is not supported on all browsers. removeResizeListener(canvas); return; } var expando = listener[EXPANDO_KEY] || {}; var proxies = expando.proxies || {}; var proxy = proxies[chart.id + '_' + type]; if (!proxy) { return; } removeListener(canvas, type, proxy); } }; // DEPRECATIONS /** * Provided for backward compatibility, use EventTarget.addEventListener instead. * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+ * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener * @function Chart.helpers.addEvent * @deprecated since version 2.7.0 * @todo remove at version 3 * @private */ helpers$1.addEvent = addListener; /** * Provided for backward compatibility, use EventTarget.removeEventListener instead. * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+ * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener * @function Chart.helpers.removeEvent * @deprecated since version 2.7.0 * @todo remove at version 3 * @private */ helpers$1.removeEvent = removeListener; // @TODO Make possible to select another platform at build time. var implementation = platform_dom$2._enabled ? platform_dom$2 : platform_basic; /** * @namespace Chart.platform * @see https://chartjs.gitbooks.io/proposals/content/Platform.html * @since 2.4.0 */ var platform = helpers$1.extend({ /** * @since 2.7.0 */ initialize: function() {}, /** * Called at chart construction time, returns a context2d instance implementing * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}. * @param {*} item - The native item from which to acquire context (platform specific) * @param {object} options - The chart options * @returns {CanvasRenderingContext2D} context2d instance */ acquireContext: function() {}, /** * Called at chart destruction time, releases any resources associated to the context * previously returned by the acquireContext() method. * @param {CanvasRenderingContext2D} context - The context2d instance * @returns {boolean} true if the method succeeded, else false */ releaseContext: function() {}, /** * Registers the specified listener on the given chart. * @param {Chart} chart - Chart from which to listen for event * @param {string} type - The ({@link IEvent}) type to listen for * @param {function} listener - Receives a notification (an object that implements * the {@link IEvent} interface) when an event of the specified type occurs. */ addEventListener: function() {}, /** * Removes the specified listener previously registered with addEventListener. * @param {Chart} chart - Chart from which to remove the listener * @param {string} type - The ({@link IEvent}) type to remove * @param {function} listener - The listener function to remove from the event target. */ removeEventListener: function() {} }, implementation); core_defaults._set('global', { plugins: {} }); /** * The plugin service singleton * @namespace Chart.plugins * @since 2.1.0 */ var core_plugins = { /** * Globally registered plugins. * @private */ _plugins: [], /** * This identifier is used to invalidate the descriptors cache attached to each chart * when a global plugin is registered or unregistered. In this case, the cache ID is * incremented and descriptors are regenerated during following API calls. * @private */ _cacheId: 0, /** * Registers the given plugin(s) if not already registered. * @param {IPlugin[]|IPlugin} plugins plugin instance(s). */ register: function(plugins) { var p = this._plugins; ([]).concat(plugins).forEach(function(plugin) { if (p.indexOf(plugin) === -1) { p.push(plugin); } }); this._cacheId++; }, /** * Unregisters the given plugin(s) only if registered. * @param {IPlugin[]|IPlugin} plugins plugin instance(s). */ unregister: function(plugins) { var p = this._plugins; ([]).concat(plugins).forEach(function(plugin) { var idx = p.indexOf(plugin); if (idx !== -1) { p.splice(idx, 1); } }); this._cacheId++; }, /** * Remove all registered plugins. * @since 2.1.5 */ clear: function() { this._plugins = []; this._cacheId++; }, /** * Returns the number of registered plugins? * @returns {number} * @since 2.1.5 */ count: function() { return this._plugins.length; }, /** * Returns all registered plugin instances. * @returns {IPlugin[]} array of plugin objects. * @since 2.1.5 */ getAll: function() { return this._plugins; }, /** * Calls enabled plugins for `chart` on the specified hook and with the given args. * This method immediately returns as soon as a plugin explicitly returns false. The * returned value can be used, for instance, to interrupt the current action. * @param {Chart} chart - The chart instance for which plugins should be called. * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate'). * @param {Array} [args] - Extra arguments to apply to the hook call. * @returns {boolean} false if any of the plugins return false, else returns true. */ notify: function(chart, hook, args) { var descriptors = this.descriptors(chart); var ilen = descriptors.length; var i, descriptor, plugin, params, method; for (i = 0; i < ilen; ++i) { descriptor = descriptors[i]; plugin = descriptor.plugin; method = plugin[hook]; if (typeof method === 'function') { params = [chart].concat(args || []); params.push(descriptor.options); if (method.apply(plugin, params) === false) { return false; } } } return true; }, /** * Returns descriptors of enabled plugins for the given chart. * @returns {object[]} [{ plugin, options }] * @private */ descriptors: function(chart) { var cache = chart.$plugins || (chart.$plugins = {}); if (cache.id === this._cacheId) { return cache.descriptors; } var plugins = []; var descriptors = []; var config = (chart && chart.config) || {}; var options = (config.options && config.options.plugins) || {}; this._plugins.concat(config.plugins || []).forEach(function(plugin) { var idx = plugins.indexOf(plugin); if (idx !== -1) { return; } var id = plugin.id; var opts = options[id]; if (opts === false) { return; } if (opts === true) { opts = helpers$1.clone(core_defaults.global.plugins[id]); } plugins.push(plugin); descriptors.push({ plugin: plugin, options: opts || {} }); }); cache.descriptors = descriptors; cache.id = this._cacheId; return descriptors; }, /** * Invalidates cache for the given chart: descriptors hold a reference on plugin option, * but in some cases, this reference can be changed by the user when updating options. * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167 * @private */ _invalidate: function(chart) { delete chart.$plugins; } }; var core_scaleService = { // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then // use the new chart options to grab the correct scale constructors: {}, // Use a registration function so that we can move to an ES6 map when we no longer need to support // old browsers // Scale config defaults defaults: {}, registerScaleType: function(type, scaleConstructor, scaleDefaults) { this.constructors[type] = scaleConstructor; this.defaults[type] = helpers$1.clone(scaleDefaults); }, getScaleConstructor: function(type) { return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined; }, getScaleDefaults: function(type) { // Return the scale defaults merged with the global settings so that we always use the latest ones return this.defaults.hasOwnProperty(type) ? helpers$1.merge({}, [core_defaults.scale, this.defaults[type]]) : {}; }, updateScaleDefaults: function(type, additions) { var me = this; if (me.defaults.hasOwnProperty(type)) { me.defaults[type] = helpers$1.extend(me.defaults[type], additions); } }, addScalesToLayout: function(chart) { // Adds each scale to the chart.boxes array to be sized accordingly helpers$1.each(chart.scales, function(scale) { // Set ILayoutItem parameters for backwards compatibility scale.fullWidth = scale.options.fullWidth; scale.position = scale.options.position; scale.weight = scale.options.weight; core_layouts.addBox(chart, scale); }); } }; var valueOrDefault$8 = helpers$1.valueOrDefault; var getRtlHelper = helpers$1.rtl.getRtlAdapter; core_defaults._set('global', { tooltips: { enabled: true, custom: null, mode: 'nearest', position: 'average', intersect: true, backgroundColor: 'rgba(0,0,0,0.8)', titleFontStyle: 'bold', titleSpacing: 2, titleMarginBottom: 6, titleFontColor: '#fff', titleAlign: 'left', bodySpacing: 2, bodyFontColor: '#fff', bodyAlign: 'left', footerFontStyle: 'bold', footerSpacing: 2, footerMarginTop: 6, footerFontColor: '#fff', footerAlign: 'left', yPadding: 6, xPadding: 6, caretPadding: 2, caretSize: 5, cornerRadius: 6, multiKeyBackground: '#fff', displayColors: true, borderColor: 'rgba(0,0,0,0)', borderWidth: 0, callbacks: { // Args are: (tooltipItems, data) beforeTitle: helpers$1.noop, title: function(tooltipItems, data) { var title = ''; var labels = data.labels; var labelCount = labels ? labels.length : 0; if (tooltipItems.length > 0) { var item = tooltipItems[0]; if (item.label) { title = item.label; } else if (item.xLabel) { title = item.xLabel; } else if (labelCount > 0 && item.index < labelCount) { title = labels[item.index]; } } return title; }, afterTitle: helpers$1.noop, // Args are: (tooltipItems, data) beforeBody: helpers$1.noop, // Args are: (tooltipItem, data) beforeLabel: helpers$1.noop, label: function(tooltipItem, data) { var label = data.datasets[tooltipItem.datasetIndex].label || ''; if (label) { label += ': '; } if (!helpers$1.isNullOrUndef(tooltipItem.value)) { label += tooltipItem.value; } else { label += tooltipItem.yLabel; } return label; }, labelColor: function(tooltipItem, chart) { var meta = chart.getDatasetMeta(tooltipItem.datasetIndex); var activeElement = meta.data[tooltipItem.index]; var view = activeElement._view; return { borderColor: view.borderColor, backgroundColor: view.backgroundColor }; }, labelTextColor: function() { return this._options.bodyFontColor; }, afterLabel: helpers$1.noop, // Args are: (tooltipItems, data) afterBody: helpers$1.noop, // Args are: (tooltipItems, data) beforeFooter: helpers$1.noop, footer: helpers$1.noop, afterFooter: helpers$1.noop } } }); var positioners = { /** * Average mode places the tooltip at the average position of the elements shown * @function Chart.Tooltip.positioners.average * @param elements {ChartElement[]} the elements being displayed in the tooltip * @returns {object} tooltip position */ average: function(elements) { if (!elements.length) { return false; } var i, len; var x = 0; var y = 0; var count = 0; for (i = 0, len = elements.length; i < len; ++i) { var el = elements[i]; if (el && el.hasValue()) { var pos = el.tooltipPosition(); x += pos.x; y += pos.y; ++count; } } return { x: x / count, y: y / count }; }, /** * Gets the tooltip position nearest of the item nearest to the event position * @function Chart.Tooltip.positioners.nearest * @param elements {Chart.Element[]} the tooltip elements * @param eventPosition {object} the position of the event in canvas coordinates * @returns {object} the tooltip position */ nearest: function(elements, eventPosition) { var x = eventPosition.x; var y = eventPosition.y; var minDistance = Number.POSITIVE_INFINITY; var i, len, nearestElement; for (i = 0, len = elements.length; i < len; ++i) { var el = elements[i]; if (el && el.hasValue()) { var center = el.getCenterPoint(); var d = helpers$1.distanceBetweenPoints(eventPosition, center); if (d < minDistance) { minDistance = d; nearestElement = el; } } } if (nearestElement) { var tp = nearestElement.tooltipPosition(); x = tp.x; y = tp.y; } return { x: x, y: y }; } }; // Helper to push or concat based on if the 2nd parameter is an array or not function pushOrConcat(base, toPush) { if (toPush) { if (helpers$1.isArray(toPush)) { // base = base.concat(toPush); Array.prototype.push.apply(base, toPush); } else { base.push(toPush); } } return base; } /** * Returns array of strings split by newline * @param {string} value - The value to split by newline. * @returns {string[]} value if newline present - Returned from String split() method * @function */ function splitNewlines(str) { if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) { return str.split('\n'); } return str; } /** * Private helper to create a tooltip item model * @param element - the chart element (point, arc, bar) to create the tooltip item for * @return new tooltip item */ function createTooltipItem(element) { var xScale = element._xScale; var yScale = element._yScale || element._scale; // handle radar || polarArea charts var index = element._index; var datasetIndex = element._datasetIndex; var controller = element._chart.getDatasetMeta(datasetIndex).controller; var indexScale = controller._getIndexScale(); var valueScale = controller._getValueScale(); return { xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '', yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '', label: indexScale ? '' + indexScale.getLabelForIndex(index, datasetIndex) : '', value: valueScale ? '' + valueScale.getLabelForIndex(index, datasetIndex) : '', index: index, datasetIndex: datasetIndex, x: element._model.x, y: element._model.y }; } /** * Helper to get the reset model for the tooltip * @param tooltipOpts {object} the tooltip options */ function getBaseModel(tooltipOpts) { var globalDefaults = core_defaults.global; return { // Positioning xPadding: tooltipOpts.xPadding, yPadding: tooltipOpts.yPadding, xAlign: tooltipOpts.xAlign, yAlign: tooltipOpts.yAlign, // Drawing direction and text direction rtl: tooltipOpts.rtl, textDirection: tooltipOpts.textDirection, // Body bodyFontColor: tooltipOpts.bodyFontColor, _bodyFontFamily: valueOrDefault$8(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily), _bodyFontStyle: valueOrDefault$8(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle), _bodyAlign: tooltipOpts.bodyAlign, bodyFontSize: valueOrDefault$8(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize), bodySpacing: tooltipOpts.bodySpacing, // Title titleFontColor: tooltipOpts.titleFontColor, _titleFontFamily: valueOrDefault$8(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily), _titleFontStyle: valueOrDefault$8(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle), titleFontSize: valueOrDefault$8(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize), _titleAlign: tooltipOpts.titleAlign, titleSpacing: tooltipOpts.titleSpacing, titleMarginBottom: tooltipOpts.titleMarginBottom, // Footer footerFontColor: tooltipOpts.footerFontColor, _footerFontFamily: valueOrDefault$8(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily), _footerFontStyle: valueOrDefault$8(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle), footerFontSize: valueOrDefault$8(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize), _footerAlign: tooltipOpts.footerAlign, footerSpacing: tooltipOpts.footerSpacing, footerMarginTop: tooltipOpts.footerMarginTop, // Appearance caretSize: tooltipOpts.caretSize, cornerRadius: tooltipOpts.cornerRadius, backgroundColor: tooltipOpts.backgroundColor, opacity: 0, legendColorBackground: tooltipOpts.multiKeyBackground, displayColors: tooltipOpts.displayColors, borderColor: tooltipOpts.borderColor, borderWidth: tooltipOpts.borderWidth }; } /** * Get the size of the tooltip */ function getTooltipSize(tooltip, model) { var ctx = tooltip._chart.ctx; var height = model.yPadding * 2; // Tooltip Padding var width = 0; // Count of all lines in the body var body = model.body; var combinedBodyLength = body.reduce(function(count, bodyItem) { return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length; }, 0); combinedBodyLength += model.beforeBody.length + model.afterBody.length; var titleLineCount = model.title.length; var footerLineCount = model.footer.length; var titleFontSize = model.titleFontSize; var bodyFontSize = model.bodyFontSize; var footerFontSize = model.footerFontSize; height += titleLineCount * titleFontSize; // Title Lines height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin height += combinedBodyLength * bodyFontSize; // Body Lines height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin height += footerLineCount * (footerFontSize); // Footer Lines height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing // Title width var widthPadding = 0; var maxLineWidth = function(line) { width = Math.max(width, ctx.measureText(line).width + widthPadding); }; ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily); helpers$1.each(model.title, maxLineWidth); // Body width ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily); helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth); // Body lines may includes some extra width due to the color box widthPadding = model.displayColors ? (bodyFontSize + 2) : 0; helpers$1.each(body, function(bodyItem) { helpers$1.each(bodyItem.before, maxLineWidth); helpers$1.each(bodyItem.lines, maxLineWidth); helpers$1.each(bodyItem.after, maxLineWidth); }); // Reset back to 0 widthPadding = 0; // Footer width ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily); helpers$1.each(model.footer, maxLineWidth); // Add padding width += 2 * model.xPadding; return { width: width, height: height }; } /** * Helper to get the alignment of a tooltip given the size */ function determineAlignment(tooltip, size) { var model = tooltip._model; var chart = tooltip._chart; var chartArea = tooltip._chart.chartArea; var xAlign = 'center'; var yAlign = 'center'; if (model.y < size.height) { yAlign = 'top'; } else if (model.y > (chart.height - size.height)) { yAlign = 'bottom'; } var lf, rf; // functions to determine left, right alignment var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges var midX = (chartArea.left + chartArea.right) / 2; var midY = (chartArea.top + chartArea.bottom) / 2; if (yAlign === 'center') { lf = function(x) { return x <= midX; }; rf = function(x) { return x > midX; }; } else { lf = function(x) { return x <= (size.width / 2); }; rf = function(x) { return x >= (chart.width - (size.width / 2)); }; } olf = function(x) { return x + size.width + model.caretSize + model.caretPadding > chart.width; }; orf = function(x) { return x - size.width - model.caretSize - model.caretPadding < 0; }; yf = function(y) { return y <= midY ? 'top' : 'bottom'; }; if (lf(model.x)) { xAlign = 'left'; // Is tooltip too wide and goes over the right side of the chart.? if (olf(model.x)) { xAlign = 'center'; yAlign = yf(model.y); } } else if (rf(model.x)) { xAlign = 'right'; // Is tooltip too wide and goes outside left edge of canvas? if (orf(model.x)) { xAlign = 'center'; yAlign = yf(model.y); } } var opts = tooltip._options; return { xAlign: opts.xAlign ? opts.xAlign : xAlign, yAlign: opts.yAlign ? opts.yAlign : yAlign }; } /** * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment */ function getBackgroundPoint(vm, size, alignment, chart) { // Background Position var x = vm.x; var y = vm.y; var caretSize = vm.caretSize; var caretPadding = vm.caretPadding; var cornerRadius = vm.cornerRadius; var xAlign = alignment.xAlign; var yAlign = alignment.yAlign; var paddingAndSize = caretSize + caretPadding; var radiusAndPadding = cornerRadius + caretPadding; if (xAlign === 'right') { x -= size.width; } else if (xAlign === 'center') { x -= (size.width / 2); if (x + size.width > chart.width) { x = chart.width - size.width; } if (x < 0) { x = 0; } } if (yAlign === 'top') { y += paddingAndSize; } else if (yAlign === 'bottom') { y -= size.height + paddingAndSize; } else { y -= (size.height / 2); } if (yAlign === 'center') { if (xAlign === 'left') { x += paddingAndSize; } else if (xAlign === 'right') { x -= paddingAndSize; } } else if (xAlign === 'left') { x -= radiusAndPadding; } else if (xAlign === 'right') { x += radiusAndPadding; } return { x: x, y: y }; } function getAlignedX(vm, align) { return align === 'center' ? vm.x + vm.width / 2 : align === 'right' ? vm.x + vm.width - vm.xPadding : vm.x + vm.xPadding; } /** * Helper to build before and after body lines */ function getBeforeAfterBodyLines(callback) { return pushOrConcat([], splitNewlines(callback)); } var exports$4 = core_element.extend({ initialize: function() { this._model = getBaseModel(this._options); this._lastActive = []; }, // Get the title // Args are: (tooltipItem, data) getTitle: function() { var me = this; var opts = me._options; var callbacks = opts.callbacks; var beforeTitle = callbacks.beforeTitle.apply(me, arguments); var title = callbacks.title.apply(me, arguments); var afterTitle = callbacks.afterTitle.apply(me, arguments); var lines = []; lines = pushOrConcat(lines, splitNewlines(beforeTitle)); lines = pushOrConcat(lines, splitNewlines(title)); lines = pushOrConcat(lines, splitNewlines(afterTitle)); return lines; }, // Args are: (tooltipItem, data) getBeforeBody: function() { return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments)); }, // Args are: (tooltipItem, data) getBody: function(tooltipItems, data) { var me = this; var callbacks = me._options.callbacks; var bodyItems = []; helpers$1.each(tooltipItems, function(tooltipItem) { var bodyItem = { before: [], lines: [], after: [] }; pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data))); pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data)); pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data))); bodyItems.push(bodyItem); }); return bodyItems; }, // Args are: (tooltipItem, data) getAfterBody: function() { return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments)); }, // Get the footer and beforeFooter and afterFooter lines // Args are: (tooltipItem, data) getFooter: function() { var me = this; var callbacks = me._options.callbacks; var beforeFooter = callbacks.beforeFooter.apply(me, arguments); var footer = callbacks.footer.apply(me, arguments); var afterFooter = callbacks.afterFooter.apply(me, arguments); var lines = []; lines = pushOrConcat(lines, splitNewlines(beforeFooter)); lines = pushOrConcat(lines, splitNewlines(footer)); lines = pushOrConcat(lines, splitNewlines(afterFooter)); return lines; }, update: function(changed) { var me = this; var opts = me._options; // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition // that does _view = _model if ease === 1. This causes the 2nd tooltip update to set properties in both the view and model at the same time // which breaks any animations. var existingModel = me._model; var model = me._model = getBaseModel(opts); var active = me._active; var data = me._data; // In the case where active.length === 0 we need to keep these at existing values for good animations var alignment = { xAlign: existingModel.xAlign, yAlign: existingModel.yAlign }; var backgroundPoint = { x: existingModel.x, y: existingModel.y }; var tooltipSize = { width: existingModel.width, height: existingModel.height }; var tooltipPosition = { x: existingModel.caretX, y: existingModel.caretY }; var i, len; if (active.length) { model.opacity = 1; var labelColors = []; var labelTextColors = []; tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition); var tooltipItems = []; for (i = 0, len = active.length; i < len; ++i) { tooltipItems.push(createTooltipItem(active[i])); } // If the user provided a filter function, use it to modify the tooltip items if (opts.filter) { tooltipItems = tooltipItems.filter(function(a) { return opts.filter(a, data); }); } // If the user provided a sorting function, use it to modify the tooltip items if (opts.itemSort) { tooltipItems = tooltipItems.sort(function(a, b) { return opts.itemSort(a, b, data); }); } // Determine colors for boxes helpers$1.each(tooltipItems, function(tooltipItem) { labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart)); labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart)); }); // Build the Text Lines model.title = me.getTitle(tooltipItems, data); model.beforeBody = me.getBeforeBody(tooltipItems, data); model.body = me.getBody(tooltipItems, data); model.afterBody = me.getAfterBody(tooltipItems, data); model.footer = me.getFooter(tooltipItems, data); // Initial positioning and colors model.x = tooltipPosition.x; model.y = tooltipPosition.y; model.caretPadding = opts.caretPadding; model.labelColors = labelColors; model.labelTextColors = labelTextColors; // data points model.dataPoints = tooltipItems; // We need to determine alignment of the tooltip tooltipSize = getTooltipSize(this, model); alignment = determineAlignment(this, tooltipSize); // Final Size and Position backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart); } else { model.opacity = 0; } model.xAlign = alignment.xAlign; model.yAlign = alignment.yAlign; model.x = backgroundPoint.x; model.y = backgroundPoint.y; model.width = tooltipSize.width; model.height = tooltipSize.height; // Point where the caret on the tooltip points to model.caretX = tooltipPosition.x; model.caretY = tooltipPosition.y; me._model = model; if (changed && opts.custom) { opts.custom.call(me, model); } return me; }, drawCaret: function(tooltipPoint, size) { var ctx = this._chart.ctx; var vm = this._view; var caretPosition = this.getCaretPosition(tooltipPoint, size, vm); ctx.lineTo(caretPosition.x1, caretPosition.y1); ctx.lineTo(caretPosition.x2, caretPosition.y2); ctx.lineTo(caretPosition.x3, caretPosition.y3); }, getCaretPosition: function(tooltipPoint, size, vm) { var x1, x2, x3, y1, y2, y3; var caretSize = vm.caretSize; var cornerRadius = vm.cornerRadius; var xAlign = vm.xAlign; var yAlign = vm.yAlign; var ptX = tooltipPoint.x; var ptY = tooltipPoint.y; var width = size.width; var height = size.height; if (yAlign === 'center') { y2 = ptY + (height / 2); if (xAlign === 'left') { x1 = ptX; x2 = x1 - caretSize; x3 = x1; y1 = y2 + caretSize; y3 = y2 - caretSize; } else { x1 = ptX + width; x2 = x1 + caretSize; x3 = x1; y1 = y2 - caretSize; y3 = y2 + caretSize; } } else { if (xAlign === 'left') { x2 = ptX + cornerRadius + (caretSize); x1 = x2 - caretSize; x3 = x2 + caretSize; } else if (xAlign === 'right') { x2 = ptX + width - cornerRadius - caretSize; x1 = x2 - caretSize; x3 = x2 + caretSize; } else { x2 = vm.caretX; x1 = x2 - caretSize; x3 = x2 + caretSize; } if (yAlign === 'top') { y1 = ptY; y2 = y1 - caretSize; y3 = y1; } else { y1 = ptY + height; y2 = y1 + caretSize; y3 = y1; // invert drawing order var tmp = x3; x3 = x1; x1 = tmp; } } return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3}; }, drawTitle: function(pt, vm, ctx) { var title = vm.title; var length = title.length; var titleFontSize, titleSpacing, i; if (length) { var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width); pt.x = getAlignedX(vm, vm._titleAlign); ctx.textAlign = rtlHelper.textAlign(vm._titleAlign); ctx.textBaseline = 'middle'; titleFontSize = vm.titleFontSize; titleSpacing = vm.titleSpacing; ctx.fillStyle = vm.titleFontColor; ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily); for (i = 0; i < length; ++i) { ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFontSize / 2); pt.y += titleFontSize + titleSpacing; // Line Height and spacing if (i + 1 === length) { pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing } } } }, drawBody: function(pt, vm, ctx) { var bodyFontSize = vm.bodyFontSize; var bodySpacing = vm.bodySpacing; var bodyAlign = vm._bodyAlign; var body = vm.body; var drawColorBoxes = vm.displayColors; var xLinePadding = 0; var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0; var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width); var fillLineOfText = function(line) { ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyFontSize / 2); pt.y += bodyFontSize + bodySpacing; }; var bodyItem, textColor, labelColors, lines, i, j, ilen, jlen; var bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign); ctx.textAlign = bodyAlign; ctx.textBaseline = 'middle'; ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily); pt.x = getAlignedX(vm, bodyAlignForCalculation); // Before body lines ctx.fillStyle = vm.bodyFontColor; helpers$1.each(vm.beforeBody, fillLineOfText); xLinePadding = drawColorBoxes && bodyAlignForCalculation !== 'right' ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2) : 0; // Draw body lines now for (i = 0, ilen = body.length; i < ilen; ++i) { bodyItem = body[i]; textColor = vm.labelTextColors[i]; labelColors = vm.labelColors[i]; ctx.fillStyle = textColor; helpers$1.each(bodyItem.before, fillLineOfText); lines = bodyItem.lines; for (j = 0, jlen = lines.length; j < jlen; ++j) { // Draw Legend-like boxes if needed if (drawColorBoxes) { var rtlColorX = rtlHelper.x(colorX); // Fill a white rect so that colours merge nicely if the opacity is < 1 ctx.fillStyle = vm.legendColorBackground; ctx.fillRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize); // Border ctx.lineWidth = 1; ctx.strokeStyle = labelColors.borderColor; ctx.strokeRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize); // Inner square ctx.fillStyle = labelColors.backgroundColor; ctx.fillRect(rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), bodyFontSize - 2), pt.y + 1, bodyFontSize - 2, bodyFontSize - 2); ctx.fillStyle = textColor; } fillLineOfText(lines[j]); } helpers$1.each(bodyItem.after, fillLineOfText); } // Reset back to 0 for after body xLinePadding = 0; // After body lines helpers$1.each(vm.afterBody, fillLineOfText); pt.y -= bodySpacing; // Remove last body spacing }, drawFooter: function(pt, vm, ctx) { var footer = vm.footer; var length = footer.length; var footerFontSize, i; if (length) { var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width); pt.x = getAlignedX(vm, vm._footerAlign); pt.y += vm.footerMarginTop; ctx.textAlign = rtlHelper.textAlign(vm._footerAlign); ctx.textBaseline = 'middle'; footerFontSize = vm.footerFontSize; ctx.fillStyle = vm.footerFontColor; ctx.font = helpers$1.fontString(footerFontSize, vm._footerFontStyle, vm._footerFontFamily); for (i = 0; i < length; ++i) { ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFontSize / 2); pt.y += footerFontSize + vm.footerSpacing; } } }, drawBackground: function(pt, vm, ctx, tooltipSize) { ctx.fillStyle = vm.backgroundColor; ctx.strokeStyle = vm.borderColor; ctx.lineWidth = vm.borderWidth; var xAlign = vm.xAlign; var yAlign = vm.yAlign; var x = pt.x; var y = pt.y; var width = tooltipSize.width; var height = tooltipSize.height; var radius = vm.cornerRadius; ctx.beginPath(); ctx.moveTo(x + radius, y); if (yAlign === 'top') { this.drawCaret(pt, tooltipSize); } ctx.lineTo(x + width - radius, y); ctx.quadraticCurveTo(x + width, y, x + width, y + radius); if (yAlign === 'center' && xAlign === 'right') { this.drawCaret(pt, tooltipSize); } ctx.lineTo(x + width, y + height - radius); ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height); if (yAlign === 'bottom') { this.drawCaret(pt, tooltipSize); } ctx.lineTo(x + radius, y + height); ctx.quadraticCurveTo(x, y + height, x, y + height - radius); if (yAlign === 'center' && xAlign === 'left') { this.drawCaret(pt, tooltipSize); } ctx.lineTo(x, y + radius); ctx.quadraticCurveTo(x, y, x + radius, y); ctx.closePath(); ctx.fill(); if (vm.borderWidth > 0) { ctx.stroke(); } }, draw: function() { var ctx = this._chart.ctx; var vm = this._view; if (vm.opacity === 0) { return; } var tooltipSize = { width: vm.width, height: vm.height }; var pt = { x: vm.x, y: vm.y }; // IE11/Edge does not like very small opacities, so snap to 0 var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity; // Truthy/falsey value for empty tooltip var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length; if (this._options.enabled && hasTooltipContent) { ctx.save(); ctx.globalAlpha = opacity; // Draw Background this.drawBackground(pt, vm, ctx, tooltipSize); // Draw Title, Body, and Footer pt.y += vm.yPadding; helpers$1.rtl.overrideTextDirection(ctx, vm.textDirection); // Titles this.drawTitle(pt, vm, ctx); // Body this.drawBody(pt, vm, ctx); // Footer this.drawFooter(pt, vm, ctx); helpers$1.rtl.restoreTextDirection(ctx, vm.textDirection); ctx.restore(); } }, /** * Handle an event * @private * @param {IEvent} event - The event to handle * @returns {boolean} true if the tooltip changed */ handleEvent: function(e) { var me = this; var options = me._options; var changed = false; me._lastActive = me._lastActive || []; // Find Active Elements for tooltips if (e.type === 'mouseout') { me._active = []; } else { me._active = me._chart.getElementsAtEventForMode(e, options.mode, options); if (options.reverse) { me._active.reverse(); } } // Remember Last Actives changed = !helpers$1.arrayEquals(me._active, me._lastActive); // Only handle target event on tooltip change if (changed) { me._lastActive = me._active; if (options.enabled || options.custom) { me._eventPosition = { x: e.x, y: e.y }; me.update(true); me.pivot(); } } return changed; } }); /** * @namespace Chart.Tooltip.positioners */ var positioners_1 = positioners; var core_tooltip = exports$4; core_tooltip.positioners = positioners_1; var valueOrDefault$9 = helpers$1.valueOrDefault; core_defaults._set('global', { elements: {}, events: [ 'mousemove', 'mouseout', 'click', 'touchstart', 'touchmove' ], hover: { onHover: null, mode: 'nearest', intersect: true, animationDuration: 400 }, onClick: null, maintainAspectRatio: true, responsive: true, responsiveAnimationDuration: 0 }); /** * Recursively merge the given config objects representing the `scales` option * by incorporating scale defaults in `xAxes` and `yAxes` array items, then * returns a deep copy of the result, thus doesn't alter inputs. */ function mergeScaleConfig(/* config objects ... */) { return helpers$1.merge({}, [].slice.call(arguments), { merger: function(key, target, source, options) { if (key === 'xAxes' || key === 'yAxes') { var slen = source[key].length; var i, type, scale; if (!target[key]) { target[key] = []; } for (i = 0; i < slen; ++i) { scale = source[key][i]; type = valueOrDefault$9(scale.type, key === 'xAxes' ? 'category' : 'linear'); if (i >= target[key].length) { target[key].push({}); } if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) { // new/untyped scale or type changed: let's apply the new defaults // then merge source scale to correctly overwrite the defaults. helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]); } else { // scales type are the same helpers$1.merge(target[key][i], scale); } } } else { helpers$1._merger(key, target, source, options); } } }); } /** * Recursively merge the given config objects as the root options by handling * default scale options for the `scales` and `scale` properties, then returns * a deep copy of the result, thus doesn't alter inputs. */ function mergeConfig(/* config objects ... */) { return helpers$1.merge({}, [].slice.call(arguments), { merger: function(key, target, source, options) { var tval = target[key] || {}; var sval = source[key]; if (key === 'scales') { // scale config merging is complex. Add our own function here for that target[key] = mergeScaleConfig(tval, sval); } else if (key === 'scale') { // used in polar area & radar charts since there is only one scale target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]); } else { helpers$1._merger(key, target, source, options); } } }); } function initConfig(config) { config = config || {}; // Do NOT use mergeConfig for the data object because this method merges arrays // and so would change references to labels and datasets, preventing data updates. var data = config.data = config.data || {}; data.datasets = data.datasets || []; data.labels = data.labels || []; config.options = mergeConfig( core_defaults.global, core_defaults[config.type], config.options || {}); return config; } function updateConfig(chart) { var newOptions = chart.options; helpers$1.each(chart.scales, function(scale) { core_layouts.removeBox(chart, scale); }); newOptions = mergeConfig( core_defaults.global, core_defaults[chart.config.type], newOptions); chart.options = chart.config.options = newOptions; chart.ensureScalesHaveIDs(); chart.buildOrUpdateScales(); // Tooltip chart.tooltip._options = newOptions.tooltips; chart.tooltip.initialize(); } function nextAvailableScaleId(axesOpts, prefix, index) { var id; var hasId = function(obj) { return obj.id === id; }; do { id = prefix + index++; } while (helpers$1.findIndex(axesOpts, hasId) >= 0); return id; } function positionIsHorizontal(position) { return position === 'top' || position === 'bottom'; } function compare2Level(l1, l2) { return function(a, b) { return a[l1] === b[l1] ? a[l2] - b[l2] : a[l1] - b[l1]; }; } var Chart = function(item, config) { this.construct(item, config); return this; }; helpers$1.extend(Chart.prototype, /** @lends Chart */ { /** * @private */ construct: function(item, config) { var me = this; config = initConfig(config); var context = platform.acquireContext(item, config); var canvas = context && context.canvas; var height = canvas && canvas.height; var width = canvas && canvas.width; me.id = helpers$1.uid(); me.ctx = context; me.canvas = canvas; me.config = config; me.width = width; me.height = height; me.aspectRatio = height ? width / height : null; me.options = config.options; me._bufferedRender = false; me._layers = []; /** * Provided for backward compatibility, Chart and Chart.Controller have been merged, * the "instance" still need to be defined since it might be called from plugins. * @prop Chart#chart * @deprecated since version 2.6.0 * @todo remove at version 3 * @private */ me.chart = me; me.controller = me; // chart.chart.controller #inception // Add the chart instance to the global namespace Chart.instances[me.id] = me; // Define alias to the config data: `chart.data === chart.config.data` Object.defineProperty(me, 'data', { get: function() { return me.config.data; }, set: function(value) { me.config.data = value; } }); if (!context || !canvas) { // The given item is not a compatible context2d element, let's return before finalizing // the chart initialization but after setting basic chart / controller properties that // can help to figure out that the chart is not valid (e.g chart.canvas !== null); // https://github.com/chartjs/Chart.js/issues/2807 console.error("Failed to create chart: can't acquire context from the given item"); return; } me.initialize(); me.update(); }, /** * @private */ initialize: function() { var me = this; // Before init plugin notification core_plugins.notify(me, 'beforeInit'); helpers$1.retinaScale(me, me.options.devicePixelRatio); me.bindEvents(); if (me.options.responsive) { // Initial resize before chart draws (must be silent to preserve initial animations). me.resize(true); } me.initToolTip(); // After init plugin notification core_plugins.notify(me, 'afterInit'); return me; }, clear: function() { helpers$1.canvas.clear(this); return this; }, stop: function() { // Stops any current animation loop occurring core_animations.cancelAnimation(this); return this; }, resize: function(silent) { var me = this; var options = me.options; var canvas = me.canvas; var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null; // the canvas render width and height will be casted to integers so make sure that // the canvas display style uses the same integer values to avoid blurring effect. // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas))); var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas))); if (me.width === newWidth && me.height === newHeight) { return; } canvas.width = me.width = newWidth; canvas.height = me.height = newHeight; canvas.style.width = newWidth + 'px'; canvas.style.height = newHeight + 'px'; helpers$1.retinaScale(me, options.devicePixelRatio); if (!silent) { // Notify any plugins about the resize var newSize = {width: newWidth, height: newHeight}; core_plugins.notify(me, 'resize', [newSize]); // Notify of resize if (options.onResize) { options.onResize(me, newSize); } me.stop(); me.update({ duration: options.responsiveAnimationDuration }); } }, ensureScalesHaveIDs: function() { var options = this.options; var scalesOptions = options.scales || {}; var scaleOptions = options.scale; helpers$1.each(scalesOptions.xAxes, function(xAxisOptions, index) { if (!xAxisOptions.id) { xAxisOptions.id = nextAvailableScaleId(scalesOptions.xAxes, 'x-axis-', index); } }); helpers$1.each(scalesOptions.yAxes, function(yAxisOptions, index) { if (!yAxisOptions.id) { yAxisOptions.id = nextAvailableScaleId(scalesOptions.yAxes, 'y-axis-', index); } }); if (scaleOptions) { scaleOptions.id = scaleOptions.id || 'scale'; } }, /** * Builds a map of scale ID to scale object for future lookup. */ buildOrUpdateScales: function() { var me = this; var options = me.options; var scales = me.scales || {}; var items = []; var updated = Object.keys(scales).reduce(function(obj, id) { obj[id] = false; return obj; }, {}); if (options.scales) { items = items.concat( (options.scales.xAxes || []).map(function(xAxisOptions) { return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'}; }), (options.scales.yAxes || []).map(function(yAxisOptions) { return {options: yAxisOptions, dtype: 'linear', dposition: 'left'}; }) ); } if (options.scale) { items.push({ options: options.scale, dtype: 'radialLinear', isDefault: true, dposition: 'chartArea' }); } helpers$1.each(items, function(item) { var scaleOptions = item.options; var id = scaleOptions.id; var scaleType = valueOrDefault$9(scaleOptions.type, item.dtype); if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) { scaleOptions.position = item.dposition; } updated[id] = true; var scale = null; if (id in scales && scales[id].type === scaleType) { scale = scales[id]; scale.options = scaleOptions; scale.ctx = me.ctx; scale.chart = me; } else { var scaleClass = core_scaleService.getScaleConstructor(scaleType); if (!scaleClass) { return; } scale = new scaleClass({ id: id, type: scaleType, options: scaleOptions, ctx: me.ctx, chart: me }); scales[scale.id] = scale; } scale.mergeTicksOptions(); // TODO(SB): I think we should be able to remove this custom case (options.scale) // and consider it as a regular scale part of the "scales"" map only! This would // make the logic easier and remove some useless? custom code. if (item.isDefault) { me.scale = scale; } }); // clear up discarded scales helpers$1.each(updated, function(hasUpdated, id) { if (!hasUpdated) { delete scales[id]; } }); me.scales = scales; core_scaleService.addScalesToLayout(this); }, buildOrUpdateControllers: function() { var me = this; var newControllers = []; var datasets = me.data.datasets; var i, ilen; for (i = 0, ilen = datasets.length; i < ilen; i++) { var dataset = datasets[i]; var meta = me.getDatasetMeta(i); var type = dataset.type || me.config.type; if (meta.type && meta.type !== type) { me.destroyDatasetMeta(i); meta = me.getDatasetMeta(i); } meta.type = type; meta.order = dataset.order || 0; meta.index = i; if (meta.controller) { meta.controller.updateIndex(i); meta.controller.linkScales(); } else { var ControllerClass = controllers[meta.type]; if (ControllerClass === undefined) { throw new Error('"' + meta.type + '" is not a chart type.'); } meta.controller = new ControllerClass(me, i); newControllers.push(meta.controller); } } return newControllers; }, /** * Reset the elements of all datasets * @private */ resetElements: function() { var me = this; helpers$1.each(me.data.datasets, function(dataset, datasetIndex) { me.getDatasetMeta(datasetIndex).controller.reset(); }, me); }, /** * Resets the chart back to it's state before the initial animation */ reset: function() { this.resetElements(); this.tooltip.initialize(); }, update: function(config) { var me = this; var i, ilen; if (!config || typeof config !== 'object') { // backwards compatibility config = { duration: config, lazy: arguments[1] }; } updateConfig(me); // plugins options references might have change, let's invalidate the cache // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167 core_plugins._invalidate(me); if (core_plugins.notify(me, 'beforeUpdate') === false) { return; } // In case the entire data object changed me.tooltip._data = me.data; // Make sure dataset controllers are updated and new controllers are reset var newControllers = me.buildOrUpdateControllers(); // Make sure all dataset controllers have correct meta data counts for (i = 0, ilen = me.data.datasets.length; i < ilen; i++) { me.getDatasetMeta(i).controller.buildOrUpdateElements(); } me.updateLayout(); // Can only reset the new controllers after the scales have been updated if (me.options.animation && me.options.animation.duration) { helpers$1.each(newControllers, function(controller) { controller.reset(); }); } me.updateDatasets(); // Need to reset tooltip in case it is displayed with elements that are removed // after update. me.tooltip.initialize(); // Last active contains items that were previously in the tooltip. // When we reset the tooltip, we need to clear it me.lastActive = []; // Do this before render so that any plugins that need final scale updates can use it core_plugins.notify(me, 'afterUpdate'); me._layers.sort(compare2Level('z', '_idx')); if (me._bufferedRender) { me._bufferedRequest = { duration: config.duration, easing: config.easing, lazy: config.lazy }; } else { me.render(config); } }, /** * Updates the chart layout unless a plugin returns `false` to the `beforeLayout` * hook, in which case, plugins will not be called on `afterLayout`. * @private */ updateLayout: function() { var me = this; if (core_plugins.notify(me, 'beforeLayout') === false) { return; } core_layouts.update(this, this.width, this.height); me._layers = []; helpers$1.each(me.boxes, function(box) { // _configure is called twice, once in core.scale.update and once here. // Here the boxes are fully updated and at their final positions. if (box._configure) { box._configure(); } me._layers.push.apply(me._layers, box._layers()); }, me); me._layers.forEach(function(item, index) { item._idx = index; }); /** * Provided for backward compatibility, use `afterLayout` instead. * @method IPlugin#afterScaleUpdate * @deprecated since version 2.5.0 * @todo remove at version 3 * @private */ core_plugins.notify(me, 'afterScaleUpdate'); core_plugins.notify(me, 'afterLayout'); }, /** * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate` * hook, in which case, plugins will not be called on `afterDatasetsUpdate`. * @private */ updateDatasets: function() { var me = this; if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) { return; } for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) { me.updateDataset(i); } core_plugins.notify(me, 'afterDatasetsUpdate'); }, /** * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate` * hook, in which case, plugins will not be called on `afterDatasetUpdate`. * @private */ updateDataset: function(index) { var me = this; var meta = me.getDatasetMeta(index); var args = { meta: meta, index: index }; if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) { return; } meta.controller._update(); core_plugins.notify(me, 'afterDatasetUpdate', [args]); }, render: function(config) { var me = this; if (!config || typeof config !== 'object') { // backwards compatibility config = { duration: config, lazy: arguments[1] }; } var animationOptions = me.options.animation; var duration = valueOrDefault$9(config.duration, animationOptions && animationOptions.duration); var lazy = config.lazy; if (core_plugins.notify(me, 'beforeRender') === false) { return; } var onComplete = function(animation) { core_plugins.notify(me, 'afterRender'); helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me); }; if (animationOptions && duration) { var animation = new core_animation({ numSteps: duration / 16.66, // 60 fps easing: config.easing || animationOptions.easing, render: function(chart, animationObject) { var easingFunction = helpers$1.easing.effects[animationObject.easing]; var currentStep = animationObject.currentStep; var stepDecimal = currentStep / animationObject.numSteps; chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep); }, onAnimationProgress: animationOptions.onProgress, onAnimationComplete: onComplete }); core_animations.addAnimation(me, animation, duration, lazy); } else { me.draw(); // See https://github.com/chartjs/Chart.js/issues/3781 onComplete(new core_animation({numSteps: 0, chart: me})); } return me; }, draw: function(easingValue) { var me = this; var i, layers; me.clear(); if (helpers$1.isNullOrUndef(easingValue)) { easingValue = 1; } me.transition(easingValue); if (me.width <= 0 || me.height <= 0) { return; } if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) { return; } // Because of plugin hooks (before/afterDatasetsDraw), datasets can't // currently be part of layers. Instead, we draw // layers <= 0 before(default, backward compat), and the rest after layers = me._layers; for (i = 0; i < layers.length && layers[i].z <= 0; ++i) { layers[i].draw(me.chartArea); } me.drawDatasets(easingValue); // Rest of layers for (; i < layers.length; ++i) { layers[i].draw(me.chartArea); } me._drawTooltip(easingValue); core_plugins.notify(me, 'afterDraw', [easingValue]); }, /** * @private */ transition: function(easingValue) { var me = this; for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) { if (me.isDatasetVisible(i)) { me.getDatasetMeta(i).controller.transition(easingValue); } } me.tooltip.transition(easingValue); }, /** * @private */ _getSortedDatasetMetas: function(filterVisible) { var me = this; var datasets = me.data.datasets || []; var result = []; var i, ilen; for (i = 0, ilen = datasets.length; i < ilen; ++i) { if (!filterVisible || me.isDatasetVisible(i)) { result.push(me.getDatasetMeta(i)); } } result.sort(compare2Level('order', 'index')); return result; }, /** * @private */ _getSortedVisibleDatasetMetas: function() { return this._getSortedDatasetMetas(true); }, /** * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw` * hook, in which case, plugins will not be called on `afterDatasetsDraw`. * @private */ drawDatasets: function(easingValue) { var me = this; var metasets, i; if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) { return; } metasets = me._getSortedVisibleDatasetMetas(); for (i = metasets.length - 1; i >= 0; --i) { me.drawDataset(metasets[i], easingValue); } core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]); }, /** * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw` * hook, in which case, plugins will not be called on `afterDatasetDraw`. * @private */ drawDataset: function(meta, easingValue) { var me = this; var args = { meta: meta, index: meta.index, easingValue: easingValue }; if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) { return; } meta.controller.draw(easingValue); core_plugins.notify(me, 'afterDatasetDraw', [args]); }, /** * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw` * hook, in which case, plugins will not be called on `afterTooltipDraw`. * @private */ _drawTooltip: function(easingValue) { var me = this; var tooltip = me.tooltip; var args = { tooltip: tooltip, easingValue: easingValue }; if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) { return; } tooltip.draw(); core_plugins.notify(me, 'afterTooltipDraw', [args]); }, /** * Get the single element that was clicked on * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw */ getElementAtEvent: function(e) { return core_interaction.modes.single(this, e); }, getElementsAtEvent: function(e) { return core_interaction.modes.label(this, e, {intersect: true}); }, getElementsAtXAxis: function(e) { return core_interaction.modes['x-axis'](this, e, {intersect: true}); }, getElementsAtEventForMode: function(e, mode, options) { var method = core_interaction.modes[mode]; if (typeof method === 'function') { return method(this, e, options); } return []; }, getDatasetAtEvent: function(e) { return core_interaction.modes.dataset(this, e, {intersect: true}); }, getDatasetMeta: function(datasetIndex) { var me = this; var dataset = me.data.datasets[datasetIndex]; if (!dataset._meta) { dataset._meta = {}; } var meta = dataset._meta[me.id]; if (!meta) { meta = dataset._meta[me.id] = { type: null, data: [], dataset: null, controller: null, hidden: null, // See isDatasetVisible() comment xAxisID: null, yAxisID: null, order: dataset.order || 0, index: datasetIndex }; } return meta; }, getVisibleDatasetCount: function() { var count = 0; for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) { if (this.isDatasetVisible(i)) { count++; } } return count; }, isDatasetVisible: function(datasetIndex) { var meta = this.getDatasetMeta(datasetIndex); // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false, // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned. return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden; }, generateLegend: function() { return this.options.legendCallback(this); }, /** * @private */ destroyDatasetMeta: function(datasetIndex) { var id = this.id; var dataset = this.data.datasets[datasetIndex]; var meta = dataset._meta && dataset._meta[id]; if (meta) { meta.controller.destroy(); delete dataset._meta[id]; } }, destroy: function() { var me = this; var canvas = me.canvas; var i, ilen; me.stop(); // dataset controllers need to cleanup associated data for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) { me.destroyDatasetMeta(i); } if (canvas) { me.unbindEvents(); helpers$1.canvas.clear(me); platform.releaseContext(me.ctx); me.canvas = null; me.ctx = null; } core_plugins.notify(me, 'destroy'); delete Chart.instances[me.id]; }, toBase64Image: function() { return this.canvas.toDataURL.apply(this.canvas, arguments); }, initToolTip: function() { var me = this; me.tooltip = new core_tooltip({ _chart: me, _chartInstance: me, // deprecated, backward compatibility _data: me.data, _options: me.options.tooltips }, me); }, /** * @private */ bindEvents: function() { var me = this; var listeners = me._listeners = {}; var listener = function() { me.eventHandler.apply(me, arguments); }; helpers$1.each(me.options.events, function(type) { platform.addEventListener(me, type, listener); listeners[type] = listener; }); // Elements used to detect size change should not be injected for non responsive charts. // See https://github.com/chartjs/Chart.js/issues/2210 if (me.options.responsive) { listener = function() { me.resize(); }; platform.addEventListener(me, 'resize', listener); listeners.resize = listener; } }, /** * @private */ unbindEvents: function() { var me = this; var listeners = me._listeners; if (!listeners) { return; } delete me._listeners; helpers$1.each(listeners, function(listener, type) { platform.removeEventListener(me, type, listener); }); }, updateHoverStyle: function(elements, mode, enabled) { var prefix = enabled ? 'set' : 'remove'; var element, i, ilen; for (i = 0, ilen = elements.length; i < ilen; ++i) { element = elements[i]; if (element) { this.getDatasetMeta(element._datasetIndex).controller[prefix + 'HoverStyle'](element); } } if (mode === 'dataset') { this.getDatasetMeta(elements[0]._datasetIndex).controller['_' + prefix + 'DatasetHoverStyle'](); } }, /** * @private */ eventHandler: function(e) { var me = this; var tooltip = me.tooltip; if (core_plugins.notify(me, 'beforeEvent', [e]) === false) { return; } // Buffer any update calls so that renders do not occur me._bufferedRender = true; me._bufferedRequest = null; var changed = me.handleEvent(e); // for smooth tooltip animations issue #4989 // the tooltip should be the source of change // Animation check workaround: // tooltip._start will be null when tooltip isn't animating if (tooltip) { changed = tooltip._start ? tooltip.handleEvent(e) : changed | tooltip.handleEvent(e); } core_plugins.notify(me, 'afterEvent', [e]); var bufferedRequest = me._bufferedRequest; if (bufferedRequest) { // If we have an update that was triggered, we need to do a normal render me.render(bufferedRequest); } else if (changed && !me.animating) { // If entering, leaving, or changing elements, animate the change via pivot me.stop(); // We only need to render at this point. Updating will cause scales to be // recomputed generating flicker & using more memory than necessary. me.render({ duration: me.options.hover.animationDuration, lazy: true }); } me._bufferedRender = false; me._bufferedRequest = null; return me; }, /** * Handle an event * @private * @param {IEvent} event the event to handle * @return {boolean} true if the chart needs to re-render */ handleEvent: function(e) { var me = this; var options = me.options || {}; var hoverOptions = options.hover; var changed = false; me.lastActive = me.lastActive || []; // Find Active Elements for hover and tooltips if (e.type === 'mouseout') { me.active = []; } else { me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions); } // Invoke onHover hook // Need to call with native event here to not break backwards compatibility helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me); if (e.type === 'mouseup' || e.type === 'click') { if (options.onClick) { // Use e.native here for backwards compatibility options.onClick.call(me, e.native, me.active); } } // Remove styling for last active (even if it may still be active) if (me.lastActive.length) { me.updateHoverStyle(me.lastActive, hoverOptions.mode, false); } // Built in hover styling if (me.active.length && hoverOptions.mode) { me.updateHoverStyle(me.active, hoverOptions.mode, true); } changed = !helpers$1.arrayEquals(me.active, me.lastActive); // Remember Last Actives me.lastActive = me.active; return changed; } }); /** * NOTE(SB) We actually don't use this container anymore but we need to keep it * for backward compatibility. Though, it can still be useful for plugins that * would need to work on multiple charts?! */ Chart.instances = {}; var core_controller = Chart; // DEPRECATIONS /** * Provided for backward compatibility, use Chart instead. * @class Chart.Controller * @deprecated since version 2.6 * @todo remove at version 3 * @private */ Chart.Controller = Chart; /** * Provided for backward compatibility, not available anymore. * @namespace Chart * @deprecated since version 2.8 * @todo remove at version 3 * @private */ Chart.types = {}; /** * Provided for backward compatibility, not available anymore. * @namespace Chart.helpers.configMerge * @deprecated since version 2.8.0 * @todo remove at version 3 * @private */ helpers$1.configMerge = mergeConfig; /** * Provided for backward compatibility, not available anymore. * @namespace Chart.helpers.scaleMerge * @deprecated since version 2.8.0 * @todo remove at version 3 * @private */ helpers$1.scaleMerge = mergeScaleConfig; var core_helpers = function() { // -- Basic js utility methods helpers$1.where = function(collection, filterCallback) { if (helpers$1.isArray(collection) && Array.prototype.filter) { return collection.filter(filterCallback); } var filtered = []; helpers$1.each(collection, function(item) { if (filterCallback(item)) { filtered.push(item); } }); return filtered; }; helpers$1.findIndex = Array.prototype.findIndex ? function(array, callback, scope) { return array.findIndex(callback, scope); } : function(array, callback, scope) { scope = scope === undefined ? array : scope; for (var i = 0, ilen = array.length; i < ilen; ++i) { if (callback.call(scope, array[i], i, array)) { return i; } } return -1; }; helpers$1.findNextWhere = function(arrayToSearch, filterCallback, startIndex) { // Default to start of the array if (helpers$1.isNullOrUndef(startIndex)) { startIndex = -1; } for (var i = startIndex + 1; i < arrayToSearch.length; i++) { var currentItem = arrayToSearch[i]; if (filterCallback(currentItem)) { return currentItem; } } }; helpers$1.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) { // Default to end of the array if (helpers$1.isNullOrUndef(startIndex)) { startIndex = arrayToSearch.length; } for (var i = startIndex - 1; i >= 0; i--) { var currentItem = arrayToSearch[i]; if (filterCallback(currentItem)) { return currentItem; } } }; // -- Math methods helpers$1.isNumber = function(n) { return !isNaN(parseFloat(n)) && isFinite(n); }; helpers$1.almostEquals = function(x, y, epsilon) { return Math.abs(x - y) < epsilon; }; helpers$1.almostWhole = function(x, epsilon) { var rounded = Math.round(x); return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x); }; helpers$1.max = function(array) { return array.reduce(function(max, value) { if (!isNaN(value)) { return Math.max(max, value); } return max; }, Number.NEGATIVE_INFINITY); }; helpers$1.min = function(array) { return array.reduce(function(min, value) { if (!isNaN(value)) { return Math.min(min, value); } return min; }, Number.POSITIVE_INFINITY); }; helpers$1.sign = Math.sign ? function(x) { return Math.sign(x); } : function(x) { x = +x; // convert to a number if (x === 0 || isNaN(x)) { return x; } return x > 0 ? 1 : -1; }; helpers$1.toRadians = function(degrees) { return degrees * (Math.PI / 180); }; helpers$1.toDegrees = function(radians) { return radians * (180 / Math.PI); }; /** * Returns the number of decimal places * i.e. the number of digits after the decimal point, of the value of this Number. * @param {number} x - A number. * @returns {number} The number of decimal places. * @private */ helpers$1._decimalPlaces = function(x) { if (!helpers$1.isFinite(x)) { return; } var e = 1; var p = 0; while (Math.round(x * e) / e !== x) { e *= 10; p++; } return p; }; // Gets the angle from vertical upright to the point about a centre. helpers$1.getAngleFromPoint = function(centrePoint, anglePoint) { var distanceFromXCenter = anglePoint.x - centrePoint.x; var distanceFromYCenter = anglePoint.y - centrePoint.y; var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter); var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter); if (angle < (-0.5 * Math.PI)) { angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2] } return { angle: angle, distance: radialDistanceFromCenter }; }; helpers$1.distanceBetweenPoints = function(pt1, pt2) { return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2)); }; /** * Provided for backward compatibility, not available anymore * @function Chart.helpers.aliasPixel * @deprecated since version 2.8.0 * @todo remove at version 3 */ helpers$1.aliasPixel = function(pixelWidth) { return (pixelWidth % 2 === 0) ? 0 : 0.5; }; /** * Returns the aligned pixel value to avoid anti-aliasing blur * @param {Chart} chart - The chart instance. * @param {number} pixel - A pixel value. * @param {number} width - The width of the element. * @returns {number} The aligned pixel value. * @private */ helpers$1._alignPixel = function(chart, pixel, width) { var devicePixelRatio = chart.currentDevicePixelRatio; var halfWidth = width / 2; return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth; }; helpers$1.splineCurve = function(firstPoint, middlePoint, afterPoint, t) { // Props to Rob Spencer at scaled innovation for his post on splining between points // http://scaledinnovation.com/analytics/splines/aboutSplines.html // This function must also respect "skipped" points var previous = firstPoint.skip ? middlePoint : firstPoint; var current = middlePoint; var next = afterPoint.skip ? middlePoint : afterPoint; var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2)); var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2)); var s01 = d01 / (d01 + d12); var s12 = d12 / (d01 + d12); // If all points are the same, s01 & s02 will be inf s01 = isNaN(s01) ? 0 : s01; s12 = isNaN(s12) ? 0 : s12; var fa = t * s01; // scaling factor for triangle Ta var fb = t * s12; return { previous: { x: current.x - fa * (next.x - previous.x), y: current.y - fa * (next.y - previous.y) }, next: { x: current.x + fb * (next.x - previous.x), y: current.y + fb * (next.y - previous.y) } }; }; helpers$1.EPSILON = Number.EPSILON || 1e-14; helpers$1.splineCurveMonotone = function(points) { // This function calculates Bézier control points in a similar way than |splineCurve|, // but preserves monotonicity of the provided data and ensures no local extremums are added // between the dataset discrete points due to the interpolation. // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation var pointsWithTangents = (points || []).map(function(point) { return { model: point._model, deltaK: 0, mK: 0 }; }); // Calculate slopes (deltaK) and initialize tangents (mK) var pointsLen = pointsWithTangents.length; var i, pointBefore, pointCurrent, pointAfter; for (i = 0; i < pointsLen; ++i) { pointCurrent = pointsWithTangents[i]; if (pointCurrent.model.skip) { continue; } pointBefore = i > 0 ? pointsWithTangents[i - 1] : null; pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null; if (pointAfter && !pointAfter.model.skip) { var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x); // In the case of two points that appear at the same x pixel, slopeDeltaX is 0 pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0; } if (!pointBefore || pointBefore.model.skip) { pointCurrent.mK = pointCurrent.deltaK; } else if (!pointAfter || pointAfter.model.skip) { pointCurrent.mK = pointBefore.deltaK; } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) { pointCurrent.mK = 0; } else { pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2; } } // Adjust tangents to ensure monotonic properties var alphaK, betaK, tauK, squaredMagnitude; for (i = 0; i < pointsLen - 1; ++i) { pointCurrent = pointsWithTangents[i]; pointAfter = pointsWithTangents[i + 1]; if (pointCurrent.model.skip || pointAfter.model.skip) { continue; } if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) { pointCurrent.mK = pointAfter.mK = 0; continue; } alphaK = pointCurrent.mK / pointCurrent.deltaK; betaK = pointAfter.mK / pointCurrent.deltaK; squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2); if (squaredMagnitude <= 9) { continue; } tauK = 3 / Math.sqrt(squaredMagnitude); pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK; pointAfter.mK = betaK * tauK * pointCurrent.deltaK; } // Compute control points var deltaX; for (i = 0; i < pointsLen; ++i) { pointCurrent = pointsWithTangents[i]; if (pointCurrent.model.skip) { continue; } pointBefore = i > 0 ? pointsWithTangents[i - 1] : null; pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null; if (pointBefore && !pointBefore.model.skip) { deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3; pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX; pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK; } if (pointAfter && !pointAfter.model.skip) { deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3; pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX; pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK; } } }; helpers$1.nextItem = function(collection, index, loop) { if (loop) { return index >= collection.length - 1 ? collection[0] : collection[index + 1]; } return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1]; }; helpers$1.previousItem = function(collection, index, loop) { if (loop) { return index <= 0 ? collection[collection.length - 1] : collection[index - 1]; } return index <= 0 ? collection[0] : collection[index - 1]; }; // Implementation of the nice number algorithm used in determining where axis labels will go helpers$1.niceNum = function(range, round) { var exponent = Math.floor(helpers$1.log10(range)); var fraction = range / Math.pow(10, exponent); var niceFraction; if (round) { if (fraction < 1.5) { niceFraction = 1; } else if (fraction < 3) { niceFraction = 2; } else if (fraction < 7) { niceFraction = 5; } else { niceFraction = 10; } } else if (fraction <= 1.0) { niceFraction = 1; } else if (fraction <= 2) { niceFraction = 2; } else if (fraction <= 5) { niceFraction = 5; } else { niceFraction = 10; } return niceFraction * Math.pow(10, exponent); }; // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ helpers$1.requestAnimFrame = (function() { if (typeof window === 'undefined') { return function(callback) { callback(); }; } return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { return window.setTimeout(callback, 1000 / 60); }; }()); // -- DOM methods helpers$1.getRelativePosition = function(evt, chart) { var mouseX, mouseY; var e = evt.originalEvent || evt; var canvas = evt.target || evt.srcElement; var boundingRect = canvas.getBoundingClientRect(); var touches = e.touches; if (touches && touches.length > 0) { mouseX = touches[0].clientX; mouseY = touches[0].clientY; } else { mouseX = e.clientX; mouseY = e.clientY; } // Scale mouse coordinates into canvas coordinates // by following the pattern laid out by 'jerryj' in the comments of // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/ var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left')); var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top')); var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right')); var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom')); var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight; var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom; // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio); mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio); return { x: mouseX, y: mouseY }; }; // Private helper function to convert max-width/max-height values that may be percentages into a number function parseMaxStyle(styleValue, node, parentProperty) { var valueInPixels; if (typeof styleValue === 'string') { valueInPixels = parseInt(styleValue, 10); if (styleValue.indexOf('%') !== -1) { // percentage * size in dimension valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty]; } } else { valueInPixels = styleValue; } return valueInPixels; } /** * Returns if the given value contains an effective constraint. * @private */ function isConstrainedValue(value) { return value !== undefined && value !== null && value !== 'none'; } /** * Returns the max width or height of the given DOM node in a cross-browser compatible fashion * @param {HTMLElement} domNode - the node to check the constraint on * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height') * @param {string} percentageProperty - property of parent to use when calculating width as a percentage * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser} */ function getConstraintDimension(domNode, maxStyle, percentageProperty) { var view = document.defaultView; var parentNode = helpers$1._getParentNode(domNode); var constrainedNode = view.getComputedStyle(domNode)[maxStyle]; var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle]; var hasCNode = isConstrainedValue(constrainedNode); var hasCContainer = isConstrainedValue(constrainedContainer); var infinity = Number.POSITIVE_INFINITY; if (hasCNode || hasCContainer) { return Math.min( hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity, hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity); } return 'none'; } // returns Number or undefined if no constraint helpers$1.getConstraintWidth = function(domNode) { return getConstraintDimension(domNode, 'max-width', 'clientWidth'); }; // returns Number or undefined if no constraint helpers$1.getConstraintHeight = function(domNode) { return getConstraintDimension(domNode, 'max-height', 'clientHeight'); }; /** * @private */ helpers$1._calculatePadding = function(container, padding, parentDimension) { padding = helpers$1.getStyle(container, padding); return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10); }; /** * @private */ helpers$1._getParentNode = function(domNode) { var parent = domNode.parentNode; if (parent && parent.toString() === '[object ShadowRoot]') { parent = parent.host; } return parent; }; helpers$1.getMaximumWidth = function(domNode) { var container = helpers$1._getParentNode(domNode); if (!container) { return domNode.clientWidth; } var clientWidth = container.clientWidth; var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth); var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth); var w = clientWidth - paddingLeft - paddingRight; var cw = helpers$1.getConstraintWidth(domNode); return isNaN(cw) ? w : Math.min(w, cw); }; helpers$1.getMaximumHeight = function(domNode) { var container = helpers$1._getParentNode(domNode); if (!container) { return domNode.clientHeight; } var clientHeight = container.clientHeight; var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight); var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight); var h = clientHeight - paddingTop - paddingBottom; var ch = helpers$1.getConstraintHeight(domNode); return isNaN(ch) ? h : Math.min(h, ch); }; helpers$1.getStyle = function(el, property) { return el.currentStyle ? el.currentStyle[property] : document.defaultView.getComputedStyle(el, null).getPropertyValue(property); }; helpers$1.retinaScale = function(chart, forceRatio) { var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1; if (pixelRatio === 1) { return; } var canvas = chart.canvas; var height = chart.height; var width = chart.width; canvas.height = height * pixelRatio; canvas.width = width * pixelRatio; chart.ctx.scale(pixelRatio, pixelRatio); // If no style has been set on the canvas, the render size is used as display size, // making the chart visually bigger, so let's enforce it to the "correct" values. // See https://github.com/chartjs/Chart.js/issues/3575 if (!canvas.style.height && !canvas.style.width) { canvas.style.height = height + 'px'; canvas.style.width = width + 'px'; } }; // -- Canvas methods helpers$1.fontString = function(pixelSize, fontStyle, fontFamily) { return fontStyle + ' ' + pixelSize + 'px ' + fontFamily; }; helpers$1.longestText = function(ctx, font, arrayOfThings, cache) { cache = cache || {}; var data = cache.data = cache.data || {}; var gc = cache.garbageCollect = cache.garbageCollect || []; if (cache.font !== font) { data = cache.data = {}; gc = cache.garbageCollect = []; cache.font = font; } ctx.font = font; var longest = 0; var ilen = arrayOfThings.length; var i, j, jlen, thing, nestedThing; for (i = 0; i < ilen; i++) { thing = arrayOfThings[i]; // Undefined strings and arrays should not be measured if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) { longest = helpers$1.measureText(ctx, data, gc, longest, thing); } else if (helpers$1.isArray(thing)) { // if it is an array lets measure each element // to do maybe simplify this function a bit so we can do this more recursively? for (j = 0, jlen = thing.length; j < jlen; j++) { nestedThing = thing[j]; // Undefined strings and arrays should not be measured if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) { longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing); } } } } var gcLen = gc.length / 2; if (gcLen > arrayOfThings.length) { for (i = 0; i < gcLen; i++) { delete data[gc[i]]; } gc.splice(0, gcLen); } return longest; }; helpers$1.measureText = function(ctx, data, gc, longest, string) { var textWidth = data[string]; if (!textWidth) { textWidth = data[string] = ctx.measureText(string).width; gc.push(string); } if (textWidth > longest) { longest = textWidth; } return longest; }; /** * @deprecated */ helpers$1.numberOfLabelLines = function(arrayOfThings) { var numberOfLines = 1; helpers$1.each(arrayOfThings, function(thing) { if (helpers$1.isArray(thing)) { if (thing.length > numberOfLines) { numberOfLines = thing.length; } } }); return numberOfLines; }; helpers$1.color = !chartjsColor ? function(value) { console.error('Color.js not found!'); return value; } : function(value) { /* global CanvasGradient */ if (value instanceof CanvasGradient) { value = core_defaults.global.defaultColor; } return chartjsColor(value); }; helpers$1.getHoverColor = function(colorValue) { /* global CanvasPattern */ return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ? colorValue : helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString(); }; }; function abstract() { throw new Error( 'This method is not implemented: either no adapter can ' + 'be found or an incomplete integration was provided.' ); } /** * Date adapter (current used by the time scale) * @namespace Chart._adapters._date * @memberof Chart._adapters * @private */ /** * Currently supported unit string values. * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')} * @memberof Chart._adapters._date * @name Unit */ /** * @class */ function DateAdapter(options) { this.options = options || {}; } helpers$1.extend(DateAdapter.prototype, /** @lends DateAdapter */ { /** * Returns a map of time formats for the supported formatting units defined * in Unit as well as 'datetime' representing a detailed date/time string. * @returns {{string: string}} */ formats: abstract, /** * Parses the given `value` and return the associated timestamp. * @param {any} value - the value to parse (usually comes from the data) * @param {string} [format] - the expected data format * @returns {(number|null)} * @function */ parse: abstract, /** * Returns the formatted date in the specified `format` for a given `timestamp`. * @param {number} timestamp - the timestamp to format * @param {string} format - the date/time token * @return {string} * @function */ format: abstract, /** * Adds the specified `amount` of `unit` to the given `timestamp`. * @param {number} timestamp - the input timestamp * @param {number} amount - the amount to add * @param {Unit} unit - the unit as string * @return {number} * @function */ add: abstract, /** * Returns the number of `unit` between the given timestamps. * @param {number} max - the input timestamp (reference) * @param {number} min - the timestamp to substract * @param {Unit} unit - the unit as string * @return {number} * @function */ diff: abstract, /** * Returns start of `unit` for the given `timestamp`. * @param {number} timestamp - the input timestamp * @param {Unit} unit - the unit as string * @param {number} [weekday] - the ISO day of the week with 1 being Monday * and 7 being Sunday (only needed if param *unit* is `isoWeek`). * @function */ startOf: abstract, /** * Returns end of `unit` for the given `timestamp`. * @param {number} timestamp - the input timestamp * @param {Unit} unit - the unit as string * @function */ endOf: abstract, // DEPRECATIONS /** * Provided for backward compatibility for scale.getValueForPixel(), * this method should be overridden only by the moment adapter. * @deprecated since version 2.8.0 * @todo remove at version 3 * @private */ _create: function(value) { return value; } }); DateAdapter.override = function(members) { helpers$1.extend(DateAdapter.prototype, members); }; var _date = DateAdapter; var core_adapters = { _date: _date }; /** * Namespace to hold static tick generation functions * @namespace Chart.Ticks */ var core_ticks = { /** * Namespace to hold formatters for different types of ticks * @namespace Chart.Ticks.formatters */ formatters: { /** * Formatter for value labels * @method Chart.Ticks.formatters.values * @param value the value to display * @return {string|string[]} the label to display */ values: function(value) { return helpers$1.isArray(value) ? value : '' + value; }, /** * Formatter for linear numeric ticks * @method Chart.Ticks.formatters.linear * @param tickValue {number} the value to be formatted * @param index {number} the position of the tickValue parameter in the ticks array * @param ticks {number[]} the list of ticks being converted * @return {string} string representation of the tickValue parameter */ linear: function(tickValue, index, ticks) { // If we have lots of ticks, don't use the ones var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0]; // If we have a number like 2.5 as the delta, figure out how many decimal places we need if (Math.abs(delta) > 1) { if (tickValue !== Math.floor(tickValue)) { // not an integer delta = tickValue - Math.floor(tickValue); } } var logDelta = helpers$1.log10(Math.abs(delta)); var tickString = ''; if (tickValue !== 0) { var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1])); if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation var logTick = helpers$1.log10(Math.abs(tickValue)); var numExponential = Math.floor(logTick) - Math.floor(logDelta); numExponential = Math.max(Math.min(numExponential, 20), 0); tickString = tickValue.toExponential(numExponential); } else { var numDecimal = -1 * Math.floor(logDelta); numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places tickString = tickValue.toFixed(numDecimal); } } else { tickString = '0'; // never show decimal places for 0 } return tickString; }, logarithmic: function(tickValue, index, ticks) { var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue)))); if (tickValue === 0) { return '0'; } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) { return tickValue.toExponential(); } return ''; } } }; var isArray = helpers$1.isArray; var isNullOrUndef = helpers$1.isNullOrUndef; var valueOrDefault$a = helpers$1.valueOrDefault; var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault; core_defaults._set('scale', { display: true, position: 'left', offset: false, // grid line settings gridLines: { display: true, color: 'rgba(0,0,0,0.1)', lineWidth: 1, drawBorder: true, drawOnChartArea: true, drawTicks: true, tickMarkLength: 10, zeroLineWidth: 1, zeroLineColor: 'rgba(0,0,0,0.25)', zeroLineBorderDash: [], zeroLineBorderDashOffset: 0.0, offsetGridLines: false, borderDash: [], borderDashOffset: 0.0 }, // scale label scaleLabel: { // display property display: false, // actual label labelString: '', // top/bottom padding padding: { top: 4, bottom: 4 } }, // label settings ticks: { beginAtZero: false, minRotation: 0, maxRotation: 50, mirror: false, padding: 0, reverse: false, display: true, autoSkip: true, autoSkipPadding: 0, labelOffset: 0, // We pass through arrays to be rendered as multiline labels, we convert Others to strings here. callback: core_ticks.formatters.values, minor: {}, major: {} } }); /** Returns a new array containing numItems from arr */ function sample(arr, numItems) { var result = []; var increment = arr.length / numItems; var i = 0; var len = arr.length; for (; i < len; i += increment) { result.push(arr[Math.floor(i)]); } return result; } function getPixelForGridLine(scale, index, offsetGridLines) { var length = scale.getTicks().length; var validIndex = Math.min(index, length - 1); var lineValue = scale.getPixelForTick(validIndex); var start = scale._startPixel; var end = scale._endPixel; var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error. var offset; if (offsetGridLines) { if (length === 1) { offset = Math.max(lineValue - start, end - lineValue); } else if (index === 0) { offset = (scale.getPixelForTick(1) - lineValue) / 2; } else { offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2; } lineValue += validIndex < index ? offset : -offset; // Return undefined if the pixel is out of the range if (lineValue < start - epsilon || lineValue > end + epsilon) { return; } } return lineValue; } function garbageCollect(caches, length) { helpers$1.each(caches, function(cache) { var gc = cache.gc; var gcLen = gc.length / 2; var i; if (gcLen > length) { for (i = 0; i < gcLen; ++i) { delete cache.data[gc[i]]; } gc.splice(0, gcLen); } }); } /** * Returns {width, height, offset} objects for the first, last, widest, highest tick * labels where offset indicates the anchor point offset from the top in pixels. */ function computeLabelSizes(ctx, tickFonts, ticks, caches) { var length = ticks.length; var widths = []; var heights = []; var offsets = []; var i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel, widest, highest; for (i = 0; i < length; ++i) { label = ticks[i].label; tickFont = ticks[i].major ? tickFonts.major : tickFonts.minor; ctx.font = fontString = tickFont.string; cache = caches[fontString] = caches[fontString] || {data: {}, gc: []}; lineHeight = tickFont.lineHeight; width = height = 0; // Undefined labels and arrays should not be measured if (!isNullOrUndef(label) && !isArray(label)) { width = helpers$1.measureText(ctx, cache.data, cache.gc, width, label); height = lineHeight; } else if (isArray(label)) { // if it is an array let's measure each element for (j = 0, jlen = label.length; j < jlen; ++j) { nestedLabel = label[j]; // Undefined labels and arrays should not be measured if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) { width = helpers$1.measureText(ctx, cache.data, cache.gc, width, nestedLabel); height += lineHeight; } } } widths.push(width); heights.push(height); offsets.push(lineHeight / 2); } garbageCollect(caches, length); widest = widths.indexOf(Math.max.apply(null, widths)); highest = heights.indexOf(Math.max.apply(null, heights)); function valueAt(idx) { return { width: widths[idx] || 0, height: heights[idx] || 0, offset: offsets[idx] || 0 }; } return { first: valueAt(0), last: valueAt(length - 1), widest: valueAt(widest), highest: valueAt(highest) }; } function getTickMarkLength(options) { return options.drawTicks ? options.tickMarkLength : 0; } function getScaleLabelHeight(options) { var font, padding; if (!options.display) { return 0; } font = helpers$1.options._parseFont(options); padding = helpers$1.options.toPadding(options.padding); return font.lineHeight + padding.height; } function parseFontOptions(options, nestedOpts) { return helpers$1.extend(helpers$1.options._parseFont({ fontFamily: valueOrDefault$a(nestedOpts.fontFamily, options.fontFamily), fontSize: valueOrDefault$a(nestedOpts.fontSize, options.fontSize), fontStyle: valueOrDefault$a(nestedOpts.fontStyle, options.fontStyle), lineHeight: valueOrDefault$a(nestedOpts.lineHeight, options.lineHeight) }), { color: helpers$1.options.resolve([nestedOpts.fontColor, options.fontColor, core_defaults.global.defaultFontColor]) }); } function parseTickFontOptions(options) { var minor = parseFontOptions(options, options.minor); var major = options.major.enabled ? parseFontOptions(options, options.major) : minor; return {minor: minor, major: major}; } function nonSkipped(ticksToFilter) { var filtered = []; var item, index, len; for (index = 0, len = ticksToFilter.length; index < len; ++index) { item = ticksToFilter[index]; if (typeof item._index !== 'undefined') { filtered.push(item); } } return filtered; } function getEvenSpacing(arr) { var len = arr.length; var i, diff; if (len < 2) { return false; } for (diff = arr[0], i = 1; i < len; ++i) { if (arr[i] - arr[i - 1] !== diff) { return false; } } return diff; } function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) { var evenMajorSpacing = getEvenSpacing(majorIndices); var spacing = (ticks.length - 1) / ticksLimit; var factors, factor, i, ilen; // If the major ticks are evenly spaced apart, place the minor ticks // so that they divide the major ticks into even chunks if (!evenMajorSpacing) { return Math.max(spacing, 1); } factors = helpers$1.math._factorize(evenMajorSpacing); for (i = 0, ilen = factors.length - 1; i < ilen; i++) { factor = factors[i]; if (factor > spacing) { return factor; } } return Math.max(spacing, 1); } function getMajorIndices(ticks) { var result = []; var i, ilen; for (i = 0, ilen = ticks.length; i < ilen; i++) { if (ticks[i].major) { result.push(i); } } return result; } function skipMajors(ticks, majorIndices, spacing) { var count = 0; var next = majorIndices[0]; var i, tick; spacing = Math.ceil(spacing); for (i = 0; i < ticks.length; i++) { tick = ticks[i]; if (i === next) { tick._index = i; count++; next = majorIndices[count * spacing]; } else { delete tick.label; } } } function skip(ticks, spacing, majorStart, majorEnd) { var start = valueOrDefault$a(majorStart, 0); var end = Math.min(valueOrDefault$a(majorEnd, ticks.length), ticks.length); var count = 0; var length, i, tick, next; spacing = Math.ceil(spacing); if (majorEnd) { length = majorEnd - majorStart; spacing = length / Math.floor(length / spacing); } next = start; while (next < 0) { count++; next = Math.round(start + count * spacing); } for (i = Math.max(start, 0); i < end; i++) { tick = ticks[i]; if (i === next) { tick._index = i; count++; next = Math.round(start + count * spacing); } else { delete tick.label; } } } var Scale = core_element.extend({ zeroLineIndex: 0, /** * Get the padding needed for the scale * @method getPadding * @private * @returns {Padding} the necessary padding */ getPadding: function() { var me = this; return { left: me.paddingLeft || 0, top: me.paddingTop || 0, right: me.paddingRight || 0, bottom: me.paddingBottom || 0 }; }, /** * Returns the scale tick objects ({label, major}) * @since 2.7 */ getTicks: function() { return this._ticks; }, /** * @private */ _getLabels: function() { var data = this.chart.data; return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels; }, // These methods are ordered by lifecyle. Utilities then follow. // Any function defined here is inherited by all scale types. // Any function can be extended by the scale type /** * Provided for backward compatibility, not available anymore * @function Chart.Scale.mergeTicksOptions * @deprecated since version 2.8.0 * @todo remove at version 3 */ mergeTicksOptions: function() { // noop }, beforeUpdate: function() { helpers$1.callback(this.options.beforeUpdate, [this]); }, /** * @param {number} maxWidth - the max width in pixels * @param {number} maxHeight - the max height in pixels * @param {object} margins - the space between the edge of the other scales and edge of the chart * This space comes from two sources: * - padding - space that's required to show the labels at the edges of the scale * - thickness of scales or legends in another orientation */ update: function(maxWidth, maxHeight, margins) { var me = this; var tickOpts = me.options.ticks; var sampleSize = tickOpts.sampleSize; var i, ilen, labels, ticks, samplingEnabled; // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) me.beforeUpdate(); // Absorb the master measurements me.maxWidth = maxWidth; me.maxHeight = maxHeight; me.margins = helpers$1.extend({ left: 0, right: 0, top: 0, bottom: 0 }, margins); me._ticks = null; me.ticks = null; me._labelSizes = null; me._maxLabelLines = 0; me.longestLabelWidth = 0; me.longestTextCache = me.longestTextCache || {}; me._gridLineItems = null; me._labelItems = null; // Dimensions me.beforeSetDimensions(); me.setDimensions(); me.afterSetDimensions(); // Data min/max me.beforeDataLimits(); me.determineDataLimits(); me.afterDataLimits(); // Ticks - `this.ticks` is now DEPRECATED! // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member // and must not be accessed directly from outside this class. `this.ticks` being // around for long time and not marked as private, we can't change its structure // without unexpected breaking changes. If you need to access the scale ticks, // use scale.getTicks() instead. me.beforeBuildTicks(); // New implementations should return an array of objects but for BACKWARD COMPAT, // we still support no return (`this.ticks` internally set by calling this method). ticks = me.buildTicks() || []; // Allow modification of ticks in callback. ticks = me.afterBuildTicks(ticks) || ticks; // Ensure ticks contains ticks in new tick format if ((!ticks || !ticks.length) && me.ticks) { ticks = []; for (i = 0, ilen = me.ticks.length; i < ilen; ++i) { ticks.push({ value: me.ticks[i], major: false }); } } me._ticks = ticks; // Compute tick rotation and fit using a sampled subset of labels // We generally don't need to compute the size of every single label for determining scale size samplingEnabled = sampleSize < ticks.length; labels = me._convertTicksToLabels(samplingEnabled ? sample(ticks, sampleSize) : ticks); // _configure is called twice, once here, once from core.controller.updateLayout. // Here we haven't been positioned yet, but dimensions are correct. // Variables set in _configure are needed for calculateTickRotation, and // it's ok that coordinates are not correct there, only dimensions matter. me._configure(); // Tick Rotation me.beforeCalculateTickRotation(); me.calculateTickRotation(); me.afterCalculateTickRotation(); me.beforeFit(); me.fit(); me.afterFit(); // Auto-skip me._ticksToDraw = tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto') ? me._autoSkip(ticks) : ticks; if (samplingEnabled) { // Generate labels using all non-skipped ticks labels = me._convertTicksToLabels(me._ticksToDraw); } me.ticks = labels; // BACKWARD COMPATIBILITY // IMPORTANT: after this point, we consider that `this.ticks` will NEVER change! me.afterUpdate(); // TODO(v3): remove minSize as a public property and return value from all layout boxes. It is unused // make maxWidth and maxHeight private return me.minSize; }, /** * @private */ _configure: function() { var me = this; var reversePixels = me.options.ticks.reverse; var startPixel, endPixel; if (me.isHorizontal()) { startPixel = me.left; endPixel = me.right; } else { startPixel = me.top; endPixel = me.bottom; // by default vertical scales are from bottom to top, so pixels are reversed reversePixels = !reversePixels; } me._startPixel = startPixel; me._endPixel = endPixel; me._reversePixels = reversePixels; me._length = endPixel - startPixel; }, afterUpdate: function() { helpers$1.callback(this.options.afterUpdate, [this]); }, // beforeSetDimensions: function() { helpers$1.callback(this.options.beforeSetDimensions, [this]); }, setDimensions: function() { var me = this; // Set the unconstrained dimension before label rotation if (me.isHorizontal()) { // Reset position before calculating rotation me.width = me.maxWidth; me.left = 0; me.right = me.width; } else { me.height = me.maxHeight; // Reset position before calculating rotation me.top = 0; me.bottom = me.height; } // Reset padding me.paddingLeft = 0; me.paddingTop = 0; me.paddingRight = 0; me.paddingBottom = 0; }, afterSetDimensions: function() { helpers$1.callback(this.options.afterSetDimensions, [this]); }, // Data limits beforeDataLimits: function() { helpers$1.callback(this.options.beforeDataLimits, [this]); }, determineDataLimits: helpers$1.noop, afterDataLimits: function() { helpers$1.callback(this.options.afterDataLimits, [this]); }, // beforeBuildTicks: function() { helpers$1.callback(this.options.beforeBuildTicks, [this]); }, buildTicks: helpers$1.noop, afterBuildTicks: function(ticks) { var me = this; // ticks is empty for old axis implementations here if (isArray(ticks) && ticks.length) { return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]); } // Support old implementations (that modified `this.ticks` directly in buildTicks) me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks; return ticks; }, beforeTickToLabelConversion: function() { helpers$1.callback(this.options.beforeTickToLabelConversion, [this]); }, convertTicksToLabels: function() { var me = this; // Convert ticks to strings var tickOpts = me.options.ticks; me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this); }, afterTickToLabelConversion: function() { helpers$1.callback(this.options.afterTickToLabelConversion, [this]); }, // beforeCalculateTickRotation: function() { helpers$1.callback(this.options.beforeCalculateTickRotation, [this]); }, calculateTickRotation: function() { var me = this; var options = me.options; var tickOpts = options.ticks; var numTicks = me.getTicks().length; var minRotation = tickOpts.minRotation || 0; var maxRotation = tickOpts.maxRotation; var labelRotation = minRotation; var labelSizes, maxLabelWidth, maxLabelHeight, maxWidth, tickWidth, maxHeight, maxLabelDiagonal; if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) { me.labelRotation = minRotation; return; } labelSizes = me._getLabelSizes(); maxLabelWidth = labelSizes.widest.width; maxLabelHeight = labelSizes.highest.height - labelSizes.highest.offset; // Estimate the width of each grid based on the canvas width, the maximum // label width and the number of tick intervals maxWidth = Math.min(me.maxWidth, me.chart.width - maxLabelWidth); tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1); // Allow 3 pixels x2 padding either side for label readability if (maxLabelWidth + 6 > tickWidth) { tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1)); maxHeight = me.maxHeight - getTickMarkLength(options.gridLines) - tickOpts.padding - getScaleLabelHeight(options.scaleLabel); maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight); labelRotation = helpers$1.toDegrees(Math.min( Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)), Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal) )); labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation)); } me.labelRotation = labelRotation; }, afterCalculateTickRotation: function() { helpers$1.callback(this.options.afterCalculateTickRotation, [this]); }, // beforeFit: function() { helpers$1.callback(this.options.beforeFit, [this]); }, fit: function() { var me = this; // Reset var minSize = me.minSize = { width: 0, height: 0 }; var chart = me.chart; var opts = me.options; var tickOpts = opts.ticks; var scaleLabelOpts = opts.scaleLabel; var gridLineOpts = opts.gridLines; var display = me._isVisible(); var isBottom = opts.position === 'bottom'; var isHorizontal = me.isHorizontal(); // Width if (isHorizontal) { minSize.width = me.maxWidth; } else if (display) { minSize.width = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts); } // height if (!isHorizontal) { minSize.height = me.maxHeight; // fill all the height } else if (display) { minSize.height = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts); } // Don't bother fitting the ticks if we are not showing the labels if (tickOpts.display && display) { var tickFonts = parseTickFontOptions(tickOpts); var labelSizes = me._getLabelSizes(); var firstLabelSize = labelSizes.first; var lastLabelSize = labelSizes.last; var widestLabelSize = labelSizes.widest; var highestLabelSize = labelSizes.highest; var lineSpace = tickFonts.minor.lineHeight * 0.4; var tickPadding = tickOpts.padding; if (isHorizontal) { // A horizontal axis is more constrained by the height. var isRotated = me.labelRotation !== 0; var angleRadians = helpers$1.toRadians(me.labelRotation); var cosRotation = Math.cos(angleRadians); var sinRotation = Math.sin(angleRadians); var labelHeight = sinRotation * widestLabelSize.width + cosRotation * (highestLabelSize.height - (isRotated ? highestLabelSize.offset : 0)) + (isRotated ? 0 : lineSpace); // padding minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding); var offsetLeft = me.getPixelForTick(0) - me.left; var offsetRight = me.right - me.getPixelForTick(me.getTicks().length - 1); var paddingLeft, paddingRight; // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned // which means that the right padding is dominated by the font height if (isRotated) { paddingLeft = isBottom ? cosRotation * firstLabelSize.width + sinRotation * firstLabelSize.offset : sinRotation * (firstLabelSize.height - firstLabelSize.offset); paddingRight = isBottom ? sinRotation * (lastLabelSize.height - lastLabelSize.offset) : cosRotation * lastLabelSize.width + sinRotation * lastLabelSize.offset; } else { paddingLeft = firstLabelSize.width / 2; paddingRight = lastLabelSize.width / 2; } // Adjust padding taking into account changes in offsets // and add 3 px to move away from canvas edges me.paddingLeft = Math.max((paddingLeft - offsetLeft) * me.width / (me.width - offsetLeft), 0) + 3; me.paddingRight = Math.max((paddingRight - offsetRight) * me.width / (me.width - offsetRight), 0) + 3; } else { // A vertical axis is more constrained by the width. Labels are the // dominant factor here, so get that length first and account for padding var labelWidth = tickOpts.mirror ? 0 : // use lineSpace for consistency with horizontal axis // tickPadding is not implemented for horizontal widestLabelSize.width + tickPadding + lineSpace; minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth); me.paddingTop = firstLabelSize.height / 2; me.paddingBottom = lastLabelSize.height / 2; } } me.handleMargins(); if (isHorizontal) { me.width = me._length = chart.width - me.margins.left - me.margins.right; me.height = minSize.height; } else { me.width = minSize.width; me.height = me._length = chart.height - me.margins.top - me.margins.bottom; } }, /** * Handle margins and padding interactions * @private */ handleMargins: function() { var me = this; if (me.margins) { me.margins.left = Math.max(me.paddingLeft, me.margins.left); me.margins.top = Math.max(me.paddingTop, me.margins.top); me.margins.right = Math.max(me.paddingRight, me.margins.right); me.margins.bottom = Math.max(me.paddingBottom, me.margins.bottom); } }, afterFit: function() { helpers$1.callback(this.options.afterFit, [this]); }, // Shared Methods isHorizontal: function() { var pos = this.options.position; return pos === 'top' || pos === 'bottom'; }, isFullWidth: function() { return this.options.fullWidth; }, // Get the correct value. NaN bad inputs, If the value type is object get the x or y based on whether we are horizontal or not getRightValue: function(rawValue) { // Null and undefined values first if (isNullOrUndef(rawValue)) { return NaN; } // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) { return NaN; } // If it is in fact an object, dive in one more level if (rawValue) { if (this.isHorizontal()) { if (rawValue.x !== undefined) { return this.getRightValue(rawValue.x); } } else if (rawValue.y !== undefined) { return this.getRightValue(rawValue.y); } } // Value is good, return it return rawValue; }, _convertTicksToLabels: function(ticks) { var me = this; var labels, i, ilen; me.ticks = ticks.map(function(tick) { return tick.value; }); me.beforeTickToLabelConversion(); // New implementations should return the formatted tick labels but for BACKWARD // COMPAT, we still support no return (`this.ticks` internally changed by calling // this method and supposed to contain only string values). labels = me.convertTicksToLabels(ticks) || me.ticks; me.afterTickToLabelConversion(); // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`) for (i = 0, ilen = ticks.length; i < ilen; ++i) { ticks[i].label = labels[i]; } return labels; }, /** * @private */ _getLabelSizes: function() { var me = this; var labelSizes = me._labelSizes; if (!labelSizes) { me._labelSizes = labelSizes = computeLabelSizes(me.ctx, parseTickFontOptions(me.options.ticks), me.getTicks(), me.longestTextCache); me.longestLabelWidth = labelSizes.widest.width; } return labelSizes; }, /** * @private */ _parseValue: function(value) { var start, end, min, max; if (isArray(value)) { start = +this.getRightValue(value[0]); end = +this.getRightValue(value[1]); min = Math.min(start, end); max = Math.max(start, end); } else { value = +this.getRightValue(value); start = undefined; end = value; min = value; max = value; } return { min: min, max: max, start: start, end: end }; }, /** * @private */ _getScaleLabel: function(rawValue) { var v = this._parseValue(rawValue); if (v.start !== undefined) { return '[' + v.start + ', ' + v.end + ']'; } return +this.getRightValue(rawValue); }, /** * Used to get the value to display in the tooltip for the data at the given index * @param index * @param datasetIndex */ getLabelForIndex: helpers$1.noop, /** * Returns the location of the given data point. Value can either be an index or a numerical value * The coordinate (0, 0) is at the upper-left corner of the canvas * @param value * @param index * @param datasetIndex */ getPixelForValue: helpers$1.noop, /** * Used to get the data value from a given pixel. This is the inverse of getPixelForValue * The coordinate (0, 0) is at the upper-left corner of the canvas * @param pixel */ getValueForPixel: helpers$1.noop, /** * Returns the location of the tick at the given index * The coordinate (0, 0) is at the upper-left corner of the canvas */ getPixelForTick: function(index) { var me = this; var offset = me.options.offset; var numTicks = me._ticks.length; var tickWidth = 1 / Math.max(numTicks - (offset ? 0 : 1), 1); return index < 0 || index > numTicks - 1 ? null : me.getPixelForDecimal(index * tickWidth + (offset ? tickWidth / 2 : 0)); }, /** * Utility for getting the pixel location of a percentage of scale * The coordinate (0, 0) is at the upper-left corner of the canvas */ getPixelForDecimal: function(decimal) { var me = this; if (me._reversePixels) { decimal = 1 - decimal; } return me._startPixel + decimal * me._length; }, getDecimalForPixel: function(pixel) { var decimal = (pixel - this._startPixel) / this._length; return this._reversePixels ? 1 - decimal : decimal; }, /** * Returns the pixel for the minimum chart value * The coordinate (0, 0) is at the upper-left corner of the canvas */ getBasePixel: function() { return this.getPixelForValue(this.getBaseValue()); }, getBaseValue: function() { var me = this; var min = me.min; var max = me.max; return me.beginAtZero ? 0 : min < 0 && max < 0 ? max : min > 0 && max > 0 ? min : 0; }, /** * Returns a subset of ticks to be plotted to avoid overlapping labels. * @private */ _autoSkip: function(ticks) { var me = this; var tickOpts = me.options.ticks; var axisLength = me._length; var ticksLimit = tickOpts.maxTicksLimit || axisLength / me._tickSize() + 1; var majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : []; var numMajorIndices = majorIndices.length; var first = majorIndices[0]; var last = majorIndices[numMajorIndices - 1]; var i, ilen, spacing, avgMajorSpacing; // If there are too many major ticks to display them all if (numMajorIndices > ticksLimit) { skipMajors(ticks, majorIndices, numMajorIndices / ticksLimit); return nonSkipped(ticks); } spacing = calculateSpacing(majorIndices, ticks, axisLength, ticksLimit); if (numMajorIndices > 0) { for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) { skip(ticks, spacing, majorIndices[i], majorIndices[i + 1]); } avgMajorSpacing = numMajorIndices > 1 ? (last - first) / (numMajorIndices - 1) : null; skip(ticks, spacing, helpers$1.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first); skip(ticks, spacing, last, helpers$1.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing); return nonSkipped(ticks); } skip(ticks, spacing); return nonSkipped(ticks); }, /** * @private */ _tickSize: function() { var me = this; var optionTicks = me.options.ticks; // Calculate space needed by label in axis direction. var rot = helpers$1.toRadians(me.labelRotation); var cos = Math.abs(Math.cos(rot)); var sin = Math.abs(Math.sin(rot)); var labelSizes = me._getLabelSizes(); var padding = optionTicks.autoSkipPadding || 0; var w = labelSizes ? labelSizes.widest.width + padding : 0; var h = labelSizes ? labelSizes.highest.height + padding : 0; // Calculate space needed for 1 tick in axis direction. return me.isHorizontal() ? h * cos > w * sin ? w / cos : h / sin : h * sin < w * cos ? h / cos : w / sin; }, /** * @private */ _isVisible: function() { var me = this; var chart = me.chart; var display = me.options.display; var i, ilen, meta; if (display !== 'auto') { return !!display; } // When 'auto', the scale is visible if at least one associated dataset is visible. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) { if (chart.isDatasetVisible(i)) { meta = chart.getDatasetMeta(i); if (meta.xAxisID === me.id || meta.yAxisID === me.id) { return true; } } } return false; }, /** * @private */ _computeGridLineItems: function(chartArea) { var me = this; var chart = me.chart; var options = me.options; var gridLines = options.gridLines; var position = options.position; var offsetGridLines = gridLines.offsetGridLines; var isHorizontal = me.isHorizontal(); var ticks = me._ticksToDraw; var ticksLength = ticks.length + (offsetGridLines ? 1 : 0); var tl = getTickMarkLength(gridLines); var items = []; var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0; var axisHalfWidth = axisWidth / 2; var alignPixel = helpers$1._alignPixel; var alignBorderValue = function(pixel) { return alignPixel(chart, pixel, axisWidth); }; var borderValue, i, tick, lineValue, alignedLineValue; var tx1, ty1, tx2, ty2, x1, y1, x2, y2, lineWidth, lineColor, borderDash, borderDashOffset; if (position === 'top') { borderValue = alignBorderValue(me.bottom); ty1 = me.bottom - tl; ty2 = borderValue - axisHalfWidth; y1 = alignBorderValue(chartArea.top) + axisHalfWidth; y2 = chartArea.bottom; } else if (position === 'bottom') { borderValue = alignBorderValue(me.top); y1 = chartArea.top; y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth; ty1 = borderValue + axisHalfWidth; ty2 = me.top + tl; } else if (position === 'left') { borderValue = alignBorderValue(me.right); tx1 = me.right - tl; tx2 = borderValue - axisHalfWidth; x1 = alignBorderValue(chartArea.left) + axisHalfWidth; x2 = chartArea.right; } else { borderValue = alignBorderValue(me.left); x1 = chartArea.left; x2 = alignBorderValue(chartArea.right) - axisHalfWidth; tx1 = borderValue + axisHalfWidth; tx2 = me.left + tl; } for (i = 0; i < ticksLength; ++i) { tick = ticks[i] || {}; // autoskipper skipped this tick (#4635) if (isNullOrUndef(tick.label) && i < ticks.length) { continue; } if (i === me.zeroLineIndex && options.offset === offsetGridLines) { // Draw the first index specially lineWidth = gridLines.zeroLineWidth; lineColor = gridLines.zeroLineColor; borderDash = gridLines.zeroLineBorderDash || []; borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0; } else { lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, i, 1); lineColor = valueAtIndexOrDefault(gridLines.color, i, 'rgba(0,0,0,0.1)'); borderDash = gridLines.borderDash || []; borderDashOffset = gridLines.borderDashOffset || 0.0; } lineValue = getPixelForGridLine(me, tick._index || i, offsetGridLines); // Skip if the pixel is out of the range if (lineValue === undefined) { continue; } alignedLineValue = alignPixel(chart, lineValue, lineWidth); if (isHorizontal) { tx1 = tx2 = x1 = x2 = alignedLineValue; } else { ty1 = ty2 = y1 = y2 = alignedLineValue; } items.push({ tx1: tx1, ty1: ty1, tx2: tx2, ty2: ty2, x1: x1, y1: y1, x2: x2, y2: y2, width: lineWidth, color: lineColor, borderDash: borderDash, borderDashOffset: borderDashOffset, }); } items.ticksLength = ticksLength; items.borderValue = borderValue; return items; }, /** * @private */ _computeLabelItems: function() { var me = this; var options = me.options; var optionTicks = options.ticks; var position = options.position; var isMirrored = optionTicks.mirror; var isHorizontal = me.isHorizontal(); var ticks = me._ticksToDraw; var fonts = parseTickFontOptions(optionTicks); var tickPadding = optionTicks.padding; var tl = getTickMarkLength(options.gridLines); var rotation = -helpers$1.toRadians(me.labelRotation); var items = []; var i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset; if (position === 'top') { y = me.bottom - tl - tickPadding; textAlign = !rotation ? 'center' : 'left'; } else if (position === 'bottom') { y = me.top + tl + tickPadding; textAlign = !rotation ? 'center' : 'right'; } else if (position === 'left') { x = me.right - (isMirrored ? 0 : tl) - tickPadding; textAlign = isMirrored ? 'left' : 'right'; } else { x = me.left + (isMirrored ? 0 : tl) + tickPadding; textAlign = isMirrored ? 'right' : 'left'; } for (i = 0, ilen = ticks.length; i < ilen; ++i) { tick = ticks[i]; label = tick.label; // autoskipper skipped this tick (#4635) if (isNullOrUndef(label)) { continue; } pixel = me.getPixelForTick(tick._index || i) + optionTicks.labelOffset; font = tick.major ? fonts.major : fonts.minor; lineHeight = font.lineHeight; lineCount = isArray(label) ? label.length : 1; if (isHorizontal) { x = pixel; textOffset = position === 'top' ? ((!rotation ? 0.5 : 1) - lineCount) * lineHeight : (!rotation ? 0.5 : 0) * lineHeight; } else { y = pixel; textOffset = (1 - lineCount) * lineHeight / 2; } items.push({ x: x, y: y, rotation: rotation, label: label, font: font, textOffset: textOffset, textAlign: textAlign }); } return items; }, /** * @private */ _drawGrid: function(chartArea) { var me = this; var gridLines = me.options.gridLines; if (!gridLines.display) { return; } var ctx = me.ctx; var chart = me.chart; var alignPixel = helpers$1._alignPixel; var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0; var items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea)); var width, color, i, ilen, item; for (i = 0, ilen = items.length; i < ilen; ++i) { item = items[i]; width = item.width; color = item.color; if (width && color) { ctx.save(); ctx.lineWidth = width; ctx.strokeStyle = color; if (ctx.setLineDash) { ctx.setLineDash(item.borderDash); ctx.lineDashOffset = item.borderDashOffset; } ctx.beginPath(); if (gridLines.drawTicks) { ctx.moveTo(item.tx1, item.ty1); ctx.lineTo(item.tx2, item.ty2); } if (gridLines.drawOnChartArea) { ctx.moveTo(item.x1, item.y1); ctx.lineTo(item.x2, item.y2); } ctx.stroke(); ctx.restore(); } } if (axisWidth) { // Draw the line at the edge of the axis var firstLineWidth = axisWidth; var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, items.ticksLength - 1, 1); var borderValue = items.borderValue; var x1, x2, y1, y2; if (me.isHorizontal()) { x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2; x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2; y1 = y2 = borderValue; } else { y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2; y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2; x1 = x2 = borderValue; } ctx.lineWidth = axisWidth; ctx.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0); ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); } }, /** * @private */ _drawLabels: function() { var me = this; var optionTicks = me.options.ticks; if (!optionTicks.display) { return; } var ctx = me.ctx; var items = me._labelItems || (me._labelItems = me._computeLabelItems()); var i, j, ilen, jlen, item, tickFont, label, y; for (i = 0, ilen = items.length; i < ilen; ++i) { item = items[i]; tickFont = item.font; // Make sure we draw text in the correct color and font ctx.save(); ctx.translate(item.x, item.y); ctx.rotate(item.rotation); ctx.font = tickFont.string; ctx.fillStyle = tickFont.color; ctx.textBaseline = 'middle'; ctx.textAlign = item.textAlign; label = item.label; y = item.textOffset; if (isArray(label)) { for (j = 0, jlen = label.length; j < jlen; ++j) { // We just make sure the multiline element is a string here.. ctx.fillText('' + label[j], 0, y); y += tickFont.lineHeight; } } else { ctx.fillText(label, 0, y); } ctx.restore(); } }, /** * @private */ _drawTitle: function() { var me = this; var ctx = me.ctx; var options = me.options; var scaleLabel = options.scaleLabel; if (!scaleLabel.display) { return; } var scaleLabelFontColor = valueOrDefault$a(scaleLabel.fontColor, core_defaults.global.defaultFontColor); var scaleLabelFont = helpers$1.options._parseFont(scaleLabel); var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding); var halfLineHeight = scaleLabelFont.lineHeight / 2; var position = options.position; var rotation = 0; var scaleLabelX, scaleLabelY; if (me.isHorizontal()) { scaleLabelX = me.left + me.width / 2; // midpoint of the width scaleLabelY = position === 'bottom' ? me.bottom - halfLineHeight - scaleLabelPadding.bottom : me.top + halfLineHeight + scaleLabelPadding.top; } else { var isLeft = position === 'left'; scaleLabelX = isLeft ? me.left + halfLineHeight + scaleLabelPadding.top : me.right - halfLineHeight - scaleLabelPadding.top; scaleLabelY = me.top + me.height / 2; rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI; } ctx.save(); ctx.translate(scaleLabelX, scaleLabelY); ctx.rotate(rotation); ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillStyle = scaleLabelFontColor; // render in correct colour ctx.font = scaleLabelFont.string; ctx.fillText(scaleLabel.labelString, 0, 0); ctx.restore(); }, draw: function(chartArea) { var me = this; if (!me._isVisible()) { return; } me._drawGrid(chartArea); me._drawTitle(); me._drawLabels(); }, /** * @private */ _layers: function() { var me = this; var opts = me.options; var tz = opts.ticks && opts.ticks.z || 0; var gz = opts.gridLines && opts.gridLines.z || 0; if (!me._isVisible() || tz === gz || me.draw !== me._draw) { // backward compatibility: draw has been overridden by custom scale return [{ z: tz, draw: function() { me.draw.apply(me, arguments); } }]; } return [{ z: gz, draw: function() { me._drawGrid.apply(me, arguments); me._drawTitle.apply(me, arguments); } }, { z: tz, draw: function() { me._drawLabels.apply(me, arguments); } }]; }, /** * @private */ _getMatchingVisibleMetas: function(type) { var me = this; var isHorizontal = me.isHorizontal(); return me.chart._getSortedVisibleDatasetMetas() .filter(function(meta) { return (!type || meta.type === type) && (isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id); }); } }); Scale.prototype._draw = Scale.prototype.draw; var core_scale = Scale; var isNullOrUndef$1 = helpers$1.isNullOrUndef; var defaultConfig = { position: 'bottom' }; var scale_category = core_scale.extend({ determineDataLimits: function() { var me = this; var labels = me._getLabels(); var ticksOpts = me.options.ticks; var min = ticksOpts.min; var max = ticksOpts.max; var minIndex = 0; var maxIndex = labels.length - 1; var findIndex; if (min !== undefined) { // user specified min value findIndex = labels.indexOf(min); if (findIndex >= 0) { minIndex = findIndex; } } if (max !== undefined) { // user specified max value findIndex = labels.indexOf(max); if (findIndex >= 0) { maxIndex = findIndex; } } me.minIndex = minIndex; me.maxIndex = maxIndex; me.min = labels[minIndex]; me.max = labels[maxIndex]; }, buildTicks: function() { var me = this; var labels = me._getLabels(); var minIndex = me.minIndex; var maxIndex = me.maxIndex; // If we are viewing some subset of labels, slice the original array me.ticks = (minIndex === 0 && maxIndex === labels.length - 1) ? labels : labels.slice(minIndex, maxIndex + 1); }, getLabelForIndex: function(index, datasetIndex) { var me = this; var chart = me.chart; if (chart.getDatasetMeta(datasetIndex).controller._getValueScaleId() === me.id) { return me.getRightValue(chart.data.datasets[datasetIndex].data[index]); } return me._getLabels()[index]; }, _configure: function() { var me = this; var offset = me.options.offset; var ticks = me.ticks; core_scale.prototype._configure.call(me); if (!me.isHorizontal()) { // For backward compatibility, vertical categories scale reverse is inverted. me._reversePixels = !me._reversePixels; } if (!ticks) { return; } me._startValue = me.minIndex - (offset ? 0.5 : 0); me._valueRange = Math.max(ticks.length - (offset ? 0 : 1), 1); }, // Used to get data value locations. Value can either be an index or a numerical value getPixelForValue: function(value, index, datasetIndex) { var me = this; var valueCategory, labels, idx; if (!isNullOrUndef$1(index) && !isNullOrUndef$1(datasetIndex)) { value = me.chart.data.datasets[datasetIndex].data[index]; } // If value is a data object, then index is the index in the data array, // not the index of the scale. We need to change that. if (!isNullOrUndef$1(value)) { valueCategory = me.isHorizontal() ? value.x : value.y; } if (valueCategory !== undefined || (value !== undefined && isNaN(index))) { labels = me._getLabels(); value = helpers$1.valueOrDefault(valueCategory, value); idx = labels.indexOf(value); index = idx !== -1 ? idx : index; if (isNaN(index)) { index = value; } } return me.getPixelForDecimal((index - me._startValue) / me._valueRange); }, getPixelForTick: function(index) { var ticks = this.ticks; return index < 0 || index > ticks.length - 1 ? null : this.getPixelForValue(ticks[index], index + this.minIndex); }, getValueForPixel: function(pixel) { var me = this; var value = Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange); return Math.min(Math.max(value, 0), me.ticks.length - 1); }, getBasePixel: function() { return this.bottom; } }); // INTERNAL: static default options, registered in src/index.js var _defaults = defaultConfig; scale_category._defaults = _defaults; var noop = helpers$1.noop; var isNullOrUndef$2 = helpers$1.isNullOrUndef; /** * Generate a set of linear ticks * @param generationOptions the options used to generate the ticks * @param dataRange the range of the data * @returns {number[]} array of tick values */ function generateTicks(generationOptions, dataRange) { var ticks = []; // To get a "nice" value for the tick spacing, we will use the appropriately named // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks // for details. var MIN_SPACING = 1e-14; var stepSize = generationOptions.stepSize; var unit = stepSize || 1; var maxNumSpaces = generationOptions.maxTicks - 1; var min = generationOptions.min; var max = generationOptions.max; var precision = generationOptions.precision; var rmin = dataRange.min; var rmax = dataRange.max; var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit; var factor, niceMin, niceMax, numSpaces; // Beyond MIN_SPACING floating point numbers being to lose precision // such that we can't do the math necessary to generate ticks if (spacing < MIN_SPACING && isNullOrUndef$2(min) && isNullOrUndef$2(max)) { return [rmin, rmax]; } numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing); if (numSpaces > maxNumSpaces) { // If the calculated num of spaces exceeds maxNumSpaces, recalculate it spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit; } if (stepSize || isNullOrUndef$2(precision)) { // If a precision is not specified, calculate factor based on spacing factor = Math.pow(10, helpers$1._decimalPlaces(spacing)); } else { // If the user specified a precision, round to that number of decimal places factor = Math.pow(10, precision); spacing = Math.ceil(spacing * factor) / factor; } niceMin = Math.floor(rmin / spacing) * spacing; niceMax = Math.ceil(rmax / spacing) * spacing; // If min, max and stepSize is set and they make an evenly spaced scale use it. if (stepSize) { // If very close to our whole number, use it. if (!isNullOrUndef$2(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) { niceMin = min; } if (!isNullOrUndef$2(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) { niceMax = max; } } numSpaces = (niceMax - niceMin) / spacing; // If very close to our rounded value, use it. if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) { numSpaces = Math.round(numSpaces); } else { numSpaces = Math.ceil(numSpaces); } niceMin = Math.round(niceMin * factor) / factor; niceMax = Math.round(niceMax * factor) / factor; ticks.push(isNullOrUndef$2(min) ? niceMin : min); for (var j = 1; j < numSpaces; ++j) { ticks.push(Math.round((niceMin + j * spacing) * factor) / factor); } ticks.push(isNullOrUndef$2(max) ? niceMax : max); return ticks; } var scale_linearbase = core_scale.extend({ getRightValue: function(value) { if (typeof value === 'string') { return +value; } return core_scale.prototype.getRightValue.call(this, value); }, handleTickRangeOptions: function() { var me = this; var opts = me.options; var tickOpts = opts.ticks; // If we are forcing it to begin at 0, but 0 will already be rendered on the chart, // do nothing since that would make the chart weird. If the user really wants a weird chart // axis, they can manually override it if (tickOpts.beginAtZero) { var minSign = helpers$1.sign(me.min); var maxSign = helpers$1.sign(me.max); if (minSign < 0 && maxSign < 0) { // move the top up to 0 me.max = 0; } else if (minSign > 0 && maxSign > 0) { // move the bottom down to 0 me.min = 0; } } var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined; var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined; if (tickOpts.min !== undefined) { me.min = tickOpts.min; } else if (tickOpts.suggestedMin !== undefined) { if (me.min === null) { me.min = tickOpts.suggestedMin; } else { me.min = Math.min(me.min, tickOpts.suggestedMin); } } if (tickOpts.max !== undefined) { me.max = tickOpts.max; } else if (tickOpts.suggestedMax !== undefined) { if (me.max === null) { me.max = tickOpts.suggestedMax; } else { me.max = Math.max(me.max, tickOpts.suggestedMax); } } if (setMin !== setMax) { // We set the min or the max but not both. // So ensure that our range is good // Inverted or 0 length range can happen when // ticks.min is set, and no datasets are visible if (me.min >= me.max) { if (setMin) { me.max = me.min + 1; } else { me.min = me.max - 1; } } } if (me.min === me.max) { me.max++; if (!tickOpts.beginAtZero) { me.min--; } } }, getTickLimit: function() { var me = this; var tickOpts = me.options.ticks; var stepSize = tickOpts.stepSize; var maxTicksLimit = tickOpts.maxTicksLimit; var maxTicks; if (stepSize) { maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1; } else { maxTicks = me._computeTickLimit(); maxTicksLimit = maxTicksLimit || 11; } if (maxTicksLimit) { maxTicks = Math.min(maxTicksLimit, maxTicks); } return maxTicks; }, _computeTickLimit: function() { return Number.POSITIVE_INFINITY; }, handleDirectionalChanges: noop, buildTicks: function() { var me = this; var opts = me.options; var tickOpts = opts.ticks; // Figure out what the max number of ticks we can support it is based on the size of // the axis area. For now, we say that the minimum tick spacing in pixels must be 40 // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on // the graph. Make sure we always have at least 2 ticks var maxTicks = me.getTickLimit(); maxTicks = Math.max(2, maxTicks); var numericGeneratorOptions = { maxTicks: maxTicks, min: tickOpts.min, max: tickOpts.max, precision: tickOpts.precision, stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize) }; var ticks = me.ticks = generateTicks(numericGeneratorOptions, me); me.handleDirectionalChanges(); // At this point, we need to update our max and min given the tick values since we have expanded the // range of the scale me.max = helpers$1.max(ticks); me.min = helpers$1.min(ticks); if (tickOpts.reverse) { ticks.reverse(); me.start = me.max; me.end = me.min; } else { me.start = me.min; me.end = me.max; } }, convertTicksToLabels: function() { var me = this; me.ticksAsNumbers = me.ticks.slice(); me.zeroLineIndex = me.ticks.indexOf(0); core_scale.prototype.convertTicksToLabels.call(me); }, _configure: function() { var me = this; var ticks = me.getTicks(); var start = me.min; var end = me.max; var offset; core_scale.prototype._configure.call(me); if (me.options.offset && ticks.length) { offset = (end - start) / Math.max(ticks.length - 1, 1) / 2; start -= offset; end += offset; } me._startValue = start; me._endValue = end; me._valueRange = end - start; } }); var defaultConfig$1 = { position: 'left', ticks: { callback: core_ticks.formatters.linear } }; var DEFAULT_MIN = 0; var DEFAULT_MAX = 1; function getOrCreateStack(stacks, stacked, meta) { var key = [ meta.type, // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined stacked === undefined && meta.stack === undefined ? meta.index : '', meta.stack ].join('.'); if (stacks[key] === undefined) { stacks[key] = { pos: [], neg: [] }; } return stacks[key]; } function stackData(scale, stacks, meta, data) { var opts = scale.options; var stacked = opts.stacked; var stack = getOrCreateStack(stacks, stacked, meta); var pos = stack.pos; var neg = stack.neg; var ilen = data.length; var i, value; for (i = 0; i < ilen; ++i) { value = scale._parseValue(data[i]); if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) { continue; } pos[i] = pos[i] || 0; neg[i] = neg[i] || 0; if (opts.relativePoints) { pos[i] = 100; } else if (value.min < 0 || value.max < 0) { neg[i] += value.min; } else { pos[i] += value.max; } } } function updateMinMax(scale, meta, data) { var ilen = data.length; var i, value; for (i = 0; i < ilen; ++i) { value = scale._parseValue(data[i]); if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) { continue; } scale.min = Math.min(scale.min, value.min); scale.max = Math.max(scale.max, value.max); } } var scale_linear = scale_linearbase.extend({ determineDataLimits: function() { var me = this; var opts = me.options; var chart = me.chart; var datasets = chart.data.datasets; var metasets = me._getMatchingVisibleMetas(); var hasStacks = opts.stacked; var stacks = {}; var ilen = metasets.length; var i, meta, data, values; me.min = Number.POSITIVE_INFINITY; me.max = Number.NEGATIVE_INFINITY; if (hasStacks === undefined) { for (i = 0; !hasStacks && i < ilen; ++i) { meta = metasets[i]; hasStacks = meta.stack !== undefined; } } for (i = 0; i < ilen; ++i) { meta = metasets[i]; data = datasets[meta.index].data; if (hasStacks) { stackData(me, stacks, meta, data); } else { updateMinMax(me, meta, data); } } helpers$1.each(stacks, function(stackValues) { values = stackValues.pos.concat(stackValues.neg); me.min = Math.min(me.min, helpers$1.min(values)); me.max = Math.max(me.max, helpers$1.max(values)); }); me.min = helpers$1.isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN; me.max = helpers$1.isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX; // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero me.handleTickRangeOptions(); }, // Returns the maximum number of ticks based on the scale dimension _computeTickLimit: function() { var me = this; var tickFont; if (me.isHorizontal()) { return Math.ceil(me.width / 40); } tickFont = helpers$1.options._parseFont(me.options.ticks); return Math.ceil(me.height / tickFont.lineHeight); }, // Called after the ticks are built. We need handleDirectionalChanges: function() { if (!this.isHorizontal()) { // We are in a vertical orientation. The top value is the highest. So reverse the array this.ticks.reverse(); } }, getLabelForIndex: function(index, datasetIndex) { return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]); }, // Utils getPixelForValue: function(value) { var me = this; return me.getPixelForDecimal((+me.getRightValue(value) - me._startValue) / me._valueRange); }, getValueForPixel: function(pixel) { return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange; }, getPixelForTick: function(index) { var ticks = this.ticksAsNumbers; if (index < 0 || index > ticks.length - 1) { return null; } return this.getPixelForValue(ticks[index]); } }); // INTERNAL: static default options, registered in src/index.js var _defaults$1 = defaultConfig$1; scale_linear._defaults = _defaults$1; var valueOrDefault$b = helpers$1.valueOrDefault; var log10 = helpers$1.math.log10; /** * Generate a set of logarithmic ticks * @param generationOptions the options used to generate the ticks * @param dataRange the range of the data * @returns {number[]} array of tick values */ function generateTicks$1(generationOptions, dataRange) { var ticks = []; var tickVal = valueOrDefault$b(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min)))); var endExp = Math.floor(log10(dataRange.max)); var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp)); var exp, significand; if (tickVal === 0) { exp = Math.floor(log10(dataRange.minNotZero)); significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp)); ticks.push(tickVal); tickVal = significand * Math.pow(10, exp); } else { exp = Math.floor(log10(tickVal)); significand = Math.floor(tickVal / Math.pow(10, exp)); } var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1; do { ticks.push(tickVal); ++significand; if (significand === 10) { significand = 1; ++exp; precision = exp >= 0 ? 1 : precision; } tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision; } while (exp < endExp || (exp === endExp && significand < endSignificand)); var lastTick = valueOrDefault$b(generationOptions.max, tickVal); ticks.push(lastTick); return ticks; } var defaultConfig$2 = { position: 'left', // label settings ticks: { callback: core_ticks.formatters.logarithmic } }; // TODO(v3): change this to positiveOrDefault function nonNegativeOrDefault(value, defaultValue) { return helpers$1.isFinite(value) && value >= 0 ? value : defaultValue; } var scale_logarithmic = core_scale.extend({ determineDataLimits: function() { var me = this; var opts = me.options; var chart = me.chart; var datasets = chart.data.datasets; var isHorizontal = me.isHorizontal(); function IDMatches(meta) { return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id; } var datasetIndex, meta, value, data, i, ilen; // Calculate Range me.min = Number.POSITIVE_INFINITY; me.max = Number.NEGATIVE_INFINITY; me.minNotZero = Number.POSITIVE_INFINITY; var hasStacks = opts.stacked; if (hasStacks === undefined) { for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) { meta = chart.getDatasetMeta(datasetIndex); if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) && meta.stack !== undefined) { hasStacks = true; break; } } } if (opts.stacked || hasStacks) { var valuesPerStack = {}; for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) { meta = chart.getDatasetMeta(datasetIndex); var key = [ meta.type, // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''), meta.stack ].join('.'); if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { if (valuesPerStack[key] === undefined) { valuesPerStack[key] = []; } data = datasets[datasetIndex].data; for (i = 0, ilen = data.length; i < ilen; i++) { var values = valuesPerStack[key]; value = me._parseValue(data[i]); // invalid, hidden and negative values are ignored if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) { continue; } values[i] = values[i] || 0; values[i] += value.max; } } } helpers$1.each(valuesPerStack, function(valuesForType) { if (valuesForType.length > 0) { var minVal = helpers$1.min(valuesForType); var maxVal = helpers$1.max(valuesForType); me.min = Math.min(me.min, minVal); me.max = Math.max(me.max, maxVal); } }); } else { for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) { meta = chart.getDatasetMeta(datasetIndex); if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { data = datasets[datasetIndex].data; for (i = 0, ilen = data.length; i < ilen; i++) { value = me._parseValue(data[i]); // invalid, hidden and negative values are ignored if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) { continue; } me.min = Math.min(value.min, me.min); me.max = Math.max(value.max, me.max); if (value.min !== 0) { me.minNotZero = Math.min(value.min, me.minNotZero); } } } } } me.min = helpers$1.isFinite(me.min) ? me.min : null; me.max = helpers$1.isFinite(me.max) ? me.max : null; me.minNotZero = helpers$1.isFinite(me.minNotZero) ? me.minNotZero : null; // Common base implementation to handle ticks.min, ticks.max this.handleTickRangeOptions(); }, handleTickRangeOptions: function() { var me = this; var tickOpts = me.options.ticks; var DEFAULT_MIN = 1; var DEFAULT_MAX = 10; me.min = nonNegativeOrDefault(tickOpts.min, me.min); me.max = nonNegativeOrDefault(tickOpts.max, me.max); if (me.min === me.max) { if (me.min !== 0 && me.min !== null) { me.min = Math.pow(10, Math.floor(log10(me.min)) - 1); me.max = Math.pow(10, Math.floor(log10(me.max)) + 1); } else { me.min = DEFAULT_MIN; me.max = DEFAULT_MAX; } } if (me.min === null) { me.min = Math.pow(10, Math.floor(log10(me.max)) - 1); } if (me.max === null) { me.max = me.min !== 0 ? Math.pow(10, Math.floor(log10(me.min)) + 1) : DEFAULT_MAX; } if (me.minNotZero === null) { if (me.min > 0) { me.minNotZero = me.min; } else if (me.max < 1) { me.minNotZero = Math.pow(10, Math.floor(log10(me.max))); } else { me.minNotZero = DEFAULT_MIN; } } }, buildTicks: function() { var me = this; var tickOpts = me.options.ticks; var reverse = !me.isHorizontal(); var generationOptions = { min: nonNegativeOrDefault(tickOpts.min), max: nonNegativeOrDefault(tickOpts.max) }; var ticks = me.ticks = generateTicks$1(generationOptions, me); // At this point, we need to update our max and min given the tick values since we have expanded the // range of the scale me.max = helpers$1.max(ticks); me.min = helpers$1.min(ticks); if (tickOpts.reverse) { reverse = !reverse; me.start = me.max; me.end = me.min; } else { me.start = me.min; me.end = me.max; } if (reverse) { ticks.reverse(); } }, convertTicksToLabels: function() { this.tickValues = this.ticks.slice(); core_scale.prototype.convertTicksToLabels.call(this); }, // Get the correct tooltip label getLabelForIndex: function(index, datasetIndex) { return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]); }, getPixelForTick: function(index) { var ticks = this.tickValues; if (index < 0 || index > ticks.length - 1) { return null; } return this.getPixelForValue(ticks[index]); }, /** * Returns the value of the first tick. * @param {number} value - The minimum not zero value. * @return {number} The first tick value. * @private */ _getFirstTickValue: function(value) { var exp = Math.floor(log10(value)); var significand = Math.floor(value / Math.pow(10, exp)); return significand * Math.pow(10, exp); }, _configure: function() { var me = this; var start = me.min; var offset = 0; core_scale.prototype._configure.call(me); if (start === 0) { start = me._getFirstTickValue(me.minNotZero); offset = valueOrDefault$b(me.options.ticks.fontSize, core_defaults.global.defaultFontSize) / me._length; } me._startValue = log10(start); me._valueOffset = offset; me._valueRange = (log10(me.max) - log10(start)) / (1 - offset); }, getPixelForValue: function(value) { var me = this; var decimal = 0; value = +me.getRightValue(value); if (value > me.min && value > 0) { decimal = (log10(value) - me._startValue) / me._valueRange + me._valueOffset; } return me.getPixelForDecimal(decimal); }, getValueForPixel: function(pixel) { var me = this; var decimal = me.getDecimalForPixel(pixel); return decimal === 0 && me.min === 0 ? 0 : Math.pow(10, me._startValue + (decimal - me._valueOffset) * me._valueRange); } }); // INTERNAL: static default options, registered in src/index.js var _defaults$2 = defaultConfig$2; scale_logarithmic._defaults = _defaults$2; var valueOrDefault$c = helpers$1.valueOrDefault; var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault; var resolve$4 = helpers$1.options.resolve; var defaultConfig$3 = { display: true, // Boolean - Whether to animate scaling the chart from the centre animate: true, position: 'chartArea', angleLines: { display: true, color: 'rgba(0,0,0,0.1)', lineWidth: 1, borderDash: [], borderDashOffset: 0.0 }, gridLines: { circular: false }, // label settings ticks: { // Boolean - Show a backdrop to the scale label showLabelBackdrop: true, // String - The colour of the label backdrop backdropColor: 'rgba(255,255,255,0.75)', // Number - The backdrop padding above & below the label in pixels backdropPaddingY: 2, // Number - The backdrop padding to the side of the label in pixels backdropPaddingX: 2, callback: core_ticks.formatters.linear }, pointLabels: { // Boolean - if true, show point labels display: true, // Number - Point label font size in pixels fontSize: 10, // Function - Used to convert point labels callback: function(label) { return label; } } }; function getTickBackdropHeight(opts) { var tickOpts = opts.ticks; if (tickOpts.display && opts.display) { return valueOrDefault$c(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2; } return 0; } function measureLabelSize(ctx, lineHeight, label) { if (helpers$1.isArray(label)) { return { w: helpers$1.longestText(ctx, ctx.font, label), h: label.length * lineHeight }; } return { w: ctx.measureText(label).width, h: lineHeight }; } function determineLimits(angle, pos, size, min, max) { if (angle === min || angle === max) { return { start: pos - (size / 2), end: pos + (size / 2) }; } else if (angle < min || angle > max) { return { start: pos - size, end: pos }; } return { start: pos, end: pos + size }; } /** * Helper function to fit a radial linear scale with point labels */ function fitWithPointLabels(scale) { // Right, this is really confusing and there is a lot of maths going on here // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9 // // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif // // Solution: // // We assume the radius of the polygon is half the size of the canvas at first // at each index we check if the text overlaps. // // Where it does, we store that angle and that index. // // After finding the largest index and angle we calculate how much we need to remove // from the shape radius to move the point inwards by that x. // // We average the left and right distances to get the maximum shape radius that can fit in the box // along with labels. // // Once we have that, we can find the centre point for the chart, by taking the x text protrusion // on each side, removing that from the size, halving it and adding the left x protrusion width. // // This will mean we have a shape fitted to the canvas, as large as it can be with the labels // and position it in the most space efficient manner // // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif var plFont = helpers$1.options._parseFont(scale.options.pointLabels); // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points var furthestLimits = { l: 0, r: scale.width, t: 0, b: scale.height - scale.paddingTop }; var furthestAngles = {}; var i, textSize, pointPosition; scale.ctx.font = plFont.string; scale._pointLabelSizes = []; var valueCount = scale.chart.data.labels.length; for (i = 0; i < valueCount; i++) { pointPosition = scale.getPointPosition(i, scale.drawingArea + 5); textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i]); scale._pointLabelSizes[i] = textSize; // Add quarter circle to make degree 0 mean top of circle var angleRadians = scale.getIndexAngle(i); var angle = helpers$1.toDegrees(angleRadians) % 360; var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180); var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270); if (hLimits.start < furthestLimits.l) { furthestLimits.l = hLimits.start; furthestAngles.l = angleRadians; } if (hLimits.end > furthestLimits.r) { furthestLimits.r = hLimits.end; furthestAngles.r = angleRadians; } if (vLimits.start < furthestLimits.t) { furthestLimits.t = vLimits.start; furthestAngles.t = angleRadians; } if (vLimits.end > furthestLimits.b) { furthestLimits.b = vLimits.end; furthestAngles.b = angleRadians; } } scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles); } function getTextAlignForAngle(angle) { if (angle === 0 || angle === 180) { return 'center'; } else if (angle < 180) { return 'left'; } return 'right'; } function fillText(ctx, text, position, lineHeight) { var y = position.y + lineHeight / 2; var i, ilen; if (helpers$1.isArray(text)) { for (i = 0, ilen = text.length; i < ilen; ++i) { ctx.fillText(text[i], position.x, y); y += lineHeight; } } else { ctx.fillText(text, position.x, y); } } function adjustPointPositionForLabelHeight(angle, textSize, position) { if (angle === 90 || angle === 270) { position.y -= (textSize.h / 2); } else if (angle > 270 || angle < 90) { position.y -= textSize.h; } } function drawPointLabels(scale) { var ctx = scale.ctx; var opts = scale.options; var pointLabelOpts = opts.pointLabels; var tickBackdropHeight = getTickBackdropHeight(opts); var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max); var plFont = helpers$1.options._parseFont(pointLabelOpts); ctx.save(); ctx.font = plFont.string; ctx.textBaseline = 'middle'; for (var i = scale.chart.data.labels.length - 1; i >= 0; i--) { // Extra pixels out for some label spacing var extra = (i === 0 ? tickBackdropHeight / 2 : 0); var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5); // Keep this in loop since we may support array properties here var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor); ctx.fillStyle = pointLabelFontColor; var angleRadians = scale.getIndexAngle(i); var angle = helpers$1.toDegrees(angleRadians); ctx.textAlign = getTextAlignForAngle(angle); adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition); fillText(ctx, scale.pointLabels[i], pointLabelPosition, plFont.lineHeight); } ctx.restore(); } function drawRadiusLine(scale, gridLineOpts, radius, index) { var ctx = scale.ctx; var circular = gridLineOpts.circular; var valueCount = scale.chart.data.labels.length; var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1); var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1); var pointPosition; if ((!circular && !valueCount) || !lineColor || !lineWidth) { return; } ctx.save(); ctx.strokeStyle = lineColor; ctx.lineWidth = lineWidth; if (ctx.setLineDash) { ctx.setLineDash(gridLineOpts.borderDash || []); ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0; } ctx.beginPath(); if (circular) { // Draw circular arcs between the points ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2); } else { // Draw straight lines connecting each index pointPosition = scale.getPointPosition(0, radius); ctx.moveTo(pointPosition.x, pointPosition.y); for (var i = 1; i < valueCount; i++) { pointPosition = scale.getPointPosition(i, radius); ctx.lineTo(pointPosition.x, pointPosition.y); } } ctx.closePath(); ctx.stroke(); ctx.restore(); } function numberOrZero(param) { return helpers$1.isNumber(param) ? param : 0; } var scale_radialLinear = scale_linearbase.extend({ setDimensions: function() { var me = this; // Set the unconstrained dimension before label rotation me.width = me.maxWidth; me.height = me.maxHeight; me.paddingTop = getTickBackdropHeight(me.options) / 2; me.xCenter = Math.floor(me.width / 2); me.yCenter = Math.floor((me.height - me.paddingTop) / 2); me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2; }, determineDataLimits: function() { var me = this; var chart = me.chart; var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; helpers$1.each(chart.data.datasets, function(dataset, datasetIndex) { if (chart.isDatasetVisible(datasetIndex)) { var meta = chart.getDatasetMeta(datasetIndex); helpers$1.each(dataset.data, function(rawValue, index) { var value = +me.getRightValue(rawValue); if (isNaN(value) || meta.data[index].hidden) { return; } min = Math.min(value, min); max = Math.max(value, max); }); } }); me.min = (min === Number.POSITIVE_INFINITY ? 0 : min); me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max); // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero me.handleTickRangeOptions(); }, // Returns the maximum number of ticks based on the scale dimension _computeTickLimit: function() { return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options)); }, convertTicksToLabels: function() { var me = this; scale_linearbase.prototype.convertTicksToLabels.call(me); // Point labels me.pointLabels = me.chart.data.labels.map(function() { var label = helpers$1.callback(me.options.pointLabels.callback, arguments, me); return label || label === 0 ? label : ''; }); }, getLabelForIndex: function(index, datasetIndex) { return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]); }, fit: function() { var me = this; var opts = me.options; if (opts.display && opts.pointLabels.display) { fitWithPointLabels(me); } else { me.setCenterPoint(0, 0, 0, 0); } }, /** * Set radius reductions and determine new radius and center point * @private */ setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) { var me = this; var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l); var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r); var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t); var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b); radiusReductionLeft = numberOrZero(radiusReductionLeft); radiusReductionRight = numberOrZero(radiusReductionRight); radiusReductionTop = numberOrZero(radiusReductionTop); radiusReductionBottom = numberOrZero(radiusReductionBottom); me.drawingArea = Math.min( Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2), Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2)); me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom); }, setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) { var me = this; var maxRight = me.width - rightMovement - me.drawingArea; var maxLeft = leftMovement + me.drawingArea; var maxTop = topMovement + me.drawingArea; var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea; me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left); me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop); }, getIndexAngle: function(index) { var chart = this.chart; var angleMultiplier = 360 / chart.data.labels.length; var options = chart.options || {}; var startAngle = options.startAngle || 0; // Start from the top instead of right, so remove a quarter of the circle var angle = (index * angleMultiplier + startAngle) % 360; return (angle < 0 ? angle + 360 : angle) * Math.PI * 2 / 360; }, getDistanceFromCenterForValue: function(value) { var me = this; if (helpers$1.isNullOrUndef(value)) { return NaN; } // Take into account half font size + the yPadding of the top value var scalingFactor = me.drawingArea / (me.max - me.min); if (me.options.ticks.reverse) { return (me.max - value) * scalingFactor; } return (value - me.min) * scalingFactor; }, getPointPosition: function(index, distanceFromCenter) { var me = this; var thisAngle = me.getIndexAngle(index) - (Math.PI / 2); return { x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter, y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter }; }, getPointPositionForValue: function(index, value) { return this.getPointPosition(index, this.getDistanceFromCenterForValue(value)); }, getBasePosition: function(index) { var me = this; var min = me.min; var max = me.max; return me.getPointPositionForValue(index || 0, me.beginAtZero ? 0 : min < 0 && max < 0 ? max : min > 0 && max > 0 ? min : 0); }, /** * @private */ _drawGrid: function() { var me = this; var ctx = me.ctx; var opts = me.options; var gridLineOpts = opts.gridLines; var angleLineOpts = opts.angleLines; var lineWidth = valueOrDefault$c(angleLineOpts.lineWidth, gridLineOpts.lineWidth); var lineColor = valueOrDefault$c(angleLineOpts.color, gridLineOpts.color); var i, offset, position; if (opts.pointLabels.display) { drawPointLabels(me); } if (gridLineOpts.display) { helpers$1.each(me.ticks, function(label, index) { if (index !== 0) { offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]); drawRadiusLine(me, gridLineOpts, offset, index); } }); } if (angleLineOpts.display && lineWidth && lineColor) { ctx.save(); ctx.lineWidth = lineWidth; ctx.strokeStyle = lineColor; if (ctx.setLineDash) { ctx.setLineDash(resolve$4([angleLineOpts.borderDash, gridLineOpts.borderDash, []])); ctx.lineDashOffset = resolve$4([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]); } for (i = me.chart.data.labels.length - 1; i >= 0; i--) { offset = me.getDistanceFromCenterForValue(opts.ticks.reverse ? me.min : me.max); position = me.getPointPosition(i, offset); ctx.beginPath(); ctx.moveTo(me.xCenter, me.yCenter); ctx.lineTo(position.x, position.y); ctx.stroke(); } ctx.restore(); } }, /** * @private */ _drawLabels: function() { var me = this; var ctx = me.ctx; var opts = me.options; var tickOpts = opts.ticks; if (!tickOpts.display) { return; } var startAngle = me.getIndexAngle(0); var tickFont = helpers$1.options._parseFont(tickOpts); var tickFontColor = valueOrDefault$c(tickOpts.fontColor, core_defaults.global.defaultFontColor); var offset, width; ctx.save(); ctx.font = tickFont.string; ctx.translate(me.xCenter, me.yCenter); ctx.rotate(startAngle); ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; helpers$1.each(me.ticks, function(label, index) { if (index === 0 && !tickOpts.reverse) { return; } offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]); if (tickOpts.showLabelBackdrop) { width = ctx.measureText(label).width; ctx.fillStyle = tickOpts.backdropColor; ctx.fillRect( -width / 2 - tickOpts.backdropPaddingX, -offset - tickFont.size / 2 - tickOpts.backdropPaddingY, width + tickOpts.backdropPaddingX * 2, tickFont.size + tickOpts.backdropPaddingY * 2 ); } ctx.fillStyle = tickFontColor; ctx.fillText(label, 0, -offset); }); ctx.restore(); }, /** * @private */ _drawTitle: helpers$1.noop }); // INTERNAL: static default options, registered in src/index.js var _defaults$3 = defaultConfig$3; scale_radialLinear._defaults = _defaults$3; var deprecated$1 = helpers$1._deprecated; var resolve$5 = helpers$1.options.resolve; var valueOrDefault$d = helpers$1.valueOrDefault; // Integer constants are from the ES6 spec. var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991; var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; var INTERVALS = { millisecond: { common: true, size: 1, steps: 1000 }, second: { common: true, size: 1000, steps: 60 }, minute: { common: true, size: 60000, steps: 60 }, hour: { common: true, size: 3600000, steps: 24 }, day: { common: true, size: 86400000, steps: 30 }, week: { common: false, size: 604800000, steps: 4 }, month: { common: true, size: 2.628e9, steps: 12 }, quarter: { common: false, size: 7.884e9, steps: 4 }, year: { common: true, size: 3.154e10 } }; var UNITS = Object.keys(INTERVALS); function sorter(a, b) { return a - b; } function arrayUnique(items) { var hash = {}; var out = []; var i, ilen, item; for (i = 0, ilen = items.length; i < ilen; ++i) { item = items[i]; if (!hash[item]) { hash[item] = true; out.push(item); } } return out; } function getMin(options) { return helpers$1.valueOrDefault(options.time.min, options.ticks.min); } function getMax(options) { return helpers$1.valueOrDefault(options.time.max, options.ticks.max); } /** * Returns an array of {time, pos} objects used to interpolate a specific `time` or position * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other * extremity (left + width or top + height). Note that it would be more optimized to directly * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need * to create the lookup table. The table ALWAYS contains at least two items: min and max. * * @param {number[]} timestamps - timestamps sorted from lowest to highest. * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}. * If 'series', timestamps will be positioned at the same distance from each other. In this * case, only timestamps that break the time linearity are registered, meaning that in the * best case, all timestamps are linear, the table contains only min and max. */ function buildLookupTable(timestamps, min, max, distribution) { if (distribution === 'linear' || !timestamps.length) { return [ {time: min, pos: 0}, {time: max, pos: 1} ]; } var table = []; var items = [min]; var i, ilen, prev, curr, next; for (i = 0, ilen = timestamps.length; i < ilen; ++i) { curr = timestamps[i]; if (curr > min && curr < max) { items.push(curr); } } items.push(max); for (i = 0, ilen = items.length; i < ilen; ++i) { next = items[i + 1]; prev = items[i - 1]; curr = items[i]; // only add points that breaks the scale linearity if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) { table.push({time: curr, pos: i / (ilen - 1)}); } } return table; } // @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/ function lookup(table, key, value) { var lo = 0; var hi = table.length - 1; var mid, i0, i1; while (lo >= 0 && lo <= hi) { mid = (lo + hi) >> 1; i0 = table[mid - 1] || null; i1 = table[mid]; if (!i0) { // given value is outside table (before first item) return {lo: null, hi: i1}; } else if (i1[key] < value) { lo = mid + 1; } else if (i0[key] > value) { hi = mid - 1; } else { return {lo: i0, hi: i1}; } } // given value is outside table (after last item) return {lo: i1, hi: null}; } /** * Linearly interpolates the given source `value` using the table items `skey` values and * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos') * returns the position for a timestamp equal to 42. If value is out of bounds, values at * index [0, 1] or [n - 1, n] are used for the interpolation. */ function interpolate$1(table, skey, sval, tkey) { var range = lookup(table, skey, sval); // Note: the lookup table ALWAYS contains at least 2 items (min and max) var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo; var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi; var span = next[skey] - prev[skey]; var ratio = span ? (sval - prev[skey]) / span : 0; var offset = (next[tkey] - prev[tkey]) * ratio; return prev[tkey] + offset; } function toTimestamp(scale, input) { var adapter = scale._adapter; var options = scale.options.time; var parser = options.parser; var format = parser || options.format; var value = input; if (typeof parser === 'function') { value = parser(value); } // Only parse if its not a timestamp already if (!helpers$1.isFinite(value)) { value = typeof format === 'string' ? adapter.parse(value, format) : adapter.parse(value); } if (value !== null) { return +value; } // Labels are in an incompatible format and no `parser` has been provided. // The user might still use the deprecated `format` option for parsing. if (!parser && typeof format === 'function') { value = format(input); // `format` could return something else than a timestamp, if so, parse it if (!helpers$1.isFinite(value)) { value = adapter.parse(value); } } return value; } function parse(scale, input) { if (helpers$1.isNullOrUndef(input)) { return null; } var options = scale.options.time; var value = toTimestamp(scale, scale.getRightValue(input)); if (value === null) { return value; } if (options.round) { value = +scale._adapter.startOf(value, options.round); } return value; } /** * Figures out what unit results in an appropriate number of auto-generated ticks */ function determineUnitForAutoTicks(minUnit, min, max, capacity) { var ilen = UNITS.length; var i, interval, factor; for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) { interval = INTERVALS[UNITS[i]]; factor = interval.steps ? interval.steps : MAX_INTEGER; if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) { return UNITS[i]; } } return UNITS[ilen - 1]; } /** * Figures out what unit to format a set of ticks with */ function determineUnitForFormatting(scale, numTicks, minUnit, min, max) { var i, unit; for (i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) { unit = UNITS[i]; if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) { return unit; } } return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0]; } function determineMajorUnit(unit) { for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) { if (INTERVALS[UNITS[i]].common) { return UNITS[i]; } } } /** * Generates a maximum of `capacity` timestamps between min and max, rounded to the * `minor` unit using the given scale time `options`. * Important: this method can return ticks outside the min and max range, it's the * responsibility of the calling code to clamp values if needed. */ function generate(scale, min, max, capacity) { var adapter = scale._adapter; var options = scale.options; var timeOpts = options.time; var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity); var stepSize = resolve$5([timeOpts.stepSize, timeOpts.unitStepSize, 1]); var weekday = minor === 'week' ? timeOpts.isoWeekday : false; var first = min; var ticks = []; var time; // For 'week' unit, handle the first day of week option if (weekday) { first = +adapter.startOf(first, 'isoWeek', weekday); } // Align first ticks on unit first = +adapter.startOf(first, weekday ? 'day' : minor); // Prevent browser from freezing in case user options request millions of milliseconds if (adapter.diff(max, min, minor) > 100000 * stepSize) { throw min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor; } for (time = first; time < max; time = +adapter.add(time, stepSize, minor)) { ticks.push(time); } if (time === max || options.bounds === 'ticks') { ticks.push(time); } return ticks; } /** * Returns the start and end offsets from edges in the form of {start, end} * where each value is a relative width to the scale and ranges between 0 and 1. * They add extra margins on the both sides by scaling down the original scale. * Offsets are added when the `offset` option is true. */ function computeOffsets(table, ticks, min, max, options) { var start = 0; var end = 0; var first, last; if (options.offset && ticks.length) { first = interpolate$1(table, 'time', ticks[0], 'pos'); if (ticks.length === 1) { start = 1 - first; } else { start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2; } last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos'); if (ticks.length === 1) { end = last; } else { end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2; } } return {start: start, end: end, factor: 1 / (start + 1 + end)}; } function setMajorTicks(scale, ticks, map, majorUnit) { var adapter = scale._adapter; var first = +adapter.startOf(ticks[0].value, majorUnit); var last = ticks[ticks.length - 1].value; var major, index; for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) { index = map[major]; if (index >= 0) { ticks[index].major = true; } } return ticks; } function ticksFromTimestamps(scale, values, majorUnit) { var ticks = []; var map = {}; var ilen = values.length; var i, value; for (i = 0; i < ilen; ++i) { value = values[i]; map[value] = i; ticks.push({ value: value, major: false }); } // We set the major ticks separately from the above loop because calling startOf for every tick // is expensive when there is a large number of ticks return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit); } var defaultConfig$4 = { position: 'bottom', /** * Data distribution along the scale: * - 'linear': data are spread according to their time (distances can vary), * - 'series': data are spread at the same distance from each other. * @see https://github.com/chartjs/Chart.js/pull/4507 * @since 2.7.0 */ distribution: 'linear', /** * Scale boundary strategy (bypassed by min/max time options) * - `data`: make sure data are fully visible, ticks outside are removed * - `ticks`: make sure ticks are fully visible, data outside are truncated * @see https://github.com/chartjs/Chart.js/pull/4556 * @since 2.7.0 */ bounds: 'data', adapters: {}, time: { parser: false, // false == a pattern string from https://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment unit: false, // false == automatic or override with week, month, year, etc. round: false, // none, or override with week, month, year, etc. displayFormat: false, // DEPRECATED isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/ minUnit: 'millisecond', displayFormats: {} }, ticks: { autoSkip: false, /** * Ticks generation input values: * - 'auto': generates "optimal" ticks based on scale size and time options. * - 'data': generates ticks from data (including labels from data {t|x|y} objects). * - 'labels': generates ticks from user given `data.labels` values ONLY. * @see https://github.com/chartjs/Chart.js/pull/4507 * @since 2.7.0 */ source: 'auto', major: { enabled: false } } }; var scale_time = core_scale.extend({ initialize: function() { this.mergeTicksOptions(); core_scale.prototype.initialize.call(this); }, update: function() { var me = this; var options = me.options; var time = options.time || (options.time = {}); var adapter = me._adapter = new core_adapters._date(options.adapters.date); // DEPRECATIONS: output a message only one time per update deprecated$1('time scale', time.format, 'time.format', 'time.parser'); deprecated$1('time scale', time.min, 'time.min', 'ticks.min'); deprecated$1('time scale', time.max, 'time.max', 'ticks.max'); // Backward compatibility: before introducing adapter, `displayFormats` was // supposed to contain *all* unit/string pairs but this can't be resolved // when loading the scale (adapters are loaded afterward), so let's populate // missing formats on update helpers$1.mergeIf(time.displayFormats, adapter.formats()); return core_scale.prototype.update.apply(me, arguments); }, /** * Allows data to be referenced via 't' attribute */ getRightValue: function(rawValue) { if (rawValue && rawValue.t !== undefined) { rawValue = rawValue.t; } return core_scale.prototype.getRightValue.call(this, rawValue); }, determineDataLimits: function() { var me = this; var chart = me.chart; var adapter = me._adapter; var options = me.options; var unit = options.time.unit || 'day'; var min = MAX_INTEGER; var max = MIN_INTEGER; var timestamps = []; var datasets = []; var labels = []; var i, j, ilen, jlen, data, timestamp, labelsAdded; var dataLabels = me._getLabels(); for (i = 0, ilen = dataLabels.length; i < ilen; ++i) { labels.push(parse(me, dataLabels[i])); } for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) { if (chart.isDatasetVisible(i)) { data = chart.data.datasets[i].data; // Let's consider that all data have the same format. if (helpers$1.isObject(data[0])) { datasets[i] = []; for (j = 0, jlen = data.length; j < jlen; ++j) { timestamp = parse(me, data[j]); timestamps.push(timestamp); datasets[i][j] = timestamp; } } else { datasets[i] = labels.slice(0); if (!labelsAdded) { timestamps = timestamps.concat(labels); labelsAdded = true; } } } else { datasets[i] = []; } } if (labels.length) { min = Math.min(min, labels[0]); max = Math.max(max, labels[labels.length - 1]); } if (timestamps.length) { timestamps = ilen > 1 ? arrayUnique(timestamps).sort(sorter) : timestamps.sort(sorter); min = Math.min(min, timestamps[0]); max = Math.max(max, timestamps[timestamps.length - 1]); } min = parse(me, getMin(options)) || min; max = parse(me, getMax(options)) || max; // In case there is no valid min/max, set limits based on unit time option min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min; max = max === MIN_INTEGER ? +adapter.endOf(Date.now(), unit) + 1 : max; // Make sure that max is strictly higher than min (required by the lookup table) me.min = Math.min(min, max); me.max = Math.max(min + 1, max); // PRIVATE me._table = []; me._timestamps = { data: timestamps, datasets: datasets, labels: labels }; }, buildTicks: function() { var me = this; var min = me.min; var max = me.max; var options = me.options; var tickOpts = options.ticks; var timeOpts = options.time; var timestamps = me._timestamps; var ticks = []; var capacity = me.getLabelCapacity(min); var source = tickOpts.source; var distribution = options.distribution; var i, ilen, timestamp; if (source === 'data' || (source === 'auto' && distribution === 'series')) { timestamps = timestamps.data; } else if (source === 'labels') { timestamps = timestamps.labels; } else { timestamps = generate(me, min, max, capacity); } if (options.bounds === 'ticks' && timestamps.length) { min = timestamps[0]; max = timestamps[timestamps.length - 1]; } // Enforce limits with user min/max options min = parse(me, getMin(options)) || min; max = parse(me, getMax(options)) || max; // Remove ticks outside the min/max range for (i = 0, ilen = timestamps.length; i < ilen; ++i) { timestamp = timestamps[i]; if (timestamp >= min && timestamp <= max) { ticks.push(timestamp); } } me.min = min; me.max = max; // PRIVATE // determineUnitForFormatting relies on the number of ticks so we don't use it when // autoSkip is enabled because we don't yet know what the final number of ticks will be me._unit = timeOpts.unit || (tickOpts.autoSkip ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, capacity) : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max)); me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined : determineMajorUnit(me._unit); me._table = buildLookupTable(me._timestamps.data, min, max, distribution); me._offsets = computeOffsets(me._table, ticks, min, max, options); if (tickOpts.reverse) { ticks.reverse(); } return ticksFromTimestamps(me, ticks, me._majorUnit); }, getLabelForIndex: function(index, datasetIndex) { var me = this; var adapter = me._adapter; var data = me.chart.data; var timeOpts = me.options.time; var label = data.labels && index < data.labels.length ? data.labels[index] : ''; var value = data.datasets[datasetIndex].data[index]; if (helpers$1.isObject(value)) { label = me.getRightValue(value); } if (timeOpts.tooltipFormat) { return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat); } if (typeof label === 'string') { return label; } return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime); }, /** * Function to format an individual tick mark * @private */ tickFormatFunction: function(time, index, ticks, format) { var me = this; var adapter = me._adapter; var options = me.options; var formats = options.time.displayFormats; var minorFormat = formats[me._unit]; var majorUnit = me._majorUnit; var majorFormat = formats[majorUnit]; var tick = ticks[index]; var tickOpts = options.ticks; var major = majorUnit && majorFormat && tick && tick.major; var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat); var nestedTickOpts = major ? tickOpts.major : tickOpts.minor; var formatter = resolve$5([ nestedTickOpts.callback, nestedTickOpts.userCallback, tickOpts.callback, tickOpts.userCallback ]); return formatter ? formatter(label, index, ticks) : label; }, convertTicksToLabels: function(ticks) { var labels = []; var i, ilen; for (i = 0, ilen = ticks.length; i < ilen; ++i) { labels.push(this.tickFormatFunction(ticks[i].value, i, ticks)); } return labels; }, /** * @private */ getPixelForOffset: function(time) { var me = this; var offsets = me._offsets; var pos = interpolate$1(me._table, 'time', time, 'pos'); return me.getPixelForDecimal((offsets.start + pos) * offsets.factor); }, getPixelForValue: function(value, index, datasetIndex) { var me = this; var time = null; if (index !== undefined && datasetIndex !== undefined) { time = me._timestamps.datasets[datasetIndex][index]; } if (time === null) { time = parse(me, value); } if (time !== null) { return me.getPixelForOffset(time); } }, getPixelForTick: function(index) { var ticks = this.getTicks(); return index >= 0 && index < ticks.length ? this.getPixelForOffset(ticks[index].value) : null; }, getValueForPixel: function(pixel) { var me = this; var offsets = me._offsets; var pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end; var time = interpolate$1(me._table, 'pos', pos, 'time'); // DEPRECATION, we should return time directly return me._adapter._create(time); }, /** * @private */ _getLabelSize: function(label) { var me = this; var ticksOpts = me.options.ticks; var tickLabelWidth = me.ctx.measureText(label).width; var angle = helpers$1.toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation); var cosRotation = Math.cos(angle); var sinRotation = Math.sin(angle); var tickFontSize = valueOrDefault$d(ticksOpts.fontSize, core_defaults.global.defaultFontSize); return { w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation), h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation) }; }, /** * Crude approximation of what the label width might be * @private */ getLabelWidth: function(label) { return this._getLabelSize(label).w; }, /** * @private */ getLabelCapacity: function(exampleTime) { var me = this; var timeOpts = me.options.time; var displayFormats = timeOpts.displayFormats; // pick the longest format (milliseconds) for guestimation var format = displayFormats[timeOpts.unit] || displayFormats.millisecond; var exampleLabel = me.tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format); var size = me._getLabelSize(exampleLabel); var capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h); if (me.options.offset) { capacity--; } return capacity > 0 ? capacity : 1; } }); // INTERNAL: static default options, registered in src/index.js var _defaults$4 = defaultConfig$4; scale_time._defaults = _defaults$4; var scales = { category: scale_category, linear: scale_linear, logarithmic: scale_logarithmic, radialLinear: scale_radialLinear, time: scale_time }; var FORMATS = { datetime: 'MMM D, YYYY, h:mm:ss a', millisecond: 'h:mm:ss.SSS a', second: 'h:mm:ss a', minute: 'h:mm a', hour: 'hA', day: 'MMM D', week: 'll', month: 'MMM YYYY', quarter: '[Q]Q - YYYY', year: 'YYYY' }; core_adapters._date.override(typeof moment === 'function' ? { _id: 'moment', // DEBUG ONLY formats: function() { return FORMATS; }, parse: function(value, format) { if (typeof value === 'string' && typeof format === 'string') { value = moment(value, format); } else if (!(value instanceof moment)) { value = moment(value); } return value.isValid() ? value.valueOf() : null; }, format: function(time, format) { return moment(time).format(format); }, add: function(time, amount, unit) { return moment(time).add(amount, unit).valueOf(); }, diff: function(max, min, unit) { return moment(max).diff(moment(min), unit); }, startOf: function(time, unit, weekday) { time = moment(time); if (unit === 'isoWeek') { return time.isoWeekday(weekday).valueOf(); } return time.startOf(unit).valueOf(); }, endOf: function(time, unit) { return moment(time).endOf(unit).valueOf(); }, // DEPRECATIONS /** * Provided for backward compatibility with scale.getValueForPixel(). * @deprecated since version 2.8.0 * @todo remove at version 3 * @private */ _create: function(time) { return moment(time); }, } : {}); core_defaults._set('global', { plugins: { filler: { propagate: true } } }); var mappers = { dataset: function(source) { var index = source.fill; var chart = source.chart; var meta = chart.getDatasetMeta(index); var visible = meta && chart.isDatasetVisible(index); var points = (visible && meta.dataset._children) || []; var length = points.length || 0; return !length ? null : function(point, i) { return (i < length && points[i]._view) || null; }; }, boundary: function(source) { var boundary = source.boundary; var x = boundary ? boundary.x : null; var y = boundary ? boundary.y : null; if (helpers$1.isArray(boundary)) { return function(point, i) { return boundary[i]; }; } return function(point) { return { x: x === null ? point.x : x, y: y === null ? point.y : y, }; }; } }; // @todo if (fill[0] === '#') function decodeFill(el, index, count) { var model = el._model || {}; var fill = model.fill; var target; if (fill === undefined) { fill = !!model.backgroundColor; } if (fill === false || fill === null) { return false; } if (fill === true) { return 'origin'; } target = parseFloat(fill, 10); if (isFinite(target) && Math.floor(target) === target) { if (fill[0] === '-' || fill[0] === '+') { target = index + target; } if (target === index || target < 0 || target >= count) { return false; } return target; } switch (fill) { // compatibility case 'bottom': return 'start'; case 'top': return 'end'; case 'zero': return 'origin'; // supported boundaries case 'origin': case 'start': case 'end': return fill; // invalid fill values default: return false; } } function computeLinearBoundary(source) { var model = source.el._model || {}; var scale = source.el._scale || {}; var fill = source.fill; var target = null; var horizontal; if (isFinite(fill)) { return null; } // Backward compatibility: until v3, we still need to support boundary values set on // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and // controllers might still use it (e.g. the Smith chart). if (fill === 'start') { target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom; } else if (fill === 'end') { target = model.scaleTop === undefined ? scale.top : model.scaleTop; } else if (model.scaleZero !== undefined) { target = model.scaleZero; } else if (scale.getBasePixel) { target = scale.getBasePixel(); } if (target !== undefined && target !== null) { if (target.x !== undefined && target.y !== undefined) { return target; } if (helpers$1.isFinite(target)) { horizontal = scale.isHorizontal(); return { x: horizontal ? target : null, y: horizontal ? null : target }; } } return null; } function computeCircularBoundary(source) { var scale = source.el._scale; var options = scale.options; var length = scale.chart.data.labels.length; var fill = source.fill; var target = []; var start, end, center, i, point; if (!length) { return null; } start = options.ticks.reverse ? scale.max : scale.min; end = options.ticks.reverse ? scale.min : scale.max; center = scale.getPointPositionForValue(0, start); for (i = 0; i < length; ++i) { point = fill === 'start' || fill === 'end' ? scale.getPointPositionForValue(i, fill === 'start' ? start : end) : scale.getBasePosition(i); if (options.gridLines.circular) { point.cx = center.x; point.cy = center.y; point.angle = scale.getIndexAngle(i) - Math.PI / 2; } target.push(point); } return target; } function computeBoundary(source) { var scale = source.el._scale || {}; if (scale.getPointPositionForValue) { return computeCircularBoundary(source); } return computeLinearBoundary(source); } function resolveTarget(sources, index, propagate) { var source = sources[index]; var fill = source.fill; var visited = [index]; var target; if (!propagate) { return fill; } while (fill !== false && visited.indexOf(fill) === -1) { if (!isFinite(fill)) { return fill; } target = sources[fill]; if (!target) { return false; } if (target.visible) { return fill; } visited.push(fill); fill = target.fill; } return false; } function createMapper(source) { var fill = source.fill; var type = 'dataset'; if (fill === false) { return null; } if (!isFinite(fill)) { type = 'boundary'; } return mappers[type](source); } function isDrawable(point) { return point && !point.skip; } function drawArea(ctx, curve0, curve1, len0, len1) { var i, cx, cy, r; if (!len0 || !len1) { return; } // building first area curve (normal) ctx.moveTo(curve0[0].x, curve0[0].y); for (i = 1; i < len0; ++i) { helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]); } if (curve1[0].angle !== undefined) { cx = curve1[0].cx; cy = curve1[0].cy; r = Math.sqrt(Math.pow(curve1[0].x - cx, 2) + Math.pow(curve1[0].y - cy, 2)); for (i = len1 - 1; i > 0; --i) { ctx.arc(cx, cy, r, curve1[i].angle, curve1[i - 1].angle, true); } return; } // joining the two area curves ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y); // building opposite area curve (reverse) for (i = len1 - 1; i > 0; --i) { helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true); } } function doFill(ctx, points, mapper, view, color, loop) { var count = points.length; var span = view.spanGaps; var curve0 = []; var curve1 = []; var len0 = 0; var len1 = 0; var i, ilen, index, p0, p1, d0, d1, loopOffset; ctx.beginPath(); for (i = 0, ilen = count; i < ilen; ++i) { index = i % count; p0 = points[index]._view; p1 = mapper(p0, index, view); d0 = isDrawable(p0); d1 = isDrawable(p1); if (loop && loopOffset === undefined && d0) { loopOffset = i + 1; ilen = count + loopOffset; } if (d0 && d1) { len0 = curve0.push(p0); len1 = curve1.push(p1); } else if (len0 && len1) { if (!span) { drawArea(ctx, curve0, curve1, len0, len1); len0 = len1 = 0; curve0 = []; curve1 = []; } else { if (d0) { curve0.push(p0); } if (d1) { curve1.push(p1); } } } } drawArea(ctx, curve0, curve1, len0, len1); ctx.closePath(); ctx.fillStyle = color; ctx.fill(); } var plugin_filler = { id: 'filler', afterDatasetsUpdate: function(chart, options) { var count = (chart.data.datasets || []).length; var propagate = options.propagate; var sources = []; var meta, i, el, source; for (i = 0; i < count; ++i) { meta = chart.getDatasetMeta(i); el = meta.dataset; source = null; if (el && el._model && el instanceof elements.Line) { source = { visible: chart.isDatasetVisible(i), fill: decodeFill(el, i, count), chart: chart, el: el }; } meta.$filler = source; sources.push(source); } for (i = 0; i < count; ++i) { source = sources[i]; if (!source) { continue; } source.fill = resolveTarget(sources, i, propagate); source.boundary = computeBoundary(source); source.mapper = createMapper(source); } }, beforeDatasetsDraw: function(chart) { var metasets = chart._getSortedVisibleDatasetMetas(); var ctx = chart.ctx; var meta, i, el, view, points, mapper, color; for (i = metasets.length - 1; i >= 0; --i) { meta = metasets[i].$filler; if (!meta || !meta.visible) { continue; } el = meta.el; view = el._view; points = el._children || []; mapper = meta.mapper; color = view.backgroundColor || core_defaults.global.defaultColor; if (mapper && color && points.length) { helpers$1.canvas.clipArea(ctx, chart.chartArea); doFill(ctx, points, mapper, view, color, el._loop); helpers$1.canvas.unclipArea(ctx); } } } }; var getRtlHelper$1 = helpers$1.rtl.getRtlAdapter; var noop$1 = helpers$1.noop; var valueOrDefault$e = helpers$1.valueOrDefault; core_defaults._set('global', { legend: { display: true, position: 'top', align: 'center', fullWidth: true, reverse: false, weight: 1000, // a callback that will handle onClick: function(e, legendItem) { var index = legendItem.datasetIndex; var ci = this.chart; var meta = ci.getDatasetMeta(index); // See controller.isDatasetVisible comment meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null; // We hid a dataset ... rerender the chart ci.update(); }, onHover: null, onLeave: null, labels: { boxWidth: 40, padding: 10, // Generates labels shown in the legend // Valid properties to return: // text : text to display // fillStyle : fill of coloured box // strokeStyle: stroke of coloured box // hidden : if this legend item refers to a hidden item // lineCap : cap style for line // lineDash // lineDashOffset : // lineJoin : // lineWidth : generateLabels: function(chart) { var datasets = chart.data.datasets; var options = chart.options.legend || {}; var usePointStyle = options.labels && options.labels.usePointStyle; return chart._getSortedDatasetMetas().map(function(meta) { var style = meta.controller.getStyle(usePointStyle ? 0 : undefined); return { text: datasets[meta.index].label, fillStyle: style.backgroundColor, hidden: !chart.isDatasetVisible(meta.index), lineCap: style.borderCapStyle, lineDash: style.borderDash, lineDashOffset: style.borderDashOffset, lineJoin: style.borderJoinStyle, lineWidth: style.borderWidth, strokeStyle: style.borderColor, pointStyle: style.pointStyle, rotation: style.rotation, // Below is extra data used for toggling the datasets datasetIndex: meta.index }; }, this); } } }, legendCallback: function(chart) { var list = document.createElement('ul'); var datasets = chart.data.datasets; var i, ilen, listItem, listItemSpan; list.setAttribute('class', chart.id + '-legend'); for (i = 0, ilen = datasets.length; i < ilen; i++) { listItem = list.appendChild(document.createElement('li')); listItemSpan = listItem.appendChild(document.createElement('span')); listItemSpan.style.backgroundColor = datasets[i].backgroundColor; if (datasets[i].label) { listItem.appendChild(document.createTextNode(datasets[i].label)); } } return list.outerHTML; } }); /** * Helper function to get the box width based on the usePointStyle option * @param {object} labelopts - the label options on the legend * @param {number} fontSize - the label font size * @return {number} width of the color box area */ function getBoxWidth(labelOpts, fontSize) { return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ? fontSize : labelOpts.boxWidth; } /** * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required! */ var Legend = core_element.extend({ initialize: function(config) { var me = this; helpers$1.extend(me, config); // Contains hit boxes for each dataset (in dataset order) me.legendHitBoxes = []; /** * @private */ me._hoveredItem = null; // Are we in doughnut mode which has a different data type me.doughnutMode = false; }, // These methods are ordered by lifecycle. Utilities then follow. // Any function defined here is inherited by all legend types. // Any function can be extended by the legend type beforeUpdate: noop$1, update: function(maxWidth, maxHeight, margins) { var me = this; // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) me.beforeUpdate(); // Absorb the master measurements me.maxWidth = maxWidth; me.maxHeight = maxHeight; me.margins = margins; // Dimensions me.beforeSetDimensions(); me.setDimensions(); me.afterSetDimensions(); // Labels me.beforeBuildLabels(); me.buildLabels(); me.afterBuildLabels(); // Fit me.beforeFit(); me.fit(); me.afterFit(); // me.afterUpdate(); return me.minSize; }, afterUpdate: noop$1, // beforeSetDimensions: noop$1, setDimensions: function() { var me = this; // Set the unconstrained dimension before label rotation if (me.isHorizontal()) { // Reset position before calculating rotation me.width = me.maxWidth; me.left = 0; me.right = me.width; } else { me.height = me.maxHeight; // Reset position before calculating rotation me.top = 0; me.bottom = me.height; } // Reset padding me.paddingLeft = 0; me.paddingTop = 0; me.paddingRight = 0; me.paddingBottom = 0; // Reset minSize me.minSize = { width: 0, height: 0 }; }, afterSetDimensions: noop$1, // beforeBuildLabels: noop$1, buildLabels: function() { var me = this; var labelOpts = me.options.labels || {}; var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || []; if (labelOpts.filter) { legendItems = legendItems.filter(function(item) { return labelOpts.filter(item, me.chart.data); }); } if (me.options.reverse) { legendItems.reverse(); } me.legendItems = legendItems; }, afterBuildLabels: noop$1, // beforeFit: noop$1, fit: function() { var me = this; var opts = me.options; var labelOpts = opts.labels; var display = opts.display; var ctx = me.ctx; var labelFont = helpers$1.options._parseFont(labelOpts); var fontSize = labelFont.size; // Reset hit boxes var hitboxes = me.legendHitBoxes = []; var minSize = me.minSize; var isHorizontal = me.isHorizontal(); if (isHorizontal) { minSize.width = me.maxWidth; // fill all the width minSize.height = display ? 10 : 0; } else { minSize.width = display ? 10 : 0; minSize.height = me.maxHeight; // fill all the height } // Increase sizes here if (!display) { me.width = minSize.width = me.height = minSize.height = 0; return; } ctx.font = labelFont.string; if (isHorizontal) { // Labels // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one var lineWidths = me.lineWidths = [0]; var totalHeight = 0; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; helpers$1.each(me.legendItems, function(legendItem, i) { var boxWidth = getBoxWidth(labelOpts, fontSize); var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; if (i === 0 || lineWidths[lineWidths.length - 1] + width + 2 * labelOpts.padding > minSize.width) { totalHeight += fontSize + labelOpts.padding; lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0; } // Store the hitbox width and height here. Final position will be updated in `draw` hitboxes[i] = { left: 0, top: 0, width: width, height: fontSize }; lineWidths[lineWidths.length - 1] += width + labelOpts.padding; }); minSize.height += totalHeight; } else { var vPadding = labelOpts.padding; var columnWidths = me.columnWidths = []; var columnHeights = me.columnHeights = []; var totalWidth = labelOpts.padding; var currentColWidth = 0; var currentColHeight = 0; helpers$1.each(me.legendItems, function(legendItem, i) { var boxWidth = getBoxWidth(labelOpts, fontSize); var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; // If too tall, go to new column if (i > 0 && currentColHeight + fontSize + 2 * vPadding > minSize.height) { totalWidth += currentColWidth + labelOpts.padding; columnWidths.push(currentColWidth); // previous column width columnHeights.push(currentColHeight); currentColWidth = 0; currentColHeight = 0; } // Get max width currentColWidth = Math.max(currentColWidth, itemWidth); currentColHeight += fontSize + vPadding; // Store the hitbox width and height here. Final position will be updated in `draw` hitboxes[i] = { left: 0, top: 0, width: itemWidth, height: fontSize }; }); totalWidth += currentColWidth; columnWidths.push(currentColWidth); columnHeights.push(currentColHeight); minSize.width += totalWidth; } me.width = minSize.width; me.height = minSize.height; }, afterFit: noop$1, // Shared Methods isHorizontal: function() { return this.options.position === 'top' || this.options.position === 'bottom'; }, // Actually draw the legend on the canvas draw: function() { var me = this; var opts = me.options; var labelOpts = opts.labels; var globalDefaults = core_defaults.global; var defaultColor = globalDefaults.defaultColor; var lineDefault = globalDefaults.elements.line; var legendHeight = me.height; var columnHeights = me.columnHeights; var legendWidth = me.width; var lineWidths = me.lineWidths; if (!opts.display) { return; } var rtlHelper = getRtlHelper$1(opts.rtl, me.left, me.minSize.width); var ctx = me.ctx; var fontColor = valueOrDefault$e(labelOpts.fontColor, globalDefaults.defaultFontColor); var labelFont = helpers$1.options._parseFont(labelOpts); var fontSize = labelFont.size; var cursor; // Canvas setup ctx.textAlign = rtlHelper.textAlign('left'); ctx.textBaseline = 'middle'; ctx.lineWidth = 0.5; ctx.strokeStyle = fontColor; // for strikethrough effect ctx.fillStyle = fontColor; // render in correct colour ctx.font = labelFont.string; var boxWidth = getBoxWidth(labelOpts, fontSize); var hitboxes = me.legendHitBoxes; // current position var drawLegendBox = function(x, y, legendItem) { if (isNaN(boxWidth) || boxWidth <= 0) { return; } // Set the ctx for the box ctx.save(); var lineWidth = valueOrDefault$e(legendItem.lineWidth, lineDefault.borderWidth); ctx.fillStyle = valueOrDefault$e(legendItem.fillStyle, defaultColor); ctx.lineCap = valueOrDefault$e(legendItem.lineCap, lineDefault.borderCapStyle); ctx.lineDashOffset = valueOrDefault$e(legendItem.lineDashOffset, lineDefault.borderDashOffset); ctx.lineJoin = valueOrDefault$e(legendItem.lineJoin, lineDefault.borderJoinStyle); ctx.lineWidth = lineWidth; ctx.strokeStyle = valueOrDefault$e(legendItem.strokeStyle, defaultColor); if (ctx.setLineDash) { // IE 9 and 10 do not support line dash ctx.setLineDash(valueOrDefault$e(legendItem.lineDash, lineDefault.borderDash)); } if (labelOpts && labelOpts.usePointStyle) { // Recalculate x and y for drawPoint() because its expecting // x and y to be center of figure (instead of top left) var radius = boxWidth * Math.SQRT2 / 2; var centerX = rtlHelper.xPlus(x, boxWidth / 2); var centerY = y + fontSize / 2; // Draw pointStyle as legend symbol helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY, legendItem.rotation); } else { // Draw box as legend symbol ctx.fillRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize); if (lineWidth !== 0) { ctx.strokeRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize); } } ctx.restore(); }; var fillText = function(x, y, legendItem, textWidth) { var halfFontSize = fontSize / 2; var xLeft = rtlHelper.xPlus(x, boxWidth + halfFontSize); var yMiddle = y + halfFontSize; ctx.fillText(legendItem.text, xLeft, yMiddle); if (legendItem.hidden) { // Strikethrough the text if hidden ctx.beginPath(); ctx.lineWidth = 2; ctx.moveTo(xLeft, yMiddle); ctx.lineTo(rtlHelper.xPlus(xLeft, textWidth), yMiddle); ctx.stroke(); } }; var alignmentOffset = function(dimension, blockSize) { switch (opts.align) { case 'start': return labelOpts.padding; case 'end': return dimension - blockSize; default: // center return (dimension - blockSize + labelOpts.padding) / 2; } }; // Horizontal var isHorizontal = me.isHorizontal(); if (isHorizontal) { cursor = { x: me.left + alignmentOffset(legendWidth, lineWidths[0]), y: me.top + labelOpts.padding, line: 0 }; } else { cursor = { x: me.left + labelOpts.padding, y: me.top + alignmentOffset(legendHeight, columnHeights[0]), line: 0 }; } helpers$1.rtl.overrideTextDirection(me.ctx, opts.textDirection); var itemHeight = fontSize + labelOpts.padding; helpers$1.each(me.legendItems, function(legendItem, i) { var textWidth = ctx.measureText(legendItem.text).width; var width = boxWidth + (fontSize / 2) + textWidth; var x = cursor.x; var y = cursor.y; rtlHelper.setWidth(me.minSize.width); // Use (me.left + me.minSize.width) and (me.top + me.minSize.height) // instead of me.right and me.bottom because me.width and me.height // may have been changed since me.minSize was calculated if (isHorizontal) { if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) { y = cursor.y += itemHeight; cursor.line++; x = cursor.x = me.left + alignmentOffset(legendWidth, lineWidths[cursor.line]); } } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) { x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding; cursor.line++; y = cursor.y = me.top + alignmentOffset(legendHeight, columnHeights[cursor.line]); } var realX = rtlHelper.x(x); drawLegendBox(realX, y, legendItem); hitboxes[i].left = rtlHelper.leftForLtr(realX, hitboxes[i].width); hitboxes[i].top = y; // Fill the actual label fillText(realX, y, legendItem, textWidth); if (isHorizontal) { cursor.x += width + labelOpts.padding; } else { cursor.y += itemHeight; } }); helpers$1.rtl.restoreTextDirection(me.ctx, opts.textDirection); }, /** * @private */ _getLegendItemAt: function(x, y) { var me = this; var i, hitBox, lh; if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) { // See if we are touching one of the dataset boxes lh = me.legendHitBoxes; for (i = 0; i < lh.length; ++i) { hitBox = lh[i]; if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) { // Touching an element return me.legendItems[i]; } } } return null; }, /** * Handle an event * @private * @param {IEvent} event - The event to handle */ handleEvent: function(e) { var me = this; var opts = me.options; var type = e.type === 'mouseup' ? 'click' : e.type; var hoveredItem; if (type === 'mousemove') { if (!opts.onHover && !opts.onLeave) { return; } } else if (type === 'click') { if (!opts.onClick) { return; } } else { return; } // Chart event already has relative position in it hoveredItem = me._getLegendItemAt(e.x, e.y); if (type === 'click') { if (hoveredItem && opts.onClick) { // use e.native for backwards compatibility opts.onClick.call(me, e.native, hoveredItem); } } else { if (opts.onLeave && hoveredItem !== me._hoveredItem) { if (me._hoveredItem) { opts.onLeave.call(me, e.native, me._hoveredItem); } me._hoveredItem = hoveredItem; } if (opts.onHover && hoveredItem) { // use e.native for backwards compatibility opts.onHover.call(me, e.native, hoveredItem); } } } }); function createNewLegendAndAttach(chart, legendOpts) { var legend = new Legend({ ctx: chart.ctx, options: legendOpts, chart: chart }); core_layouts.configure(chart, legend, legendOpts); core_layouts.addBox(chart, legend); chart.legend = legend; } var plugin_legend = { id: 'legend', /** * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of * the plugin, which one will be re-exposed in the chart.js file. * https://github.com/chartjs/Chart.js/pull/2640 * @private */ _element: Legend, beforeInit: function(chart) { var legendOpts = chart.options.legend; if (legendOpts) { createNewLegendAndAttach(chart, legendOpts); } }, beforeUpdate: function(chart) { var legendOpts = chart.options.legend; var legend = chart.legend; if (legendOpts) { helpers$1.mergeIf(legendOpts, core_defaults.global.legend); if (legend) { core_layouts.configure(chart, legend, legendOpts); legend.options = legendOpts; } else { createNewLegendAndAttach(chart, legendOpts); } } else if (legend) { core_layouts.removeBox(chart, legend); delete chart.legend; } }, afterEvent: function(chart, e) { var legend = chart.legend; if (legend) { legend.handleEvent(e); } } }; var noop$2 = helpers$1.noop; core_defaults._set('global', { title: { display: false, fontStyle: 'bold', fullWidth: true, padding: 10, position: 'top', text: '', weight: 2000 // by default greater than legend (1000) to be above } }); /** * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required! */ var Title = core_element.extend({ initialize: function(config) { var me = this; helpers$1.extend(me, config); // Contains hit boxes for each dataset (in dataset order) me.legendHitBoxes = []; }, // These methods are ordered by lifecycle. Utilities then follow. beforeUpdate: noop$2, update: function(maxWidth, maxHeight, margins) { var me = this; // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) me.beforeUpdate(); // Absorb the master measurements me.maxWidth = maxWidth; me.maxHeight = maxHeight; me.margins = margins; // Dimensions me.beforeSetDimensions(); me.setDimensions(); me.afterSetDimensions(); // Labels me.beforeBuildLabels(); me.buildLabels(); me.afterBuildLabels(); // Fit me.beforeFit(); me.fit(); me.afterFit(); // me.afterUpdate(); return me.minSize; }, afterUpdate: noop$2, // beforeSetDimensions: noop$2, setDimensions: function() { var me = this; // Set the unconstrained dimension before label rotation if (me.isHorizontal()) { // Reset position before calculating rotation me.width = me.maxWidth; me.left = 0; me.right = me.width; } else { me.height = me.maxHeight; // Reset position before calculating rotation me.top = 0; me.bottom = me.height; } // Reset padding me.paddingLeft = 0; me.paddingTop = 0; me.paddingRight = 0; me.paddingBottom = 0; // Reset minSize me.minSize = { width: 0, height: 0 }; }, afterSetDimensions: noop$2, // beforeBuildLabels: noop$2, buildLabels: noop$2, afterBuildLabels: noop$2, // beforeFit: noop$2, fit: function() { var me = this; var opts = me.options; var minSize = me.minSize = {}; var isHorizontal = me.isHorizontal(); var lineCount, textSize; if (!opts.display) { me.width = minSize.width = me.height = minSize.height = 0; return; } lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1; textSize = lineCount * helpers$1.options._parseFont(opts).lineHeight + opts.padding * 2; me.width = minSize.width = isHorizontal ? me.maxWidth : textSize; me.height = minSize.height = isHorizontal ? textSize : me.maxHeight; }, afterFit: noop$2, // Shared Methods isHorizontal: function() { var pos = this.options.position; return pos === 'top' || pos === 'bottom'; }, // Actually draw the title block on the canvas draw: function() { var me = this; var ctx = me.ctx; var opts = me.options; if (!opts.display) { return; } var fontOpts = helpers$1.options._parseFont(opts); var lineHeight = fontOpts.lineHeight; var offset = lineHeight / 2 + opts.padding; var rotation = 0; var top = me.top; var left = me.left; var bottom = me.bottom; var right = me.right; var maxWidth, titleX, titleY; ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour ctx.font = fontOpts.string; // Horizontal if (me.isHorizontal()) { titleX = left + ((right - left) / 2); // midpoint of the width titleY = top + offset; maxWidth = right - left; } else { titleX = opts.position === 'left' ? left + offset : right - offset; titleY = top + ((bottom - top) / 2); maxWidth = bottom - top; rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5); } ctx.save(); ctx.translate(titleX, titleY); ctx.rotate(rotation); ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; var text = opts.text; if (helpers$1.isArray(text)) { var y = 0; for (var i = 0; i < text.length; ++i) { ctx.fillText(text[i], 0, y, maxWidth); y += lineHeight; } } else { ctx.fillText(text, 0, 0, maxWidth); } ctx.restore(); } }); function createNewTitleBlockAndAttach(chart, titleOpts) { var title = new Title({ ctx: chart.ctx, options: titleOpts, chart: chart }); core_layouts.configure(chart, title, titleOpts); core_layouts.addBox(chart, title); chart.titleBlock = title; } var plugin_title = { id: 'title', /** * Backward compatibility: since 2.1.5, the title is registered as a plugin, making * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of * the plugin, which one will be re-exposed in the chart.js file. * https://github.com/chartjs/Chart.js/pull/2640 * @private */ _element: Title, beforeInit: function(chart) { var titleOpts = chart.options.title; if (titleOpts) { createNewTitleBlockAndAttach(chart, titleOpts); } }, beforeUpdate: function(chart) { var titleOpts = chart.options.title; var titleBlock = chart.titleBlock; if (titleOpts) { helpers$1.mergeIf(titleOpts, core_defaults.global.title); if (titleBlock) { core_layouts.configure(chart, titleBlock, titleOpts); titleBlock.options = titleOpts; } else { createNewTitleBlockAndAttach(chart, titleOpts); } } else if (titleBlock) { core_layouts.removeBox(chart, titleBlock); delete chart.titleBlock; } } }; var plugins = {}; var filler = plugin_filler; var legend = plugin_legend; var title = plugin_title; plugins.filler = filler; plugins.legend = legend; plugins.title = title; /** * @namespace Chart */ core_controller.helpers = helpers$1; // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests! core_helpers(); core_controller._adapters = core_adapters; core_controller.Animation = core_animation; core_controller.animationService = core_animations; core_controller.controllers = controllers; core_controller.DatasetController = core_datasetController; core_controller.defaults = core_defaults; core_controller.Element = core_element; core_controller.elements = elements; core_controller.Interaction = core_interaction; core_controller.layouts = core_layouts; core_controller.platform = platform; core_controller.plugins = core_plugins; core_controller.Scale = core_scale; core_controller.scaleService = core_scaleService; core_controller.Ticks = core_ticks; core_controller.Tooltip = core_tooltip; // Register built-in scales core_controller.helpers.each(scales, function(scale, type) { core_controller.scaleService.registerScaleType(type, scale, scale._defaults); }); // Load to register built-in adapters (as side effects) // Loading built-in plugins for (var k in plugins) { if (plugins.hasOwnProperty(k)) { core_controller.plugins.register(plugins[k]); } } core_controller.platform.initialize(); var src = core_controller; if (typeof window !== 'undefined') { window.Chart = core_controller; } // DEPRECATIONS /** * Provided for backward compatibility, not available anymore * @namespace Chart.Chart * @deprecated since version 2.8.0 * @todo remove at version 3 * @private */ core_controller.Chart = core_controller; /** * Provided for backward compatibility, not available anymore * @namespace Chart.Legend * @deprecated since version 2.1.5 * @todo remove at version 3 * @private */ core_controller.Legend = plugins.legend._element; /** * Provided for backward compatibility, not available anymore * @namespace Chart.Title * @deprecated since version 2.1.5 * @todo remove at version 3 * @private */ core_controller.Title = plugins.title._element; /** * Provided for backward compatibility, use Chart.plugins instead * @namespace Chart.pluginService * @deprecated since version 2.1.5 * @todo remove at version 3 * @private */ core_controller.pluginService = core_controller.plugins; /** * Provided for backward compatibility, inheriting from Chart.PlugingBase has no * effect, instead simply create/register plugins via plain JavaScript objects. * @interface Chart.PluginBase * @deprecated since version 2.5.0 * @todo remove at version 3 * @private */ core_controller.PluginBase = core_controller.Element.extend({}); /** * Provided for backward compatibility, use Chart.helpers.canvas instead. * @namespace Chart.canvasHelpers * @deprecated since version 2.6.0 * @todo remove at version 3 * @private */ core_controller.canvasHelpers = core_controller.helpers.canvas; /** * Provided for backward compatibility, use Chart.layouts instead. * @namespace Chart.layoutService * @deprecated since version 2.7.3 * @todo remove at version 3 * @private */ core_controller.layoutService = core_controller.layouts; /** * Provided for backward compatibility, not available anymore. * @namespace Chart.LinearScaleBase * @deprecated since version 2.8 * @todo remove at version 3 * @private */ core_controller.LinearScaleBase = scale_linearbase; /** * Provided for backward compatibility, instead we should create a new Chart * by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`). * @deprecated since version 2.8.0 * @todo remove at version 3 */ core_controller.helpers.each( [ 'Bar', 'Bubble', 'Doughnut', 'Line', 'PolarArea', 'Radar', 'Scatter' ], function(klass) { core_controller[klass] = function(ctx, cfg) { return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, { type: klass.charAt(0).toLowerCase() + klass.slice(1) })); }; } ); return src; })));
""" Custom Norm wrappers to enable sync BN, regular BN and for weight initialization """ import torch.nn as nn def Norm2d(in_channels): """ Custom Norm Function to allow flexible switching """ return nn.BatchNorm2d(in_channels) def initialize_weights(*models): """ Initialize Model Weights """ for model in models: for module in model.modules(): if isinstance(module, (nn.Conv2d, nn.Linear)): nn.init.kaiming_normal_(module.weight) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.BatchNorm2d): module.weight.data.fill_(1) module.bias.data.zero_() def Upsample(x, size): """ Wrapper Around the Upsample Call """ return nn.functional.interpolate(x, size=size, mode="bilinear", align_corners=True)
import os import numpy as np import pandas as pd import seaborn as sn import matplotlib import matplotlib.pyplot as plt import glob from time import gmtime, strftime from datetime import datetime import timeit import yaml import argparse from tensorflow.keras.optimizers import Adam from go_model.evaluate_model import evaluate_model from utils.write_txt import write_txt from utils.get_stats_plots import get_stats_plots if __name__ == '__main__': proj_dir = '/home/bhkann/zezhong/git_repo/IV-Contrast-CNN-Project' out_dir = '/mnt/aertslab/USERS/Zezhong/contrast_detection' saved_model = 'EffNet_2021_08_21_22_41_34' # 'ResNet_2021_07_18_06_28_40', 'cnn_2021_07_19_21_56_34', 'inception_2021_08_21_15_16_12' batch_size = 32 epoch = 500 lr = 1e-5 run_model = 'EffNet' model_dir = os.path.join(out_dir, 'model') pro_data_dir = os.path.join(proj_dir, 'pro_data') if not os.path.exists(model_dir): os.mkdir(model_dir) if not os.path.exists(pro_data_dir): os.mkdir(pro_data_dir) print('\n--- STEP 3 - MODEL EVALUATION ---\n') for run_type in ['val', 'test']: # evalute model loss, acc = evaluate_model( run_type=run_type, model_dir=model_dir, pro_data_dir=pro_data_dir, saved_model=saved_model, threshold=0.5, activation='sigmoid' ) # get statistic and plots get_stats_plots( out_dir=out_dir, proj_dir=proj_dir, run_type=run_type, run_model=run_model, loss=None, acc=None, saved_model=saved_model, epoch=epoch, batch_size=batch_size, lr=lr, thr_img=0.5, thr_prob=0.5, thr_pos=0.5, bootstrap=1000, )
#!/usr/bin/env python3 # Copyright (c) 2012-2018 The Picscoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Extract _("...") strings for translation and convert to Qt stringdefs so that they can be picked up by Qt linguist. ''' from subprocess import Popen, PIPE import operator import os import sys OUT_CPP="qt/picscoinstrings.cpp" EMPTY=['""'] def parse_po(text): """ Parse 'po' format produced by xgettext. Return a list of (msgid,msgstr) tuples. """ messages = [] msgid = [] msgstr = [] in_msgid = False in_msgstr = False for line in text.split('\n'): line = line.rstrip('\r') if line.startswith('msgid '): if in_msgstr: messages.append((msgid, msgstr)) in_msgstr = False # message start in_msgid = True msgid = [line[6:]] elif line.startswith('msgstr '): in_msgid = False in_msgstr = True msgstr = [line[7:]] elif line.startswith('"'): if in_msgid: msgid.append(line) if in_msgstr: msgstr.append(line) if in_msgstr: messages.append((msgid, msgstr)) return messages files = sys.argv[1:] # xgettext -n --keyword=_ $FILES XGETTEXT=os.getenv('XGETTEXT', 'xgettext') if not XGETTEXT: print('Cannot extract strings: xgettext utility is not installed or not configured.',file=sys.stderr) print('Please install package "gettext" and re-run \'./configure\'.',file=sys.stderr) sys.exit(1) child = Popen([XGETTEXT,'--output=-','-n','--keyword=_'] + files, stdout=PIPE) (out, err) = child.communicate() messages = parse_po(out.decode('utf-8')) f = open(OUT_CPP, 'w', encoding="utf8") f.write(""" #include <QtGlobal> // Automatically generated by extract_strings_qt.py #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else #define UNUSED #endif """) f.write('static const char UNUSED *picscoin_strings[] = {\n') f.write('QT_TRANSLATE_NOOP("picscoin-core", "%s"),\n' % (os.getenv('COPYRIGHT_HOLDERS'),)) messages.sort(key=operator.itemgetter(0)) for (msgid, msgstr) in messages: if msgid != EMPTY: f.write('QT_TRANSLATE_NOOP("picscoin-core", %s),\n' % ('\n'.join(msgid))) f.write('};\n') f.close()
# global import torch from torch import Tensor import typing import math # local import ivy def expm1(x: Tensor)\ -> Tensor: return torch.expm1(x) def bitwise_invert(x: torch.Tensor) \ -> torch.Tensor: return torch.bitwise_not(x) def isfinite(x: Tensor)\ -> Tensor: return torch.isfinite(x) def isinf(x: torch.Tensor) \ -> torch.Tensor: return torch.isinf(x) def _cast_for_binary_op(x1: Tensor, x2: Tensor)\ -> typing.Tuple[typing.Union[Tensor, int, float, bool], typing.Union[Tensor, int, float, bool]]: x1_bits = ivy.functional.backends.torch.dtype_bits(x1.dtype) if isinstance(x2, (int, float, bool)): return x1, x2 x2_bits = ivy.functional.backends.torch.dtype_bits(x2.dtype) if x1_bits > x2_bits: x2 = x2.type(x1.dtype) elif x2_bits > x1_bits: x1 = x1.type(x2.dtype) return x1, x2 def equal(x1: Tensor, x2: Tensor)\ -> Tensor: x1, x2 = _cast_for_binary_op(x1, x2) return x1 == x2 def less_equal(x1: Tensor, x2: Tensor)\ -> Tensor: x1, x2 = _cast_for_binary_op(x1, x2) return x1 <= x2 def bitwise_and(x1: torch.Tensor, x2: torch.Tensor)\ -> torch.Tensor: return torch.bitwise_and(x1, x2) def ceil(x: torch.Tensor)\ -> torch.Tensor: if 'int' in str(x.dtype): return x return torch.ceil(x) def floor(x: torch.Tensor)\ -> torch.Tensor: if 'int' in str(x.dtype): return x return torch.floor(x) def isfinite(x: torch.Tensor) \ -> torch.Tensor: return torch.isfinite(x) def asin(x: torch.Tensor) \ -> torch.Tensor: return torch.asin(x) def asinh(x: torch.Tensor) \ -> torch.Tensor: return torch.asinh(x) def sqrt(x: torch.Tensor)\ -> torch.Tensor: return torch.sqrt(x) def cosh(x: torch.Tensor) \ -> torch.Tensor: return torch.cosh(x) def log10(x: torch.Tensor) \ -> torch.Tensor: return torch.log10(x) def log(x: torch.Tensor)\ -> torch.Tensor: return torch.log(x) def log2(x: torch.Tensor) \ -> torch.Tensor: return torch.log2(x) def log1p(x: torch.Tensor) \ -> torch.Tensor: return torch.log1p(x) def isnan(x: torch.Tensor)\ -> torch.Tensor: return torch.isnan(x) def less(x1: torch.Tensor, x2: torch.Tensor): if hasattr(x1, 'dtype') and hasattr(x2, 'dtype'): promoted_type = torch.promote_types(x1.dtype, x2.dtype) x1 = x1.to(promoted_type) x2 = x2.to(promoted_type) return torch.lt(x1, x2) def multiply(x1: torch.Tensor, x2: torch.Tensor)\ -> torch.Tensor: if hasattr(x1, 'dtype') and hasattr(x2, 'dtype'): promoted_type = torch.promote_types(x1.dtype, x2.dtype) x1 = x1.to(promoted_type) x2 = x2.to(promoted_type) return torch.multiply(x1, x2) def cos(x: torch.Tensor)\ -> torch.Tensor: return torch.cos(x) def logical_not(x: torch.Tensor)\ -> torch.Tensor: return torch.logical_not(x.type(torch.bool)) def greater_equal(x1: torch.Tensor, x2: torch.Tensor): if hasattr(x1, 'dtype') and hasattr(x2, 'dtype'): promoted_type = torch.promote_types(x1.dtype, x2.dtype) x1 = x1.to(promoted_type) x2 = x2.to(promoted_type) return torch.greater_equal(x1, x2) def acos(x: torch.Tensor)\ -> torch.Tensor: return torch.acos(x) def logical_xor(x1: torch.Tensor, x2: torch.Tensor) \ -> torch.Tensor: return torch.logical_xor(x1.type(torch.bool), x2.type(torch.bool)) def logical_and(x1: torch.Tensor, x2: torch.Tensor)\ -> torch.Tensor: return torch.logical_and(x1.type(torch.bool), x2.type(torch.bool)) def logical_or(x1: torch.Tensor, x2: torch.Tensor)\ -> torch.Tensor: return torch.logical_or(x1.type(torch.bool), x2.type(torch.bool)) def acosh(x: torch.Tensor) \ -> torch.Tensor: return torch.acosh(x) def sin(x: torch.Tensor)\ -> torch.Tensor: return torch.sin(x) def negative(x: torch.Tensor) -> torch.Tensor: return torch.neg(x) def not_equal(x1: Tensor, x2: Tensor)\ -> Tensor: x1, x2 = _cast_for_binary_op(x1, x2) return torch.not_equal(x1, x2) def tanh(x: torch.Tensor) -> torch.Tensor: return torch.tanh(x) def bitwise_or(x1: torch.Tensor, x2: torch.Tensor) \ -> torch.Tensor: x1, x2 = _cast_for_binary_op(x1, x2) return torch.bitwise_or(x1, x2) def sinh(x: torch.Tensor) -> torch.Tensor: return torch.sinh(x) def positive(x: torch.Tensor)\ -> torch.Tensor: return torch.positive(x) def square(x: torch.Tensor) \ -> torch.Tensor: return torch.square(x) def round(x: torch.Tensor)\ -> torch.Tensor: if 'int' in str(x.dtype): return x return torch.round(x) def abs(x: torch.Tensor)\ -> torch.Tensor: return torch.abs(x) def logaddexp(x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor: x1, x2 = _cast_for_binary_op(x1, x2) return torch.logaddexp(x1, x2) def tan(x: torch.Tensor)\ -> torch.Tensor: return torch.tan(x) def acos(x: torch.Tensor)\ -> torch.Tensor: return torch.acos(x) def atan(x: torch.Tensor) \ -> torch.Tensor: return torch.atan(x) def atan2(x1: Tensor, x2: Tensor) -> Tensor: if hasattr(x1, 'dtype') and hasattr(x2, 'dtype'): promoted_type = torch.promote_types(x1.dtype, x2.dtype) x1 = x1.to(promoted_type) x2 = x2.to(promoted_type) return torch.atan2(x1, x2) def cosh(x: torch.Tensor)\ -> torch.Tensor: return torch.cosh(x) def log(x: torch.Tensor)\ -> torch.Tensor: return torch.log(x) def exp(x: torch.Tensor)\ -> torch.Tensor: return torch.exp(x) def subtract(x1: torch.Tensor, x2: torch.Tensor)\ -> torch.Tensor: if hasattr(x1, 'dtype') and hasattr(x2, 'dtype'): promoted_type = torch.promote_types(x1.dtype, x2.dtype) x1 = x1.to(promoted_type) x2 = x2.to(promoted_type) return torch.subtract(x1, x2) def remainder(x1: torch.Tensor, x2: torch.Tensor)\ -> torch.Tensor: x1, x2 = _cast_for_binary_op(x1, x2) return torch.remainder(x1, x2) def atanh(x: torch.Tensor) \ -> torch.Tensor: if isinstance(x, float): return math.atanh(x) return torch.atanh(x) def bitwise_right_shift(x1: torch.Tensor, x2: torch.Tensor)\ -> torch.Tensor: if hasattr(x1, 'dtype') and hasattr(x2, 'dtype'): promoted_type = torch.promote_types(x1.dtype, x2.dtype) x2 = torch.clamp(x2, max=torch.iinfo(promoted_type).bits - 1) x1 = x1.to(promoted_type) x2 = x2.to(promoted_type) return torch.bitwise_right_shift(x1, x2) # Extra # # ------# def erf(x: torch.Tensor)\ -> torch.Tensor: return torch.erf(x) def minimum(x, y): x_val = torch.tensor(x) if (isinstance(x, int) or isinstance(x, float)) else x y_val = torch.tensor(y) if (isinstance(y, int) or isinstance(y, float)) else y return torch.min(x_val, y_val) def maximum(x, y): x_val = torch.tensor(x) if (isinstance(x, int) or isinstance(x, float)) else x y_val = torch.tensor(y) if (isinstance(y, int) or isinstance(y, float)) else y return torch.max(x_val, y_val)
# Iterative approach using stack # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: if root1 == None: return root2 stack = [] stack.append([root1, root2]) while stack: node = stack.pop() # possible when tree2 node was None if node[0]==None or node[1]==None: continue node[0].val += node[1].val # merging tree2's left subtree with tree1's left subtree if node[0].left == None: node[0].left = node[1].left else: stack.append([node[0].left, node[1].left]) # merging tree2's right subtree with tree1's right subtree if node[0].right == None: node[0].right = node[1].right else: stack.append([node[0].right, node[1].right]) return root1
const {encode} = require('cbor'); const {grpcProxyServer} = require('ln-service/routers'); const moment = require('moment'); const {restrictMacaroon} = require('ln-service'); const base64AsBuf = base64 => Buffer.from(base64, 'base64'); const bufferAsHex = buffer => buffer.toString('hex'); const expiryMs = n => 1000 * 60 * n; const maxTimeLimitMinutes = 60; const {now} = Date; const path = '/v0/grpc/'; /** Start an LND gateway server { credentials: { cert: <LND Base64 Encoded String> socket: <LND Socket String> } [is_nospend]: <Restrict Credentials To Non-Spending Permissions Bool> logger: <Winston Logger Object> minutes: <Expire Access in Minutes Number> port: <Listen Port Number> remote: <Remote Gateway URL String> } @returns {} */ module.exports = args => { if (!args.credentials) { throw new Error('ExpectedCredentialsForLndGateway'); } if (!args.credentials.cert) { throw new Error('ExpectedCertToStartLndGateway'); } if (!args.logger) { throw new Error('ExpectedLoggerToStartLndGateway'); } if (!args.minutes) { throw new Error('ExpectedMinutesToStartLndGateway'); } if (args.minutes > maxTimeLimitMinutes) { throw new Error('ExpectedMinutesToBeLessThanOrEqualToOneHour'); } if (!args.port) { throw new Error('ExpectedPortToStartLndGateway'); } if (!args.credentials.socket) { throw new Error('ExpectedLndRpcSocketToStartLndGateway'); } const expiry = new Date(now() + expiryMs(args.minutes)); const {macaroon} = restrictMacaroon({ expires_at: expiry.toISOString(), macaroon: args.credentials.macaroon, }); const code = encode({ macaroon: base64AsBuf(macaroon), port: !args.remote ? args.port : undefined, url: args.remote || undefined, }); args.logger.info({ connection_code: bufferAsHex(code), expires_at: moment(expiry).calendar(), }); if (!!args.remote) { return; } const log = (err, line) => { if (!!err) { return args.logger.error({gateway: err}); } return args.logger.info({ gateway: line, is_nospend: !!args.is_nospend, }) }; const {app, server, wss} = grpcProxyServer({ log, path, cert: args.credentials.cert, port: args.port, socket: args.credentials.socket, }); return {}; };
#!/usr/bin/python import sys import argparse import terminal_colors as tc import app_ui as ui import os import json #import time #import datetime import wx global app_description, verbose_mode, quiet_mode app_description = None verbose_mode = None quiet_mode = None def get_options(): global app_description, verbose_mode app_description = "WX Library Specs - Apollo Lighting System v.0.1 1-0-2019" parser = argparse.ArgumentParser(description=app_description) parser.add_argument("-v", "--verbose", dest="verbose", action="store_true", help="display verbose info (False)") parser.add_argument("-q", "--quiet", dest="quiet", action="store_true", help="don't use terminal colors (False)") args = parser.parse_args() verbose_mode = args.verbose quiet_mode = args.quiet def validate_options(): pass def introduction(): ui.app_description(app_description) ui.report_verbose("verbose mode") ui.report_verbose() def initialize(): get_options() validate_options() tc.begin(quiet_mode) ui.begin(verbose_mode, quiet_mode) introduction() def reset_library(): wx.begin(api_key, zip_code, timezone_offset, verbose_mode, quiet_mode) def fixture_path(filename): script_path = os.getcwd() return os.path.join(script_path, "spec_fixtures", filename) def load_fixture(filename): filename = fixture_path(filename) ui.report_verbose("opening fixture file: " + filename) with open(filename, "r") as text_file: data_str = text_file.read() return data_str def load_fixture_json(filename): json_str = load_fixture(filename) json_data = json.loads(json_str) ui.report_verbose("parsed json data: " + str(json_data)) return json_data def expected(text): return tc.green(text) def got(text): return tc.red(text) def report_failed_expectation(description, message): ui.report_error("failed expectation: " + description); ui.report_info_alt(message) def expect_equal(description, got_, expected_): if expected_ == got_: return True else: message = "expected: " + expected(str(expected_)) + " got: " + got(str(got_)) report_failed_expectation(description, message) def loop(): ui.report_info("known good daily data") json_data = load_fixture_json("weather_daily_known_good.json") expect_equal("daily city", wx.daily_city(json_data), "Antioch") expect_equal("daily latitude", wx.daily_lat(json_data), 38.02) expect_equal("daily longitude", wx.daily_lon(json_data), -121.89) expect_equal("daily timestamp", wx.daily_timestamp(json_data), 1548007800) expect_equal("daily visibility", wx.daily_visibility(json_data), 16093) expect_equal("daily sunrise", wx.daily_sunrise(json_data), 1547997595) expect_equal("daily sunset", wx.daily_sunset(json_data), 1548033483) expect_equal("daily wind speed", wx.daily_wind_speed(json_data), 14.99) expect_equal("daily wind direction", wx.daily_wind_deg(json_data), 190) expect_equal("daily pressure", wx.daily_pressure(json_data), 1018) expect_equal("daily humidity", wx.daily_humidity(json_data), 93) expect_equal("daily temp min", wx.daily_temp_min(json_data), 55.04) expect_equal("daily temp max", wx.daily_temp_max(json_data), 60.8) expect_equal("daily temp", wx.daily_temp(json_data), 57.63) expect_equal("daily description", wx.daily_description(json_data), "light rain") expect_equal("daily conditions", wx.daily_conditions(json_data), "Rain") expect_equal("daily conditions id", wx.daily_id(json_data), 500) ui.report_info("empty daily data") json_data = load_fixture_json("weather_daily_empty.json") expect_equal("daily city", wx.daily_city(json_data), "") expect_equal("daily latitide", wx.daily_lat(json_data), 0.0) expect_equal("daily longitude", wx.daily_lon(json_data), 0.0) expect_equal("daily timestamp", wx.daily_timestamp(json_data), 0) expect_equal("daily visibility", wx.daily_visibility(json_data), 0) expect_equal("daily sunrise", wx.daily_sunrise(json_data), 0) expect_equal("daily sunset", wx.daily_sunset(json_data), 0) expect_equal("daily wind speed", wx.daily_wind_speed(json_data), 0.0) expect_equal("daily wind direction", wx.daily_wind_deg(json_data), 0) expect_equal("daily pressure", wx.daily_pressure(json_data), 0) expect_equal("daily humidity", wx.daily_humidity(json_data), 0) expect_equal("daily temp min", wx.daily_temp_min(json_data), 0.0) expect_equal("daily temp max", wx.daily_temp_max(json_data), 0.0) expect_equal("daily temp", wx.daily_temp(json_data), 0.0) expect_equal("daily description", wx.daily_description(json_data), "") expect_equal("daily conditions", wx.daily_conditions(json_data), "") expect_equal("daily conditions id", wx.daily_id(json_data), 0) ui.report_info("corrupt daily data") json_data = load_fixture_json("weather_daily_corrupt.json") expect_equal("daily city", wx.daily_city(json_data), "") expect_equal("daily latitide", wx.daily_lat(json_data), 0.0) expect_equal("daily longitude", wx.daily_lon(json_data), 0.0) expect_equal("daily timestamp", wx.daily_timestamp(json_data), 0) expect_equal("daily visibility", wx.daily_visibility(json_data), 0) expect_equal("daily sunrise", wx.daily_sunrise(json_data), 0) expect_equal("daily sunset", wx.daily_sunset(json_data), 0) expect_equal("daily wind speed", wx.daily_wind_speed(json_data), 0.0) expect_equal("daily wind direction", wx.daily_wind_deg(json_data), 0) expect_equal("daily pressure", wx.daily_pressure(json_data), 0) expect_equal("daily humidity", wx.daily_humidity(json_data), 0) expect_equal("daily temp min", wx.daily_temp_min(json_data), 0.0) expect_equal("daily temp max", wx.daily_temp_max(json_data), 0.0) expect_equal("daily temp", wx.daily_temp(json_data), 0.0) expect_equal("daily description", wx.daily_description(json_data), "") expect_equal("daily conditions", wx.daily_conditions(json_data), "") expect_equal("daily conditions id", wx.daily_id(json_data), 0) sys.exit() if __name__ == '__main__': initialize() while True: try: loop() except KeyboardInterrupt: sys.exit("\nExiting...\n") except Exception: raise
import random import matplotlib.pyplot as plt from typing import Tuple def trans_1(p: Tuple[float, float]): x, y = p x, y = 0.85*x + 0.04*y, -0.04*x + 0.85*y + 16 return x, y def trans_2(p: Tuple[float, float]): x, y = p x, y = 0.2*x - 0.26*y, 0.23*x + 0.22*y + 1.6 return x, y def trans_3(p: Tuple[float, float]): x, y = p x, y = -0.15*x + 0.28*y, 0.26*x + 0.24*y + 0.44 return x, y def trans_4(p: Tuple[float, float]): x, y = p x, y = 0, 0.16*y return x, y def transform(p: Tuple[float, float]): transformations = [trans_1, trans_2, trans_3, trans_4] probability = [0.85, 0.07, 0.07, 0.01] trans = random.choices(transformations, weights=probability) return trans[0](p) def draw_fern(n, p): xi, yi = p x, y = [xi], [yi] for _ in range(n): xi, yi = transform((xi, yi)) x.append(xi) y.append(yi) return x, y if __name__ == '__main__': n = int(input("Enter the number of points in the Fern: ")) x, y = draw_fern(n, (0.0, 0.0)) plt.plot(x, y, '*') plt.title("Fern with {} points.".format(n)) plt.show()
import os import platform from glob import glob from setuptools import setup from setuptools.extension import Extension from Cython.Distutils import build_ext import numpy VERSION = "3.8.0" NAME = "ms2pip" LICENSE = "apache-2.0" DESCRIPTION = "MS²PIP: MS² Peak Intensity Prediction" AUTHOR = "Sven Degroeve, Ralf Gabriels, Kevin Velghe, Ana Sílvia C. Silva" AUTHOR_EMAIL = "sven.degroeve@vib-ugent.be" URL = "https://www.github.com/compomics/ms2pip_c" PROJECT_URLS = { "Documentation": "http://compomics.github.io/projects/ms2pip_c", "Source": "https://github.com/compomics/ms2pip_c", "Tracker": "https://github.com/compomics/ms2pip_c/issues", "Webserver": "https://iomics.ugent.be/ms2pip/", "Publication": "https://doi.org/10.1093/nar/gkz299/", } KEYWORDS = [ "MS2PIP", "Proteomics", "peptides", "peak intensity prediction", "spectrum", "machine learning", "spectral library", "fasta2speclib", ] CLASSIFIERS = [ "Intended Audience :: Science/Research", "License :: OSI Approved :: Apache Software License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3 :: Only", "Topic :: Scientific/Engineering :: Bio-Informatics", "Development Status :: 5 - Production/Stable", ] INSTALL_REQUIRES = [ "biopython>=1.74,<2", "numpy>=1.16,<2", "pandas>=0.24,<2", "pyteomics>=3.5,<5", "scipy>=1.2,<2", "tqdm>=4,<5", "tables>=3.4", "tomlkit>=0.5,<1", "sqlalchemy>=1.3,<2", "spectrum-utils>=0.3,<2", "click>=7,<9", "xgboost>=1.3,<2" "matplotlib>=3.0", "spectrum_utils>=0.3.5" ] PYTHON_REQUIRES = ">=3.6,<4" with open("README.md", "r") as fh: LONG_DESCRIPTION = fh.read() to_remove = [ "ms2pip/cython_modules/ms2pip_pyx.c*", "ms2pip/cython_modules/ms2pip_pyx.so", ] #_ = [[os.remove(f) for f in glob(pat)] for pat in to_remove] # Large machine-written C model files require optimization to be disabled compile_args = { "Linux": [ "-O0", "-fno-var-tracking", "-Wno-unused-result", "-Wno-cpp", "-Wno-unused-function", ], "Darwin": [ "-O0", ], "Windows": [ "/Od", "/DEBUG", "/GL-", "/bigobj", "/wd4244", ] } extensions = [ Extension( "ms2pip.cython_modules.ms2pip_pyx", sources=["ms2pip/cython_modules/ms2pip_pyx.pyx"] + glob("ms2pip/models/*/*.c"), extra_compile_args=compile_args[platform.system()], ) ] setup( name=NAME, version=VERSION, license=LICENSE, description=DESCRIPTION, long_description=LONG_DESCRIPTION, long_description_content_type="text/markdown", author=AUTHOR, author_email=AUTHOR_EMAIL, url=URL, project_urls=PROJECT_URLS, keywords=KEYWORDS, classifiers=CLASSIFIERS, packages=["ms2pip", "ms2pip.ms2pip_tools", "fasta2speclib"], include_package_data=True, entry_points={ "console_scripts": [ "ms2pip=ms2pip.__main__:main", "fasta2speclib=fasta2speclib.fasta2speclib:main", "ms2pip-single-prediction=ms2pip.single_prediction:_main", ], }, install_requires=INSTALL_REQUIRES, python_requires=PYTHON_REQUIRES, ext_modules=extensions, include_dirs=[numpy.get_include()], cmdclass={"build_ext": build_ext}, )
import axios from 'axios'; import adapter from "axios/lib/adapters/http"; import { Product } from './product'; axios.defaults.adapter = adapter; export class API { constructor(url) { if (url === undefined || url === "") { url = process.env.REACT_APP_API_BASE_URL; } if (url.endsWith("/")) { url = url.substr(0, url.length - 1) } this.url = url } withPath(path) { if (!path.startsWith("/")) { path = "/" + path } return `${this.url}${path}` } generateAuthToken() { return "Bearer " + new Date().toISOString() } async getAllProducts() { return axios.get(this.withPath("/products"), { headers: { "Authorization": this.generateAuthToken() } }) .then(r => r.data.map(p => new Product(p))); } async getProduct(id) { return axios.get(this.withPath("/product/" + id), { headers: { "Authorization": this.generateAuthToken() } }) .then(r => new Product(r.data)); } } export default new API(process.env.REACT_APP_API_BASE_URL);
import { hasInterpolation } from "../utils" /** * Check whether a value is standard * * @param {string} value * @return {boolean} If `true`, the value is a variable */ export default function (value) { // SCSS variable if (value[0] === "$") { return false } // Less variable if (value[0] === "@") { return false } // SCSS or Less interpolation if (hasInterpolation(value)) { return false } return true }