text
stringlengths 3
1.05M
|
---|
/**
* Renders a given attributes object into a format suitable for adding to an
* HTML element.
*/
const nunjucks = require('nunjucks');
/**
* Attribute values will be HTML/attribute escaped.
*
* Example:
* Given: {class: 'basic', 'data-ga': 3}
* Output: class="basic" data-ga="3"
*
* @param {object} attrsObject Attributes object (in name:value pairs)
* @return {string} Formatted
*/
module.exports = function renderAsAttributes(attrsObject) {
const attrsList = [];
if (typeof attrsObject === 'object') {
Object.keys(attrsObject).forEach((key) => {
const value = String(attrsObject[key]).replace(/[<>"'&]/g, (m) => ({
'<': '<',
'>': '>',
'"': '"',
'\'': ''',
'&': '&',
}[m]));
attrsList.push(`${key}="${value}"`);
});
}
return new nunjucks.runtime.SafeString(attrsList.join(' '));
};
|
define([
'exports',
'module',
'./config/config',
'./model/CssRule',
'./model/CssRules',
'./view/CssRulesView',
'../selector_manager/model/Selectors',
'../selector_manager/model/Selector'
], function(exports, module, defaults, CssRule, CssRules, CssRulesView, Selectors, Selector) {
/**
* This module contains and manage CSS rules for the template inside the canvas
* Before using the methods you should get first the module from the editor instance, in this way:
*
* ```js
* var cssComposer = editor.CssComposer;
* ```
*
* @module CssComposer
* @param {Object} config Configurations
* @param {string|Array<Object>} [config.rules=[]] CSS string or an array of rule objects
* @example
* ...
* CssComposer: {
* rules: '.myClass{ color: red}',
* }
*/
'use strict';
var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
module.exports = function() {
var em = undefined;
var c = {};
var rules, rulesView;
return {
Selectors: Selectors,
/**
* Name of the module
* @type {String}
* @private
*/
name: 'CssComposer',
/**
* Mandatory for the storage manager
* @type {String}
* @private
*/
storageKey: function storageKey() {
var keys = [];
var smc = c.stm && c.stm.getConfig() || {};
if (smc.storeCss) keys.push('css');
if (smc.storeStyles) keys.push('styles');
return keys;
},
/**
* Initializes module. Automatically called with a new instance of the editor
* @param {Object} config Configurations
* @private
*/
init: function init(config) {
c = config || {};
for (var name in defaults) {
if (!(name in c)) c[name] = defaults[name];
}
var ppfx = c.pStylePrefix;
if (ppfx) c.stylePrefix = ppfx + c.stylePrefix;
var elStyle = c.em && c.em.config.style || '';
c.rules = elStyle || c.rules;
c.sm = c.em;
em = c.em;
rules = new CssRules([], c);
rulesView = new CssRulesView({
collection: rules,
config: c
});
return this;
},
/**
* On load callback
* @private
*/
onLoad: function onLoad() {
rules.add(c.rules);
},
/**
* Do stuff after load
* @param {Editor} em
* @private
*/
postLoad: function postLoad(em) {
var _this = this;
var ev = 'add remove';
var rules = this.getAll();
em.stopListening(rules, ev, this.handleChange);
em.listenTo(rules, ev, this.handleChange);
rules.each(function(rule) {
return _this.handleChange(rule);
});
},
/**
* Handle rule changes
* @private
*/
handleChange: function handleChange(model) {
var ev = 'change:style';
var um = em.get('UndoManager');
um && um.add(model);
var handleUpdates = em.handleUpdates.bind(em);
em.stopListening(model, ev, handleUpdates);
em.listenTo(model, ev, handleUpdates);
},
/**
* Load data from the passed object, if the object is empty will try to fetch them
* autonomously from the storage manager.
* The fetched data will be added to the collection
* @param {Object} data Object of data to load
* @return {Object} Loaded rules
*/
load: function load(data) {
var d = data || '';
if (!d && c.stm) {
d = c.em.getCacheLoad();
}
var obj = d.styles || '';
if (d.styles) {
try {
obj = JSON.parse(d.styles);
} catch (err) {}
} else if (d.css) {
obj = c.em.get('Parser').parseCss(d.css);
}
if (obj) {
rules.reset(obj);
}
return obj;
},
/**
* Store data to the selected storage
* @param {Boolean} noStore If true, won't store
* @return {Object} Data to store
*/
store: function store(noStore) {
if (!c.stm) return;
var obj = {};
var keys = this.storageKey();
if (keys.indexOf('css') >= 0) obj.css = c.em.getCss();
if (keys.indexOf('styles') >= 0) obj.styles = JSON.stringify(rules);
if (!noStore) c.stm.store(obj);
return obj;
},
/**
* Add new rule to the collection, if not yet exists with the same selectors
* @param {Array<Selector>} selectors Array of selectors
* @param {String} state Css rule state
* @param {String} width For which device this style is oriented
* @param {Object} opts Other options for the rule
* @return {Model}
* @example
* var sm = editor.SelectorManager;
* var sel1 = sm.add('myClass1');
* var sel2 = sm.add('myClass2');
* var rule = cssComposer.add([sel1, sel2], 'hover');
* rule.set('style', {
* width: '100px',
* color: '#fff',
* });
* */
add: function add(selectors, state, width, opts) {
var s = state || '';
var w = width || '';
var opt = opts || {};
var rule = this.get(selectors, s, w, opt);
if (rule) return rule;
else {
opt.state = s;
opt.mediaText = w;
opt.selectors = '';
rule = new CssRule(opt, c);
rule.get('selectors').add(selectors);
rules.add(rule);
return rule;
}
},
/**
* Get the rule
* @param {Array<Selector>} selectors Array of selectors
* @param {String} state Css rule state
* @param {String} width For which device this style is oriented
* @param {Object} ruleProps Other rule props
* @return {Model|null}
* @example
* var sm = editor.SelectorManager;
* var sel1 = sm.add('myClass1');
* var sel2 = sm.add('myClass2');
* var rule = cssComposer.get([sel1, sel2], 'hover');
* // Update the style
* rule.set('style', {
* width: '300px',
* color: '#000',
* });
* */
get: function get(selectors, state, width, ruleProps) {
var rule = null;
rules.each(function(m) {
if (rule) return;
if (m.compare(selectors, state, width, ruleProps)) rule = m;
});
return rule;
},
/**
* Get the collection of rules
* @return {Collection}
* */
getAll: function getAll() {
return rules;
},
/**
* Remove all rules
* @return {this}
*/
clear: function clear() {
this.getAll().reset();
return this;
},
/**
* Add a raw collection of rule objects
* This method overrides styles, in case, of already defined rule
* @param {Array<Object>} data Array of rule objects, eg . [{selectors: ['class1'], style: {....}}, ..]
* @param {Object} opts Options
* @return {Array<Model>}
* @private
*/
addCollection: function addCollection(data) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var result = [];
var d = data instanceof Array ? data : [data];
for (var i = 0, l = d.length; i < l; i++) {
var rule = d[i] || {};
if (!rule.selectors) continue;
var sm = c.em && c.em.get('SelectorManager');
if (!sm) console.warn('Selector Manager not found');
var sl = rule.selectors;
var sels = sl instanceof Array ? sl : [sl];
var newSels = [];
for (var j = 0, le = sels.length; j < le; j++) {
var selec = sm.add(sels[j]);
newSels.push(selec);
}
var modelExists = this.get(newSels, rule.state, rule.mediaText, rule);
var model = this.add(newSels, rule.state, rule.mediaText, rule);
var updateStyle = !modelExists || !opts.avoidUpdateStyle;
var style = rule.style || {};
if (updateStyle) {
var styleUpdate = opts.extend ? _extends({}, model.get('style'), style) : style;
model.set('style', styleUpdate);
}
result.push(model);
}
return result;
},
/**
* Add/update the CSS rule with id selector
* @param {string} name Id selector name, eg. 'my-id'
* @param {Object} style Style properties and values
* @param {Object} [opts={}] Custom options, like `state` and `mediaText`
* @return {CssRule} The new/updated rule
* @example
* const rule = cc.setIdRule('myid', { color: 'red' });
* const ruleHover = cc.setIdRule('myid', { color: 'blue' }, { state: 'hover' });
* // This will add current CSS:
* // #myid { color: red }
* // #myid:hover { color: blue }
*/
setIdRule: function setIdRule(name) {
var style = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var state = opts.state || '';
var media = opts.mediaText || em.getCurrentMedia();
var sm = em.get('SelectorManager');
var selector = sm.add({ name: name, type: Selector.TYPE_ID });
var rule = this.add(selector, state, media);
rule.setStyle(style, opts);
return rule;
},
/**
* Get the CSS rule by id selector
* @param {string} name Id selector name, eg. 'my-id'
* @param {Object} [opts={}] Custom options, like `state` and `mediaText`
* @return {CssRule}
* @example
* const rule = cc.getIdRule('myid');
* const ruleHover = cc.setIdRule('myid', { state: 'hover' });
*/
getIdRule: function getIdRule(name) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var state = opts.state || '';
var media = opts.mediaText || em.getCurrentMedia();
var selector = em.get('SelectorManager').get(name, Selector.TYPE_ID);
return selector && this.get(selector, state, media);
},
/**
* Add/update the CSS rule with class selector
* @param {string} name Class selector name, eg. 'my-class'
* @param {Object} style Style properties and values
* @param {Object} [opts={}] Custom options, like `state` and `mediaText`
* @return {CssRule} The new/updated rule
* @example
* const rule = cc.setClassRule('myclass', { color: 'red' });
* const ruleHover = cc.setClassRule('myclass', { color: 'blue' }, { state: 'hover' });
* // This will add current CSS:
* // .myclass { color: red }
* // .myclass:hover { color: blue }
*/
setClassRule: function setClassRule(name) {
var style = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var state = opts.state || '';
var media = opts.mediaText || em.getCurrentMedia();
var sm = em.get('SelectorManager');
var selector = sm.add({ name: name, type: Selector.TYPE_CLASS });
var rule = this.add(selector, state, media);
rule.setStyle(style, opts);
return rule;
},
/**
* Get the CSS rule by class selector
* @param {string} name Class selector name, eg. 'my-class'
* @param {Object} [opts={}] Custom options, like `state` and `mediaText`
* @return {CssRule}
* @example
* const rule = cc.getClassRule('myclass');
* const ruleHover = cc.getClassRule('myclass', { state: 'hover' });
*/
getClassRule: function getClassRule(name) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var state = opts.state || '';
var media = opts.mediaText || em.getCurrentMedia();
var selector = em.get('SelectorManager').get(name, Selector.TYPE_CLASS);
return selector && this.get(selector, state, media);
},
/**
* Render the block of CSS rules
* @return {HTMLElement}
* @private
*/
render: function render() {
return rulesView.render().el;
}
};
};
}); |
"""
Test module for pibackbone.
@author: Charlie Lewis
"""
from pibackbone.main import PiBackbone
def test_initial_question():
instance = PiBackbone()
instance.initial_question()
|
"""Module with all ImageNet models."""
import torch.nn as nn
# simply import all torchvision models here
from torchvision.models import * # noqa: F401, F403
# also import torchvision models with name
import torchvision.models as models
# below we overwrite the torchvision.models.vgg models since we have to wrap
# them.
class _VGGWrapper(nn.Module):
"""A custom wrapper to make sure it's compatible with Filter Pruning."""
def __init__(self, vgg_net):
"""Initialize the class with a vanilla VGG network."""
super().__init__()
# create a conv layer that corresponds to the first linear layer
linear1 = vgg_net.classifier[0]
conv = nn.Conv2d(512, 4096, 7, 7)
# copy data into it
conv.bias.data.copy_(linear1.bias.data)
conv.weight.data.view(4096, -1).copy_(linear1.weight.data)
# replace the layer in the sequential classifier part
vgg_net.classifier = nn.Sequential(
conv, nn.Flatten(1), *vgg_net.classifier[1:]
)
self.vgg_net = vgg_net
def forward(self, x):
"""Pytorch forward function."""
x = self.vgg_net.features(x)
x = self.vgg_net.avgpool(x)
x = self.vgg_net.classifier(x)
return x
def vgg11(*args):
"""Return a wrapped torchvision.models.vgg11."""
return _VGGWrapper(models.vgg11(*args))
def vgg11_bn(*args):
"""Return a wrapped torchvision.models.vgg11_bn."""
return _VGGWrapper(models.vgg11_bn(*args))
def vgg13(*args):
"""Return a wrapped torchvision.models.vgg13."""
return _VGGWrapper(models.vgg13(*args))
def vgg13_bn(*args):
"""Return a wrapped torchvision.models.vgg13_bn."""
return _VGGWrapper(models.vgg13_bn(*args))
def vgg16(*args):
"""Return a wrapped torchvision.models.vgg16."""
return _VGGWrapper(models.vgg16(*args))
def vgg16_bn(*args):
"""Return a wrapped torchvision.models.vgg16_bn."""
return _VGGWrapper(models.vgg16_bn(*args))
def vgg19(*args):
"""Return a wrapped torchvision.models.vgg19."""
return _VGGWrapper(models.vgg19(*args))
def vgg19_bn(*args):
"""Return a wrapped torchvision.models.vgg19_bn."""
return _VGGWrapper(models.vgg19_bn(*args))
class AlexNetBn(nn.Module):
"""An AlexNet with batch normalization added after each linear layer."""
def __init__(self, num_classes=1000):
"""Initialize with batch normalization now."""
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(64, 192, kernel_size=5, padding=2, bias=False),
nn.BatchNorm2d(192),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(192, 384, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(384),
nn.ReLU(inplace=True),
nn.Conv2d(384, 256, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(256),
nn.ReLU(inplace=True),
nn.Conv2d(256, 256, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(256),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
)
self.avgpool = nn.AdaptiveAvgPool2d((6, 6))
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Conv2d(256, 4096, 6, bias=False),
nn.BatchNorm2d(4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Conv2d(4096, 4096, 1, bias=False),
nn.BatchNorm2d(4096),
nn.ReLU(inplace=True),
nn.Flatten(1),
nn.Linear(4096, num_classes),
)
def forward(self, x):
"""Regular forward function."""
x = self.features(x)
x = self.avgpool(x)
x = self.classifier(x)
return x
def alexnet_bn(*args, **kwargs):
"""Return a batch-normalized AlexNet with desired number of classes."""
return AlexNetBn(*args, **kwargs)
|
/*
* Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
#include <stdio.h>
#include "ssl_locl.h"
#include <openssl/evp.h>
#include <openssl/md5.h>
static int ssl3_generate_key_block(SSL *s, unsigned char *km, int num)
{
EVP_MD_CTX *m5;
EVP_MD_CTX *s1;
unsigned char buf[16], smd[SHA_DIGEST_LENGTH];
unsigned char c = 'A';
unsigned int i, j, k;
int ret = 0;
#ifdef CHARSET_EBCDIC
c = os_toascii[c]; /* 'A' in ASCII */
#endif
k = 0;
m5 = EVP_MD_CTX_new();
s1 = EVP_MD_CTX_new();
if (m5 == NULL || s1 == NULL) {
SSLerr(SSL_F_SSL3_GENERATE_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
goto err;
}
EVP_MD_CTX_set_flags(m5, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
for (i = 0; (int)i < num; i += MD5_DIGEST_LENGTH) {
k++;
if (k > sizeof(buf)) {
/* bug: 'buf' is too small for this ciphersuite */
SSLerr(SSL_F_SSL3_GENERATE_KEY_BLOCK, ERR_R_INTERNAL_ERROR);
goto err;
}
for (j = 0; j < k; j++)
buf[j] = c;
c++;
if (!EVP_DigestInit_ex(s1, EVP_sha1(), NULL)
|| !EVP_DigestUpdate(s1, buf, k)
|| !EVP_DigestUpdate(s1, s->session->master_key,
s->session->master_key_length)
|| !EVP_DigestUpdate(s1, s->s3->server_random, SSL3_RANDOM_SIZE)
|| !EVP_DigestUpdate(s1, s->s3->client_random, SSL3_RANDOM_SIZE)
|| !EVP_DigestFinal_ex(s1, smd, NULL)
|| !EVP_DigestInit_ex(m5, EVP_md5(), NULL)
|| !EVP_DigestUpdate(m5, s->session->master_key,
s->session->master_key_length)
|| !EVP_DigestUpdate(m5, smd, SHA_DIGEST_LENGTH))
goto err;
if ((int)(i + MD5_DIGEST_LENGTH) > num) {
if (!EVP_DigestFinal_ex(m5, smd, NULL))
goto err;
memcpy(km, smd, (num - i));
} else {
if (!EVP_DigestFinal_ex(m5, km, NULL))
goto err;
}
km += MD5_DIGEST_LENGTH;
}
OPENSSL_cleanse(smd, sizeof(smd));
ret = 1;
err:
EVP_MD_CTX_free(m5);
EVP_MD_CTX_free(s1);
return ret;
}
int ssl3_change_cipher_state(SSL *s, int which)
{
unsigned char *p, *mac_secret;
unsigned char exp_key[EVP_MAX_KEY_LENGTH];
unsigned char exp_iv[EVP_MAX_IV_LENGTH];
unsigned char *ms, *key, *iv;
EVP_CIPHER_CTX *dd;
const EVP_CIPHER *c;
#ifndef OPENSSL_NO_COMP
COMP_METHOD *comp;
#endif
const EVP_MD *m;
int n, i, j, k, cl;
int reuse_dd = 0;
c = s->s3->tmp.new_sym_enc;
m = s->s3->tmp.new_hash;
/* m == NULL will lead to a crash later */
OPENSSL_assert(m);
#ifndef OPENSSL_NO_COMP
if (s->s3->tmp.new_compression == NULL)
comp = NULL;
else
comp = s->s3->tmp.new_compression->method;
#endif
if (which & SSL3_CC_READ) {
if (s->enc_read_ctx != NULL)
reuse_dd = 1;
else if ((s->enc_read_ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
else
/*
* make sure it's initialised in case we exit later with an error
*/
EVP_CIPHER_CTX_reset(s->enc_read_ctx);
dd = s->enc_read_ctx;
if (ssl_replace_hash(&s->read_hash, m) == NULL) {
SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
#ifndef OPENSSL_NO_COMP
/* COMPRESS */
COMP_CTX_free(s->expand);
s->expand = NULL;
if (comp != NULL) {
s->expand = COMP_CTX_new(comp);
if (s->expand == NULL) {
SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE,
SSL_R_COMPRESSION_LIBRARY_ERROR);
goto err2;
}
}
#endif
RECORD_LAYER_reset_read_sequence(&s->rlayer);
mac_secret = &(s->s3->read_mac_secret[0]);
} else {
if (s->enc_write_ctx != NULL)
reuse_dd = 1;
else if ((s->enc_write_ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
else
/*
* make sure it's initialised in case we exit later with an error
*/
EVP_CIPHER_CTX_reset(s->enc_write_ctx);
dd = s->enc_write_ctx;
if (ssl_replace_hash(&s->write_hash, m) == NULL) {
SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
#ifndef OPENSSL_NO_COMP
/* COMPRESS */
COMP_CTX_free(s->compress);
s->compress = NULL;
if (comp != NULL) {
s->compress = COMP_CTX_new(comp);
if (s->compress == NULL) {
SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE,
SSL_R_COMPRESSION_LIBRARY_ERROR);
goto err2;
}
}
#endif
RECORD_LAYER_reset_write_sequence(&s->rlayer);
mac_secret = &(s->s3->write_mac_secret[0]);
}
if (reuse_dd)
EVP_CIPHER_CTX_reset(dd);
p = s->s3->tmp.key_block;
i = EVP_MD_size(m);
if (i < 0)
goto err2;
cl = EVP_CIPHER_key_length(c);
j = cl;
k = EVP_CIPHER_iv_length(c);
if ((which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
(which == SSL3_CHANGE_CIPHER_SERVER_READ)) {
ms = &(p[0]);
n = i + i;
key = &(p[n]);
n += j + j;
iv = &(p[n]);
n += k + k;
} else {
n = i;
ms = &(p[n]);
n += i + j;
key = &(p[n]);
n += j + k;
iv = &(p[n]);
n += k;
}
if (n > s->s3->tmp.key_block_length) {
SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
memcpy(mac_secret, ms, i);
if (!EVP_CipherInit_ex(dd, c, NULL, key, iv, (which & SSL3_CC_WRITE)))
goto err2;
OPENSSL_cleanse(exp_key, sizeof(exp_key));
OPENSSL_cleanse(exp_iv, sizeof(exp_iv));
return (1);
err:
SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
err2:
OPENSSL_cleanse(exp_key, sizeof(exp_key));
OPENSSL_cleanse(exp_iv, sizeof(exp_iv));
return (0);
}
int ssl3_setup_key_block(SSL *s)
{
unsigned char *p;
const EVP_CIPHER *c;
const EVP_MD *hash;
int num;
int ret = 0;
SSL_COMP *comp;
if (s->s3->tmp.key_block_length != 0)
return (1);
if (!ssl_cipher_get_evp(s->session, &c, &hash, NULL, NULL, &comp, 0)) {
SSLerr(SSL_F_SSL3_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
return (0);
}
s->s3->tmp.new_sym_enc = c;
s->s3->tmp.new_hash = hash;
#ifdef OPENSSL_NO_COMP
s->s3->tmp.new_compression = NULL;
#else
s->s3->tmp.new_compression = comp;
#endif
num = EVP_MD_size(hash);
if (num < 0)
return 0;
num = EVP_CIPHER_key_length(c) + num + EVP_CIPHER_iv_length(c);
num *= 2;
ssl3_cleanup_key_block(s);
if ((p = OPENSSL_malloc(num)) == NULL)
goto err;
s->s3->tmp.key_block_length = num;
s->s3->tmp.key_block = p;
ret = ssl3_generate_key_block(s, p, num);
if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)) {
/*
* enable vulnerability countermeasure for CBC ciphers with known-IV
* problem (http://www.openssl.org/~bodo/tls-cbc.txt)
*/
s->s3->need_empty_fragments = 1;
if (s->session->cipher != NULL) {
if (s->session->cipher->algorithm_enc == SSL_eNULL)
s->s3->need_empty_fragments = 0;
#ifndef OPENSSL_NO_RC4
if (s->session->cipher->algorithm_enc == SSL_RC4)
s->s3->need_empty_fragments = 0;
#endif
}
}
return ret;
err:
SSLerr(SSL_F_SSL3_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
return (0);
}
void ssl3_cleanup_key_block(SSL *s)
{
OPENSSL_clear_free(s->s3->tmp.key_block, s->s3->tmp.key_block_length);
s->s3->tmp.key_block = NULL;
s->s3->tmp.key_block_length = 0;
}
int ssl3_init_finished_mac(SSL *s)
{
BIO *buf = BIO_new(BIO_s_mem());
if (buf == NULL) {
SSLerr(SSL_F_SSL3_INIT_FINISHED_MAC, ERR_R_MALLOC_FAILURE);
return 0;
}
ssl3_free_digest_list(s);
s->s3->handshake_buffer = buf;
(void)BIO_set_close(s->s3->handshake_buffer, BIO_CLOSE);
return 1;
}
/*
* Free digest list. Also frees handshake buffer since they are always freed
* together.
*/
void ssl3_free_digest_list(SSL *s)
{
BIO_free(s->s3->handshake_buffer);
s->s3->handshake_buffer = NULL;
EVP_MD_CTX_free(s->s3->handshake_dgst);
s->s3->handshake_dgst = NULL;
}
int ssl3_finish_mac(SSL *s, const unsigned char *buf, int len)
{
if (s->s3->handshake_dgst == NULL)
/* Note: this writes to a memory BIO so a failure is a fatal error */
return BIO_write(s->s3->handshake_buffer, (void *)buf, len) == len;
else
return EVP_DigestUpdate(s->s3->handshake_dgst, buf, len);
}
int ssl3_digest_cached_records(SSL *s, int keep)
{
const EVP_MD *md;
long hdatalen;
void *hdata;
if (s->s3->handshake_dgst == NULL) {
hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
if (hdatalen <= 0) {
SSLerr(SSL_F_SSL3_DIGEST_CACHED_RECORDS,
SSL_R_BAD_HANDSHAKE_LENGTH);
return 0;
}
s->s3->handshake_dgst = EVP_MD_CTX_new();
if (s->s3->handshake_dgst == NULL) {
SSLerr(SSL_F_SSL3_DIGEST_CACHED_RECORDS, ERR_R_MALLOC_FAILURE);
return 0;
}
md = ssl_handshake_md(s);
if (md == NULL || !EVP_DigestInit_ex(s->s3->handshake_dgst, md, NULL)
|| !EVP_DigestUpdate(s->s3->handshake_dgst, hdata, hdatalen)) {
SSLerr(SSL_F_SSL3_DIGEST_CACHED_RECORDS, ERR_R_INTERNAL_ERROR);
return 0;
}
}
if (keep == 0) {
BIO_free(s->s3->handshake_buffer);
s->s3->handshake_buffer = NULL;
}
return 1;
}
int ssl3_final_finish_mac(SSL *s, const char *sender, int len, unsigned char *p)
{
int ret;
EVP_MD_CTX *ctx = NULL;
if (!ssl3_digest_cached_records(s, 0))
return 0;
if (EVP_MD_CTX_type(s->s3->handshake_dgst) != NID_md5_sha1) {
SSLerr(SSL_F_SSL3_FINAL_FINISH_MAC, SSL_R_NO_REQUIRED_DIGEST);
return 0;
}
ctx = EVP_MD_CTX_new();
if (ctx == NULL) {
SSLerr(SSL_F_SSL3_FINAL_FINISH_MAC, ERR_R_MALLOC_FAILURE);
return 0;
}
if (!EVP_MD_CTX_copy_ex(ctx, s->s3->handshake_dgst)) {
SSLerr(SSL_F_SSL3_FINAL_FINISH_MAC, ERR_R_INTERNAL_ERROR);
ret = 0;
goto err;
}
ret = EVP_MD_CTX_size(ctx);
if (ret < 0) {
ret = 0;
goto err;
}
if ((sender != NULL && EVP_DigestUpdate(ctx, sender, len) <= 0)
|| EVP_MD_CTX_ctrl(ctx, EVP_CTRL_SSL3_MASTER_SECRET,
s->session->master_key_length,
s->session->master_key) <= 0
|| EVP_DigestFinal_ex(ctx, p, NULL) <= 0) {
SSLerr(SSL_F_SSL3_FINAL_FINISH_MAC, ERR_R_INTERNAL_ERROR);
ret = 0;
}
err:
EVP_MD_CTX_free(ctx);
return ret;
}
int ssl3_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
int len)
{
static const unsigned char *salt[3] = {
#ifndef CHARSET_EBCDIC
(const unsigned char *)"A",
(const unsigned char *)"BB",
(const unsigned char *)"CCC",
#else
(const unsigned char *)"\x41",
(const unsigned char *)"\x42\x42",
(const unsigned char *)"\x43\x43\x43",
#endif
};
unsigned char buf[EVP_MAX_MD_SIZE];
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
int i, ret = 0;
unsigned int n;
if (ctx == NULL) {
SSLerr(SSL_F_SSL3_GENERATE_MASTER_SECRET, ERR_R_MALLOC_FAILURE);
return 0;
}
for (i = 0; i < 3; i++) {
if (EVP_DigestInit_ex(ctx, s->ctx->sha1, NULL) <= 0
|| EVP_DigestUpdate(ctx, salt[i],
strlen((const char *)salt[i])) <= 0
|| EVP_DigestUpdate(ctx, p, len) <= 0
|| EVP_DigestUpdate(ctx, &(s->s3->client_random[0]),
SSL3_RANDOM_SIZE) <= 0
|| EVP_DigestUpdate(ctx, &(s->s3->server_random[0]),
SSL3_RANDOM_SIZE) <= 0
|| EVP_DigestFinal_ex(ctx, buf, &n) <= 0
|| EVP_DigestInit_ex(ctx, s->ctx->md5, NULL) <= 0
|| EVP_DigestUpdate(ctx, p, len) <= 0
|| EVP_DigestUpdate(ctx, buf, n) <= 0
|| EVP_DigestFinal_ex(ctx, out, &n) <= 0) {
SSLerr(SSL_F_SSL3_GENERATE_MASTER_SECRET, ERR_R_INTERNAL_ERROR);
ret = 0;
break;
}
out += n;
ret += n;
}
EVP_MD_CTX_free(ctx);
OPENSSL_cleanse(buf, sizeof(buf));
return (ret);
}
int ssl3_alert_code(int code)
{
switch (code) {
case SSL_AD_CLOSE_NOTIFY:
return (SSL3_AD_CLOSE_NOTIFY);
case SSL_AD_UNEXPECTED_MESSAGE:
return (SSL3_AD_UNEXPECTED_MESSAGE);
case SSL_AD_BAD_RECORD_MAC:
return (SSL3_AD_BAD_RECORD_MAC);
case SSL_AD_DECRYPTION_FAILED:
return (SSL3_AD_BAD_RECORD_MAC);
case SSL_AD_RECORD_OVERFLOW:
return (SSL3_AD_BAD_RECORD_MAC);
case SSL_AD_DECOMPRESSION_FAILURE:
return (SSL3_AD_DECOMPRESSION_FAILURE);
case SSL_AD_HANDSHAKE_FAILURE:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_NO_CERTIFICATE:
return (SSL3_AD_NO_CERTIFICATE);
case SSL_AD_BAD_CERTIFICATE:
return (SSL3_AD_BAD_CERTIFICATE);
case SSL_AD_UNSUPPORTED_CERTIFICATE:
return (SSL3_AD_UNSUPPORTED_CERTIFICATE);
case SSL_AD_CERTIFICATE_REVOKED:
return (SSL3_AD_CERTIFICATE_REVOKED);
case SSL_AD_CERTIFICATE_EXPIRED:
return (SSL3_AD_CERTIFICATE_EXPIRED);
case SSL_AD_CERTIFICATE_UNKNOWN:
return (SSL3_AD_CERTIFICATE_UNKNOWN);
case SSL_AD_ILLEGAL_PARAMETER:
return (SSL3_AD_ILLEGAL_PARAMETER);
case SSL_AD_UNKNOWN_CA:
return (SSL3_AD_BAD_CERTIFICATE);
case SSL_AD_ACCESS_DENIED:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_DECODE_ERROR:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_DECRYPT_ERROR:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_EXPORT_RESTRICTION:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_PROTOCOL_VERSION:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_INSUFFICIENT_SECURITY:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_INTERNAL_ERROR:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_USER_CANCELLED:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_NO_RENEGOTIATION:
return (-1); /* Don't send it :-) */
case SSL_AD_UNSUPPORTED_EXTENSION:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_CERTIFICATE_UNOBTAINABLE:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_UNRECOGNIZED_NAME:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_UNKNOWN_PSK_IDENTITY:
return (TLS1_AD_UNKNOWN_PSK_IDENTITY);
case SSL_AD_INAPPROPRIATE_FALLBACK:
return (TLS1_AD_INAPPROPRIATE_FALLBACK);
case SSL_AD_NO_APPLICATION_PROTOCOL:
return (TLS1_AD_NO_APPLICATION_PROTOCOL);
default:
return (-1);
}
}
|
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([[2],{"8IMR":function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M908.1 353.1l-253.9-36.9L540.7 86.1c-3.1-6.3-8.2-11.4-14.5-14.5-15.8-7.8-35-1.3-42.9 14.5L369.8 316.2l-253.9 36.9c-7 1-13.4 4.3-18.3 9.3a32.05 32.05 0 00.6 45.3l183.7 179.1-43.4 252.9a31.95 31.95 0 0046.4 33.7L512 754l227.1 119.4c6.2 3.3 13.4 4.4 20.3 3.2 17.4-3 29.1-19.5 26.1-36.9l-43.4-252.9 183.7-179.1c5-4.9 8.3-11.3 9.3-18.3 2.7-17.5-9.5-33.7-27-36.3z"}}]},name:"star",theme:"filled"};t.default=r},Lerx:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var r=a(n("Mds0"));function a(e){return e&&e.__esModule?e:{default:e}}var o=r;t.default=o,e.exports=o},Mds0:function(e,t,n){"use strict";var r=n("TqRt"),a=n("284h");Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=a(n("q1tI")),c=r(n("8IMR")),i=r(n("KQxl")),l=function(e,t){return o.createElement(i.default,Object.assign({},e,{ref:t,icon:c.default}))};l.displayName="StarFilled";var u=o.forwardRef(l);t.default=u},"O/iA":function(e,t,n){e.exports={"ant-select-auto-complete":"ant-select-auto-complete","ant-select-clear":"ant-select-clear"}},bsDN:function(e,t,n){e.exports={menu:"antd-pro-components-global-header-index-menu",right:"antd-pro-components-global-header-index-right",action:"antd-pro-components-global-header-index-action",search:"antd-pro-components-global-header-index-search",account:"antd-pro-components-global-header-index-account",avatar:"antd-pro-components-global-header-index-avatar",dark:"antd-pro-components-global-header-index-dark",name:"antd-pro-components-global-header-index-name"}},bx7e:function(e,t,n){"use strict";n.r(t);var r=n("VTBJ"),a=n("wx14"),o=n("KQm4"),c=(n("sPJy"),n("bE4q")),i=(n("lUTK"),n("BvKs")),l=n("ODXe"),u=(n("J+/v"),n("MoRW")),s=(n("+L6B"),n("2/Rp")),f=n("Hx5s"),p=n("q1tI"),d=n.n(p),m=n("55Ip"),h=n("9kvl"),v="NULL",b=function(e){return function(t){return t?("function"===typeof t&&(v=t()),("[object String]"===Object.prototype.toString.call(t)||Array.isArray(t))&&(v=t)):v="NULL",e}},y=function(e){return b(e)},g=(n("T2oS"),n("W9HT")),O=n("Ff2n"),j=n("1OyB"),x=n("vuIU"),E=n("Ji7U"),w=n("LK+K"),S=n("Y+p1"),P=n.n(S),C=function(){return 403},k=function e(t){if(!t)return!1;var n=Object.getPrototypeOf(t);return n===d.a.Component||n===Function.prototype||e(n)},R=function(e){if(k(e)){var t=e;return function(e){return d.a.createElement(t,e)}}return d.a.isValidElement(e)?function(t){return d.a.cloneElement(e,t)}:function(){return e}},N=function(e,t){var n=!1;if(t&&(n=function(){return t}),!e)throw new Error("authority is required");return function(t){var r=F(e,t,n||C);return R(r)}},M=N,T=function(e){Object(E["a"])(n,e);var t=Object(w["a"])(n);function n(){var e;Object(j["a"])(this,n);for(var r=arguments.length,a=new Array(r),o=0;o<r;o++)a[o]=arguments[o];return e=t.call.apply(t,[this].concat(a)),e.state={component:function(){return null}},e.shouldComponentUpdate=function(t,n){var r=e.state.component;return P()(t,e.props)||e.setRenderComponent(t),n.component!==r},e.checkIsInstantiation=function(e){if(k(e)){var t=e;return function(e){return d.a.createElement(t,e)}}return d.a.isValidElement(e)?function(t){return d.a.cloneElement(e,t)}:function(){return e}},e}return Object(x["a"])(n,[{key:"componentDidMount",value:function(){this.setRenderComponent(this.props)}},{key:"setRenderComponent",value:function(e){var t=this,n=this.checkIsInstantiation(e.ok),r=this.checkIsInstantiation(e.error);e.promise.then((function(){return t.setState({component:n}),!0})).catch((function(){t.setState({component:r})}))}},{key:"render",value:function(){var e=this.state.component,t=this.props,n=(t.ok,t.error,t.promise,Object(O["a"])(t,["ok","error","promise"]));return e?d.a.createElement(e,n):d.a.createElement("div",{style:{width:"100%",height:"100%",margin:"auto",paddingTop:50,textAlign:"center"}},d.a.createElement(g["a"],{size:"large"}))}}]),n}(d.a.Component),A=function(e,t,n,r){if(!e)return n;if(Array.isArray(e)){if(Array.isArray(t)){if(t.some((function(t){return e.includes(t)})))return n}else if(e.includes(t))return n;return r}if("string"===typeof e){if(Array.isArray(t)){if(t.some((function(t){return e===t})))return n}else if(e===t)return n;return r}if(e instanceof Promise)return d.a.createElement(T,{ok:n,error:r,promise:e});if("function"===typeof e)try{var a=e(t);return a instanceof Promise?d.a.createElement(T,{ok:n,error:r,promise:a}):a?n:r}catch(o){throw o}throw new Error("unsupported parameters")};function D(e,t,n){return A(e,v,t,n)}var F=D,I=function(e){var t=e.children,n=e.authority,r=e.noMatch,a=void 0===r?d.a.createElement(u["a"],{status:403,title:"403",subTitle:"Sorry, you are not authorized to access this page."}):r,o="undefined"===typeof t?null:t,c=F(n,o,a);return d.a.createElement(d.a.Fragment,null,c)},L=I;L.Secured=M,L.check=F;var _=y(L),V=_;function B(e){var t,n="undefined"===typeof e&&localStorage?localStorage.getItem("antd-pro-authority"):e;try{n&&(t=JSON.parse(n))}catch(r){t=n}return"string"===typeof t?[t]:t}var H=V(B()),z=function(){H=V(B())};window.reloadAuthorized=z;var U=H,K=(n("+BJd"),n("5Dmo"),n("3S7+")),X={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"}},{tag:"path",attrs:{d:"M623.6 316.7C593.6 290.4 554 276 512 276s-81.6 14.5-111.6 40.7C369.2 344 352 380.7 352 420v7.6c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8V420c0-44.1 43.1-80 96-80s96 35.9 96 80c0 31.1-22 59.6-56.1 72.7-21.2 8.1-39.2 22.3-52.1 40.9-13.1 19-19.9 41.8-19.9 64.9V620c0 4.4 3.6 8 8 8h48c4.4 0 8-3.6 8-8v-22.7a48.3 48.3 0 0130.9-44.8c59-22.7 97.1-74.7 97.1-132.5.1-39.3-17.1-76-48.3-103.3zM472 732a40 40 0 1080 0 40 40 0 10-80 0z"}}]},name:"question-circle",theme:"outlined"},Y=X,G=n("6VBw"),W=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:Y}))};W.displayName="QuestionCircleOutlined";var q=p["forwardRef"](W),$=(n("Telt"),n("Tckk")),J=n("cJ7L"),Q=n("eFNv"),Z={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M868 732h-70.3c-4.8 0-9.3 2.1-12.3 5.8-7 8.5-14.5 16.7-22.4 24.5a353.84 353.84 0 01-112.7 75.9A352.8 352.8 0 01512.4 866c-47.9 0-94.3-9.4-137.9-27.8a353.84 353.84 0 01-112.7-75.9 353.28 353.28 0 01-76-112.5C167.3 606.2 158 559.9 158 512s9.4-94.2 27.8-137.8c17.8-42.1 43.4-80 76-112.5s70.5-58.1 112.7-75.9c43.6-18.4 90-27.8 137.9-27.8 47.9 0 94.3 9.3 137.9 27.8 42.2 17.8 80.1 43.4 112.7 75.9 7.9 7.9 15.3 16.1 22.4 24.5 3 3.7 7.6 5.8 12.3 5.8H868c6.3 0 10.2-7 6.7-12.3C798 160.5 663.8 81.6 511.3 82 271.7 82.6 79.6 277.1 82 516.4 84.4 751.9 276.2 942 512.4 942c152.1 0 285.7-78.8 362.3-197.7 3.4-5.3-.4-12.3-6.7-12.3zm88.9-226.3L815 393.7c-5.3-4.2-13-.4-13 6.3v76H488c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h314v76c0 6.7 7.8 10.5 13 6.3l141.9-112a8 8 0 000-12.6z"}}]},name:"logout",theme:"outlined"},ee=Z,te=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:ee}))};te.displayName="LogoutOutlined";var ne=p["forwardRef"](te),re=n("uZXw"),ae=n("bsDN"),oe=n.n(ae),ce=function(e){Object(E["a"])(n,e);var t=Object(w["a"])(n);function n(){var e;Object(j["a"])(this,n);for(var r=arguments.length,a=new Array(r),o=0;o<r;o++)a[o]=arguments[o];return e=t.call.apply(t,[this].concat(a)),e.onMenuClick=function(t){var n=t.key;if("logout"===n){var r=e.props.dispatch;r&&r({type:"login/logout"})}else"settings"===n&&h["e"].push("/system/accountsettings")},e}return Object(x["a"])(n,[{key:"render",value:function(){var e=this.props,t=e.currentUser,n=void 0===t?{avatar:"",name:""}:t,r=e.menu,a=d.a.createElement(i["a"],{className:oe.a.menu,selectedKeys:[],onClick:this.onMenuClick},r&&d.a.createElement(i["a"].Item,{key:"center"},d.a.createElement(J["a"],null),"\u4e2a\u4eba\u4e2d\u5fc3"),d.a.createElement(i["a"].Item,{key:"settings"},d.a.createElement(Q["a"],null),"\u8d26\u6237\u8bbe\u7f6e"),d.a.createElement(i["a"].Divider,null),d.a.createElement(i["a"].Item,{key:"logout"},d.a.createElement(ne,null),"\u9000\u51fa\u767b\u5f55"));return n&&n.name?d.a.createElement(re["a"],{overlay:a},d.a.createElement("span",{className:"".concat(oe.a.action," ").concat(oe.a.account)},d.a.createElement($["a"],{size:"small",className:oe.a.avatar,src:n.avatar||"https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png",alt:"avatar"}),d.a.createElement("span",{className:oe.a.name},n.name))):d.a.createElement(g["a"],{size:"small",style:{marginLeft:8,marginRight:8}})}}]),n}(d.a.Component),ie=Object(h["b"])((function(e){var t=e.account;return{currentUser:t.currentAccount}}))(ce),le=(n("cIOH"),n("O/iA"),n("OaEy"),n("Zm9Q")),ue=n("TSYQ"),se=n.n(ue),fe=n("BGR+"),pe=n("2fM7"),de=n("H84U"),me=n("uaoM"),he=n("0n0R");function ve(){return ve=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},ve.apply(this,arguments)}function be(e){return be="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},be(e)}function ye(e,t){return Ee(e)||xe(e,t)||Oe(e,t)||ge()}function ge(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Oe(e,t){if(e){if("string"===typeof e)return je(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?je(e,t):void 0}}function je(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function xe(e,t){if("undefined"!==typeof Symbol&&Symbol.iterator in Object(e)){var n=[],r=!0,a=!1,o=void 0;try{for(var c,i=e[Symbol.iterator]();!(r=(c=i.next()).done);r=!0)if(n.push(c.value),t&&n.length===t)break}catch(l){a=!0,o=l}finally{try{r||null==i["return"]||i["return"]()}finally{if(a)throw o}}return n}}function Ee(e){if(Array.isArray(e))return e}var we=pe["a"].Option,Se=pe["a"];function Pe(e){return e&&e.type&&(e.type.isSelectOption||e.type.isSelectOptGroup)}var Ce=function(e,t){var n,r=e.prefixCls,a=e.className,o=e.children,c=e.dataSource,i=Object(le["a"])(o),l=p["useRef"]();if(p["useImperativeHandle"](t,(function(){return l.current})),1===i.length&&Object(he["b"])(i[0])&&!Pe(i[0])){var u=ye(i,1);n=u[0]}var s,f=function(){return n};return s=i.length&&Pe(i[0])?o:c?c.map((function(e){if(Object(he["b"])(e))return e;switch(be(e)){case"string":return p["createElement"](we,{key:e,value:e},e);case"object":var t=e.value;return p["createElement"](we,{key:t,value:t},e.text);default:throw new Error("AutoComplete[dataSource] only supports type `string[] | Object[]`.")}})):[],p["useEffect"]((function(){Object(me["a"])(!("dataSource"in e),"AutoComplete","`dataSource` is deprecated, please use `options` instead."),Object(me["a"])(!n||!("size"in e),"AutoComplete","You need to control style self instead of setting `size` when using customize input.")}),[]),p["createElement"](de["a"],null,(function(t){var n=t.getPrefixCls,o=n("select",r);return p["createElement"](Se,ve({ref:l},Object(fe["a"])(e,["dataSource"]),{prefixCls:o,className:se()(a,"".concat(o,"-auto-complete")),mode:pe["a"].SECRET_COMBOBOX_MODE_DO_NOT_USE,getInputElement:f}),s)}))},ke=p["forwardRef"](Ce);ke.Option=we;var Re=ke,Ne=(n("5NDa"),n("5rEg")),Me=n("rePB"),Te={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M909.6 854.5L649.9 594.8C690.2 542.7 712 479 712 412c0-80.2-31.3-155.4-87.9-212.1-56.6-56.7-132-87.9-212.1-87.9s-155.5 31.3-212.1 87.9C143.2 256.5 112 331.8 112 412c0 80.1 31.3 155.5 87.9 212.1C256.5 680.8 331.8 712 412 712c67 0 130.6-21.8 182.7-62l259.7 259.6a8.2 8.2 0 0011.6 0l43.6-43.5a8.2 8.2 0 000-11.6zM570.4 570.4C528 612.7 471.8 636 412 636s-116-23.3-158.4-65.6C211.3 528 188 471.8 188 412s23.3-116.1 65.6-158.4C296 211.3 352.2 188 412 188s116.1 23.2 158.4 65.6S636 352.2 636 412s-23.3 116.1-65.6 158.4z"}}]},name:"search",theme:"outlined"},Ae=Te,De=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:Ae}))};De.displayName="SearchOutlined";var Fe=p["forwardRef"](De),Ie=n("yUgw"),Le=n("j5Qg"),_e=n.n(Le),Ve=function(e){var t=e.className,n=e.defaultValue,r=e.onVisibleChange,a=e.placeholder,o=(e.open,e.defaultOpen),c=Object(O["a"])(e,["className","defaultValue","onVisibleChange","placeholder","open","defaultOpen"]),i=Object(p["useRef"])(null),u=Object(Ie["a"])(n,{value:e.value,onChange:e.onChange}),s=Object(l["a"])(u,2),f=s[0],m=s[1],h=Object(Ie["a"])(o||!1,{value:e.open,onChange:r}),v=Object(l["a"])(h,2),b=v[0],y=v[1],g=se()(_e.a.input,Object(Me["a"])({},_e.a.show,b));return d.a.createElement("div",{className:se()(t,_e.a.headerSearch),onClick:function(){y(!0),b&&i.current&&i.current.focus()},onTransitionEnd:function(e){var t=e.propertyName;"width"!==t||b||r&&r(b)}},d.a.createElement(Fe,{key:"Icon",style:{cursor:"pointer"}}),d.a.createElement(Re,{key:"AutoComplete",className:g,value:f,style:{height:28,marginTop:-6},options:c.options,onChange:m},d.a.createElement(Ne["a"],{ref:i,defaultValue:n,"aria-label":a,placeholder:a,onKeyDown:function(e){"Enter"===e.key&&c.onSearch&&c.onSearch(f)},onBlur:function(){y(!1)}})))},Be=Ve,He=n("trCS"),ze=function(e){var t=e.theme,n=e.layout,r=oe.a.right;return"dark"===t&&"topmenu"===n&&(r="".concat(oe.a.right," ").concat(oe.a.dark)),d.a.createElement("div",{className:r},d.a.createElement(Be,{className:"".concat(oe.a.action," ").concat(oe.a.search),placeholder:"\u7ad9\u5185\u641c\u7d22",defaultValue:"umi ui",options:[{label:d.a.createElement("a",{href:"https://umijs.org/zh/guide/umi-ui.html"},"umi ui"),value:"umi ui"},{label:d.a.createElement("a",{href:"next.ant.design"},"Ant Design"),value:"Ant Design"},{label:d.a.createElement("a",{href:"https://protable.ant.design/"},"Pro Table"),value:"Pro Table"},{label:d.a.createElement("a",{href:"https://prolayout.ant.design/"},"Pro Layout"),value:"Pro Layout"}]}),d.a.createElement(K["a"],{title:"\u4f7f\u7528\u6587\u6863"},d.a.createElement("a",{target:"_blank",href:"https://pro.ant.design/docs/getting-started",rel:"noopener noreferrer",className:oe.a.action},d.a.createElement(q,null))),d.a.createElement(ie,null),!1,d.a.createElement(He["a"],{className:oe.a.action}))},Ue=Object(h["b"])((function(e){var t=e.settings;return{theme:t.navTheme,layout:t.layout}}))(ze),Ke=n("dxGJ"),Xe=n("wJku"),Ye={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M946.5 505L560.1 118.8l-25.9-25.9a31.5 31.5 0 00-44.4 0L77.5 505a63.9 63.9 0 00-18.8 46c.4 35.2 29.7 63.3 64.9 63.3h42.5V940h691.8V614.3h43.4c17.1 0 33.2-6.7 45.3-18.8a63.6 63.6 0 0018.7-45.3c0-17-6.7-33.1-18.8-45.2zM568 868H456V664h112v204zm217.9-325.7V868H632V640c0-22.1-17.9-40-40-40H432c-22.1 0-40 17.9-40 40v228H238.1V542.3h-96l370-369.7 23.1 23.1L882 542.3h-96.1z"}}]},name:"home",theme:"outlined"},Ge=Ye,We=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:Ge}))};We.displayName="HomeOutlined";var qe=p["forwardRef"](We),$e={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zm-40 728H184V184h656v656zM492 400h184c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8H492c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8zm0 144h184c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8H492c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8zm0 144h184c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8H492c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8zM340 368a40 40 0 1080 0 40 40 0 10-80 0zm0 144a40 40 0 1080 0 40 40 0 10-80 0zm0 144a40 40 0 1080 0 40 40 0 10-80 0z"}}]},name:"profile",theme:"outlined"},Je=$e,Qe=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:Je}))};Qe.displayName="ProfileOutlined";var Ze=p["forwardRef"](Qe),et={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M832 64H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V96c0-17.7-14.3-32-32-32zm-600 72h560v208H232V136zm560 480H232V408h560v208zm0 272H232V680h560v208zM304 240a40 40 0 1080 0 40 40 0 10-80 0zm0 272a40 40 0 1080 0 40 40 0 10-80 0zm0 272a40 40 0 1080 0 40 40 0 10-80 0z"}}]},name:"database",theme:"outlined"},tt=et,nt=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:tt}))};nt.displayName="DatabaseOutlined";var rt=p["forwardRef"](nt),at={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M928 160H96c-17.7 0-32 14.3-32 32v640c0 17.7 14.3 32 32 32h832c17.7 0 32-14.3 32-32V192c0-17.7-14.3-32-32-32zm-40 208H676V232h212v136zm0 224H676V432h212v160zM412 432h200v160H412V432zm200-64H412V232h200v136zm-476 64h212v160H136V432zm0-200h212v136H136V232zm0 424h212v136H136V656zm276 0h200v136H412V656zm476 136H676V656h212v136z"}}]},name:"table",theme:"outlined"},ot=at,ct=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:ot}))};ct.displayName="TableOutlined";var it=p["forwardRef"](ct),lt={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M280 752h80c4.4 0 8-3.6 8-8V280c0-4.4-3.6-8-8-8h-80c-4.4 0-8 3.6-8 8v464c0 4.4 3.6 8 8 8zm192-280h80c4.4 0 8-3.6 8-8V280c0-4.4-3.6-8-8-8h-80c-4.4 0-8 3.6-8 8v184c0 4.4 3.6 8 8 8zm192 72h80c4.4 0 8-3.6 8-8V280c0-4.4-3.6-8-8-8h-80c-4.4 0-8 3.6-8 8v256c0 4.4 3.6 8 8 8zm216-432H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zm-40 728H184V184h656v656z"}}]},name:"project",theme:"outlined"},ut=lt,st=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:ut}))};st.displayName="ProjectOutlined";var ft=p["forwardRef"](st),pt={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M882 272.1V144c0-17.7-14.3-32-32-32H174c-17.7 0-32 14.3-32 32v128.1c-16.7 1-30 14.9-30 31.9v131.7a177 177 0 0014.4 70.4c4.3 10.2 9.6 19.8 15.6 28.9v345c0 17.6 14.3 32 32 32h676c17.7 0 32-14.3 32-32V535a175 175 0 0015.6-28.9c9.5-22.3 14.4-46 14.4-70.4V304c0-17-13.3-30.9-30-31.9zM214 184h596v88H214v-88zm362 656.1H448V736h128v104.1zm234 0H640V704c0-17.7-14.3-32-32-32H416c-17.7 0-32 14.3-32 32v136.1H214V597.9c2.9 1.4 5.9 2.8 9 4 22.3 9.4 46 14.1 70.4 14.1s48-4.7 70.4-14.1c13.8-5.8 26.8-13.2 38.7-22.1.2-.1.4-.1.6 0a180.4 180.4 0 0038.7 22.1c22.3 9.4 46 14.1 70.4 14.1 24.4 0 48-4.7 70.4-14.1 13.8-5.8 26.8-13.2 38.7-22.1.2-.1.4-.1.6 0a180.4 180.4 0 0038.7 22.1c22.3 9.4 46 14.1 70.4 14.1 24.4 0 48-4.7 70.4-14.1 3-1.3 6-2.6 9-4v242.2zm30-404.4c0 59.8-49 108.3-109.3 108.3-40.8 0-76.4-22.1-95.2-54.9-2.9-5-8.1-8.1-13.9-8.1h-.6c-5.7 0-11 3.1-13.9 8.1A109.24 109.24 0 01512 544c-40.7 0-76.2-22-95-54.7-3-5.1-8.4-8.3-14.3-8.3s-11.4 3.2-14.3 8.3a109.63 109.63 0 01-95.1 54.7C233 544 184 495.5 184 435.7v-91.2c0-.3.2-.5.5-.5h655c.3 0 .5.2.5.5v91.2z"}}]},name:"shop",theme:"outlined"},dt=pt,mt=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:dt}))};mt.displayName="ShopOutlined";var ht=p["forwardRef"](mt),vt={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M917.7 148.8l-42.4-42.4c-1.6-1.6-3.6-2.3-5.7-2.3s-4.1.8-5.7 2.3l-76.1 76.1a199.27 199.27 0 00-112.1-34.3c-51.2 0-102.4 19.5-141.5 58.6L432.3 308.7a8.03 8.03 0 000 11.3L704 591.7c1.6 1.6 3.6 2.3 5.7 2.3 2 0 4.1-.8 5.7-2.3l101.9-101.9c68.9-69 77-175.7 24.3-253.5l76.1-76.1c3.1-3.2 3.1-8.3 0-11.4zM769.1 441.7l-59.4 59.4-186.8-186.8 59.4-59.4c24.9-24.9 58.1-38.7 93.4-38.7 35.3 0 68.4 13.7 93.4 38.7 24.9 24.9 38.7 58.1 38.7 93.4 0 35.3-13.8 68.4-38.7 93.4zm-190.2 105a8.03 8.03 0 00-11.3 0L501 613.3 410.7 523l66.7-66.7c3.1-3.1 3.1-8.2 0-11.3L441 408.6a8.03 8.03 0 00-11.3 0L363 475.3l-43-43a7.85 7.85 0 00-5.7-2.3c-2 0-4.1.8-5.7 2.3L206.8 534.2c-68.9 69-77 175.7-24.3 253.5l-76.1 76.1a8.03 8.03 0 000 11.3l42.4 42.4c1.6 1.6 3.6 2.3 5.7 2.3s4.1-.8 5.7-2.3l76.1-76.1c33.7 22.9 72.9 34.3 112.1 34.3 51.2 0 102.4-19.5 141.5-58.6l101.9-101.9c3.1-3.1 3.1-8.2 0-11.3l-43-43 66.7-66.7c3.1-3.1 3.1-8.2 0-11.3l-36.6-36.2zM441.7 769.1a131.32 131.32 0 01-93.4 38.7c-35.3 0-68.4-13.7-93.4-38.7a131.32 131.32 0 01-38.7-93.4c0-35.3 13.7-68.4 38.7-93.4l59.4-59.4 186.8 186.8-59.4 59.4z"}}]},name:"api",theme:"outlined"},bt=vt,yt=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:bt}))};yt.displayName="ApiOutlined";var gt=p["forwardRef"](yt),Ot={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M928 160H96c-17.7 0-32 14.3-32 32v640c0 17.7 14.3 32 32 32h832c17.7 0 32-14.3 32-32V192c0-17.7-14.3-32-32-32zm-40 110.8V792H136V270.8l-27.6-21.5 39.3-50.5 42.8 33.3h643.1l42.8-33.3 39.3 50.5-27.7 21.5zM833.6 232L512 482 190.4 232l-42.8-33.3-39.3 50.5 27.6 21.5 341.6 265.6a55.99 55.99 0 0068.7 0L888 270.8l27.6-21.5-39.3-50.5-42.7 33.2z"}}]},name:"mail",theme:"outlined"},jt=Ot,xt=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:jt}))};xt.displayName="MailOutlined";var Et=p["forwardRef"](xt),wt={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M464 512a48 48 0 1096 0 48 48 0 10-96 0zm200 0a48 48 0 1096 0 48 48 0 10-96 0zm-400 0a48 48 0 1096 0 48 48 0 10-96 0zm661.2-173.6c-22.6-53.7-55-101.9-96.3-143.3a444.35 444.35 0 00-143.3-96.3C630.6 75.7 572.2 64 512 64h-2c-60.6.3-119.3 12.3-174.5 35.9a445.35 445.35 0 00-142 96.5c-40.9 41.3-73 89.3-95.2 142.8-23 55.4-34.6 114.3-34.3 174.9A449.4 449.4 0 00112 714v152a46 46 0 0046 46h152.1A449.4 449.4 0 00510 960h2.1c59.9 0 118-11.6 172.7-34.3a444.48 444.48 0 00142.8-95.2c41.3-40.9 73.8-88.7 96.5-142 23.6-55.2 35.6-113.9 35.9-174.5.3-60.9-11.5-120-34.8-175.6zm-151.1 438C704 845.8 611 884 512 884h-1.7c-60.3-.3-120.2-15.3-173.1-43.5l-8.4-4.5H188V695.2l-4.5-8.4C155.3 633.9 140.3 574 140 513.7c-.4-99.7 37.7-193.3 107.6-263.8 69.8-70.5 163.1-109.5 262.8-109.9h1.7c50 0 98.5 9.7 144.2 28.9 44.6 18.7 84.6 45.6 119 80 34.3 34.3 61.3 74.4 80 119 19.4 46.2 29.1 95.2 28.9 145.8-.6 99.6-39.7 192.9-110.1 262.7z"}}]},name:"message",theme:"outlined"},St=wt,Pt=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:St}))};Pt.displayName="MessageOutlined";var Ct=p["forwardRef"](Pt),kt={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M876.6 239.5c-.5-.9-1.2-1.8-2-2.5-5-5-13.1-5-18.1 0L684.2 409.3l-67.9-67.9L788.7 169c.8-.8 1.4-1.6 2-2.5 3.6-6.1 1.6-13.9-4.5-17.5-98.2-58-226.8-44.7-311.3 39.7-67 67-89.2 162-66.5 247.4l-293 293c-3 3-2.8 7.9.3 11l169.7 169.7c3.1 3.1 8.1 3.3 11 .3l292.9-292.9c85.5 22.8 180.5.7 247.6-66.4 84.4-84.5 97.7-213.1 39.7-311.3zM786 499.8c-58.1 58.1-145.3 69.3-214.6 33.6l-8.8 8.8-.1-.1-274 274.1-79.2-79.2 230.1-230.1s0 .1.1.1l52.8-52.8c-35.7-69.3-24.5-156.5 33.6-214.6a184.2 184.2 0 01144-53.5L537 318.9a32.05 32.05 0 000 45.3l124.5 124.5a32.05 32.05 0 0045.3 0l132.8-132.8c3.7 51.8-14.4 104.8-53.6 143.9z"}}]},name:"tool",theme:"outlined"},Rt=kt,Nt=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:Rt}))};Nt.displayName="ToolOutlined";var Mt=p["forwardRef"](Nt),Tt={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M811.4 418.7C765.6 297.9 648.9 212 512.2 212S258.8 297.8 213 418.6C127.3 441.1 64 519.1 64 612c0 110.5 89.5 200 199.9 200h496.2C870.5 812 960 722.5 960 612c0-92.7-63.1-170.7-148.6-193.3zm36.3 281a123.07 123.07 0 01-87.6 36.3H263.9c-33.1 0-64.2-12.9-87.6-36.3A123.3 123.3 0 01140 612c0-28 9.1-54.3 26.2-76.3a125.7 125.7 0 0166.1-43.7l37.9-9.9 13.9-36.6c8.6-22.8 20.6-44.1 35.7-63.4a245.6 245.6 0 0152.4-49.9c41.1-28.9 89.5-44.2 140-44.2s98.9 15.3 140 44.2c19.9 14 37.5 30.8 52.4 49.9 15.1 19.3 27.1 40.7 35.7 63.4l13.8 36.5 37.8 10c54.3 14.5 92.1 63.8 92.1 120 0 33.1-12.9 64.3-36.3 87.7z"}}]},name:"cloud",theme:"outlined"},At=Tt,Dt=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:At}))};Dt.displayName="CloudOutlined";var Ft=p["forwardRef"](Dt),It={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M854.6 288.6L639.4 73.4c-6-6-14.1-9.4-22.6-9.4H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V311.3c0-8.5-3.4-16.7-9.4-22.7zM790.2 326H602V137.8L790.2 326zm1.8 562H232V136h302v216a42 42 0 0042 42h216v494z"}}]},name:"file",theme:"outlined"},Lt=It,_t=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:Lt}))};_t.displayName="FileOutlined";var Vt=p["forwardRef"](_t);function Bt(e){var t;switch(e){case"home":t=d.a.createElement(qe,null);break;case"user":t=d.a.createElement(J["a"],null);break;case"profile":t=d.a.createElement(Ze,null);break;case"database":t=d.a.createElement(rt,null);break;case"table":t=d.a.createElement(it,null);break;case"project":t=d.a.createElement(ft,null);break;case"shop":t=d.a.createElement(ht,null);break;case"api":t=d.a.createElement(gt,null);break;case"mail":t=d.a.createElement(Et,null);break;case"message":t=d.a.createElement(Ct,null);break;case"setting":t=d.a.createElement(Q["a"],null);break;case"tool":t=d.a.createElement(Mt,null);break;case"cloud":t=d.a.createElement(Ft,null);break;case"file":t=d.a.createElement(Vt,null);break;default:t=e;break}return t}var Ht=n("mxmt"),zt=n.n(Ht);function Ut(e){var t=[],n=0;while(n<e.length){var r=e[n];if("*"!==r&&"+"!==r&&"?"!==r)if("\\"!==r)if("{"!==r)if("}"!==r)if(":"!==r)if("("!==r)t.push({type:"CHAR",index:n,value:e[n++]});else{var a=1,o="";i=n+1;if("?"===e[i])throw new TypeError('Pattern cannot start with "?" at '+i);while(i<e.length)if("\\"!==e[i]){if(")"===e[i]){if(a--,0===a){i++;break}}else if("("===e[i]&&(a++,"?"!==e[i+1]))throw new TypeError("Capturing groups are not allowed at "+i);o+=e[i++]}else o+=e[i++]+e[i++];if(a)throw new TypeError("Unbalanced pattern at "+n);if(!o)throw new TypeError("Missing pattern at "+n);t.push({type:"PATTERN",index:n,value:o}),n=i}else{var c="",i=n+1;while(i<e.length){var l=e.charCodeAt(i);if(!(l>=48&&l<=57||l>=65&&l<=90||l>=97&&l<=122||95===l))break;c+=e[i++]}if(!c)throw new TypeError("Missing parameter name at "+n);t.push({type:"NAME",index:n,value:c}),n=i}else t.push({type:"CLOSE",index:n,value:e[n++]});else t.push({type:"OPEN",index:n,value:e[n++]});else t.push({type:"ESCAPED_CHAR",index:n++,value:e[n++]});else t.push({type:"MODIFIER",index:n,value:e[n++]})}return t.push({type:"END",index:n,value:""}),t}function Kt(e,t){void 0===t&&(t={});var n=Ut(e),r=t.prefixes,a=void 0===r?"./":r,o="[^"+Xt(t.delimiter||"/#?")+"]+?",c=[],i=0,l=0,u="",s=function(e){if(l<n.length&&n[l].type===e)return n[l++].value},f=function(e){var t=s(e);if(void 0!==t)return t;var r=n[l],a=r.type,o=r.index;throw new TypeError("Unexpected "+a+" at "+o+", expected "+e)},p=function(){var e,t="";while(e=s("CHAR")||s("ESCAPED_CHAR"))t+=e;return t};while(l<n.length){var d=s("CHAR"),m=s("NAME"),h=s("PATTERN");if(m||h){var v=d||"";-1===a.indexOf(v)&&(u+=v,v=""),u&&(c.push(u),u=""),c.push({name:m||i++,prefix:v,suffix:"",pattern:h||o,modifier:s("MODIFIER")||""})}else{var b=d||s("ESCAPED_CHAR");if(b)u+=b;else{u&&(c.push(u),u="");var y=s("OPEN");if(y){v=p();var g=s("NAME")||"",O=s("PATTERN")||"",j=p();f("CLOSE"),c.push({name:g||(O?i++:""),pattern:g&&!O?o:O,prefix:v,suffix:j,modifier:s("MODIFIER")||""})}else f("END")}}}return c}function Xt(e){return e.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}function Yt(e){return e&&e.sensitive?"":"i"}function Gt(e,t){if(!t)return e;var n=e.source.match(/\((?!\?)/g);if(n)for(var r=0;r<n.length;r++)t.push({name:r,prefix:"",suffix:"",modifier:"",pattern:""});return e}function Wt(e,t,n){var r=e.map((function(e){return Jt(e,t,n).source}));return new RegExp("(?:"+r.join("|")+")",Yt(n))}function qt(e,t,n){return $t(Kt(e,n),t,n)}function $t(e,t,n){void 0===n&&(n={});for(var r=n.strict,a=void 0!==r&&r,o=n.start,c=void 0===o||o,i=n.end,l=void 0===i||i,u=n.encode,s=void 0===u?function(e){return e}:u,f="["+Xt(n.endsWith||"")+"]|$",p="["+Xt(n.delimiter||"/#?")+"]",d=c?"^":"",m=0,h=e;m<h.length;m++){var v=h[m];if("string"===typeof v)d+=Xt(s(v));else{var b=Xt(s(v.prefix)),y=Xt(s(v.suffix));if(v.pattern)if(t&&t.push(v),b||y)if("+"===v.modifier||"*"===v.modifier){var g="*"===v.modifier?"?":"";d+="(?:"+b+"((?:"+v.pattern+")(?:"+y+b+"(?:"+v.pattern+"))*)"+y+")"+g}else d+="(?:"+b+"("+v.pattern+")"+y+")"+v.modifier;else d+="("+v.pattern+")"+v.modifier;else d+="(?:"+b+y+")"+v.modifier}}if(l)a||(d+=p+"?"),d+=n.endsWith?"(?="+f+")":"$";else{var O=e[e.length-1],j="string"===typeof O?p.indexOf(O[O.length-1])>-1:void 0===O;a||(d+="(?:"+p+"(?="+f+"))?"),j||(d+="(?="+p+"|"+f+")")}return new RegExp(d,Yt(n))}function Jt(e,t,n){return e instanceof RegExp?Gt(e,t):Array.isArray(e)?Wt(e,t,n):qt(e,t,n)}var Qt=function(){return Qt=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},Qt.apply(this,arguments)},Zt=function(e){return d.a.createElement(s["a"],Qt({type:"link"},e))},en=n("xtZR"),tn=n("wd/R"),nn=n.n(tn),rn=n("kl6h"),an=n("vuNf"),on=function(e){if(""!==e)return e},cn=function(e,t){var n=e.value;if(!t.editable)return e;try{Object(an["isStr"])(n)&&n?e.value=nn()(n,"HH:mm:ss"):Object(an["isArr"])(n)&&n.length&&(e.value=n.map((function(e){return e&&nn()(e,"HH:mm:ss")||""})))}catch(r){throw new Error(r)}return e},ln=Object(en["connect"])({getValueFromEvent:function(e,t){return on(t)},getProps:Object(an["compose"])(an["mapStyledProps"],cn),getComponent:an["mapTextComponent"]})(rn["a"]);ln.RangePicker=Object(en["connect"])({getValueFromEvent:function(e,t){var n=t[0],r=t[1];return[on(n),on(r)]},getProps:Object(an["compose"])(an["mapStyledProps"],cn),getComponent:an["mapTextComponent"]})(rn["a"].RangePicker);var un=n("HQEm"),sn=n.n(un),fn=n("kaz8"),pn=n("jsC+"),dn=n("kbBi"),mn=n.n(dn),hn=n("w6Tc"),vn=n.n(hn);function bn(e){return bn="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},bn(e)}function yn(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function gn(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function On(e,t,n){return t&&gn(e.prototype,t),n&&gn(e,n),e}function jn(e,t){if("function"!==typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&xn(e,t)}function xn(e,t){return xn=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},xn(e,t)}function En(e){var t=Pn();return function(){var n,r=Cn(e);if(t){var a=Cn(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return wn(this,n)}}function wn(e,t){return!t||"object"!==bn(t)&&"function"!==typeof t?Sn(e):t}function Sn(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Pn(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function Cn(e){return Cn=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},Cn(e)}var kn=function(e){jn(n,e);var t=En(n);function n(){var e;return yn(this,n),e=t.apply(this,arguments),e.handleChange=function(t){var n=e.props.onChange;n&&n(t)},e.handleClear=function(t){t.preventDefault();var n=e.props,r=n.handleClear,a=n.disabled;!a&&r&&r(t)},e}return On(n,[{key:"render",value:function(){var e=this.props,t=e.placeholder,n=e.value,r=e.prefixCls,a=e.disabled,o=n&&n.length>0?p["createElement"]("a",{href:"#",className:"".concat(r,"-action"),onClick:this.handleClear},p["createElement"](mn.a,null)):p["createElement"]("span",{className:"".concat(r,"-action")},p["createElement"](vn.a,null));return p["createElement"]("div",null,p["createElement"](Ne["a"],{placeholder:t,className:r,value:n,onChange:this.handleChange,disabled:a}),o)}}]),n}(p["Component"]);kn.defaultProps={placeholder:""};var Rn=n("CWQg"),Nn=n("NUBc"),Mn=n("QB+1"),Tn=n.n(Mn),An=n("ZvpZ"),Dn=n("gDlH"),Fn=n("YMnH");function In(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var Ln=function(e){var t,n,r=e.renderedText,a=e.renderedEl,o=e.item,c=e.checked,i=e.disabled,l=e.prefixCls,u=e.onClick,s=e.onRemove,f=e.showRemove,d=se()((t={},In(t,"".concat(l,"-content-item"),!0),In(t,"".concat(l,"-content-item-disabled"),i||o.disabled),In(t,"".concat(l,"-content-item-checked"),c),t));return"string"!==typeof r&&"number"!==typeof r||(n=String(r)),p["createElement"](Fn["a"],{componentName:"Transfer",defaultLocale:An["a"].Transfer},(function(e){var t={className:d,title:n},r=p["createElement"]("span",{className:"".concat(l,"-content-item-text")},a);return f?p["createElement"]("li",t,r,p["createElement"](Dn["a"],{disabled:i||o.disabled,className:"".concat(l,"-content-item-remove"),"aria-label":e.remove,onClick:function(){null===s||void 0===s||s(o)}},p["createElement"](Tn.a,null))):(t.onClick=i||o.disabled?void 0:function(){return u(o)},p["createElement"]("li",t,p["createElement"](fn["a"],{checked:c,disabled:i||o.disabled}),r))}))},_n=p["memo"](Ln);function Vn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Bn(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Hn(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function zn(e,t,n){return t&&Hn(e.prototype,t),n&&Hn(e,n),e}function Un(e,t){if("function"!==typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&Kn(e,t)}function Kn(e,t){return Kn=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},Kn(e,t)}function Xn(e){var t=Wn();return function(){var n,r=qn(e);if(t){var a=qn(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return Yn(this,n)}}function Yn(e,t){return!t||"object"!==Jn(t)&&"function"!==typeof t?Gn(e):t}function Gn(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Wn(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function qn(e){return qn=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},qn(e)}function $n(){return $n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},$n.apply(this,arguments)}function Jn(e){return Jn="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},Jn(e)}var Qn=Object(Rn["a"])("handleFilter","handleClear","checkedKeys");function Zn(e){if(!e)return null;var t={pageSize:10};return"object"===Jn(e)?$n($n({},t),e):t}var er=function(e){Un(n,e);var t=Xn(n);function n(){var e;return Bn(this,n),e=t.apply(this,arguments),e.state={current:1},e.onItemSelect=function(t){var n=e.props,r=n.onItemSelect,a=n.selectedKeys,o=a.indexOf(t.key)>=0;r(t.key,!o)},e.onItemRemove=function(t){var n=e.props.onItemRemove;null===n||void 0===n||n([t.key])},e.onPageChange=function(t){e.setState({current:t})},e.getItems=function(){var t=e.state.current,n=e.props,r=n.pagination,a=n.filteredRenderItems,o=Zn(r),c=a;return o&&(c=a.slice((t-1)*o.pageSize,t*o.pageSize)),c},e}return zn(n,[{key:"render",value:function(){var e=this,t=this.state.current,n=this.props,r=n.prefixCls,a=n.onScroll,o=n.filteredRenderItems,c=n.selectedKeys,i=n.disabled,l=n.showRemove,u=n.pagination,s=Zn(u),f=null;return s&&(f=p["createElement"](Nn["a"],{simple:!0,className:"".concat(r,"-pagination"),total:o.length,pageSize:s.pageSize,current:t,onChange:this.onPageChange})),p["createElement"](p["Fragment"],null,p["createElement"]("ul",{className:se()("".concat(r,"-content"),Vn({},"".concat(r,"-content-show-remove"),l)),onScroll:a},this.getItems().map((function(t){var n=t.renderedEl,a=t.renderedText,o=t.item,u=o.disabled,s=c.indexOf(o.key)>=0;return p["createElement"](_n,{disabled:i||u,key:o.key,item:o,renderedText:a,renderedEl:n,checked:s,prefixCls:r,onClick:e.onItemSelect,onRemove:e.onItemRemove,showRemove:l})}))),f)}}],[{key:"getDerivedStateFromProps",value:function(e,t){var n=e.filteredRenderItems,r=e.pagination,a=t.current,o=Zn(r);if(o){var c=Math.ceil(n.length/o.pageSize);if(a>c)return{current:c}}return null}}]),n}(p["Component"]),tr=er;function nr(e){return nr="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},nr(e)}function rr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ar(){return ar=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},ar.apply(this,arguments)}function or(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function cr(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function ir(e,t,n){return t&&cr(e.prototype,t),n&&cr(e,n),e}function lr(e,t){if("function"!==typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&ur(e,t)}function ur(e,t){return ur=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},ur(e,t)}function sr(e){var t=dr();return function(){var n,r=mr(e);if(t){var a=mr(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return fr(this,n)}}function fr(e,t){return!t||"object"!==nr(t)&&"function"!==typeof t?pr(e):t}function pr(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function dr(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function mr(e){return mr=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},mr(e)}var hr=function(){return null};function vr(e){return e&&!Object(he["b"])(e)&&"[object Object]"===Object.prototype.toString.call(e)}function br(e){return e.filter((function(e){return!e.disabled})).map((function(e){return e.key}))}var yr=function(e){lr(n,e);var t=sr(n);function n(e){var r;return or(this,n),r=t.call(this,e),r.defaultListBodyRef=p["createRef"](),r.handleFilter=function(e){var t=r.props.handleFilter,n=e.target.value;r.setState({filterValue:n}),t(e)},r.handleClear=function(){var e=r.props.handleClear;r.setState({filterValue:""}),e()},r.matchFilter=function(e,t){var n=r.state.filterValue,a=r.props.filterOption;return a?a(n,t):e.indexOf(n)>=0},r.getCurrentPageItems=function(){},r.renderListBody=function(e,t){var n=e?e(t):null,a=!!n;return a||(n=p["createElement"](tr,ar({ref:r.defaultListBodyRef},t))),{customize:a,bodyContent:n}},r.renderItem=function(e){var t=r.props.render,n=void 0===t?hr:t,a=n(e),o=vr(a);return{renderedText:o?a.value:a,renderedEl:o?a.label:a,item:e}},r.getSelectAllLabel=function(e,t){var n=r.props,a=n.itemsUnit,o=n.itemUnit,c=n.selectAllLabel;if(c)return"function"===typeof c?c({selectedCount:e,totalCount:t}):c;var i=t>1?a:o;return p["createElement"](p["Fragment"],null,(e>0?"".concat(e,"/"):"")+t," ",i)},r.state={filterValue:""},r}return ir(n,[{key:"componentWillUnmount",value:function(){clearTimeout(this.triggerScrollTimer)}},{key:"getCheckStatus",value:function(e){var t=this.props.checkedKeys;return 0===t.length?"none":e.every((function(e){return t.indexOf(e.key)>=0||!!e.disabled}))?"all":"part"}},{key:"getFilteredItems",value:function(e,t){var n=this,r=[],a=[];return e.forEach((function(e){var o=n.renderItem(e),c=o.renderedText;if(t&&t.trim()&&!n.matchFilter(c,e))return null;r.push(e),a.push(o)})),{filteredItems:r,filteredRenderItems:a}}},{key:"getListBody",value:function(e,t,n,r,a,o,c,i,l,u){var s,f=l?p["createElement"]("div",{className:"".concat(e,"-body-search-wrapper")},p["createElement"](kn,{prefixCls:"".concat(e,"-search"),onChange:this.handleFilter,handleClear:this.handleClear,placeholder:t,value:n,disabled:u})):null,d=this.renderListBody(i,ar(ar({},Object(fe["a"])(this.props,Qn)),{filteredItems:r,filteredRenderItems:o,selectedKeys:c})),m=d.bodyContent,h=d.customize;return s=h?p["createElement"]("div",{className:"".concat(e,"-body-customize-wrapper")},m):r.length?m:p["createElement"]("div",{className:"".concat(e,"-body-not-found")},a),p["createElement"]("div",{className:se()(l?"".concat(e,"-body ").concat(e,"-body-with-search"):"".concat(e,"-body"))},f,s)}},{key:"getCheckBox",value:function(e,t,n,r){var a=this.getCheckStatus(e),o="all"===a,c=!1!==n&&p["createElement"](fn["a"],{disabled:r,checked:o,indeterminate:"part"===a,onChange:function(){t(e.filter((function(e){return!e.disabled})).map((function(e){var t=e.key;return t})),!o)}});return c}},{key:"render",value:function(){var e,t=this,n=this.state.filterValue,r=this.props,a=r.prefixCls,o=r.dataSource,c=r.titleText,l=r.checkedKeys,u=r.disabled,s=r.footer,f=r.showSearch,d=r.style,m=r.searchPlaceholder,h=r.notFoundContent,v=r.selectAll,b=r.selectCurrent,y=r.selectInvert,g=r.removeAll,O=r.removeCurrent,j=r.renderList,x=r.onItemSelectAll,E=r.onItemRemove,w=r.showSelectAll,S=r.showRemove,P=r.pagination,C=s&&s(this.props),k=se()(a,(e={},rr(e,"".concat(a,"-with-pagination"),P),rr(e,"".concat(a,"-with-footer"),C),e)),R=this.getFilteredItems(o,n),N=R.filteredItems,M=R.filteredRenderItems,T=this.getListBody(a,m,n,N,h,M,l,j,f,u),A=C?p["createElement"]("div",{className:"".concat(a,"-footer")},C):null,D=!S&&!P&&this.getCheckBox(N,x,w,u),F=null;F=S?p["createElement"](i["a"],null,P&&p["createElement"](i["a"].Item,{onClick:function(){var e,n=br(((null===(e=t.defaultListBodyRef.current)||void 0===e?void 0:e.getItems())||[]).map((function(e){return e.item})));null===E||void 0===E||E(n)}},O),p["createElement"](i["a"].Item,{onClick:function(){null===E||void 0===E||E(br(N))}},g)):p["createElement"](i["a"],null,p["createElement"](i["a"].Item,{onClick:function(){var e=br(N);x(e,e.length!==l.length)}},v),P&&p["createElement"](i["a"].Item,{onClick:function(){var e,n=(null===(e=t.defaultListBodyRef.current)||void 0===e?void 0:e.getItems())||[];x(br(n.map((function(e){return e.item}))),!0)}},b),p["createElement"](i["a"].Item,{onClick:function(){var e,n;n=br(P?((null===(e=t.defaultListBodyRef.current)||void 0===e?void 0:e.getItems())||[]).map((function(e){return e.item})):N);var r=new Set(l),a=[],o=[];n.forEach((function(e){r.has(e)?o.push(e):a.push(e)})),x(a,!0),x(o,!1)}},y));var I=p["createElement"](pn["a"],{className:"".concat(a,"-header-dropdown"),overlay:F,disabled:u},p["createElement"](sn.a,null));return p["createElement"]("div",{className:k,style:d},p["createElement"]("div",{className:"".concat(a,"-header")},D,I,p["createElement"]("span",{className:"".concat(a,"-header-selected")},this.getSelectAllLabel(l.length,N.length)),p["createElement"]("span",{className:"".concat(a,"-header-title")},c)),T,A)}}]),n}(p["PureComponent"]);yr.defaultProps={dataSource:[],titleText:"",showSearch:!1};var gr=n("DFhj"),Or=n.n(gr),jr=n("fEPi"),xr=n.n(jr),Er=function(e){var t=e.disabled,n=e.moveToLeft,r=e.moveToRight,a=e.leftArrowText,o=void 0===a?"":a,c=e.rightArrowText,i=void 0===c?"":c,l=e.leftActive,u=e.rightActive,f=e.className,d=e.style,m=e.direction,h=e.oneWay;return p["createElement"]("div",{className:f,style:d},p["createElement"](s["a"],{type:"primary",size:"small",disabled:t||!u,onClick:r,icon:"rtl"!==m?p["createElement"](xr.a,null):p["createElement"](Or.a,null)},i),!h&&p["createElement"](s["a"],{type:"primary",size:"small",disabled:t||!l,onClick:n,icon:"rtl"!==m?p["createElement"](Or.a,null):p["createElement"](xr.a,null)},o))},wr=Er;function Sr(e){return Sr="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},Sr(e)}function Pr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Cr(e){return Mr(e)||Nr(e)||Rr(e)||kr()}function kr(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function Rr(e,t){if(e){if("string"===typeof e)return Tr(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Tr(e,t):void 0}}function Nr(e){if("undefined"!==typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}function Mr(e){if(Array.isArray(e))return Tr(e)}function Tr(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function Ar(){return Ar=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Ar.apply(this,arguments)}function Dr(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Fr(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function Ir(e,t,n){return t&&Fr(e.prototype,t),n&&Fr(e,n),e}function Lr(e,t){if("function"!==typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&_r(e,t)}function _r(e,t){return _r=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},_r(e,t)}function Vr(e){var t=zr();return function(){var n,r=Ur(e);if(t){var a=Ur(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return Br(this,n)}}function Br(e,t){return!t||"object"!==Sr(t)&&"function"!==typeof t?Hr(e):t}function Hr(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function zr(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function Ur(e){return Ur=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},Ur(e)}var Kr=function(e){Lr(n,e);var t=Vr(n);function n(e){var r;Dr(this,n),r=t.call(this,e),r.separatedDataSource=null,r.setStateKeys=function(e,t){"left"===e?r.setState((function(e){var n=e.sourceSelectedKeys;return{sourceSelectedKeys:"function"===typeof t?t(n||[]):t}})):r.setState((function(e){var n=e.targetSelectedKeys;return{targetSelectedKeys:"function"===typeof t?t(n||[]):t}}))},r.getLocale=function(e,t){return Ar(Ar(Ar({},e),{notFoundContent:t("Transfer")}),r.props.locale)},r.moveTo=function(e){var t=r.props,n=t.targetKeys,a=void 0===n?[]:n,o=t.dataSource,c=void 0===o?[]:o,i=t.onChange,l=r.state,u=l.sourceSelectedKeys,s=l.targetSelectedKeys,f="right"===e?u:s,p=f.filter((function(e){return!c.some((function(t){return!(e!==t.key||!t.disabled)}))})),d="right"===e?p.concat(a):a.filter((function(e){return-1===p.indexOf(e)})),m="right"===e?"left":"right";r.setStateKeys(m,[]),r.handleSelectChange(m,[]),i&&i(d,e,p)},r.moveToLeft=function(){return r.moveTo("left")},r.moveToRight=function(){return r.moveTo("right")},r.onItemSelectAll=function(e,t,n){r.setStateKeys(e,(function(a){var o=[];return o=n?Array.from(new Set([].concat(Cr(a),Cr(t)))):a.filter((function(e){return-1===t.indexOf(e)})),r.handleSelectChange(e,o),o}))},r.onLeftItemSelectAll=function(e,t){return r.onItemSelectAll("left",e,t)},r.onRightItemSelectAll=function(e,t){return r.onItemSelectAll("right",e,t)},r.handleFilter=function(e,t){var n=r.props.onSearch,a=t.target.value;n&&n(e,a)},r.handleLeftFilter=function(e){return r.handleFilter("left",e)},r.handleRightFilter=function(e){return r.handleFilter("right",e)},r.handleClear=function(e){var t=r.props.onSearch;t&&t(e,"")},r.handleLeftClear=function(){return r.handleClear("left")},r.handleRightClear=function(){return r.handleClear("right")},r.onItemSelect=function(e,t,n){var a=r.state,o=a.sourceSelectedKeys,c=a.targetSelectedKeys,i=Cr("left"===e?o:c),l=i.indexOf(t);l>-1&&i.splice(l,1),n&&i.push(t),r.handleSelectChange(e,i),r.props.selectedKeys||r.setStateKeys(e,i)},r.onLeftItemSelect=function(e,t){return r.onItemSelect("left",e,t)},r.onRightItemSelect=function(e,t){return r.onItemSelect("right",e,t)},r.onRightItemRemove=function(e){var t=r.props,n=t.targetKeys,a=void 0===n?[]:n,o=t.onChange;r.setStateKeys("right",[]),o&&o(a.filter((function(t){return!e.includes(t)})),"left",Cr(e))},r.handleScroll=function(e,t){var n=r.props.onScroll;n&&n(e,t)},r.handleLeftScroll=function(e){return r.handleScroll("left",e)},r.handleRightScroll=function(e){return r.handleScroll("right",e)},r.handleListStyle=function(e,t){return"function"===typeof e?e({direction:t}):e},r.renderTransfer=function(e){return p["createElement"](de["a"],null,(function(t){var n,a=t.getPrefixCls,o=t.renderEmpty,c=t.direction,i=r.props,l=i.prefixCls,u=i.className,s=i.disabled,f=i.operations,d=void 0===f?[]:f,m=i.showSearch,h=i.footer,v=i.style,b=i.listStyle,y=i.operationStyle,g=i.filterOption,O=i.render,j=i.children,x=i.showSelectAll,E=i.oneWay,w=i.pagination,S=a("transfer",l),P=r.getLocale(e,o),C=r.state,k=C.sourceSelectedKeys,R=C.targetSelectedKeys,N=!j&&w,M=r.separateDataSource(),T=M.leftDataSource,A=M.rightDataSource,D=R.length>0,F=k.length>0,I=se()(u,S,(n={},Pr(n,"".concat(S,"-disabled"),s),Pr(n,"".concat(S,"-customize-list"),!!j),Pr(n,"".concat(S,"-rtl"),"rtl"===c),n)),L=r.getTitles(P),_=r.props.selectAllLabels||[];return p["createElement"]("div",{className:I,style:v},p["createElement"](yr,Ar({prefixCls:"".concat(S,"-list"),titleText:L[0],dataSource:T,filterOption:g,style:r.handleListStyle(b,"left"),checkedKeys:k,handleFilter:r.handleLeftFilter,handleClear:r.handleLeftClear,onItemSelect:r.onLeftItemSelect,onItemSelectAll:r.onLeftItemSelectAll,render:O,showSearch:m,renderList:j,footer:h,onScroll:r.handleLeftScroll,disabled:s,direction:"left",showSelectAll:x,selectAllLabel:_[0],pagination:N},P)),p["createElement"](wr,{className:"".concat(S,"-operation"),rightActive:F,rightArrowText:d[0],moveToRight:r.moveToRight,leftActive:D,leftArrowText:d[1],moveToLeft:r.moveToLeft,style:y,disabled:s,direction:c,oneWay:E}),p["createElement"](yr,Ar({prefixCls:"".concat(S,"-list"),titleText:L[1],dataSource:A,filterOption:g,style:r.handleListStyle(b,"right"),checkedKeys:R,handleFilter:r.handleRightFilter,handleClear:r.handleRightClear,onItemSelect:r.onRightItemSelect,onItemSelectAll:r.onRightItemSelectAll,onItemRemove:r.onRightItemRemove,render:O,showSearch:m,renderList:j,footer:h,onScroll:r.handleRightScroll,disabled:s,direction:"right",showSelectAll:x,selectAllLabel:_[1],showRemove:E,pagination:N},P)))}))};var a=e.selectedKeys,o=void 0===a?[]:a,c=e.targetKeys,i=void 0===c?[]:c;return r.state={sourceSelectedKeys:o.filter((function(e){return-1===i.indexOf(e)})),targetSelectedKeys:o.filter((function(e){return i.indexOf(e)>-1}))},r}return Ir(n,[{key:"getTitles",value:function(e){var t=this.props.titles;return t||e.titles}},{key:"handleSelectChange",value:function(e,t){var n=this.state,r=n.sourceSelectedKeys,a=n.targetSelectedKeys,o=this.props.onSelectChange;o&&("left"===e?o(t,a):o(r,t))}},{key:"separateDataSource",value:function(){var e=this.props,t=e.dataSource,n=e.rowKey,r=e.targetKeys,a=void 0===r?[]:r,o=[],c=new Array(a.length);return t.forEach((function(e){n&&(e.key=n(e));var t=a.indexOf(e.key);-1!==t?c[t]=e:o.push(e)})),{leftDataSource:o,rightDataSource:c}}},{key:"render",value:function(){return p["createElement"](Fn["a"],{componentName:"Transfer",defaultLocale:An["a"].Transfer},this.renderTransfer)}}],[{key:"getDerivedStateFromProps",value:function(e){var t=e.selectedKeys,n=e.targetKeys,r=e.pagination,a=e.children;if(t){var o=n||[];return{sourceSelectedKeys:t.filter((function(e){return!o.includes(e)})),targetSelectedKeys:t.filter((function(e){return o.includes(e)}))}}return Object(me["a"])(!r||!a,"Transfer","`pagination` not support customize render list."),null}}]),n}(p["Component"]);Kr.List=yr,Kr.Operation=wr,Kr.Search=kn,Kr.defaultProps={dataSource:[],locale:{},showSearch:!1,listStyle:function(){}};var Xr=Kr,Yr=Object(en["connect"])({getProps:an["mapStyledProps"],valueName:"targetKeys"})(Xr),Gr=n("Sdc0"),Wr=Object(en["connect"])({valueName:"checked",getProps:an["mapStyledProps"]})(Object(an["acceptEnum"])(Gr["a"])),qr=n("OAhR"),$r=n("vj3D"),Jr=function(){return Jr=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},Jr.apply(this,arguments)},Qr=function(e){var t=String(e.className||"").indexOf("has-text")>-1;return d.a.createElement(s["a"],Jr({type:t?"link":void 0,shape:t?void 0:"circle"},e))},Zr=n("bx4M"),ea=n("xvlK"),ta=n("/MfK"),na=n("8Skl"),ra={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M890.5 755.3L537.9 269.2c-12.8-17.6-39-17.6-51.7 0L133.5 755.3A8 8 0 00140 768h75c5.1 0 9.9-2.5 12.9-6.6L512 369.8l284.1 391.6c3 4.1 7.8 6.6 12.9 6.6h75c6.5 0 10.3-7.4 6.5-12.7z"}}]},name:"up",theme:"outlined"},aa=ra,oa=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:aa}))};oa.displayName="UpOutlined";var ca=p["forwardRef"](oa),ia=n("vOnD"),la=function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e},ua=function(){return ua=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},ua.apply(this,arguments)},sa=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"===typeof Object.getOwnPropertySymbols){var a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n},fa={CircleButton:Qr,TextButton:Zt,AdditionIcon:function(){return d.a.createElement(ea["a"],null)},RemoveIcon:function(){return d.a.createElement(ta["a"],null)},MoveDownIcon:function(){return d.a.createElement(na["a"],null)},MoveUpIcon:function(){return d.a.createElement(ca,null)}},pa=Object(ia["b"])((function(e){var t=e.value,n=e.schema,r=e.className,a=e.editable,o=e.path,c=e.mutators,i=n.getExtendsComponentProps()||{},l=i.renderAddition,u=i.renderRemove,s=i.renderMoveDown,f=i.renderMoveUp,m=i.renderEmpty,h=i.renderExtraOperations,v=sa(i,["renderAddition","renderRemove","renderMoveDown","renderMoveUp","renderEmpty","renderExtraOperations"]),b=Array.isArray(n.items)?n.items[n.items.length-1]:n.items,y=function(){b&&c.push(b.getEmptyValue())};return d.a.createElement("div",{className:r},d.a.createElement($r["ArrayList"],{value:t,minItems:n.minItems,maxItems:n.maxItems,editable:a,components:fa,renders:{renderAddition:l,renderRemove:u,renderMoveDown:s,renderMoveUp:f,renderEmpty:m}},Object(qr["toArr"])(t).map((function(e,t){return d.a.createElement(Zr["a"],ua({},v,{size:"small",className:"card-list-item",key:t,title:d.a.createElement("span",null,t+1,d.a.createElement("span",null,".")," ",v.title||n.title),extra:d.a.createElement(p["Fragment"],null,d.a.createElement($r["ArrayList"].Remove,{index:t,onClick:function(){return c.remove(t)}}),d.a.createElement($r["ArrayList"].MoveDown,{index:t,onClick:function(){return c.moveDown(t)}}),d.a.createElement($r["ArrayList"].MoveUp,{index:t,onClick:function(){return c.moveUp(t)}}),Object(qr["isFn"])(h)?h(t):h)}),b&&d.a.createElement(en["SchemaField"],{path:qr["FormPath"].parse(o).concat(t),schema:b}))})),d.a.createElement($r["ArrayList"].Empty,null,(function(e){var t=e.children,n=e.allowAddition;return d.a.createElement(Zr["a"],ua({},v,{size:"small",className:"card-list-item card-list-empty "+(n?"add-pointer":""),onClick:n?y:void 0}),d.a.createElement("div",{className:"empty-wrapper"},t))})),d.a.createElement($r["ArrayList"].Addition,null,(function(e){var t=e.children,n=e.isEmpty;if(!n)return d.a.createElement("div",{className:"array-cards-addition",onClick:y},t)}))))}))(da||(da=la(["\n width: 100%;\n .ant-card {\n .ant-card {\n box-shadow: none;\n }\n .ant-card-body {\n padding: 20px 10px 0 10px;\n }\n .array-cards-addition {\n box-shadow: none;\n border: 1px solid #eee;\n transition: all 0.35s ease-in-out;\n &:hover {\n border: 1px solid #ccc;\n }\n }\n .empty-wrapper {\n display: flex;\n flex-direction: column;\n align-items: center;\n margin-bottom: 10px;\n img {\n height: 85px;\n }\n .ant-btn {\n color: #888;\n }\n }\n }\n .card-list-empty.card-list-item.add-pointer {\n cursor: pointer;\n }\n\n .array-cards-addition {\n margin-top: 10px;\n margin-bottom: 3px;\n background: #fff;\n display: flex;\n cursor: pointer;\n padding: 5px 0;\n justify-content: center;\n box-shadow: 1px 1px 4px 0 rgba(0, 0, 0, 0.1);\n }\n .card-list-item {\n margin-top: 10px;\n border: 1px solid #eee;\n }\n .card-list-item:first-child {\n margin-top: 0 !important;\n }\n .ant-card-extra {\n display: flex;\n button {\n margin-right: 8px;\n }\n }\n"],["\n width: 100%;\n .ant-card {\n .ant-card {\n box-shadow: none;\n }\n .ant-card-body {\n padding: 20px 10px 0 10px;\n }\n .array-cards-addition {\n box-shadow: none;\n border: 1px solid #eee;\n transition: all 0.35s ease-in-out;\n &:hover {\n border: 1px solid #ccc;\n }\n }\n .empty-wrapper {\n display: flex;\n flex-direction: column;\n align-items: center;\n margin-bottom: 10px;\n img {\n height: 85px;\n }\n .ant-btn {\n color: #888;\n }\n }\n }\n .card-list-empty.card-list-item.add-pointer {\n cursor: pointer;\n }\n\n .array-cards-addition {\n margin-top: 10px;\n margin-bottom: 3px;\n background: #fff;\n display: flex;\n cursor: pointer;\n padding: 5px 0;\n justify-content: center;\n box-shadow: 1px 1px 4px 0 rgba(0, 0, 0, 0.1);\n }\n .card-list-item {\n margin-top: 10px;\n border: 1px solid #eee;\n }\n .card-list-item:first-child {\n margin-top: 0 !important;\n }\n .ant-card-extra {\n display: flex;\n button {\n margin-right: 8px;\n }\n }\n"])));pa.isFieldComponent=!0;var da,ma=n("Vl3Y"),ha=n("wCAj"),va=n("FVvW"),ba=function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e},ya=function(){return ya=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},ya.apply(this,arguments)},ga=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"===typeof Object.getOwnPropertySymbols){var a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n},Oa={CircleButton:Qr,TextButton:Zt,AdditionIcon:function(){return d.a.createElement(ea["a"],{style:{fontSize:20}})},RemoveIcon:function(){return d.a.createElement(ta["a"],null)},MoveDownIcon:function(){return d.a.createElement(na["a"],null)},MoveUpIcon:function(){return d.a.createElement(ca,null)}},ja=ia["b"].span(Ea||(Ea=ba(["\n width: 7px;\n display: inline-block;\n height: 14px;\n border: 2px dotted #c5c5c5;\n border-top: 0;\n border-bottom: 0;\n cursor: move;\n margin-bottom: 24px;\n"],["\n width: 7px;\n display: inline-block;\n height: 14px;\n border: 2px dotted #c5c5c5;\n border-top: 0;\n border-bottom: 0;\n cursor: move;\n margin-bottom: 24px;\n"]))),xa=Object(ia["b"])((function(e){var t=Object(p["useContext"])(en["FormExpressionScopeContext"]),n=e.value,r=e.schema,a=e.className,o=e.editable,c=e.path,i=e.mutators,l=r.getExtendsComponentProps()||{},u=l.renderAddition,s=l.renderRemove,f=l.renderMoveDown,m=l.renderMoveUp,h=l.renderEmpty,v=l.renderExtraOperations,b=l.operationsWidth,y=l.operations,g=l.draggable,O=ga(l,["renderAddition","renderRemove","renderMoveDown","renderMoveUp","renderEmpty","renderExtraOperations","operationsWidth","operations","draggable"]),j=Array.isArray(r.items)?r.items[r.items.length-1]:r.items,x=function(){j&&i.push(j.getEmptyValue())},E=function(e,t){i.move(e,t)},w=function(e){return e.mapProperties((function(e,n){var r=ya(ya({},e.getExtendsItemProps()),e.getExtendsProps());return ya(ya({title:Object(en["complieExpression"])(e.title,t)},r),{key:n,dataIndex:n,render:function(t,r,a){var o=qr["FormPath"].parse(c).concat(a,n);return d.a.createElement(va["FormItemShallowProvider"],{key:o.toString(),label:void 0,labelCol:void 0,wrapperCol:void 0},d.a.createElement(en["SchemaField"],{path:o,schema:e}))}})}))},S=[];r.items&&(S=Object(qr["isArr"])(r.items)?r.items.reduce((function(e,t){return e.concat(w(t))}),[]):w(r.items)),o&&!1!==y&&S.push(ya(ya({},y),{key:"operations",dataIndex:"operations",width:b||200,render:function(e,t,n){return d.a.createElement(ma["a"].Item,null,d.a.createElement("div",{className:"array-item-operator"},d.a.createElement($r["ArrayList"].Remove,{index:n,onClick:function(){return i.remove(n)}}),d.a.createElement($r["ArrayList"].MoveDown,{index:n,onClick:function(){return i.moveDown(n)}}),d.a.createElement($r["ArrayList"].MoveUp,{index:n,onClick:function(){return i.moveUp(n)}}),Object(qr["isFn"])(v)?v(n):v))}})),g&&S.unshift({width:20,render:function(){return d.a.createElement(ja,{className:"drag-handler"})}});var P=function(){return d.a.createElement(ha["a"],ya({},O,{rowKey:function(e){return Object(qr["toArr"])(n).indexOf(e)},pagination:!1,columns:S,dataSource:Object(qr["toArr"])(n)}))};return d.a.createElement("div",{className:a},d.a.createElement($r["ArrayList"],{value:n,minItems:r.minItems,maxItems:r.maxItems,editable:o,components:Oa,renders:{renderAddition:u,renderRemove:s,renderMoveDown:f,renderMoveUp:m,renderEmpty:h}},g?d.a.createElement($r["DragListView"],{onDragEnd:E,nodeSelector:"tr.ant-table-row",ignoreSelector:"tr.ant-table-expanded-row"},P()):P(),d.a.createElement($r["ArrayList"].Addition,null,(function(e){var t=e.children;return t&&d.a.createElement("div",{className:"array-table-addition",onClick:x},t)}))))}))(wa||(wa=ba(["\n width: 100%;\n margin-bottom: 10px;\n table {\n margin-bottom: 0 !important;\n }\n .array-table-addition {\n background: #fbfbfb;\n cursor: pointer;\n margin-top: 3px;\n border-radius: 3px;\n .next-btn-text {\n color: #888;\n }\n .next-icon:before {\n width: 16px !important;\n font-size: 16px !important;\n margin-right: 5px;\n }\n }\n .ant-btn {\n color: #888;\n }\n .array-item-operator {\n display: flex;\n button {\n margin-right: 8px;\n }\n }\n"],["\n width: 100%;\n margin-bottom: 10px;\n table {\n margin-bottom: 0 !important;\n }\n .array-table-addition {\n background: #fbfbfb;\n cursor: pointer;\n margin-top: 3px;\n border-radius: 3px;\n .next-btn-text {\n color: #888;\n }\n .next-icon:before {\n width: 16px !important;\n font-size: 16px !important;\n margin-right: 5px;\n }\n }\n .ant-btn {\n color: #888;\n }\n .array-item-operator {\n display: flex;\n button {\n margin-right: 8px;\n }\n }\n"])));xa.isFieldComponent=!0;var Ea,wa,Sa=Object(en["connect"])({valueName:"checked",getProps:an["mapStyledProps"]})(fn["a"]);Sa.Group=Object(en["connect"])({getProps:an["mapStyledProps"],getComponent:an["mapTextComponent"]})(Object(an["transformDataSourceKey"])(fn["a"].Group,"options"));var Pa=n("+eQT"),Ca=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),ka=function(){return ka=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},ka.apply(this,arguments)},Ra=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Ca(t,e),t.prototype.render=function(){return d.a.createElement(Pa["a"],ka({},this.props,{picker:"year"}))},t}(d.a.Component),Na=function(e,t){if(void 0===t&&(t="YYYY-MM-DD HH:mm:ss"),""!==e)return e&&e.format?e.format(t):e},Ma=function(e,t){var n=e.value,r=e.showTime,a=void 0!==r&&r;if(!t.editable)return e;try{Object(an["isStr"])(n)&&n?e.value=nn()(n,a?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"):Object(an["isArr"])(n)&&n.length&&(e.value=n.map((function(e){return e&&nn()(e,a?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD")||""})))}catch(o){throw new Error(o)}return e},Ta=Object(en["connect"])({getValueFromEvent:function(e,t){var n=this.props||{};return Na(t,n.format||(n.showTime?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD"))},getProps:Object(an["compose"])(an["mapStyledProps"],Ma),getComponent:an["mapTextComponent"]})(Pa["a"]);Ta.RangePicker=Object(en["connect"])({getValueFromEvent:function(e,t){var n=t[0],r=t[1],a=this.props||{},o=a.format||(a.showTime?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD");return[Na(n,o),Na(r,o)]},getProps:Object(an["compose"])(an["mapStyledProps"],Ma),getComponent:an["mapTextComponent"]})(Pa["a"].RangePicker),Ta.MonthPicker=Object(en["connect"])({getValueFromEvent:function(e,t){return Na(t)},getProps:Object(an["compose"])(an["mapStyledProps"],Ma),getComponent:an["mapTextComponent"]})(Pa["a"].MonthPicker),Ta.WeekPicker=Object(en["connect"])({getValueFromEvent:function(e,t){return Na(t,"gggg-wo")},getProps:Object(an["compose"])(an["mapStyledProps"],(function(e){if(Object(an["isStr"])(e.value)&&e.value){var t=e.value.match(/\D*(\d+)\D*(\d+)\D*/)||["","",""];e.value=nn()(t[1],"YYYY").add(t[2]-1,"weeks")}return e})),getComponent:an["mapTextComponent"]})(Pa["a"].WeekPicker),Ta.YearPicker=Object(en["connect"])({getValueFromEvent:function(e,t){return Na(t,"YYYY")},getProps:Object(an["compose"])(an["mapStyledProps"],Ma),getComponent:an["mapTextComponent"]})(Ra);var Aa,Da,Fa,Ia=function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e},La=function(){return La=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},La.apply(this,arguments)},_a=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"===typeof Object.getOwnPropertySymbols){var a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n},Va=(Object(en["createVirtualBox"])("block",Object(ia["b"])((function(e){var t=e.children,n=e.className,r=_a(e,["children","className"]);return d.a.createElement(Zr["a"],La({className:n,size:"small"},r),t)}))(Aa||(Aa=Ia(["\n margin-bottom: 10px !important;\n &.ant-card {\n border: none;\n box-shadow: none;\n }\n "],["\n margin-bottom: 10px !important;\n &.ant-card {\n border: none;\n box-shadow: none;\n }\n "])))),function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}),Ba=function(){return Ba=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},Ba.apply(this,arguments)},Ha=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"===typeof Object.getOwnPropertySymbols){var a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n},za=(Object(en["createVirtualBox"])("card",Object(ia["b"])((function(e){var t=e.children,n=e.className,r=Ha(e,["children","className"]);return d.a.createElement(Zr["a"],Ba({className:n,size:"small"},r),t)}))(Da||(Da=Va(["\n margin-bottom: 10px !important;\n "],["\n margin-bottom: 10px !important;\n "])))),n("KrTs")),Ua=n("ZTPi"),Ka=function(){return Ka=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},Ka.apply(this,arguments)},Xa=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"===typeof Object.getOwnPropertySymbols){var a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n};(function(e){e["ON_FORM_TAB_ACTIVE_KEY_CHANGE"]="onFormTabActiveKeyChange"})(Fa||(Fa={}));var Ya=en["FormEffectHooks"].onFormChange$,Ga={onTabActiveKeyChange$:Object(en["createEffectHook"])(Fa.ON_FORM_TAB_ACTIVE_KEY_CHANGE)},Wa=function(e,t){return e.reduce((function(e,n){var r=n.schema,a=n.key;return Array.isArray(t)&&t.includes(a)?e:"tabpane"===r.getExtendsComponent()?e.concat({props:r.getExtendsComponentProps(),schema:r,key:a}):e}),[])},qa=function(e,t,n){if(void 0===e&&(e=[]),!e.includes(n))return n;var r=t.findIndex((function(t){return!e.includes(t.key)}));return r>=0?t[r].key:""},$a=function(e,t){return e.filter((function(e){var n=e.path;return en["FormPath"].parse(n).includes(t)}))},Ja=function(e,t,n){var r=n.filter((function(e){var n=e.path;return en["FormPath"].parse(n).includes(t)}));return r.length>0?d.a.createElement(za["a"],{offset:[12,0],count:r.length},e):e},Qa=Object(en["createControllerBox"])("tab",(function(e){var t=e.form,n=e.schema,r=e.name,a=e.path,o=n.getOrderProperties(),c=n.getExtendsComponentProps(),i=c.hiddenKeys,l=c.defaultActiveKey,u=Xa(c,["hiddenKeys","defaultActiveKey"]);i=i||[];var s=Object(en["useFieldState"])({activeKey:qa(i,o,l),childrenErrors:[]}),f=s[0],m=f.activeKey,h=f.childrenErrors,v=s[1],b=Object(p["useRef"])([]);b.current=Wa(o,i);var y=function(e){t.notify(Fa.ON_FORM_TAB_ACTIVE_KEY_CHANGE,{name:r,path:a,value:e})},g=Object(an["createMatchUpdate"])(r,a);return Object(p["useEffect"])((function(){Array.isArray(i)&&v({activeKey:qa(i,o,l)})}),[i.length]),Object(en["useFormEffects"])((function(e){var t=e.hasChanged;Ya().subscribe((function(e){var n=t(e,"errors");n&&v({childrenErrors:$a(e.errors,a)})})),Ga.onTabActiveKeyChange$().subscribe((function(e){var t=void 0===e?{}:e,n=t.value,r=t.name,a=t.path;b.current.map((function(e){return e.key})).includes(n)&&g(r,a,(function(){v({activeKey:n})}))}))})),d.a.createElement(Ua["a"],Ka({},u,{activeKey:m,onChange:y}),b.current.map((function(e){var t=e.props,n=e.schema,r=e.key,o=en["FormPath"].parse(a).concat(r);return d.a.createElement(Ua["a"].TabPane,Ka({},t,{tab:m===r?t.tab:Ja(t.tab,o,h),key:r,forceRender:!0}),d.a.createElement(en["SchemaField"],{path:o,schema:n,onlyRenderProperties:!0}))})))}));Qa.TabPane=Object(en["createControllerBox"])("tabpane",(function(e){var t=e.children;return d.a.createElement(p["Fragment"],null,t)})),Object.assign(Qa,Fa,Ga);var Za=n("kPKH"),eo=function(){return eo=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},eo.apply(this,arguments)},to=(Object(en["createVirtualBox"])("grid-col",(function(e){return d.a.createElement(Za["a"],eo({},e),e.children)})),n("BMrR")),no=function(){return no=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},no.apply(this,arguments)},ro=(Object(en["createVirtualBox"])("grid-row",(function(e){var t=e.title,n=e.label,r=d.a.createElement(to["a"],no({},e),e.children);return t||n?d.a.createElement(va["AntdSchemaFieldAdaptor"],no({},Object(va["pickFormItemProps"])(e)),r):r})),function(){return ro=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},ro.apply(this,arguments)}),ao=(Object(en["createVirtualBox"])("grid",(function(e){var t=e.cols,n=e.title,r=e.label,a=Object(va["pickFormItemProps"])(e),o=Object(va["pickNotFormItemProps"])(e),c=Object(qr["toArr"])(e.children),i=Object(qr["toArr"])(t).map((function(e){return Object(an["normalizeCol"])(e)})),l=c.length;if(i.length<l)for(var u=l-i.length,s=24-i.reduce((function(e,t){return e+Number(t.span?t.span:0)+Number(t.offset?t.offset:0)}),0),f=0;f<u;f++)i.push({span:Math.floor(s/u)});var m=d.a.createElement(to["a"],ro({},o),c.reduce((function(e,t,n){return t?e.concat(d.a.createElement(Za["a"],ro({key:n},i[n]),t)):e}),[]));return n||r?d.a.createElement(va["AntdSchemaFieldAdaptor"],ro({},a),m):d.a.createElement(p["Fragment"],null,m)})),function(){return ao=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},ao.apply(this,arguments)}),oo=(Object(en["createVirtualBox"])("layout",(function(e){var t=Object(va["useDeepFormItem"])().inline,n=e.inline||t,r=n||e.className||e.style?d.a.createElement("div",{className:se()(e.className,{"ant-form ant-form-inline":n}),style:e.style},e.children):e.children;return d.a.createElement(va["FormItemDeepProvider"],ao({},e),r)})),n("md7G")),co=n("foSv");function io(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function lo(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?io(Object(n),!0).forEach((function(t){Object(Me["a"])(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):io(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function uo(e){var t=so();return function(){var n,r=Object(co["a"])(e);if(t){var a=Object(co["a"])(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return Object(oo["a"])(this,n)}}function so(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function fo(e){return"string"===typeof e}var po=function(e){Object(E["a"])(n,e);var t=uo(n);function n(){var e;return Object(j["a"])(this,n),e=t.apply(this,arguments),e.onClick=function(){var t=e.props,n=t.onClick,r=t.onStepClick,a=t.stepIndex;n&&n.apply(void 0,arguments),r(a)},e}return Object(x["a"])(n,[{key:"renderIconNode",value:function(){var e,t,n=this.props,r=n.prefixCls,a=n.progressDot,o=n.stepNumber,c=n.status,i=n.title,l=n.description,u=n.icon,s=n.iconPrefix,f=n.icons,p=se()("".concat(r,"-icon"),"".concat(s,"icon"),(e={},Object(Me["a"])(e,"".concat(s,"icon-").concat(u),u&&fo(u)),Object(Me["a"])(e,"".concat(s,"icon-check"),!u&&"finish"===c&&(f&&!f.finish||!f)),Object(Me["a"])(e,"".concat(s,"icon-cross"),!u&&"error"===c&&(f&&!f.error||!f)),e)),m=d.a.createElement("span",{className:"".concat(r,"-icon-dot")});return t=a?"function"===typeof a?d.a.createElement("span",{className:"".concat(r,"-icon")},a(m,{index:o-1,status:c,title:i,description:l})):d.a.createElement("span",{className:"".concat(r,"-icon")},m):u&&!fo(u)?d.a.createElement("span",{className:"".concat(r,"-icon")},u):f&&f.finish&&"finish"===c?d.a.createElement("span",{className:"".concat(r,"-icon")},f.finish):f&&f.error&&"error"===c?d.a.createElement("span",{className:"".concat(r,"-icon")},f.error):u||"finish"===c||"error"===c?d.a.createElement("span",{className:p}):d.a.createElement("span",{className:"".concat(r,"-icon")},o),t}},{key:"render",value:function(){var e,t=this.props,n=t.className,r=t.prefixCls,a=t.style,o=t.active,c=t.status,i=void 0===c?"wait":c,l=(t.iconPrefix,t.icon),u=(t.wrapperStyle,t.stepNumber,t.disabled),s=t.description,f=t.title,p=t.subTitle,m=(t.progressDot,t.tailContent),h=(t.icons,t.stepIndex,t.onStepClick),v=t.onClick,b=Object(O["a"])(t,["className","prefixCls","style","active","status","iconPrefix","icon","wrapperStyle","stepNumber","disabled","description","title","subTitle","progressDot","tailContent","icons","stepIndex","onStepClick","onClick"]),y=se()("".concat(r,"-item"),"".concat(r,"-item-").concat(i),n,(e={},Object(Me["a"])(e,"".concat(r,"-item-custom"),l),Object(Me["a"])(e,"".concat(r,"-item-active"),o),Object(Me["a"])(e,"".concat(r,"-item-disabled"),!0===u),e)),g=lo({},a),j={};return h&&!u&&(j.role="button",j.tabIndex=0,j.onClick=this.onClick),d.a.createElement("div",Object.assign({},b,{className:y,style:g}),d.a.createElement("div",Object.assign({onClick:v},j,{className:"".concat(r,"-item-container")}),d.a.createElement("div",{className:"".concat(r,"-item-tail")},m),d.a.createElement("div",{className:"".concat(r,"-item-icon")},this.renderIconNode()),d.a.createElement("div",{className:"".concat(r,"-item-content")},d.a.createElement("div",{className:"".concat(r,"-item-title")},f,p&&d.a.createElement("div",{title:"string"===typeof p?p:void 0,className:"".concat(r,"-item-subtitle")},p)),s&&d.a.createElement("div",{className:"".concat(r,"-item-description")},s))))}}]),n}(d.a.Component);function mo(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function ho(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?mo(Object(n),!0).forEach((function(t){Object(Me["a"])(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):mo(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function vo(e){var t=bo();return function(){var n,r=Object(co["a"])(e);if(t){var a=Object(co["a"])(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return Object(oo["a"])(this,n)}}function bo(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}var yo=function(e){Object(E["a"])(n,e);var t=vo(n);function n(){var e;return Object(j["a"])(this,n),e=t.apply(this,arguments),e.onStepClick=function(t){var n=e.props,r=n.onChange,a=n.current;r&&a!==t&&r(t)},e}return Object(x["a"])(n,[{key:"render",value:function(){var e,t=this,n=this.props,r=n.prefixCls,a=n.style,o=void 0===a?{}:a,c=n.className,i=n.children,l=n.direction,u=n.type,s=n.labelPlacement,f=n.iconPrefix,m=n.status,h=n.size,v=n.current,b=n.progressDot,y=n.initial,g=n.icons,j=n.onChange,x=Object(O["a"])(n,["prefixCls","style","className","children","direction","type","labelPlacement","iconPrefix","status","size","current","progressDot","initial","icons","onChange"]),E="navigation"===u,w=d.a.Children.toArray(i).filter((function(e){return!!e})),S=b?"vertical":s,P=se()(r,"".concat(r,"-").concat(l),c,(e={},Object(Me["a"])(e,"".concat(r,"-").concat(h),h),Object(Me["a"])(e,"".concat(r,"-label-").concat(S),"horizontal"===l),Object(Me["a"])(e,"".concat(r,"-dot"),!!b),Object(Me["a"])(e,"".concat(r,"-navigation"),E),e));return d.a.createElement("div",Object.assign({className:P,style:o},x),Object(le["a"])(w).map((function(e,n){if(!e)return null;var a=y+n,c=ho({stepNumber:"".concat(a+1),stepIndex:a,key:a,prefixCls:r,iconPrefix:f,wrapperStyle:o,progressDot:b,icons:g,onStepClick:j&&t.onStepClick},e.props);return"error"===m&&n===v-1&&(c.className="".concat(r,"-next-error")),e.props.status||(c.status=a===v?m:a<v?"finish":"wait"),c.active=a===v,Object(p["cloneElement"])(e,c)})))}}]),n}(d.a.Component);yo.Step=po,yo.defaultProps={type:"default",prefixCls:"rc-steps",iconPrefix:"rc",direction:"horizontal",labelPlacement:"horizontal",initial:0,current:0,status:"process",size:"",progressDot:!1};var go=yo,Oo=n("NAnI"),jo=n.n(Oo),xo=n("V/uB"),Eo=n.n(xo);function wo(e){return wo="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},wo(e)}function So(){return So=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},So.apply(this,arguments)}function Po(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Co(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function ko(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function Ro(e,t,n){return t&&ko(e.prototype,t),n&&ko(e,n),e}function No(e,t){if("function"!==typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&Mo(e,t)}function Mo(e,t){return Mo=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},Mo(e,t)}function To(e){var t=Fo();return function(){var n,r=Io(e);if(t){var a=Io(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return Ao(this,n)}}function Ao(e,t){return!t||"object"!==wo(t)&&"function"!==typeof t?Do(e):t}function Do(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Fo(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function Io(e){return Io=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},Io(e)}var Lo=function(e){No(n,e);var t=To(n);function n(){var e;return Co(this,n),e=t.apply(this,arguments),e.renderSteps=function(t){var n=t.getPrefixCls,r=t.direction,a=n("steps",e.props.prefixCls),o=n("",e.props.iconPrefix),c=se()(e.props.className,Po({},"".concat(a,"-rtl"),"rtl"===r)),i={finish:p["createElement"](jo.a,{className:"".concat(a,"-finish-icon")}),error:p["createElement"](Eo.a,{className:"".concat(a,"-error-icon")})};return p["createElement"](go,So({icons:i},e.props,{prefixCls:a,iconPrefix:o,className:c}))},e}return Ro(n,[{key:"render",value:function(){return p["createElement"](de["a"],null,this.renderSteps)}}]),n}(p["Component"]);Lo.Step=go.Step,Lo.defaultProps={current:0};var _o,Vo=function(){return Vo=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},Vo.apply(this,arguments)},Bo=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"===typeof Object.getOwnPropertySymbols){var a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n};(function(e){e["ON_FORM_STEP_NEXT"]="onFormStepNext",e["ON_FORM_STEP_PREVIOUS"]="onFormStepPrevious",e["ON_FORM_STEP_GO_TO"]="onFormStepGoto",e["ON_FORM_STEP_CURRENT_CHANGE"]="onFormStepCurrentChange",e["ON_FORM_STEP_DATA_SOURCE_CHANGED"]="onFormStepDataSourceChanged"})(_o||(_o={}));var Ho={onStepNext$:Object(en["createEffectHook"])(_o.ON_FORM_STEP_NEXT),onStepPrevious$:Object(en["createEffectHook"])(_o.ON_FORM_STEP_PREVIOUS),onStepGoto$:Object(en["createEffectHook"])(_o.ON_FORM_STEP_GO_TO),onStepCurrentChange$:Object(en["createEffectHook"])(_o.ON_FORM_STEP_CURRENT_CHANGE)},zo=Object(en["createControllerBox"])("step",(function(e){var t=e.form,n=e.schema,r=e.path,a=e.name,o=e.children,c=n.getExtendsComponentProps(),i=c.dataSource,l=Bo(c,["dataSource"]),u=Object(en["useFieldState"])({current:l.current||0}),s=u[0].current,f=u[1],m=Object(p["useRef"])(s),h=Object(p["useRef"])([]);h.current=Object(qr["toArr"])(i);var v=Object(an["createMatchUpdate"])(a,r),b=function(e){t.notify(_o.ON_FORM_STEP_CURRENT_CHANGE,{path:r,name:a,value:e,preValue:s}),f({current:e})};return Object(p["useEffect"])((function(){t.notify(_o.ON_FORM_STEP_DATA_SOURCE_CHANGED,{path:r,name:a,value:h.current})}),[h.current.length]),Object(en["useFormEffects"])((function(e,n){var r=n.setFieldState,a=function(){h.current.forEach((function(e,t){var n=e.name;r(n,(function(e){e.display=t===s}))}))};a(),e(_o.ON_FORM_STEP_DATA_SOURCE_CHANGED).subscribe((function(e){var t=e.name,n=e.path;v(t,n,(function(){a()}))})),e(_o.ON_FORM_STEP_CURRENT_CHANGE).subscribe((function(e){var n=void 0===e?{}:e,a=n.value,o=n.name,c=n.path;v(o,c,(function(){t.hostUpdate((function(){h.current.forEach((function(e,t){var n=e.name;if(!n)throw new Error("FormStep dataSource must include `name` property");r(n,(function(e){e.display=t===a}))}))}))}))})),e(_o.ON_FORM_STEP_NEXT).subscribe((function(e){var n=void 0===e?{}:e,r=n.name,a=n.path;v(r,a,(function(){t.validate().then((function(e){var t=e.errors;0===t.length&&b(m.current+1>h.current.length-1?m.current:m.current+1)}))}))})),e(_o.ON_FORM_STEP_PREVIOUS).subscribe((function(e){var t=void 0===e?{}:e,n=t.name,r=t.path;v(n,r,(function(){b(m.current-1<0?m.current:m.current-1)}))})),e(_o.ON_FORM_STEP_GO_TO).subscribe((function(e){var t=void 0===e?{}:e,n=t.name,r=t.path,a=t.value;v(n,r,(function(){a<0||a>h.current.length||b(a)}))}))})),m.current=s,d.a.createElement(p["Fragment"],null,d.a.createElement(Lo,Vo({},l,{current:s}),h.current.map((function(e,t){return d.a.createElement(Lo.Step,Vo({},e,{key:t}))})))," ",o)}));Object.assign(zo,_o,Ho);var Uo,Ko=n("A2FF"),Xo=function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e},Yo=function(){return Yo=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},Yo.apply(this,arguments)},Go=/^4\./.test(Ko["a"]),Wo=(Object(en["createControllerBox"])("text-box",Object(ia["b"])((function(e){var t=e.props,n=e.form,r=e.className,a=e.children,o=new en["Schema"](t),c=o.getExtendsComponentProps(),i=Object.assign({gutter:5},c),l=i.title,u=i.label,s=i.text,f=i.gutter,m=i.style,h=Object(va["pickFormItemProps"])(c),v=Object(p["useRef"])(),b=Object(qr["toArr"])(a),y=s.split("%s"),g=0;Object(p["useLayoutEffect"])((function(){if(v.current){var e=v.current.querySelectorAll(".text-box-field"),t=Array.prototype.map.call(e,(function(e){return[e,function(){var t=e.querySelector(".ant-form-item-children");setTimeout((function(){if(t){var r=n.getFormState((function(e){return e.editable}));e.style.width=r?t.getBoundingClientRect().width+"px":"auto"}}))}]}));return t.forEach((function(e){var t=e[0],n=e[1];n(),t.addEventListener("DOMSubtreeModified",n)})),function(){t.forEach((function(e){var t=e[0],n=e[1];t.removeEventListener("DOMSubtreeModified",n)}))}}}),[]);var O=y.reduce((function(e,t,n){return e.concat(t?d.a.createElement("p",{key:g++,className:"text-box-words",style:Yo({marginRight:f/2,marginLeft:f/2},m)},t):null,b[n]?d.a.createElement("div",{key:g++,className:"text-box-field"},b[n]):null)}),[]),j=d.a.createElement("div",{className:r+" "+c.className,style:{marginRight:-f/2,marginLeft:-f/2},ref:v},O);return l||u?d.a.createElement(va["AntdSchemaFieldAdaptor"],Yo({},h),j):j}))(Uo||(Uo=Xo(["\n display: flex;\n .text-box-words:nth-child(1) {\n margin-left: 0;\n }\n .text-box-words {\n margin-bottom: 0 !important;\n ","\n }\n .text-box-field {\n display: inline-block;\n .ant-form-item {\n margin-bottom: 0 !important;\n }\n }\n .next-form-item {\n margin-bottom: 0 !important;\n }\n .preview-text {\n text-align: center !important;\n }\n "],["\n display: flex;\n .text-box-words:nth-child(1) {\n margin-left: 0;\n }\n .text-box-words {\n margin-bottom: 0 !important;\n ","\n }\n .text-box-field {\n display: inline-block;\n .ant-form-item {\n margin-bottom: 0 !important;\n }\n }\n .next-form-item {\n margin-bottom: 0 !important;\n }\n .preview-text {\n text-align: center !important;\n }\n "])),Go?"line-height:32px":"")),en["FormSlot"],Object(en["connect"])({getProps:an["mapStyledProps"],getComponent:an["mapTextComponent"]})(Object(an["acceptEnum"])(Ne["a"])));Wo.TextArea=Object(en["connect"])({getProps:an["mapStyledProps"],getComponent:an["mapTextComponent"]})(Object(an["acceptEnum"])(Ne["a"].TextArea));Object(en["connect"])({getProps:an["mapStyledProps"],getComponent:an["mapTextComponent"]})(an["Select"]);var qo,$o=n("fyUT"),Jo=Object(en["connect"])({getProps:an["mapStyledProps"],getComponent:an["mapTextComponent"]})(Object(an["acceptEnum"])($o["a"])),Qo=function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e},Zo=function(){return Zo=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},Zo.apply(this,arguments)},ec=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"===typeof Object.getOwnPropertySymbols){var a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n},tc=Object(en["connect"])({getProps:an["mapStyledProps"]})(Object(ia["b"])((function(e){var t=e.value,n=e.className,r=e.checkStrength,a=ec(e,["value","className","checkStrength"]);return d.a.createElement("span",{className:n},d.a.createElement(Ne["a"].Password,Zo({},a,{value:t})),r&&d.a.createElement($r["PasswordStrength"],{value:String(t)},(function(e){return d.a.createElement("div",{className:"password-strength-wrapper"},d.a.createElement("div",{className:"div-1 div"}),d.a.createElement("div",{className:"div-2 div"}),d.a.createElement("div",{className:"div-3 div"}),d.a.createElement("div",{className:"div-4 div"}),d.a.createElement("div",{className:"password-strength-bar",style:{clipPath:"polygon(0 0,"+e+"% 0,"+e+"% 100%,0 100%)"}}))})))}))(qo||(qo=Qo(["\n .password-strength-wrapper {\n background: #e0e0e0;\n margin-bottom: 3px;\n position: relative;\n .div {\n position: absolute;\n z-index: 1;\n height: 8px;\n top: 0;\n background: #fff;\n width: 1px;\n transform: translate(-50%, 0);\n }\n .div-1 {\n left: 20%;\n }\n .div-2 {\n left: 40%;\n }\n .div-3 {\n left: 60%;\n }\n .div-4 {\n left: 80%;\n }\n .password-strength-bar {\n position: relative;\n background-image: -webkit-linear-gradient(left, #ff5500, #ff9300);\n transition: all 0.35s ease-in-out;\n height: 8px;\n width: 100%;\n margin-top: 5px;\n }\n }\n"],["\n .password-strength-wrapper {\n background: #e0e0e0;\n margin-bottom: 3px;\n position: relative;\n .div {\n position: absolute;\n z-index: 1;\n height: 8px;\n top: 0;\n background: #fff;\n width: 1px;\n transform: translate(-50%, 0);\n }\n .div-1 {\n left: 20%;\n }\n .div-2 {\n left: 40%;\n }\n .div-3 {\n left: 60%;\n }\n .div-4 {\n left: 80%;\n }\n .password-strength-bar {\n position: relative;\n background-image: -webkit-linear-gradient(left, #ff5500, #ff9300);\n transition: all 0.35s ease-in-out;\n height: 8px;\n width: 100%;\n margin-top: 5px;\n }\n }\n"])))),nc=n("9yH6"),rc=Object(en["connect"])({valueName:"checked",getProps:an["mapStyledProps"]})(nc["default"]);rc.Group=Object(en["connect"])({getProps:an["mapStyledProps"],getComponent:an["mapTextComponent"]})(Object(an["transformDataSourceKey"])(nc["default"].Group,"options"));var ac=n("Kwbf");function oc(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function cc(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?oc(Object(n),!0).forEach((function(t){Object(Me["a"])(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):oc(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var ic=function(e){var t,n,r=e.className,a=e.included,o=e.vertical,c=e.style,i=e.length,l=e.offset,u=e.reverse;i<0&&(u=!u,i=Math.abs(i),l=100-l);var s=o?(t={},Object(Me["a"])(t,u?"top":"bottom","".concat(l,"%")),Object(Me["a"])(t,u?"bottom":"top","auto"),Object(Me["a"])(t,"height","".concat(i,"%")),t):(n={},Object(Me["a"])(n,u?"right":"left","".concat(l,"%")),Object(Me["a"])(n,u?"left":"right","auto"),Object(Me["a"])(n,"width","".concat(i,"%")),n),f=cc(cc({},c),s);return a?d.a.createElement("div",{className:r,style:f}):null},lc=ic;function uc(e,t){while(!Object.prototype.hasOwnProperty.call(e,t))if(e=Object(co["a"])(e),null===e)break;return e}function sc(e,t,n){return sc="undefined"!==typeof Reflect&&Reflect.get?Reflect.get:function(e,t,n){var r=uc(e,t);if(r){var a=Object.getOwnPropertyDescriptor(r,t);return a.get?a.get.call(n):a.value}},sc(e,t,n||e)}var fc=n("zT1h");function pc(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function dc(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?pc(Object(n),!0).forEach((function(t){Object(Me["a"])(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):pc(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var mc=function(e,t,n,r,a,o){Object(ac["a"])(!n||r>0,"`Slider[step]` should be a positive number in order to make Slider[dots] work.");var c=Object.keys(t).map(parseFloat).sort((function(e,t){return e-t}));if(n&&r)for(var i=a;i<=o;i+=r)-1===c.indexOf(i)&&c.push(i);return c},hc=function(e){var t=e.prefixCls,n=e.vertical,r=e.reverse,a=e.marks,o=e.dots,c=e.step,i=e.included,l=e.lowerBound,u=e.upperBound,s=e.max,f=e.min,p=e.dotStyle,m=e.activeDotStyle,h=s-f,v=mc(n,a,o,c,f,s).map((function(e){var a,o="".concat(Math.abs(e-f)/h*100,"%"),c=!i&&e===u||i&&e<=u&&e>=l,s=dc(dc({},p),{},n?Object(Me["a"])({},r?"top":"bottom",o):Object(Me["a"])({},r?"right":"left",o));c&&(s=dc(dc({},s),m));var v=se()((a={},Object(Me["a"])(a,"".concat(t,"-dot"),!0),Object(Me["a"])(a,"".concat(t,"-dot-active"),c),Object(Me["a"])(a,"".concat(t,"-dot-reverse"),r),a));return d.a.createElement("span",{className:v,style:s,key:e})}));return d.a.createElement("div",{className:"".concat(t,"-step")},v)},vc=hc,bc=n("U8pU");function yc(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function gc(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?yc(Object(n),!0).forEach((function(t){Object(Me["a"])(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):yc(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var Oc=function(e){var t=e.className,n=e.vertical,r=e.reverse,a=e.marks,o=e.included,c=e.upperBound,i=e.lowerBound,l=e.max,u=e.min,s=e.onClickLabel,f=Object.keys(a),p=l-u,m=f.map(parseFloat).sort((function(e,t){return e-t})).map((function(e){var l,f=a[e],m="object"===Object(bc["a"])(f)&&!d.a.isValidElement(f),h=m?f.label:f;if(!h&&0!==h)return null;var v=!o&&e===c||o&&e<=c&&e>=i,b=se()((l={},Object(Me["a"])(l,"".concat(t,"-text"),!0),Object(Me["a"])(l,"".concat(t,"-text-active"),v),l)),y=Object(Me["a"])({marginBottom:"-50%"},r?"top":"bottom","".concat((e-u)/p*100,"%")),g=Object(Me["a"])({transform:"translateX(".concat(r?"50%":"-50%",")"),msTransform:"translateX(".concat(r?"50%":"-50%",")")},r?"right":"left","".concat((e-u)/p*100,"%")),O=n?y:g,j=m?gc(gc({},O),f.style):O;return d.a.createElement("span",{className:b,style:j,key:e,onMouseDown:function(t){return s(t,e)},onTouchStart:function(t){return s(t,e)}},h)}));return d.a.createElement("div",{className:t},m)},jc=Oc;function xc(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Ec(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?xc(Object(n),!0).forEach((function(t){Object(Me["a"])(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):xc(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function wc(e){var t=Sc();return function(){var n,r=Object(co["a"])(e);if(t){var a=Object(co["a"])(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return Object(oo["a"])(this,n)}}function Sc(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}var Pc=function(e){Object(E["a"])(n,e);var t=wc(n);function n(){var e;return Object(j["a"])(this,n),e=t.apply(this,arguments),e.state={clickFocused:!1},e.setHandleRef=function(t){e.handle=t},e.handleMouseUp=function(){document.activeElement===e.handle&&e.setClickFocus(!0)},e.handleMouseDown=function(t){t.preventDefault(),e.focus()},e.handleBlur=function(){e.setClickFocus(!1)},e.handleKeyDown=function(){e.setClickFocus(!1)},e}return Object(x["a"])(n,[{key:"componentDidMount",value:function(){this.onMouseUpListener=Object(fc["a"])(document,"mouseup",this.handleMouseUp)}},{key:"componentWillUnmount",value:function(){this.onMouseUpListener&&this.onMouseUpListener.remove()}},{key:"setClickFocus",value:function(e){this.setState({clickFocused:e})}},{key:"clickFocus",value:function(){this.setClickFocus(!0),this.focus()}},{key:"focus",value:function(){this.handle.focus()}},{key:"blur",value:function(){this.handle.blur()}},{key:"render",value:function(){var e,t,n,r=this.props,a=r.prefixCls,o=r.vertical,c=r.reverse,i=r.offset,l=r.style,u=r.disabled,s=r.min,f=r.max,p=r.value,m=r.tabIndex,h=r.ariaLabel,v=r.ariaLabelledBy,b=r.ariaValueTextFormatter,y=Object(O["a"])(r,["prefixCls","vertical","reverse","offset","style","disabled","min","max","value","tabIndex","ariaLabel","ariaLabelledBy","ariaValueTextFormatter"]),g=se()(this.props.className,Object(Me["a"])({},"".concat(a,"-handle-click-focused"),this.state.clickFocused)),j=o?(e={},Object(Me["a"])(e,c?"top":"bottom","".concat(i,"%")),Object(Me["a"])(e,c?"bottom":"top","auto"),Object(Me["a"])(e,"transform",c?null:"translateY(+50%)"),e):(t={},Object(Me["a"])(t,c?"right":"left","".concat(i,"%")),Object(Me["a"])(t,c?"left":"right","auto"),Object(Me["a"])(t,"transform","translateX(".concat(c?"+":"-","50%)")),t),x=Ec(Ec({},l),j),E=m||0;return(u||null===m)&&(E=null),b&&(n=b(p)),d.a.createElement("div",Object.assign({ref:this.setHandleRef,tabIndex:E},y,{className:g,style:x,onBlur:this.handleBlur,onKeyDown:this.handleKeyDown,onMouseDown:this.handleMouseDown,role:"slider","aria-valuemin":s,"aria-valuemax":f,"aria-valuenow":p,"aria-disabled":!!u,"aria-label":h,"aria-labelledby":v,"aria-valuetext":n}))}}]),n}(d.a.Component),Cc=n("i8i4"),kc=n("4IlW");function Rc(e,t){try{return Object.keys(t).some((function(n){return e.target===Object(Cc["findDOMNode"])(t[n])}))}catch(n){return!1}}function Nc(e,t){var n=t.min,r=t.max;return e<n||e>r}function Mc(e){return e.touches.length>1||"touchend"===e.type.toLowerCase()&&e.touches.length>0}function Tc(e,t){var n=t.marks,r=t.step,a=t.min,c=t.max,i=Object.keys(n).map(parseFloat);if(null!==r){var l=Math.floor((c-a)/r),u=Math.min((e-a)/r,l),s=Math.round(u)*r+a;i.push(s)}var f=i.map((function(t){return Math.abs(e-t)}));return i[f.indexOf(Math.min.apply(Math,Object(o["a"])(f)))]}function Ac(e){var t=e.toString(),n=0;return t.indexOf(".")>=0&&(n=t.length-t.indexOf(".")-1),n}function Dc(e,t){return e?t.clientY:t.pageX}function Fc(e,t){return e?t.touches[0].clientY:t.touches[0].pageX}function Ic(e,t){var n=t.getBoundingClientRect();return e?n.top+.5*n.height:window.pageXOffset+n.left+.5*n.width}function Lc(e,t){var n=t.max,r=t.min;return e<=r?r:e>=n?n:e}function _c(e,t){var n=t.step,r=isFinite(Tc(e,t))?Tc(e,t):0;return null===n?r:parseFloat(r.toFixed(Ac(n)))}function Vc(e){e.stopPropagation(),e.preventDefault()}function Bc(e,t,n){var r={increase:function(e,t){return e+t},decrease:function(e,t){return e-t}},a=r[e](Object.keys(n.marks).indexOf(JSON.stringify(t)),1),o=Object.keys(n.marks)[a];return n.step?r[e](t,n.step):Object.keys(n.marks).length&&n.marks[o]?n.marks[o]:t}function Hc(e,t,n){var r="increase",a="decrease",o=r;switch(e.keyCode){case kc["a"].UP:o=t&&n?a:r;break;case kc["a"].RIGHT:o=!t&&n?a:r;break;case kc["a"].DOWN:o=t&&n?r:a;break;case kc["a"].LEFT:o=!t&&n?r:a;break;case kc["a"].END:return function(e,t){return t.max};case kc["a"].HOME:return function(e,t){return t.min};case kc["a"].PAGE_UP:return function(e,t){return e+2*t.step};case kc["a"].PAGE_DOWN:return function(e,t){return e-2*t.step};default:return}return function(e,t){return Bc(o,e,t)}}function zc(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Uc(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?zc(Object(n),!0).forEach((function(t){Object(Me["a"])(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):zc(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function Kc(e){var t=Xc();return function(){var n,r=Object(co["a"])(e);if(t){var a=Object(co["a"])(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return Object(oo["a"])(this,n)}}function Xc(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function Yc(){}function Gc(e){var t;return t=function(e){Object(E["a"])(n,e);var t=Kc(n);function n(e){var r;Object(j["a"])(this,n),r=t.call(this,e),r.onMouseDown=function(e){if(0===e.button){var t=r.props.vertical,n=Dc(t,e);if(Rc(e,r.handlesRefs)){var a=Ic(t,e.target);r.dragOffset=n-a,n=a}else r.dragOffset=0;r.removeDocumentEvents(),r.onStart(n),r.addDocumentMouseEvents()}},r.onTouchStart=function(e){if(!Mc(e)){var t=r.props.vertical,n=Fc(t,e);if(Rc(e,r.handlesRefs)){var a=Ic(t,e.target);r.dragOffset=n-a,n=a}else r.dragOffset=0;r.onStart(n),r.addDocumentTouchEvents(),Vc(e)}},r.onFocus=function(e){var t=r.props,n=t.onFocus,a=t.vertical;if(Rc(e,r.handlesRefs)){var o=Ic(a,e.target);r.dragOffset=0,r.onStart(o),Vc(e),n&&n(e)}},r.onBlur=function(e){var t=r.props.onBlur;r.onEnd(),t&&t(e)},r.onMouseUp=function(){r.handlesRefs[r.prevMovedHandleIndex]&&r.handlesRefs[r.prevMovedHandleIndex].clickFocus()},r.onMouseMove=function(e){if(r.sliderRef){var t=Dc(r.props.vertical,e);r.onMove(e,t-r.dragOffset)}else r.onEnd()},r.onTouchMove=function(e){if(!Mc(e)&&r.sliderRef){var t=Fc(r.props.vertical,e);r.onMove(e,t-r.dragOffset)}else r.onEnd()},r.onKeyDown=function(e){r.sliderRef&&Rc(e,r.handlesRefs)&&r.onKeyboard(e)},r.onClickMarkLabel=function(e,t){e.stopPropagation(),r.onChange({value:t}),r.setState({value:t},(function(){return r.onEnd(!0)}))},r.saveSlider=function(e){r.sliderRef=e};var a=e.step,o=e.max,c=e.min,i=!isFinite(o-c)||(o-c)%a===0;return Object(ac["a"])(!a||Math.floor(a)!==a||i,"Slider[max] - Slider[min] (".concat(o-c,") should be a multiple of Slider[step] (").concat(a,")")),r.handlesRefs={},r}return Object(x["a"])(n,[{key:"componentDidMount",value:function(){this.document=this.sliderRef&&this.sliderRef.ownerDocument;var e=this.props,t=e.autoFocus,n=e.disabled;t&&!n&&this.focus()}},{key:"componentWillUnmount",value:function(){sc(Object(co["a"])(n.prototype),"componentWillUnmount",this)&&sc(Object(co["a"])(n.prototype),"componentWillUnmount",this).call(this),this.removeDocumentEvents()}},{key:"getSliderStart",value:function(){var e=this.sliderRef,t=this.props,n=t.vertical,r=t.reverse,a=e.getBoundingClientRect();return n?r?a.bottom:a.top:window.pageXOffset+(r?a.right:a.left)}},{key:"getSliderLength",value:function(){var e=this.sliderRef;if(!e)return 0;var t=e.getBoundingClientRect();return this.props.vertical?t.height:t.width}},{key:"addDocumentTouchEvents",value:function(){this.onTouchMoveListener=Object(fc["a"])(this.document,"touchmove",this.onTouchMove),this.onTouchUpListener=Object(fc["a"])(this.document,"touchend",this.onEnd)}},{key:"addDocumentMouseEvents",value:function(){this.onMouseMoveListener=Object(fc["a"])(this.document,"mousemove",this.onMouseMove),this.onMouseUpListener=Object(fc["a"])(this.document,"mouseup",this.onEnd)}},{key:"removeDocumentEvents",value:function(){this.onTouchMoveListener&&this.onTouchMoveListener.remove(),this.onTouchUpListener&&this.onTouchUpListener.remove(),this.onMouseMoveListener&&this.onMouseMoveListener.remove(),this.onMouseUpListener&&this.onMouseUpListener.remove()}},{key:"focus",value:function(){this.props.disabled||this.handlesRefs[0].focus()}},{key:"blur",value:function(){var e=this;this.props.disabled||Object.keys(this.handlesRefs).forEach((function(t){e.handlesRefs[t]&&e.handlesRefs[t].blur&&e.handlesRefs[t].blur()}))}},{key:"calcValue",value:function(e){var t=this.props,n=t.vertical,r=t.min,a=t.max,o=Math.abs(Math.max(e,0)/this.getSliderLength()),c=n?(1-o)*(a-r)+r:o*(a-r)+r;return c}},{key:"calcValueByPos",value:function(e){var t=this.props.reverse?-1:1,n=t*(e-this.getSliderStart()),r=this.trimAlignValue(this.calcValue(n));return r}},{key:"calcOffset",value:function(e){var t=this.props,n=t.min,r=t.max,a=(e-n)/(r-n);return Math.max(0,100*a)}},{key:"saveHandle",value:function(e,t){this.handlesRefs[e]=t}},{key:"render",value:function(){var e,t=this.props,r=t.prefixCls,a=t.className,o=t.marks,c=t.dots,i=t.step,l=t.included,u=t.disabled,s=t.vertical,f=t.reverse,p=t.min,m=t.max,h=t.children,v=t.maximumTrackStyle,b=t.style,y=t.railStyle,g=t.dotStyle,O=t.activeDotStyle,j=sc(Object(co["a"])(n.prototype),"render",this).call(this),x=j.tracks,E=j.handles,w=se()(r,(e={},Object(Me["a"])(e,"".concat(r,"-with-marks"),Object.keys(o).length),Object(Me["a"])(e,"".concat(r,"-disabled"),u),Object(Me["a"])(e,"".concat(r,"-vertical"),s),Object(Me["a"])(e,a,a),e));return d.a.createElement("div",{ref:this.saveSlider,className:w,onTouchStart:u?Yc:this.onTouchStart,onMouseDown:u?Yc:this.onMouseDown,onMouseUp:u?Yc:this.onMouseUp,onKeyDown:u?Yc:this.onKeyDown,onFocus:u?Yc:this.onFocus,onBlur:u?Yc:this.onBlur,style:b},d.a.createElement("div",{className:"".concat(r,"-rail"),style:Uc(Uc({},v),y)}),x,d.a.createElement(vc,{prefixCls:r,vertical:s,reverse:f,marks:o,dots:c,step:i,included:l,lowerBound:this.getLowerBound(),upperBound:this.getUpperBound(),max:m,min:p,dotStyle:g,activeDotStyle:O}),E,d.a.createElement(jc,{className:"".concat(r,"-mark"),onClickLabel:u?Yc:this.onClickMarkLabel,vertical:s,marks:o,included:l,lowerBound:this.getLowerBound(),upperBound:this.getUpperBound(),max:m,min:p,reverse:f}),h)}}]),n}(e),t.displayName="ComponentEnhancer(".concat(e.displayName,")"),t.defaultProps=Uc(Uc({},e.defaultProps),{},{prefixCls:"rc-slider",className:"",min:0,max:100,step:1,marks:{},handle:function(e){var t=e.index,n=Object(O["a"])(e,["index"]);return delete n.dragging,null===n.value?null:d.a.createElement(Pc,Object.assign({},n,{key:t}))},onBeforeChange:Yc,onChange:Yc,onAfterChange:Yc,included:!0,disabled:!1,dots:!1,vertical:!1,reverse:!1,trackStyle:[{}],handleStyle:[{}],railStyle:{},dotStyle:{},activeDotStyle:{}}),t}function Wc(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function qc(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Wc(Object(n),!0).forEach((function(t){Object(Me["a"])(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Wc(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function $c(e){var t=Jc();return function(){var n,r=Object(co["a"])(e);if(t){var a=Object(co["a"])(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return Object(oo["a"])(this,n)}}function Jc(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}var Qc=function(e){Object(E["a"])(n,e);var t=$c(n);function n(e){var r;Object(j["a"])(this,n),r=t.call(this,e),r.onEnd=function(e){var t=r.state.dragging;r.removeDocumentEvents(),(t||e)&&r.props.onAfterChange(r.getValue()),r.setState({dragging:!1})};var a=void 0!==e.defaultValue?e.defaultValue:e.min,o=void 0!==e.value?e.value:a;return r.state={value:r.trimAlignValue(o),dragging:!1},Object(ac["a"])(!("minimumTrackStyle"in e),"minimumTrackStyle will be deprecated, please use trackStyle instead."),Object(ac["a"])(!("maximumTrackStyle"in e),"maximumTrackStyle will be deprecated, please use railStyle instead."),r}return Object(x["a"])(n,[{key:"calcValueByPos",value:function(e){return 0}},{key:"calcOffset",value:function(e){return 0}},{key:"saveHandle",value:function(e,t){}},{key:"removeDocumentEvents",value:function(){}},{key:"componentDidUpdate",value:function(e,t){if("value"in this.props||"min"in this.props||"max"in this.props){var n=this.props,r=n.value,a=n.onChange,o=void 0!==r?r:t.value,c=this.trimAlignValue(o,this.props);c!==t.value&&(this.setState({value:c}),Nc(o,this.props)&&a(c))}}},{key:"onChange",value:function(e){var t=this.props,n=!("value"in t),r=e.value>this.props.max?qc(qc({},e),{},{value:this.props.max}):e;n&&this.setState(r);var a=r.value;t.onChange(a)}},{key:"onStart",value:function(e){this.setState({dragging:!0});var t=this.props,n=this.getValue();t.onBeforeChange(n);var r=this.calcValueByPos(e);this.startValue=r,this.startPosition=e,r!==n&&(this.prevMovedHandleIndex=0,this.onChange({value:r}))}},{key:"onMove",value:function(e,t){Vc(e);var n=this.state.value,r=this.calcValueByPos(t);r!==n&&this.onChange({value:r})}},{key:"onKeyboard",value:function(e){var t=this.props,n=t.reverse,r=t.vertical,a=Hc(e,r,n);if(a){Vc(e);var o=this.state,c=o.value,i=a(c,this.props),l=this.trimAlignValue(i);if(l===c)return;this.onChange({value:l}),this.props.onAfterChange(l),this.onEnd()}}},{key:"getValue",value:function(){return this.state.value}},{key:"getLowerBound",value:function(){return this.props.min}},{key:"getUpperBound",value:function(){return this.state.value}},{key:"trimAlignValue",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null===e)return null;var n=qc(qc({},this.props),t),r=Lc(e,n);return _c(r,n)}},{key:"render",value:function(){var e=this,t=this.props,n=t.prefixCls,r=t.vertical,a=t.included,o=t.disabled,c=t.minimumTrackStyle,i=t.trackStyle,l=t.handleStyle,u=t.tabIndex,s=t.ariaLabelForHandle,f=t.ariaLabelledByForHandle,p=t.ariaValueTextFormatterForHandle,m=t.min,h=t.max,v=t.startPoint,b=t.reverse,y=t.handle,g=this.state,O=g.value,j=g.dragging,x=this.calcOffset(O),E=y({className:"".concat(n,"-handle"),prefixCls:n,vertical:r,offset:x,value:O,dragging:j,disabled:o,min:m,max:h,reverse:b,index:0,tabIndex:u,ariaLabel:s,ariaLabelledBy:f,ariaValueTextFormatter:p,style:l[0]||l,ref:function(t){return e.saveHandle(0,t)}}),w=void 0!==v?this.calcOffset(v):0,S=i[0]||i,P=d.a.createElement(lc,{className:"".concat(n,"-track"),vertical:r,included:a,offset:w,reverse:b,length:x-w,style:qc(qc({},c),S)});return{tracks:P,handles:E}}}]),n}(d.a.Component),Zc=Gc(Qc),ei=n("Gytx"),ti=n.n(ei);function ni(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function ri(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ni(Object(n),!0).forEach((function(t){Object(Me["a"])(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ni(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function ai(e){var t=oi();return function(){var n,r=Object(co["a"])(e);if(t){var a=Object(co["a"])(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return Object(oo["a"])(this,n)}}function oi(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}var ci=function(e){var t=e.value,n=e.handle,r=e.bounds,a=e.props,o=a.allowCross,c=a.pushable,i=Number(c),l=Lc(t,a),u=l;return o||null==n||void 0===r||(n>0&&l<=r[n-1]+i&&(u=r[n-1]+i),n<r.length-1&&l>=r[n+1]-i&&(u=r[n+1]-i)),_c(u,a)},ii=function(e){Object(E["a"])(n,e);var t=ai(n);function n(e){var r;Object(j["a"])(this,n),r=t.call(this,e),r.onEnd=function(e){var t=r.state.handle;r.removeDocumentEvents(),(null!==t||e)&&r.props.onAfterChange(r.getValue()),r.setState({handle:null})};var a=e.count,c=e.min,i=e.max,l=Array.apply(void 0,Object(o["a"])(Array(a+1))).map((function(){return c})),u="defaultValue"in e?e.defaultValue:l,s=void 0!==e.value?e.value:u,f=s.map((function(t,n){return ci({value:t,handle:n,props:e})})),p=f[0]===i?0:f.length-1;return r.state={handle:null,recent:p,bounds:f},r}return Object(x["a"])(n,[{key:"calcValueByPos",value:function(e){return 0}},{key:"calcOffset",value:function(e){return 0}},{key:"saveHandle",value:function(e,t){}},{key:"removeDocumentEvents",value:function(){}},{key:"componentDidUpdate",value:function(e,t){var n=this;if(("value"in this.props||"min"in this.props||"max"in this.props)&&(this.props.min!==e.min||this.props.max!==e.max||!ti()(this.props.value,e.value))){var r=this.props,a=r.onChange,o=r.value,c=o||t.bounds;if(c.some((function(e){return Nc(e,n.props)}))){var i=c.map((function(e){return Lc(e,n.props)}));a(i)}}}},{key:"onChange",value:function(e){var t=this.props,n=!("value"in t);if(n)this.setState(e);else{var r={};["handle","recent"].forEach((function(t){void 0!==e[t]&&(r[t]=e[t])})),Object.keys(r).length&&this.setState(r)}var a=ri(ri({},this.state),e),o=a.bounds;t.onChange(o)}},{key:"onStart",value:function(e){var t=this.props,n=this.state,r=this.getValue();t.onBeforeChange(r);var a=this.calcValueByPos(e);this.startValue=a,this.startPosition=e;var c=this.getClosestBound(a);this.prevMovedHandleIndex=this.getBoundNeedMoving(a,c),this.setState({handle:this.prevMovedHandleIndex,recent:this.prevMovedHandleIndex});var i=r[this.prevMovedHandleIndex];if(a!==i){var l=Object(o["a"])(n.bounds);l[this.prevMovedHandleIndex]=a,this.onChange({bounds:l})}}},{key:"onMove",value:function(e,t){Vc(e);var n=this.state,r=this.calcValueByPos(t),a=n.bounds[n.handle];r!==a&&this.moveTo(r)}},{key:"onKeyboard",value:function(e){var t=this.props,n=t.reverse,r=t.vertical,a=Hc(e,r,n);if(a){Vc(e);var o=this.state,c=this.props,i=o.bounds,l=o.handle,u=i[null===l?o.recent:l],s=a(u,c),f=ci({value:s,handle:l,bounds:o.bounds,props:c});if(f===u)return;var p=!0;this.moveTo(f,p)}}},{key:"getValue",value:function(){return this.state.bounds}},{key:"getClosestBound",value:function(e){for(var t=this.state.bounds,n=0,r=1;r<t.length-1;r+=1)e>=t[r]&&(n=r);return Math.abs(t[n+1]-e)<Math.abs(t[n]-e)&&(n+=1),n}},{key:"getBoundNeedMoving",value:function(e,t){var n=this.state,r=n.bounds,a=n.recent,o=t,c=r[t+1]===r[t];return c&&r[a]===r[t]&&(o=a),c&&e!==r[t+1]&&(o=e<r[t+1]?t:t+1),o}},{key:"getLowerBound",value:function(){return this.state.bounds[0]}},{key:"getUpperBound",value:function(){var e=this.state.bounds;return e[e.length-1]}},{key:"getPoints",value:function(){var e=this.props,t=e.marks,n=e.step,r=e.min,a=e.max,o=this.internalPointsCache;if(!o||o.marks!==t||o.step!==n){var c=ri({},t);if(null!==n)for(var i=r;i<=a;i+=n)c[i]=i;var l=Object.keys(c).map(parseFloat);l.sort((function(e,t){return e-t})),this.internalPointsCache={marks:t,step:n,points:l}}return this.internalPointsCache.points}},{key:"moveTo",value:function(e,t){var n=this,r=this.state,a=this.props,c=Object(o["a"])(r.bounds),i=null===r.handle?r.recent:r.handle;c[i]=e;var l=i;!1!==a.pushable?this.pushSurroundingHandles(c,l):a.allowCross&&(c.sort((function(e,t){return e-t})),l=c.indexOf(e)),this.onChange({recent:l,handle:l,bounds:c}),t&&(this.props.onAfterChange(c),this.setState({},(function(){n.handlesRefs[l].focus()})),this.onEnd())}},{key:"pushSurroundingHandles",value:function(e,t){var n=e[t],r=this.props.pushable,a=Number(r),o=0;if(e[t+1]-n<a&&(o=1),n-e[t-1]<a&&(o=-1),0!==o){var c=t+o,i=o*(e[c]-n);this.pushHandle(e,c,o,a-i)||(e[t]=e[c]-o*a)}}},{key:"pushHandle",value:function(e,t,n,r){var a=e[t],o=e[t];while(n*(o-a)<r){if(!this.pushHandleOnePoint(e,t,n))return e[t]=a,!1;o=e[t]}return!0}},{key:"pushHandleOnePoint",value:function(e,t,n){var r=this.getPoints(),a=r.indexOf(e[t]),o=a+n;if(o>=r.length||o<0)return!1;var c=t+n,i=r[o],l=this.props.pushable,u=Number(l),s=n*(e[c]-i);return!!this.pushHandle(e,c,n,u-s)&&(e[t]=i,!0)}},{key:"trimAlignValue",value:function(e){var t=this.state,n=t.handle,r=t.bounds;return ci({value:e,handle:n,bounds:r,props:this.props})}},{key:"render",value:function(){var e=this,t=this.state,n=t.handle,r=t.bounds,a=this.props,o=a.prefixCls,c=a.vertical,i=a.included,l=a.disabled,u=a.min,s=a.max,f=a.reverse,p=a.handle,m=a.trackStyle,h=a.handleStyle,v=a.tabIndex,b=a.ariaLabelGroupForHandles,y=a.ariaLabelledByGroupForHandles,g=a.ariaValueTextFormatterGroupForHandles,O=r.map((function(t){return e.calcOffset(t)})),j="".concat(o,"-handle"),x=r.map((function(t,r){var a,i=v[r]||0;(l||null===v[r])&&(i=null);var d=n===r;return p({className:se()((a={},Object(Me["a"])(a,j,!0),Object(Me["a"])(a,"".concat(j,"-").concat(r+1),!0),Object(Me["a"])(a,"".concat(j,"-dragging"),d),a)),prefixCls:o,vertical:c,dragging:d,offset:O[r],value:t,index:r,tabIndex:i,min:u,max:s,reverse:f,disabled:l,style:h[r],ref:function(t){return e.saveHandle(r,t)},ariaLabel:b[r],ariaLabelledBy:y[r],ariaValueTextFormatter:g[r]})})),E=r.slice(0,-1).map((function(e,t){var n,r=t+1,a=se()((n={},Object(Me["a"])(n,"".concat(o,"-track"),!0),Object(Me["a"])(n,"".concat(o,"-track-").concat(r),!0),n));return d.a.createElement(lc,{className:a,vertical:c,reverse:f,included:i,offset:O[r-1],length:O[r]-O[r-1],style:m[t],key:r})}));return{tracks:E,handles:x}}}],[{key:"getDerivedStateFromProps",value:function(e,t){if("value"in e||"min"in e||"max"in e){var n=e.value||t.bounds,r=n.map((function(n,r){return ci({value:n,handle:r,bounds:t.bounds,props:e})}));return r.length===t.bounds.length&&r.every((function(e,n){return e===t.bounds[n]}))?null:ri(ri({},t),{},{bounds:r})}return null}}]),n}(d.a.Component);ii.displayName="Range",ii.defaultProps={count:1,allowCross:!0,pushable:!1,tabIndex:[],ariaLabelGroupForHandles:[],ariaLabelledByGroupForHandles:[],ariaValueTextFormatterGroupForHandles:[]};var li=Gc(ii);function ui(){return ui=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},ui.apply(this,arguments)}function si(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=p["useRef"]();return p["useEffect"]((function(){t.forEach((function(e){e&&("function"===typeof e?e(r.current):e.current=r.current)}))}),[t]),r}var fi=p["forwardRef"]((function(e,t){var n=e.visible,r=p["useRef"](null),a=si(t,r),o=p["useRef"](null);function c(){window.cancelAnimationFrame(o.current),o.current=null}function i(){null===o.current&&(o.current=window.requestAnimationFrame((function(){a.current.forcePopupAlign(),o.current=null,i()})))}return p["useEffect"]((function(){return n?i():c(),c}),[n]),p["createElement"](K["a"],ui({ref:a},e))})),pi=fi;function di(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function mi(){return mi=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},mi.apply(this,arguments)}function hi(e,t){return Oi(e)||gi(e,t)||bi(e,t)||vi()}function vi(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function bi(e,t){if(e){if("string"===typeof e)return yi(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?yi(e,t):void 0}}function yi(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function gi(e,t){if("undefined"!==typeof Symbol&&Symbol.iterator in Object(e)){var n=[],r=!0,a=!1,o=void 0;try{for(var c,i=e[Symbol.iterator]();!(r=(c=i.next()).done);r=!0)if(n.push(c.value),t&&n.length===t)break}catch(l){a=!0,o=l}finally{try{r||null==i["return"]||i["return"]()}finally{if(a)throw o}}return n}}function Oi(e){if(Array.isArray(e))return e}var ji=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"===typeof Object.getOwnPropertySymbols){var a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n},xi=p["forwardRef"]((function(e,t){var n=p["useContext"](de["b"]),r=n.getPrefixCls,a=n.direction,o=n.getPopupContainer,c=p["useState"]({}),i=hi(c,2),l=i[0],u=i[1],s=function(e,t){var n=mi({},l);n[e]=t,u(n)},f=function(t){var n=t.tooltipPrefixCls,r=t.prefixCls,a=t.info,c=a.value,i=a.dragging,u=a.index,f=ji(a,["value","dragging","index"]),d=e.tipFormatter,m=e.tooltipVisible,h=e.tooltipPlacement,v=e.getTooltipPopupContainer,b=e.vertical,y=!!d&&(l[u]||i),g=m||void 0===m&&y;return p["createElement"](pi,{prefixCls:n,title:d?d(c):"",visible:g,placement:h||(b?"right":"top"),transitionName:"zoom-down",key:u,overlayClassName:"".concat(r,"-tooltip"),getPopupContainer:v||o||function(){return document.body}},p["createElement"](Pc,mi({},f,{value:c,onMouseEnter:function(){return s(u,!0)},onMouseLeave:function(){return s(u,!1)}})))},d=e.prefixCls,m=e.tooltipPrefixCls,h=e.range,v=e.className,b=ji(e,["prefixCls","tooltipPrefixCls","range","className"]),y=r("slider",d),g=r("tooltip",m),O=se()(v,di({},"".concat(y,"-rtl"),"rtl"===a));return"rtl"!==a||b.vertical||(b.reverse=!b.reverse),h?p["createElement"](li,mi({},b,{className:O,ref:t,handle:function(e){return f({tooltipPrefixCls:g,prefixCls:y,info:e})},prefixCls:y,tooltipPrefixCls:g})):p["createElement"](Zc,mi({},b,{className:O,ref:t,handle:function(e){return f({tooltipPrefixCls:g,prefixCls:y,info:e})},prefixCls:y,tooltipPrefixCls:g}))}));xi.displayName="Slider",xi.defaultProps={tipFormatter:function(e){return"number"===typeof e?e.toString():""}};var Ei=xi,wi=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Si=function(){return Si=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},Si.apply(this,arguments)},Pi=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"===typeof Object.getOwnPropertySymbols){var a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n},Ci=Object(en["connect"])({defaultProps:{style:{width:320}},getProps:an["mapStyledProps"]})(function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return wi(t,e),t.prototype.render=function(){var e=this.props,t=e.onChange,n=e.value,r=e.min,a=e.max,o=e.marks,c=Pi(e,["onChange","value","min","max","marks"]),i={};return Array.isArray(o)?o.forEach((function(e){i[e]=e})):i=o,d.a.createElement(Ei,Si({},c,{onChange:t,value:n,min:r,max:a,marks:i}))},t}(d.a.Component)),ki=n("m+aA");function Ri(e){var t=e.pageXOffset,n="scrollLeft";if("number"!==typeof t){var r=e.document;t=r.documentElement[n],"number"!==typeof t&&(t=r.body[n])}return t}function Ni(e){var t,n,r=e.ownerDocument,a=r.body,o=r&&r.documentElement,c=e.getBoundingClientRect();return t=c.left,n=c.top,t-=o.clientLeft||a.clientLeft||0,n-=o.clientTop||a.clientTop||0,{left:t,top:n}}function Mi(e){var t=Ni(e),n=e.ownerDocument,r=n.defaultView||n.parentWindow;return t.left+=Ri(r),t.left}function Ti(e){var t=Ai();return function(){var n,r=Object(co["a"])(e);if(t){var a=Object(co["a"])(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return Object(oo["a"])(this,n)}}function Ai(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}var Di=function(e){Object(E["a"])(n,e);var t=Ti(n);function n(){var e;return Object(j["a"])(this,n),e=t.apply(this,arguments),e.onHover=function(t){var n=e.props,r=n.onHover,a=n.index;r(t,a)},e.onClick=function(t){var n=e.props,r=n.onClick,a=n.index;r(t,a)},e.onKeyDown=function(t){var n=e.props,r=n.onClick,a=n.index;13===t.keyCode&&r(t,a)},e}return Object(x["a"])(n,[{key:"getClassName",value:function(){var e=this.props,t=e.prefixCls,n=e.index,r=e.value,a=e.allowHalf,o=e.focused,c=n+1,i=t;return 0===r&&0===n&&o?i+=" ".concat(t,"-focused"):a&&r+.5>=c&&r<c?(i+=" ".concat(t,"-half ").concat(t,"-active"),o&&(i+=" ".concat(t,"-focused"))):(i+=" ".concat(t,c<=r?"-full":"-zero"),c===r&&o&&(i+=" ".concat(t,"-focused"))),i}},{key:"render",value:function(){var e=this.onHover,t=this.onClick,n=this.onKeyDown,r=this.props,a=r.disabled,o=r.prefixCls,c=r.character,i=r.characterRender,l=r.index,u=r.count,s=r.value,f="function"===typeof c?c(this.props):c,p=d.a.createElement("li",{className:this.getClassName()},d.a.createElement("div",{onClick:a?null:t,onKeyDown:a?null:n,onMouseMove:a?null:e,role:"radio","aria-checked":s>l?"true":"false","aria-posinset":l+1,"aria-setsize":u,tabIndex:a?-1:0},d.a.createElement("div",{className:"".concat(o,"-first")},f),d.a.createElement("div",{className:"".concat(o,"-second")},f)));return i&&(p=i(p,this.props)),p}}]),n}(d.a.Component);function Fi(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Ii(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Fi(Object(n),!0).forEach((function(t){Object(Me["a"])(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Fi(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function Li(e){var t=_i();return function(){var n,r=Object(co["a"])(e);if(t){var a=Object(co["a"])(this).constructor;n=Reflect.construct(r,arguments,a)}else n=r.apply(this,arguments);return Object(oo["a"])(this,n)}}function _i(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function Vi(){}var Bi=function(e){Object(E["a"])(n,e);var t=Li(n);function n(e){var r;Object(j["a"])(this,n),r=t.call(this,e),r.onHover=function(e,t){var n=r.props.onHoverChange,a=r.getStarValue(t,e.pageX),o=r.state.cleanedValue;a!==o&&r.setState({hoverValue:a,cleanedValue:null}),n(a)},r.onMouseLeave=function(){var e=r.props.onHoverChange;r.setState({hoverValue:void 0,cleanedValue:null}),e(void 0)},r.onClick=function(e,t){var n=r.props.allowClear,a=r.state.value,o=r.getStarValue(t,e.pageX),c=!1;n&&(c=o===a),r.onMouseLeave(),r.changeValue(c?0:o),r.setState({cleanedValue:c?o:null})},r.onFocus=function(){var e=r.props.onFocus;r.setState({focused:!0}),e&&e()},r.onBlur=function(){var e=r.props.onBlur;r.setState({focused:!1}),e&&e()},r.onKeyDown=function(e){var t=e.keyCode,n=r.props,a=n.count,o=n.allowHalf,c=n.onKeyDown,i=n.direction,l="rtl"===i,u=r.state.value;t===kc["a"].RIGHT&&u<a&&!l?(u+=o?.5:1,r.changeValue(u),e.preventDefault()):t===kc["a"].LEFT&&u>0&&!l||t===kc["a"].RIGHT&&u>0&&l?(u-=o?.5:1,r.changeValue(u),e.preventDefault()):t===kc["a"].LEFT&&u<a&&l&&(u+=o?.5:1,r.changeValue(u),e.preventDefault()),c&&c(e)},r.saveRef=function(e){return function(t){r.stars[e]=t}},r.saveRate=function(e){r.rate=e};var a=e.value;return void 0===a&&(a=e.defaultValue),r.stars={},r.state={value:a,focused:!1,cleanedValue:null},r}return Object(x["a"])(n,[{key:"componentDidMount",value:function(){var e=this.props,t=e.autoFocus,n=e.disabled;t&&!n&&this.focus()}},{key:"getStarDOM",value:function(e){return Object(ki["a"])(this.stars[e])}},{key:"getStarValue",value:function(e,t){var n=this.props,r=n.allowHalf,a=n.direction,o="rtl"===a,c=e+1;if(r){var i=this.getStarDOM(e),l=Mi(i),u=i.clientWidth;(o&&t-l>u/2||!o&&t-l<u/2)&&(c-=.5)}return c}},{key:"focus",value:function(){var e=this.props.disabled;e||this.rate.focus()}},{key:"blur",value:function(){var e=this.props.disabled;e||this.rate.blur()}},{key:"changeValue",value:function(e){var t=this.props.onChange;"value"in this.props||this.setState({value:e}),t(e)}},{key:"render",value:function(){for(var e=this.props,t=e.count,n=e.allowHalf,r=e.style,a=e.prefixCls,o=e.disabled,c=e.className,i=e.character,l=e.characterRender,u=e.tabIndex,s=e.direction,f=this.state,p=f.value,m=f.hoverValue,h=f.focused,v=[],b=o?"".concat(a,"-disabled"):"",y=0;y<t;y+=1)v.push(d.a.createElement(Di,{ref:this.saveRef(y),index:y,count:t,disabled:o,prefixCls:"".concat(a,"-star"),allowHalf:n,value:void 0===m?p:m,onClick:this.onClick,onHover:this.onHover,key:y,character:i,characterRender:l,focused:h}));var g=se()(a,b,c,Object(Me["a"])({},"".concat(a,"-rtl"),"rtl"===s));return d.a.createElement("ul",{className:g,style:r,onMouseLeave:o?null:this.onMouseLeave,tabIndex:o?-1:u,onFocus:o?null:this.onFocus,onBlur:o?null:this.onBlur,onKeyDown:o?null:this.onKeyDown,ref:this.saveRate,role:"radiogroup"},v)}}],[{key:"getDerivedStateFromProps",value:function(e,t){return"value"in e&&void 0!==e.value?Ii(Ii({},t),{},{value:e.value}):t}}]),n}(d.a.Component);Bi.defaultProps={defaultValue:0,count:5,allowHalf:!1,allowClear:!0,style:{},prefixCls:"rc-rate",onChange:Vi,character:"\u2605",onHoverChange:Vi,tabIndex:0,direction:"ltr"};var Hi=Bi,zi=Hi,Ui=n("Lerx"),Ki=n.n(Ui);function Xi(){return Xi=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Xi.apply(this,arguments)}var Yi=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"===typeof Object.getOwnPropertySymbols){var a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n},Gi=p["forwardRef"]((function(e,t){var n=e.prefixCls,r=e.tooltips,a=Yi(e,["prefixCls","tooltips"]),o=function(e,t){var n=t.index;return r?p["createElement"](K["a"],{title:r[n]},e):e},c=p["useContext"](de["b"]),i=c.getPrefixCls,l=c.direction,u=i("rate",n);return p["createElement"](zi,Xi({ref:t,characterRender:o},a,{prefixCls:u,direction:l}))}));Gi.displayName="Rate",Gi.defaultProps={character:p["createElement"](Ki.a,null)};var Wi=Gi,qi=Object(en["connect"])({getProps:an["mapStyledProps"]})(Wi),$i=n("8z0m"),Ji={icon:{tag:"svg",attrs:{viewBox:"0 0 1024 1024",focusable:"false"},children:[{tag:"path",attrs:{d:"M988 548c-19.9 0-36-16.1-36-36 0-59.4-11.6-117-34.6-171.3a440.45 440.45 0 00-94.3-139.9 437.71 437.71 0 00-139.9-94.3C629 83.6 571.4 72 512 72c-19.9 0-36-16.1-36-36s16.1-36 36-36c69.1 0 136.2 13.5 199.3 40.3C772.3 66 827 103 874 150c47 47 83.9 101.8 109.7 162.7 26.7 63.1 40.2 130.2 40.2 199.3.1 19.9-16 36-35.9 36z"}}]},name:"loading",theme:"outlined"},Qi=Ji,Zi=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:Qi}))};Zi.displayName="LoadingOutlined";var el=p["forwardRef"](Zi),tl={icon:{tag:"svg",attrs:{viewBox:"0 0 1024 1024",focusable:"false"},children:[{tag:"path",attrs:{d:"M885.2 446.3l-.2-.8-112.2-285.1c-5-16.1-19.9-27.2-36.8-27.2H281.2c-17 0-32.1 11.3-36.9 27.6L139.4 443l-.3.7-.2.8c-1.3 4.9-1.7 9.9-1 14.8-.1 1.6-.2 3.2-.2 4.8V830a60.9 60.9 0 0060.8 60.8h627.2c33.5 0 60.8-27.3 60.9-60.8V464.1c0-1.3 0-2.6-.1-3.7.4-4.9 0-9.6-1.3-14.1zm-295.8-43l-.3 15.7c-.8 44.9-31.8 75.1-77.1 75.1-22.1 0-41.1-7.1-54.8-20.6S436 441.2 435.6 419l-.3-15.7H229.5L309 210h399.2l81.7 193.3H589.4zm-375 76.8h157.3c24.3 57.1 76 90.8 140.4 90.8 33.7 0 65-9.4 90.3-27.2 22.2-15.6 39.5-37.4 50.7-63.6h156.5V814H214.4V480.1z"}}]},name:"inbox",theme:"outlined"},nl=tl,rl=function(e,t){return p["createElement"](G["a"],Object.assign({},e,{ref:t,icon:nl}))};rl.displayName="InboxOutlined";var al,ol,cl=p["forwardRef"](rl),il=n("z7Xi"),ll=function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e},ul=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),sl=function(){return sl=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},sl.apply(this,arguments)},fl=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"===typeof Object.getOwnPropertySymbols){var a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n},pl=function(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;var r=Array(e),a=0;for(t=0;t<n;t++)for(var o=arguments[t],c=0,i=o.length;c<i;c++,a++)r[a]=o[c];return r},dl=$i["a"].Dragger,ml=[{ext:/\.docx?/i,icon:"//img.alicdn.com/tfs/TB1n8jfr1uSBuNjy1XcXXcYjFXa-200-200.png"},{ext:/\.pptx?/i,icon:"//img.alicdn.com/tfs/TB1ItgWr_tYBeNjy1XdXXXXyVXa-200-200.png"},{ext:/\.jpe?g/i,icon:"//img.alicdn.com/tfs/TB1wrT5r9BYBeNjy0FeXXbnmFXa-200-200.png"},{ext:/pdf/i,icon:"//img.alicdn.com/tfs/TB1GwD8r9BYBeNjy0FeXXbnmFXa-200-200.png"},{ext:/\.png/i,icon:"//img.alicdn.com/tfs/TB1BHT5r9BYBeNjy0FeXXbnmFXa-200-200.png"},{ext:/\.eps/i,icon:"//img.alicdn.com/tfs/TB1G_iGrVOWBuNjy0FiXXXFxVXa-200-200.png"},{ext:/\.ai/i,icon:"//img.alicdn.com/tfs/TB1B2cVr_tYBeNjy1XdXXXXyVXa-200-200.png"},{ext:/\.gif/i,icon:"//img.alicdn.com/tfs/TB1DTiGrVOWBuNjy0FiXXXFxVXa-200-200.png"},{ext:/\.svg/i,icon:"//img.alicdn.com/tfs/TB1uUm9rY9YBuNjy0FgXXcxcXXa-200-200.png"},{ext:/\.xlsx?/i,icon:"//img.alicdn.com/tfs/TB1any1r1OSBuNjy0FdXXbDnVXa-200-200.png"},{ext:/\.psd?/i,icon:"//img.alicdn.com/tfs/TB1_nu1r1OSBuNjy0FdXXbDnVXa-200-200.png"},{ext:/\.(wav|aif|aiff|au|mp1|mp2|mp3|ra|rm|ram|mid|rmi)/i,icon:"//img.alicdn.com/tfs/TB1jPvwr49YBuNjy0FfXXXIsVXa-200-200.png"},{ext:/\.(avi|wmv|mpg|mpeg|vob|dat|3gp|mp4|mkv|rm|rmvb|mov|flv)/i,icon:"//img.alicdn.com/tfs/TB1FrT5r9BYBeNjy0FeXXbnmFXa-200-200.png"},{ext:/\.(zip|rar|arj|z|gz|iso|jar|ace|tar|uue|dmg|pkg|lzh|cab)/i,icon:"//img.alicdn.com/tfs/TB10jmfr29TBuNjy0FcXXbeiFXa-200-200.png"},{ext:/\..+/i,icon:"//img.alicdn.com/tfs/TB10.R4r3mTBuNjy1XbXXaMrVXa-200-200.png"}],hl=Object(ia["b"])((function(e){return d.a.createElement("div",null,e.loading?d.a.createElement(el,null):d.a.createElement(ea["a"],null),d.a.createElement("div",{className:"ant-upload-text"},"\u4e0a\u4f20"))}))(ol||(ol=ll([""],[""]))),vl=function(e,t){return t&&Object(an["isArr"])(t.include)?t.include.some((function(t){return e.test(t)})):!t||!Object(an["isArr"])(t.exclude)||!t.exclude.some((function(t){return e.test(t)}))},bl=function(e,t){for(var n=0;n<ml.length;n++)if(ml[n].ext.test(e)&&vl(ml[n].ext,t))return ml[n].icon||e;return e},yl=function(e){return e&&e.length?e.map((function(e){return sl(sl({uid:e.uid,status:e.status,name:e.name,url:e.downloadURL||e.imgURL||e.url},e.response),{thumbUrl:bl(e.imgURL||e.downloadURL||e.url,{exclude:[".png",".jpg",".jpeg",".gif"]})})})):[]},gl=function(e){var t=Object(an["isArr"])(e)?pl(e):"object"===typeof e?sl({},e):e;return Object(an["isArr"])(t)&&(t=t.map((function(e){return sl(sl({},e),{uid:e.uid||Math.random().toFixed(16).slice(2,10)})}))),t},Ol=Object(en["connect"])({getProps:an["mapStyledProps"]})((al=function(e){function t(t){var n=e.call(this,t)||this;return n.onRemoveHandler=function(e){var t=n.state.value,r=[];t.forEach((function(t){t.uid!==e.uid&&r.push(t)})),n.props.onChange(r)},n.onChangeHandler=function(e){var t=e.fileList,r=n.props.onChange;t=Object(an["toArr"])(t),t.every((function(e){return!!("done"===e.status||e.imgURL||e.downloadURL||e.url||e.thumbUrl)||!(!e.response||!(e.response.imgURL||e.response.downloadURL||e.response.url||e.response.thumbUrl))}))&&t.length?(t=yl(t),n.setState({value:t},(function(){r(t.length>0?t:void 0)}))):n.setState({value:t})},n.state={value:gl(Object(an["toArr"])(t.value))},n}return ul(t,e),t.prototype.componentDidUpdate=function(e){this.props.value&&!Object(an["isEqual"])(this.props.value,e.value)&&this.setState({value:gl(this.props.value)})},t.prototype.render=function(){var e=this.props,t=e.listType,n=e.locale,r=(e.onChange,e.value,fl(e,["listType","locale","onChange","value"]));return t.indexOf("card")>-1?d.a.createElement($i["a"],sl({},r,{fileList:this.state.value,onChange:this.onChangeHandler,onRemove:this.onRemoveHandler,listType:"picture-card"}),d.a.createElement(hl,null)):t.indexOf("dragger")>-1?d.a.createElement(dl,sl({},r,{fileList:this.state.value,onChange:this.onChangeHandler,onRemove:this.onRemoveHandler,listType:t.indexOf("image")>-1?"picture":"text"}),d.a.createElement("p",{className:"ant-upload-drag-icon"},d.a.createElement(cl,null)),d.a.createElement("p",{className:"ant-upload-text"},"\u62d6\u62fd\u4e0a\u4f20")):d.a.createElement($i["a"],sl({},r,{fileList:this.state.value,onChange:this.onChangeHandler,onRemove:this.onRemoveHandler,listType:t}),d.a.createElement(s["a"],{style:{margin:"0 0 10px"}},d.a.createElement(il["a"],null),n&&n.uploadText||"\u4e0a\u4f20\u6587\u4ef6"))},t}(d.a.Component),al.defaultProps={action:"https://www.easy-mock.com/mock/5b713974309d0d7d107a74a3/alifd/upload",listType:"text",multiple:!0,className:"antd-uploader"},al)),jl=function(){Object(va["registerFormFields"])({time:ln,timerange:ln.RangePicker,transfer:Yr,boolean:Wr,array:pa,cards:pa,table:xa,checkbox:Sa.Group,date:Ta,daterange:Ta.RangePicker,year:Ta.YearPicker,month:Ta.MonthPicker,week:Ta.WeekPicker,string:Wo,textarea:Wo.TextArea,number:Jo,password:tc,radio:rc.Group,range:Ci,rating:qi,upload:Ol})},xl=n("ShgS");jl();var El=!1,wl=n("ujla"),Sl=[];wl.routes&&(Sl=wl.routes.filter((function(e){return"/"===e.path}))[0].routes[0].routes.filter((function(e){return void 0!==e.path})));var Pl,Cl,kl,Rl=d.a.createElement(u["a"],{status:403,title:"403",subTitle:"\u5bf9\u4e0d\u8d77\uff0c\u60a8\u65e0\u6743\u8bbf\u95ee\u6b64\u9875\u9762",extra:d.a.createElement(s["a"],{type:"primary"},d.a.createElement(m["a"],{to:"/"},"\u53bb\u4e3b\u9875"))}),Nl=d.a.createElement(f["a"],{copyright:xl["a"].copyright,links:[]}),Ml=function(){return d.a.createElement(d.a.Fragment,null,Nl)},Tl=function(e){var t=e.dispatch,n=e.children,r=e.settings,u=e.hasSysMenu,s=e.menus,v=e.authFuncs,b=e.defMenuTxt,y=e.collapsed,g=e.location,O=Object(h["i"])(),j=Object(p["useState"])(!1),x=Object(l["a"])(j,2),E=x[0],w=x[1],S=Object(p["useState"])(void 0),P=Object(l["a"])(S,2),C=P[0],k=P[1],R=Object(p["useState"])([]),N=Object(l["a"])(R,2),M=N[0],T=N[1];Object(p["useEffect"])((function(){t&&(t({type:"account/fetchCurrent"}),t({type:"account/fetchMenu",callback:function(e){"/"===g.pathname&&h["e"].push(e.menus[0].path)}}))}),[]);var A=function(e,t){var n={id:e};n.defaultMessage||(n.defaultMessage=t);var r=n.defaultMessage&&b[n.defaultMessage];return r&&(n.defaultMessage=r),!1===El?n.defaultMessage:O.formatMessage(n)},D=function(e){t&&t({type:"global/changeLayoutCollapsed",payload:e})};h["e"].listen((function(e){var t=e.pathname;"/account/login"===t&&(kl="/account/login",Pl=void 0,Cl=void 0)}));var F=function(){w(!1),setTimeout((function(){w(!0),kl=h["e"].location.pathname;var e=Sl.findIndex((function(e){return kl&&Jt(e.path).exec(kl)}));if(e>-1){var t=Sl[e],n=t.title,r=t.name,a=n||b[r];document.title=a&&""!==a?"".concat(a,"-").concat(xl["a"].title):xl["a"].title}else document.title=xl["a"].title}),10)},I=function(e){if(0!==v.length)if(kl&&h["e"].location.pathname===kl)!1===E&&F();else{var n=v.findIndex((function(e){return h["e"].location.pathname===e.url}));if(!e||0===e.length){var r;if(-1===n){var a=Sl.findIndex((function(e){return e.path===h["e"].location.pathname}));a>-1&&!1!==Sl[a].authority&&(r="none")}return k(r),void F()}var o=s,c=[],i="";e.forEach((function(e){if("/"===e)c.push({path:"/#".concat(s[0].path),name:A("menu.".concat(s[0].key),"home")});else{i+=".".concat(e);var t=o.findIndex((function(t){return t.key===e}));t>-1&&(c.push({name:A("menu.".concat(i,".").concat(o[t].key),o[t].key)}),o=o[t].children)}})),T(c),Cl=e[e.length-1],n>-1&&(g.state||(g.state={}),v[n].id&&(g.state.funcId=v[n].id)),g.state&&Pl&&Pl===g.state.funcId?!1!==E&&h["e"].location.pathname===kl||(k(void 0),F()):(g.state&&g.state.funcId&&(Pl=g.state.funcId,t({type:"schema/querySchema",payload:Pl})),k(void 0),F())}},L=function(){var e=[],t=-1,n=g.pathname?g.pathname.split("/").filter((function(e){return""!==e})):[];n.length>0&&(e=[n[0]],s.length>0&&(t=s.findIndex((function(e){return e.name===n[0]}))));var r=function(){return u?-1===t?[]:s[t]&&s[t].children||[]:s},a=[],l=function(){return d.a.createElement("div",{className:"ant-pro-global-header"},d.a.createElement("span",{onClick:function(){D(!y)},className:"ant-pro-global-header-trigger"},y?d.a.createElement(Ke["a"],null):d.a.createElement(Xe["a"],null)),u&&d.a.createElement(i["a"],{mode:"horizontal",selectedKeys:e,style:{border:"none"}},a.map((function(e){return d.a.createElement(i["a"].Item,{key:e.name},d.a.createElement(m["a"],{to:{pathname:e.path||"/"}},e.icon,e.name&&b[e.name]))}))),!u&&d.a.createElement(c["a"],null,M.map((function(e){return d.a.createElement(c["a"].Item,null,e.path?d.a.createElement("a",{href:e.path},e.name):e.name)}))),d.a.createElement(Ue,null))},f=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return[{path:"/".concat(s[t]?s[t].path||"/":""),breadcrumbName:El?O.formatMessage({id:"menu.".concat(e[0]||"home"),defaultMessage:e[0]||"Home"}):b[e[0]||"Home"]}].concat(Object(o["a"])(n))};u&&(a=s.map((function(e){return{icon:e.icon,name:e.name,defTxt:e.defTxt,path:e.path,funcId:e.funcId}})));var p=function(e){var t=e.defaultMessage&&b[e.defaultMessage];return t&&(e.defaultMessage=t),!1===El?e.defaultMessage:O.formatMessage(e)};return{breadcrumbRender:u?f:void 0,headerRender:l,menuDataRender:r,formatMessage:p}},_=L();return d.a.createElement(f["e"],Object(a["a"])({logo:zt.a,menuHeaderRender:function(e,t){return s.length>0&&d.a.createElement(m["a"],{to:s[0]&&s[0].path||"/"},e,t)},onOpenChange:I,onCollapse:D,menuProps:{onClick:function(e){e.key!==Cl&&w(!1)}},menuItemRender:function(e,t){return e.isUrl||e.children||!e.path?t:d.a.createElement(m["a"],{to:{pathname:e.path}},t)},itemRender:function(e,t,n,r){var a=0===n.indexOf(e);return a?d.a.createElement(m["a"],{to:r.join("/")},e.breadcrumbName):d.a.createElement("span",null,e.breadcrumbName)},footerRender:Ml,rightContentRender:function(){return d.a.createElement(Ue,null)}},e,r,_),E&&d.a.createElement(U,{authority:C,noMatch:Rl},n))},Al=function e(t){return t.map((function(t){var n=Object(r["a"])({},t);return t.icon&&(n.icon=Bt(t.icon)),t.children&&(n.children=e(t.children)),n}))};t["default"]=Object(h["b"])((function(e){var t=e.global,n=e.account,r=e.settings;return{collapsed:t.collapsed,hasSysMenu:n.hasSysMenu,menus:Al(n.menus),authFuncs:n.authFuncs,defMenuTxt:n.defMenuTxt,settings:r}}))(Tl)},j5Qg:function(e,t,n){e.exports={headerSearch:"antd-pro-components-header-search-index-headerSearch",input:"antd-pro-components-header-search-index-input",show:"antd-pro-components-header-search-index-show"}},vuNf:function(e,t,n){"use strict";n.d(t,"compose",(function(){return m})),n.d(t,"Select",(function(){return v})),n.d(t,"acceptEnum",(function(){return b})),n.d(t,"transformDataSourceKey",(function(){return y})),n.d(t,"createMatchUpdate",(function(){return g}));var r=n("q1tI"),a=n.n(r),o=n("FVvW");n.d(t,"mapTextComponent",(function(){return o["mapTextComponent"]})),n.d(t,"mapStyledProps",(function(){return o["mapStyledProps"]})),n.d(t,"normalizeCol",(function(){return o["normalizeCol"]}));var c=n("2fM7"),i=n("vOnD"),l=n("OAhR");n.o(l,"isArr")&&n.d(t,"isArr",(function(){return l["isArr"]})),n.o(l,"isEqual")&&n.d(t,"isEqual",(function(){return l["isEqual"]})),n.o(l,"isStr")&&n.d(t,"isStr",(function(){return l["isStr"]})),n.o(l,"toArr")&&n.d(t,"toArr",(function(){return l["toArr"]}));var u,s=function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e},f=function(){return f=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},f.apply(this,arguments)},p=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"===typeof Object.getOwnPropertySymbols){var a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n},d=function(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;var r=Array(e),a=0;for(t=0;t<n;t++)for(var o=arguments[t],c=0,i=o.length;c<i;c++,a++)r[a]=o[c];return r},m=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return function(t){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];return e.reduce((function(e,r){return void 0!==e?r.apply(void 0,d([e],n)):r.apply(void 0,d([t],n))}),t)}},h=function(e){return Object(l["isArr"])(e)?e.map((function(e){return"object"===typeof e?f({},e):{label:e,value:e}})):[]},v=Object(i["b"])((function(e){var t=e.dataSource,n=void 0===t?[]:t,r=e.onChange,o=p(e,["dataSource","onChange"]),i=h(n).map((function(e){var t=e.label,n=e.value,r=p(e,["label","value"]);return a.a.createElement(c["a"].Option,f({key:n},r,{title:t,value:n}),t)}));return a.a.createElement(c["a"],f({className:e.className},o,{onChange:function(e,t){r(e,Object(l["isArr"])(t)?t.map((function(e){return f(f({},e),{props:void 0})})):f(f({},t),{props:void 0}))}}),i)}))(u||(u=s(["\n min-width: 100px;\n width: 100%;\n"],["\n min-width: 100px;\n width: 100%;\n"]))),b=function(e){return function(t){var n=t.dataSource,r=p(t,["dataSource"]);return n?a.a.createElement(v,f({dataSource:n},r)):a.a.createElement(e,r)}},y=function(e,t){return function(n){var r,o=n.dataSource,c=p(n,["dataSource"]);return a.a.createElement(e,f((r={},r[t]=o,r),c))}},g=function(e,t){return function(n,r,a){n||r?n?l["FormPath"].parse(n).matchAliasGroup(e,t)&&a():r&&l["FormPath"].parse(r).matchAliasGroup(e,t)&&a():a()}}}}]); |
var express = require('express');
var mysql = require('mysql');
var app = express();
var readline = require('readline-sync');
app.use(express.static("../"));
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var request = require('request');
var requestHandler = require('./requestHandler');
var rH = new requestHandler.RequestHandler();
var user = readline.question("What is the username?");
var pass = readline.question("What is the password?");
var con = mysql.createConnection({
host: "localhost",
user: user,
password: pass,
database: "birdwatch"
})
//Helper function
function first(p) {
for (var i in p)
return p[i];
}
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
});
app.get('/', function (req, res) {
console.log('user accessed home, redirecting to login');
res.redirect('../front/login.html');
});
app.get('/search', function (req, res) {//When the user enters a bird in the search bar
console.log('user accessed search, redirecting...');
//res.redirect('../front/search.html');
con.query('SELECT commonName, scientificName, birdPic, description FROM bird WHERE commonName LIKE \'%' + req.query.name + '%\';', function (err, result, fields) {
if (err)
console.log("Error gettting table");
else {
result.forEach(function (bird, index) {
var URL = "https://en.wikipedia.org/w/api.php?action=query&redirects&titles=" + bird.scientificName.replace(" ", "_") + "&prop=pageimages&format=json&pithumbsize=500";
request(URL, function (error, response, body) {
var json = JSON.parse(body);
var pages = json.query.pages;
if (first(pages) && first(pages).thumbnail) {
var sql = 'UPDATE bird SET birdPic = \'' + first(pages).thumbnail.source + '\' WHERE scientificName = \'' + bird.scientificName + '\'';
con.query(sql, function (err, result) {
if (err) throw err;
});
}
});
});
res.send(result);
}
});
});
app.get('/bird', function (req, res) {//The description page for a bird
console.log('user accessed bird descript');
con.query('SELECT commonName, scientificName, birdPic, description FROM bird WHERE commonName =\'' + req.query.name + '\';', function (err, result, fields) {
if (err)
console.log("Error gettting table");
else {
result.forEach(function (bird, index) {
var URL = "https://en.wikipedia.org/w/api.php?action=query&redirects&titles=" + bird.scientificName.replace(" ", "_") + "&prop=pageimages&format=json&pithumbsize=500";
request(URL, function (error, response, body) {
var json = JSON.parse(body);
var pages = json.query.pages;
if (first(pages) && first(pages).thumbnail) {
var sql = 'UPDATE bird SET birdPic = \'' + first(pages).thumbnail.source + '\' WHERE scientificName = \'' + bird.scientificName + '\'';
con.query(sql, function (err, result) {
if (err) throw err;
});
}
});
});
rH.getDescription(result[0].description, result[0].scientificName.replace(" ", "_"));
rH.once('gotDesc', function(desc) {
//#region
var html_str = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/JavaScript" src="http://localhost:8080/front/bird.js"></script>
<script type="text/JavaScript" src="http://localhost:8080/front/searchbar.js"></script>
<script type="text/JavaScript" src="http://localhost:8080/front/search.js"></script>
<title>bird.watch</title>
<link rel="stylesheet" href="http://localhost:8080/front/css/search.css">
<link rel="stylesheet" href="http://localhost:8080/front/css/normalize.css">
<link rel="stylesheet" href="http://localhost:8080/front/css/base.css">
<link rel="stylesheet" href="http://localhost:8080/front/css/bird.css">
</head>
<body>
<header class="darkGreenBkg">
<label class="menuBut" for="menuToggle">
<img class="whiteFill" src="http://localhost:8080/front/assets/icons/menu.svg" alt="menu button">
</label>
<div class="searchCont">
<input class="searchBar bodyFont" type="text" id="searchBar">
<button class="gpsBut searchBut" onclick="searchBar()">
<img src="http://localhost:8080/front/assets/icons/round-arrow_forward-24px.svg" alt="">
</button>
<button class="gpsBut" id="gpsBut" onclick="getLocation()"><img class="whiteFill" src="http://localhost:8080/front/assets/icons/gps.svg" alt=""></button>
</div>
</header>
<input class="invisible" id="menuToggle" type="checkbox">
<div class="menuDisp greenBkg">
<ul class="menu">
<li class="menuItem" onclick="getList(this.id)" id="seenList">To See List</li>
<li class="menuItem"><label for="menuToggle">Close Menu</label></li>
</ul>
</div>
<div class="resultDisp roundCorners">
<div class="imgCardCont roundCorners">
<img class="birdImg roundCorners" src="` + result[0].birdPic + `">
<div class="butCont">
<button name="` + result[0].commonName + `" onclick="toAddList(this.attributes)"><img src="http://localhost:8080/front/assets/icons/add_white.svg" alt=""></button>
</div>
</div>
<div class="descriptDisp roundCorners whiteBkg bodyFont">
<h1 class="headFont">` + result[0].commonName + `</h1>
<h2 class="italics gray">` + result[0].scientificName + `</h2>
<p>` + desc + `</p>
</div>
</div>
</body>
</html>`;
//#endregion
res.send(html_str);
})
console.log("Getting result");
}
});
//temporary redirect, implement proper params and databse stuff here!
//res.redirect('../front/bird.html');
});
app.get('/map', function (req, res) {//The Google Map feature showing the birds in the area
console.log('user accessing map');
var URL = "http://ebird.org/ws1.1/data/notable/geo/recent?lng="
URL += req.query.lng + "&lat=" + req.query.lat + "&dist=50&maxResults=50&fmt=json&locale=en_US";
request(URL, function (error, response, body) {
var json = JSON.parse(body);
res.send(json);
});
});
app.get('/list', function (req, res) {//When the users select a list, this will show the list of birds
console.log('user accessing list');
con.query('select b.* from user as u ' +
'join userlistxref as x on u.userID = x.userID ' +
'join list as l on x.listID = l.listID ' +
'join bird as b on l.listElement = b.birdID ' +
'where u.userName = "' + req.query.username + '";',
function (err, result, fields) {
if (err)
console.log("Error gettting table");
else {
res.send(result);
}
});
});
//endpoint for adding a bird to the user's to-see list
app.get( '/add', function( req, res ) {
console.log( req.query.username + ' adding ' + req.query.name + ' to watch list' );
con.query('select x.* from user as u ' +
'join userlistxref as x on u.userID = x.userID ' +
'where u.userName = "' + req.query.username + '";', function(err, result, fields) {
if (err) throw err;
if (result.length > 0) {
con.query('select b.* from user as u ' +
'join userlistxref as x on u.userID = x.userID ' +
'join list as l on x.listID = l.listID ' +
'join bird as b on l.listElement = b.birdID ' +
'where u.userName = "' + req.query.username + '" ' +
'and b.commonName = "' + req.query.name + '";',
function(err, innerResult) {
if (innerResult.length == 0)
{
con.query('insert into list (listID, listElement, listElementRank) ' +
'values (' + result[0].listID + ', (SELECT birdID FROM bird WHERE commonName = \'' + req.query.name + '\'), NULL);', function(err, result, fields) {
if (err) throw err;
});
}
});
}
else {
con.beginTransaction(function (err) {
if (err) throw err;
con.query('insert into list (listID, listElement, listElementRank) ' +
'values (coalesce((SELECT MAX(listID) FROM userlistxref) + 1, 1), (SELECT birdID FROM bird WHERE commonName = "' + req.query.name + '"), 1);', function (err) {
if (err) {
con.rollback(function() {
throw err;
});
}
con.query('insert into userlistxref (userID, listID) ' +
'values ((SELECT userID FROM user WHERE userName = "' + req.query.username + '"), (SELECT MAX(listID) FROM list));', function (err) {
if (err) {
con.rollback(function() {
throw err;
});
}
con.commit(function(err) {
if (err) {
con.rollback(function() {
throw err;
});
}
});
});
});
});
}
});
});
//endpoint for adding a bird to the user's seen list
app.get( '/check', function( req, res ) {
con.query('delete l from user as u ' +
'join userlistxref as x on u.userID = x.userID ' +
'join list as l on x.listID = l.listID ' +
'join bird as b on l.listElement = b.birdID ' +
'where u.userName = "' + req.query.username + '" ' +
'and b.commonName = "' + req.query.name + '";',
function(err) {
if (err) throw err;
});
});
app.get('/login', function (req, res) {
con.query('SELECT * FROM user WHERE userName=\'' + req.query.username + '\' AND userPass = \'' + req.query.password + '\';', function (err, result, fields) {
if (err) throw err;
if (result.length > 0) {
var json = { "authentication": "passed" };
res.send(json);
}
else {
var json = { "authentication": "failed" };
res.send(json);
}
});
});
app.get('/initdb', function (req, res) {
var URL = 'https://ebird.org/ws1.1/ref/taxa/ebird?cat=species&fmt=json&locale=en_US';
request(URL, function (error, response, body) {
var json = JSON.parse(body);
var sql = "INSERT INTO bird (commonName, scientificName) VALUES ";
json.forEach((bird, index) => {
sql += "('" + bird.comName.replace('"', '').replace(/'/g, "\\'") + "', '" + bird.sciName + "'),";
});
//sql.replace(/.$/, ";");
sql = sql.substr(0, sql.length - 1) + ";";
con.query(sql, function (err, result) {
if (err) throw err;
});
});
});
var server = app.listen(8080, function () {// notifies in the command prompt that the server is running
console.log('Server started on port ' + server.address().port)
}); |
import IMLearn.learners.regressors.linear_regression
from IMLearn.learners.regressors import PolynomialFitting
from IMLearn.utils import split_train_test
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.io as pio
pio.templates.default = "simple_white"
pio.renderers.default = "browser"
def load_data(filename: str) -> pd.DataFrame:
"""
Load city daily temperature dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (Temp)
"""
X = pd.read_csv(filename, parse_dates=["Date"])
X = X[X.Temp > -72]
X["DayOfYear"] = X["Date"].dt.dayofyear
return X
if __name__ == '__main__':
np.random.seed(0)
# Question 1 - Load and preprocessing of city temperature dataset
X = load_data("../datasets/City_Temperature.csv")
# Question 2 - Exploring data for specific country
israel_X = X[X.Country == 'Israel']
years = israel_X["Year"].astype(str)
fig = px.scatter(israel_X, x="DayOfYear", y="Temp", color=years,
labels={
"Temp": "Temperature (°C)",
"DayOfYear": "Day of Year",
"color": "Year"
},
title="Temperature as Function of Day Of Year")
fig.show()
# calculate the standard deviation by Month
x_std = israel_X.groupby(["Month"]).std().reset_index()
fig = px.bar(x_std, x='Month', y='Temp',
labels={
"Temp": "Standard Deviation",
"Month": "Month"
},
title="Standard Deviation of Temperature in each Month"
)
fig.show()
# Question 3 - Exploring differences between countries
x_mean = X.groupby(["Country", "Month"]).mean().reset_index()
x_std = X.groupby(["Country", "Month"]).std().reset_index()
x_mean["std"] = x_std["Temp"]
fig = px.line(x_mean, x="Month", y="Temp", color='Country', error_y="std",
labels={
"Temp": "Mean Temperature (°C)",
"Month": "Month"
},
title="Mean Temperature by Month in Each Country")
fig.update_xaxes(type='category')
fig.show()
# Question 4 - Fitting model for different values of `k`
train_x, train_y, test_x, test_y = split_train_test(israel_X["DayOfYear"], israel_X["Temp"], 0.25)
train_x, train_y = np.array(train_x), np.array(train_y)
test_x, test_y = np.array(test_x), np.array(test_y)
# For every value k in [1,10], fit a polynomial model of degree k using the training set
degrees = np.arange(1, 11)
losses = np.empty(degrees.size)
for i in range(degrees.size):
learner = PolynomialFitting(degrees[i])
learner.fit(train_x, train_y)
losses[i] = learner.loss(test_x, test_y)
print("degree: %d, loss: %.2f" % (degrees[i], losses[i]))
fig = px.bar(x=degrees, y=losses, text=np.round(losses, 2),
labels={
"x": "Degree of Fitted Polynom",
"y": "Loss of the model"
},
title="Loss as Function of Degree of Fitted Polynom"
)
fig.update_xaxes(type='category')
fig.show()
# Question 5 - Evaluating fitted model on different countries
best_k = 5
learner = PolynomialFitting(best_k)
train_x = israel_X["DayOfYear"]
train_y = israel_X["Temp"]
learner.fit(train_x, train_y)
countries = X.Country.unique()
losses = []
for country in countries:
country_x = X.loc[X.Country == country, "DayOfYear"]
country_y = X.loc[X.Country == country, "Temp"]
losses.append(learner.loss(country_x, country_y))
fig = px.bar(x=countries, y=losses, text=np.round(losses, 2),
labels={
"x": "Country",
"y": "Loss of the model"
},
title="Loss of as Function the Country of the data"
)
fig.show()
|
var categories = [
["Action", 2.0],
["Action Adventure", 2.0],
["Action Platform", 2.0],
["Action RPG", 1.7],
["Action Shooter", 2.2],
["Action Stealth", 2.5],
["Action Survival Horror", 2.5],
["Beat'em Up", 1.0],
["Board Game", 0.5],
["Card Game", 0.5],
["Fighting", 0.7],
["Graphic Adventure", 2.5],
["Interactive Novel", 2.5],
["MMORPG", 0.5],
["Party", 0.5],
["Puzzle", 1.0],
["Racing", 0.7],
["Rhythm", 0.7],
["Roguelike", 1.0],
["Sandbox", 0.7],
["Simulator", 0.7],
["Single-player RPG", 1.0],
["Sport", 0.5],
["Strategy", 0.7],
["Survival Horror", 1.5],
["Text Adventure", 1.5],
["Trivia", 0.5]
];
var ratingScales = [-0.30, 0.10, 0.15, 0.20, 0.25, 0.30];
var openStar = "☆"
var closedStar = "★"
function setupCategories() {
var categorySelect = $("#categorySelect");
categories.forEach(function(cat) {
categorySelect.append("<option value='" + cat[1] + "'>" + cat[0] + "</option>");
});
}
function buildTemplateRatingArray() {
var templateArray = [];
for (var i = 1; i < ratingScales.length; i++) {
templateArray.push(openStar);
}
return templateArray;
}
function compileRatingString(array, index) {
var ratingString = "";
array.forEach(function(symbol, i) {
if (i >= index) {
ratingString += symbol;
}
else {
ratingString += closedStar;
}
});
return ratingString;
}
function setupRatings() {
var ratingArrays = [];
var ratingSelect = $("#ratingSelect");
for (var i = 0; i < ratingScales.length; i++) {
ratingArrays.push(buildTemplateRatingArray());
}
ratingArrays.forEach(function(array, index) {
var ratingString = compileRatingString(array, index);
var html = "<option value='" + ratingScales[index] + "'>" + ratingString + "</option>";
ratingSelect.append(html);
});
}
function getSelectedCategoryValue() {
return parseFloat($("#categorySelect").val());
}
function getSelectedRatingValue() {
return parseFloat($("#ratingSelect").val());
}
function getHours() {
var hours = $("#hoursInput").val();
try {
hours = parseFloat(hours);
if (isNaN(hours)) {
window.alert("Invalid number of hours.")
}
}
catch (err) {
window.alert("Invalid number of hours.")
}
return hours;
}
function calculateValue() {
var vph = getSelectedCategoryValue();
var scale = getSelectedRatingValue();
var hours = getHours();
var totalValue = Math.round((vph * hours) * (1 + scale));
console.log("vph=" + vph + ", scale=" + scale + ", hours=" + hours + ", total=" + totalValue);
return totalValue;
}
function updateTotalValue(newValue) {
if (isNaN(newValue)) {
$("#totalValue").html("");
}
else {
$("#totalValue").html("$" + newValue);
}
}
function setupButtonHandling() {
$("#calcButton").click(function() {
var totalValue = calculateValue();
updateTotalValue(totalValue);
});
}
setupCategories();
setupRatings();
setupButtonHandling(); |
var DOMPurify=require('../ThirdParty/purify');
var defaultValue=require('./defaultValue');
var defined=require('./defined');
var defineProperties=require('./defineProperties');
var Check=require('./Check');
'use strict';
var nextCreditId = 0;
var creditToId = {};
/**
* A credit contains data pertaining to how to display attributions/credits for certain content on the screen.
* @param {String} html An string representing an html code snippet
* @param {Boolean} [showOnScreen=false] If true, the credit will be visible in the main credit container. Otherwise, it will appear in a popover
*
* @alias Credit
* @constructor
*
* @exception {DeveloperError} html is required.
*
* @example
* //Create a credit with a tooltip, image and link
* var credit = new Cesium.Credit('<a href="https://cesiumjs.org/" target="_blank"><img src="/images/cesium_logo.png" title="Cesium"/></a>');
*/
function Credit(html, showOnScreen) {
//>>includeStart('debug', pragmas.debug);
Check.typeOf.string('html', html);
//>>includeEnd('debug');
var id;
var key = html;
if (defined(creditToId[key])) {
id = creditToId[key];
} else {
id = nextCreditId++;
creditToId[key] = id;
}
showOnScreen = defaultValue(showOnScreen, false);
// Credits are immutable so generate an id to use to optimize equal()
this._id = id;
this._html = html;
this._showOnScreen = showOnScreen;
this._element = undefined;
}
defineProperties(Credit.prototype, {
/**
* The credit content
* @memberof Credit.prototype
* @type {String}
* @readonly
*/
html : {
get : function() {
return this._html;
}
},
/**
* @memberof Credit.prototype
* @type {Number}
* @readonly
*
* @private
*/
id : {
get : function() {
return this._id;
}
},
/**
* Whether the credit should be displayed on screen or in a lightbox
* @memberof Credit.prototype
* @type {Boolean}
* @readonly
*/
showOnScreen : {
get : function() {
return this._showOnScreen;
}
},
/**
* Gets the credit element
* @memberof Credit.prototype
* @type {HTMLElement}
* @readonly
*/
element: {
get: function() {
if (!defined(this._element)) {
var html = DOMPurify.sanitize(this._html);
var div = document.createElement('div');
div._creditId = this._id;
div.style.display = 'inline';
div.innerHTML = html;
var links = div.querySelectorAll('a');
for (var i = 0; i < links.length; i++) {
links[i].setAttribute('target', '_blank');
}
this._element = div;
}
return this._element;
}
}
});
/**
* Returns true if the credits are equal
*
* @param {Credit} left The first credit
* @param {Credit} right The second credit
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
Credit.equals = function(left, right) {
return (left === right) ||
((defined(left)) &&
(defined(right)) &&
(left._id === right._id));
};
/**
* Returns true if the credits are equal
*
* @param {Credit} credit The credit to compare to.
* @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
*/
Credit.prototype.equals = function(credit) {
return Credit.equals(this, credit);
};
/**
* @private
* @param attribution
* @return {Credit}
*/
Credit.getIonCredit = function(attribution) {
var showOnScreen = defined(attribution.collapsible) && !attribution.collapsible;
var credit = new Credit(attribution.html, showOnScreen);
credit._isIon = credit.html.indexOf('ion-credit.png') !== -1;
return credit;
};
/**
* Duplicates a Credit instance.
*
* @param {Credit} [credit] The Credit to duplicate.
* @returns {Credit} A new Credit instance that is a duplicate of the one provided. (Returns undefined if the credit is undefined)
*/
Credit.clone = function(credit) {
if (defined(credit)) {
return new Credit(credit.html, credit.showOnScreen);
}
};
module.exports= Credit;
|
import os
import time
import pandas as pd
import tsib
def test_parallel():
starttime = time.time()
res = tsib.simHouseholdsParallel(3, 2010, 2, cores=2, get_hot_water=True)
print("Profile generation took " + str(time.time() - starttime))
if __name__ == "__main__":
test_parallel()
|
#define EXECUTIVE_MODE_ENABLED
#include "e.h"
#include <scaler-server-protocol.h>
#include <transform-server-protocol.h>
static void
_e_viewport_destroy(struct wl_resource *resource)
{
E_Client *ec = wl_resource_get_user_data(resource);
if (!ec->comp_data) return;
if (!ec->comp_data->scaler.viewport) return;
ec->comp_data->scaler.viewport = NULL;
ec->comp_data->pending.buffer_viewport.buffer.src_width = wl_fixed_from_int(-1);
ec->comp_data->pending.buffer_viewport.surface.width = -1;
ec->comp_data->pending.buffer_viewport.changed = 1;
}
static void
_e_viewport_cb_destroy(struct wl_client *client EINA_UNUSED, struct wl_resource *resource)
{
wl_resource_destroy(resource);
}
static void
_e_viewport_cb_set(struct wl_client *client EINA_UNUSED,
struct wl_resource *resource,
wl_fixed_t src_x,
wl_fixed_t src_y,
wl_fixed_t src_width,
wl_fixed_t src_height,
int32_t dst_width,
int32_t dst_height)
{
E_Client *ec = wl_resource_get_user_data(resource);
EINA_SAFETY_ON_NULL_RETURN(ec->comp_data);
EINA_SAFETY_ON_NULL_RETURN(ec->comp_data->scaler.viewport);
if (wl_fixed_to_double(src_width) < 0 || wl_fixed_to_double(src_height) < 0)
{
wl_resource_post_error(resource,
WL_VIEWPORT_ERROR_BAD_VALUE,
"source dimensions must be non-negative (%fx%f)",
wl_fixed_to_double(src_width),
wl_fixed_to_double(src_height));
return;
}
if (dst_width <= 0 || dst_height <= 0)
{
wl_resource_post_error(resource,
WL_VIEWPORT_ERROR_BAD_VALUE,
"destination dimensions must be positive (%dx%d)",
dst_width, dst_height);
return;
}
ec->comp_data->pending.buffer_viewport.buffer.src_x = src_x;
ec->comp_data->pending.buffer_viewport.buffer.src_y = src_y;
ec->comp_data->pending.buffer_viewport.buffer.src_width = src_width;
ec->comp_data->pending.buffer_viewport.buffer.src_height = src_height;
ec->comp_data->pending.buffer_viewport.surface.width = dst_width;
ec->comp_data->pending.buffer_viewport.surface.height = dst_height;
ec->comp_data->pending.buffer_viewport.changed = 1;
}
static void
_e_viewport_cb_set_source(struct wl_client *client EINA_UNUSED,
struct wl_resource *resource,
wl_fixed_t src_x,
wl_fixed_t src_y,
wl_fixed_t src_width,
wl_fixed_t src_height)
{
E_Client *ec = wl_resource_get_user_data(resource);
EINA_SAFETY_ON_NULL_RETURN(ec->comp_data);
EINA_SAFETY_ON_NULL_RETURN(ec->comp_data->scaler.viewport);
if (src_width == wl_fixed_from_int(-1) && src_height == wl_fixed_from_int(-1))
{
/* unset source size */
ec->comp_data->pending.buffer_viewport.buffer.src_width = wl_fixed_from_int(-1);
ec->comp_data->pending.buffer_viewport.changed = 1;
return;
}
if (src_width <= 0 || src_height <= 0)
{
wl_resource_post_error(resource,
WL_VIEWPORT_ERROR_BAD_VALUE,
"source size must be positive (%fx%f)",
wl_fixed_to_double(src_width),
wl_fixed_to_double(src_height));
return;
}
ec->comp_data->pending.buffer_viewport.buffer.src_x = src_x;
ec->comp_data->pending.buffer_viewport.buffer.src_y = src_y;
ec->comp_data->pending.buffer_viewport.buffer.src_width = src_width;
ec->comp_data->pending.buffer_viewport.buffer.src_height = src_height;
ec->comp_data->pending.buffer_viewport.changed = 1;
}
static void
_e_viewport_cb_set_destination(struct wl_client *client EINA_UNUSED,
struct wl_resource *resource,
int32_t dst_width,
int32_t dst_height)
{
E_Client *ec = wl_resource_get_user_data(resource);
EINA_SAFETY_ON_NULL_RETURN(ec->comp_data);
EINA_SAFETY_ON_NULL_RETURN(ec->comp_data->scaler.viewport);
if (dst_width == -1 && dst_height == -1)
{
/* unset destination size */
ec->comp_data->pending.buffer_viewport.surface.width = -1;
ec->comp_data->pending.buffer_viewport.changed = 1;
return;
}
if (dst_width <= 0 || dst_height <= 0)
{
wl_resource_post_error(resource,
WL_VIEWPORT_ERROR_BAD_VALUE,
"destination size must be positive (%dx%d)",
dst_width, dst_height);
return;
}
ec->comp_data->pending.buffer_viewport.surface.width = dst_width;
ec->comp_data->pending.buffer_viewport.surface.height = dst_height;
ec->comp_data->pending.buffer_viewport.changed = 1;
}
static const struct wl_viewport_interface _e_viewport_interface = {
_e_viewport_cb_destroy,
_e_viewport_cb_set,
_e_viewport_cb_set_source,
_e_viewport_cb_set_destination
};
static void
_e_scaler_cb_destroy(struct wl_client *client EINA_UNUSED, struct wl_resource *resource)
{
wl_resource_destroy(resource);
}
static void
_e_scaler_cb_get_viewport(struct wl_client *client EINA_UNUSED, struct wl_resource *scaler, uint32_t id, struct wl_resource *surface_resource)
{
int version = wl_resource_get_version(scaler);
E_Client *ec;
struct wl_resource *res;
if (!(ec = wl_resource_get_user_data(surface_resource))) return;
if (!ec->comp_data) return;
if (ec->comp_data && ec->comp_data->scaler.viewport)
{
wl_resource_post_error(scaler,
WL_SCALER_ERROR_VIEWPORT_EXISTS,
"a viewport for that surface already exists");
return;
}
res = wl_resource_create(client, &wl_viewport_interface, version, id);
if (res == NULL)
{
wl_client_post_no_memory(client);
return;
}
ec->comp_data->scaler.viewport = res;
wl_resource_set_implementation(res, &_e_viewport_interface, ec, _e_viewport_destroy);
}
static const struct wl_scaler_interface _e_scaler_interface =
{
_e_scaler_cb_destroy,
_e_scaler_cb_get_viewport
};
static void
_e_scaler_cb_bind(struct wl_client *client, void *data, uint32_t version, uint32_t id)
{
struct wl_resource *res;
if (!(res = wl_resource_create(client, &wl_scaler_interface, MIN(version, 2), id)))
{
ERR("Could not create scaler resource: %m");
wl_client_post_no_memory(client);
return;
}
wl_resource_set_implementation(res, &_e_scaler_interface, NULL, NULL);
}
static void
_e_rotator_cb_destroy(struct wl_client *client EINA_UNUSED, struct wl_resource *resource)
{
E_Client *ec;
if ((ec = wl_resource_get_user_data(resource)))
{
if (ec->comp_data)
ec->comp_data->transform.enabled = EINA_FALSE;
}
wl_resource_destroy(resource);
}
static void
_e_rotator_cb_set(struct wl_client *client EINA_UNUSED, struct wl_resource *resource)
{
E_Client *ec;
if (!(ec = wl_resource_get_user_data(resource))) return;
if (!ec->comp_data) return;
ec->comp_data->transform.enabled = EINA_TRUE;
DBG("SET ROTATOR");
}
static void
_e_rotator_cb_unset(struct wl_client *client EINA_UNUSED, struct wl_resource *resource)
{
E_Client *ec;
if (!(ec = wl_resource_get_user_data(resource))) return;
if (!ec->comp_data) return;
ec->comp_data->transform.enabled = EINA_FALSE;
DBG("UNSET ROTATOR");
}
static const struct wl_rotator_interface _e_rotator_interface =
{
_e_rotator_cb_destroy,
_e_rotator_cb_set,
_e_rotator_cb_unset,
};
static void
_e_transform_cb_destroy(struct wl_client *client EINA_UNUSED, struct wl_resource *resource)
{
wl_resource_destroy(resource);
}
static void
_e_transform_cb_get_rotator(struct wl_client *client EINA_UNUSED, struct wl_resource *transform, uint32_t id, struct wl_resource *surface_resource)
{
int version = wl_resource_get_version(transform);
E_Client *ec;
struct wl_resource *res;
if (!(ec = wl_resource_get_user_data(surface_resource))) return;
res = wl_resource_create(client, &wl_rotator_interface, version, id);
if (res == NULL)
{
wl_client_post_no_memory(client);
return;
}
wl_resource_set_implementation(res, &_e_rotator_interface, ec, NULL);
}
static const struct wl_transform_interface _e_transform_interface =
{
_e_transform_cb_destroy,
_e_transform_cb_get_rotator
};
static void
_e_transform_cb_bind(struct wl_client *client, void *data, uint32_t version, uint32_t id)
{
struct wl_resource *res;
if (!(res = wl_resource_create(client, &wl_transform_interface, version, id)))
{
ERR("Could not create transform resource: %m");
wl_client_post_no_memory(client);
return;
}
wl_resource_set_implementation(res, &_e_transform_interface, NULL, NULL);
}
Eina_Bool
e_scaler_init(void)
{
if (!e_comp) return EINA_FALSE;
/* try to add scaler to wayland globals */
if (!wl_global_create(e_comp_wl->wl.disp, &wl_scaler_interface, 2,
e_comp->wl_comp_data, _e_scaler_cb_bind))
{
ERR("Could not add scaler to wayland globals: %m");
return EINA_FALSE;
}
if (!wl_global_create(e_comp_wl->wl.disp, &wl_transform_interface, 1,
e_comp->wl_comp_data, _e_transform_cb_bind))
{
ERR("Could not add transform to wayland globals: %m");
return EINA_FALSE;
}
return EINA_TRUE;
}
|
/**
* @class Ext.chart.series.Radar
*
* Creates a Radar Chart. A Radar Chart is a useful visualization technique for comparing different quantitative values for
* a constrained number of categories.
*
* As with all other series, the Radar series must be appended in the *series* Chart array configuration. See the Chart
* documentation for more information. A typical configuration object for the radar series could be:
*
* @example
* var store = Ext.create('Ext.data.JsonStore', {
* fields: ['name', 'data1', 'data2', 'data3'],
* data: [
* { 'name': 'metric one', 'data1': 14, 'data2': 12, 'data3': 13 },
* { 'name': 'metric two', 'data1': 16, 'data2': 8, 'data3': 3 },
* { 'name': 'metric three', 'data1': 14, 'data2': 2, 'data3': 7 },
* { 'name': 'metric four', 'data1': 6, 'data2': 14, 'data3': 23 },
* { 'name': 'metric five', 'data1': 36, 'data2': 38, 'data3': 33 }
* ]
* });
*
* Ext.create('Ext.chart.Chart', {
* renderTo: Ext.getBody(),
* width: 500,
* height: 300,
* animate: true,
* theme:'Category2',
* store: store,
* axes: [{
* type: 'Radial',
* position: 'radial',
* label: {
* display: true
* }
* }],
* series: [{
* type: 'radar',
* xField: 'name',
* yField: 'data1',
* showInLegend: true,
* showMarkers: true,
* markerConfig: {
* radius: 5,
* size: 5
* },
* style: {
* 'stroke-width': 2,
* fill: 'none'
* }
* },{
* type: 'radar',
* xField: 'name',
* yField: 'data2',
* showMarkers: true,
* showInLegend: true,
* markerConfig: {
* radius: 5,
* size: 5
* },
* style: {
* 'stroke-width': 2,
* fill: 'none'
* }
* },{
* type: 'radar',
* xField: 'name',
* yField: 'data3',
* showMarkers: true,
* showInLegend: true,
* markerConfig: {
* radius: 5,
* size: 5
* },
* style: {
* 'stroke-width': 2,
* fill: 'none'
* }
* }]
* });
*
* In this configuration we add three series to the chart. Each of these series is bound to the same
* categories field, `name` but bound to different properties for each category, `data1`, `data2` and
* `data3` respectively. All series display markers by having `showMarkers` enabled. The configuration
* for the markers of each series can be set by adding properties onto the markerConfig object.
* Finally we override some theme styling properties by adding properties to the `style` object.
*/
Ext.define('Ext.chart.series.Radar', {
/* Begin Definitions */
extend: 'Ext.chart.series.Series',
requires: ['Ext.chart.Shape', 'Ext.fx.Anim'],
/* End Definitions */
type: "radar",
alias: 'series.radar',
rad: Math.PI / 180,
showInLegend: false,
/**
* @cfg {Object} style
* An object containing styles for overriding series styles from Theming.
*/
style: {},
/**
* @cfg {String} xField
* The name of the data Model field corresponding to the x-axis (angle) value.
*/
/**
* @cfg {String} yField
* The name of the data Model field corresponding to the y-axis (radius) value.
*/
/**
* @cfg {Boolean} showMarkers
* Whether markers should be displayed at the data points of the series. If true,
* then the {@link #markerConfig} config item will determine the markers' styling.
*/
/**
* @cfg {Object} markerConfig
* The display style for the markers. Only used if {@link #showMarkers} is true.
* The markerConfig is a configuration object containing the same set of properties defined in
* the Sprite class. For example, if we were to set red circles as markers to the series we could
* pass the object:
*
* @example
* markerConfig: {
* type: 'circle',
* radius: 4,
* 'fill': '#f00'
* }
*/
constructor: function(config) {
this.callParent(arguments);
var me = this,
surface = me.chart.surface, i, l;
me.group = surface.getGroup(me.seriesId);
if (me.showMarkers) {
me.markerGroup = surface.getGroup(me.seriesId + '-markers');
}
},
/**
* Draws the series for the current chart.
*/
drawSeries: function() {
var me = this,
store = me.chart.getChartStore(),
data = store.data.items,
d, record,
group = me.group,
sprite,
chart = me.chart,
seriesItems = chart.series.items,
s, sLen, series,
animate = chart.animate,
field = me.field || me.yField,
surface = chart.surface,
chartBBox = chart.chartBBox,
seriesIdx = me.seriesIdx,
colorArrayStyle = me.colorArrayStyle,
centerX, centerY,
items,
radius,
maxValue = 0,
fields = [],
max = Math.max,
cos = Math.cos,
sin = Math.sin,
pi2 = Math.PI * 2,
l = store.getCount(),
startPath, path, x, y, rho,
i, nfields,
seriesStyle = me.seriesStyle,
seriesLabelStyle = me.seriesLabelStyle,
first = chart.resizing || !me.radar,
axis = chart.axes && chart.axes.get(0),
aggregate = !(axis && axis.maximum);
me.setBBox();
maxValue = aggregate? 0 : (axis.maximum || 0);
Ext.apply(seriesStyle, me.style || {});
//if the store is empty then there's nothing to draw
if (!store || !store.getCount() || me.seriesIsHidden) {
me.hide();
me.items = [];
if (me.radar) {
me.radar.hide(true);
}
me.radar = null;
return;
}
if(!seriesStyle['stroke']){
seriesStyle['stroke'] = colorArrayStyle[me.themeIdx % colorArrayStyle.length];
}
me.unHighlightItem();
me.cleanHighlights();
centerX = me.centerX = chartBBox.x + (chartBBox.width / 2);
centerY = me.centerY = chartBBox.y + (chartBBox.height / 2);
me.radius = radius = Math.min(chartBBox.width, chartBBox.height) /2;
me.items = items = [];
if (aggregate) {
//get all renderer fields
for (s = 0, sLen = seriesItems.length; s < sLen; s++) {
series = seriesItems[s];
fields.push(series.yField);
}
//get maxValue to interpolate
for (d = 0; d < l; d++) {
record = data[d];
for (i = 0, nfields = fields.length; i < nfields; i++) {
maxValue = max(+record.get(fields[i]), maxValue);
}
}
}
//ensure non-zero value.
maxValue = maxValue || 1;
//create path and items
startPath = []; path = [];
for (i = 0; i < l; i++) {
record = data[i];
rho = radius * record.get(field) / maxValue;
x = rho * cos(i / l * pi2);
y = rho * sin(i / l * pi2);
if (i == 0) {
path.push('M', x + centerX, y + centerY);
startPath.push('M', 0.01 * x + centerX, 0.01 * y + centerY);
} else {
path.push('L', x + centerX, y + centerY);
startPath.push('L', 0.01 * x + centerX, 0.01 * y + centerY);
}
items.push({
sprite: false, //TODO(nico): add markers
point: [centerX + x, centerY + y],
storeItem: record,
series: me
});
}
path.push('Z');
//create path sprite
if (!me.radar) {
me.radar = surface.add(Ext.apply({
type: 'path',
group: group,
path: startPath
}, seriesStyle || {}));
}
//reset on resizing
if (chart.resizing) {
me.radar.setAttributes({
path: startPath
}, true);
}
//render/animate
if (chart.animate) {
me.onAnimate(me.radar, {
to: Ext.apply({
path: path
}, seriesStyle || {})
});
} else {
me.radar.setAttributes(Ext.apply({
path: path
}, seriesStyle || {}), true);
}
//render markers, labels and callouts
if (me.showMarkers) {
me.drawMarkers();
}
me.renderLabels();
me.renderCallouts();
},
// @private draws the markers for the lines (if any).
drawMarkers: function() {
var me = this,
chart = me.chart,
surface = chart.surface,
markerStyle = Ext.apply({}, me.markerStyle || {}),
endMarkerStyle = Ext.apply(markerStyle, me.markerConfig, {
fill: me.colorArrayStyle[me.themeIdx % me.colorArrayStyle.length]
}),
items = me.items,
type = endMarkerStyle.type,
markerGroup = me.markerGroup,
centerX = me.centerX,
centerY = me.centerY,
item, i, l, marker;
delete endMarkerStyle.type;
for (i = 0, l = items.length; i < l; i++) {
item = items[i];
marker = markerGroup.getAt(i);
if (!marker) {
marker = Ext.chart.Shape[type](surface, Ext.apply({
group: markerGroup,
x: 0,
y: 0,
translate: {
x: centerX,
y: centerY
}
}, endMarkerStyle));
}
else {
marker.show();
}
item.sprite = marker;
if (chart.resizing) {
marker.setAttributes({
x: 0,
y: 0,
translate: {
x: centerX,
y: centerY
}
}, true);
}
marker._to = {
translate: {
x: item.point[0],
y: item.point[1]
}
};
//render/animate
if (chart.animate) {
me.onAnimate(marker, {
to: marker._to
});
}
else {
marker.setAttributes(Ext.apply(marker._to, endMarkerStyle || {}), true);
}
}
},
isItemInPoint: function(x, y, item) {
var point,
tolerance = 10,
abs = Math.abs;
point = item.point;
return (abs(point[0] - x) <= tolerance &&
abs(point[1] - y) <= tolerance);
},
// @private callback for when creating a label sprite.
onCreateLabel: function(storeItem, item, i, display) {
var me = this,
group = me.labelsGroup,
config = me.label,
centerX = me.centerX,
centerY = me.centerY,
point = item.point,
endLabelStyle = Ext.apply(me.seriesLabelStyle || {}, config);
return me.chart.surface.add(Ext.apply({
'type': 'text',
'text-anchor': 'middle',
'group': group,
'x': centerX,
'y': centerY
}, config || {}));
},
// @private callback for when placing a label sprite.
onPlaceLabel: function(label, storeItem, item, i, display, animate) {
var me = this,
chart = me.chart,
resizing = chart.resizing,
config = me.label,
format = config.renderer,
field = config.field,
centerX = me.centerX,
centerY = me.centerY,
opt = {
x: item.point[0],
y: item.point[1]
},
x = opt.x - centerX,
y = opt.y - centerY;
label.setAttributes({
text: format(storeItem.get(field)),
hidden: true
},
true);
if (resizing) {
label.setAttributes({
x: centerX,
y: centerY
}, true);
}
if (animate) {
label.show(true);
me.onAnimate(label, {
to: opt
});
} else {
label.setAttributes(opt, true);
label.show(true);
}
},
// @private for toggling (show/hide) series.
toggleAll: function(show) {
var me = this,
i, ln, shadow, shadows;
if (!show) {
Ext.chart.series.Radar.superclass.hideAll.call(me);
}
else {
Ext.chart.series.Radar.superclass.showAll.call(me);
}
if (me.radar) {
me.radar.setAttributes({
hidden: !show
}, true);
//hide shadows too
if (me.radar.shadows) {
for (i = 0, shadows = me.radar.shadows, ln = shadows.length; i < ln; i++) {
shadow = shadows[i];
shadow.setAttributes({
hidden: !show
}, true);
}
}
}
},
// @private hide all elements in the series.
hideAll: function() {
this.toggleAll(false);
this.hideMarkers(0);
},
// @private show all elements in the series.
showAll: function() {
this.toggleAll(true);
},
// @private hide all markers that belong to `markerGroup`
hideMarkers: function(index) {
var me = this,
count = me.markerGroup && me.markerGroup.getCount() || 0,
i = index || 0;
for (; i < count; i++) {
me.markerGroup.getAt(i).hide(true);
}
}
});
|
import React, {useState, useEffect, useContext } from 'react'
import Fom from '../../svg/fom.svg'
import { navigate } from 'gatsby'
import { sha256, sha224 } from 'js-sha256';
import { Form, Button, Tabs, Tab, Modal, OverlayTrigger, Tooltip } from 'react-bootstrap'
import { Input } from 'reactstrap'
import Tips from '../../svg/coin.svg'
import DefaultProfile from "../../svg/profile.png"
import ToggleDisplay from 'react-toggle-display'
import Arrow from '../../svg/arrowDown.svg'
import Dialog from './common/fullScreenDialog'
import Divider from '@material-ui/core/Divider'
import AddPhotoURL from '../../svg/camera.svg'
import Avatar from '@material-ui/core/Avatar';
import { FirebaseContext, db, auth, storage } from '../../Firebase'
const Dilema = () => {
const [showModal, setShowModal] = useState(false)
const [showDetails, setShowDetails] = useState(false)
const [confModal, setConfModal] = useState(true)
const [createRefSpace, setCreateRefSpace] = useState("")
const [joinRefSpace, setJoinRefSpace] = useState("")
const [info, setInfo] = useState([])
const [list, setList] = useState(false)
const [showDialog, setShowDialog] = useState(false)
const [formValue, setFormValue] = useState({hotelName: "", job: "", level: "", mood: ""})
const [img, setImg] = useState(null)
const [url, setUrl] = useState("")
const [user, setUser] = useState(auth.currentUser)
const { userDB, setUserDB } = useContext(FirebaseContext)
const handleWorkspace = () => {
if(!user.displayName) {
if(window.innerWidth > 480) {
setShowModal(true)
}else{
setShowDialog(true)
}
}else{
navigate('/singlePage')
}
}
const handleShowDetails = () =>{
let arrowTop = document.getElementById("arrowTop")
const sentence = document.getElementById('dilema-sentence')
if(arrowTop.style.transform === "rotate(0turn)"){
setShowDetails(!showDetails)
sentence.style.display = "none"
return arrowTop.style.transform = "rotate(0.5turn)"
}
if(arrowTop.style.transform === "rotate(0.5turn)"){
setShowDetails(!showDetails)
sentence.style.display = "block"
return arrowTop.style.transform = "rotate(0turn)"
}
}
const handleChangePhotoUrl = (event) => {
event.preventDefault()
const uploadTask = storage.ref(`photo-user/${img.name}`).put(img)
uploadTask.on(
"state_changed",
snapshot => {},
error => {console.log(error)},
() => {
storage
.ref("photo-user")
.child(img.name)
.getDownloadURL()
.then(url => {
const uploadTask = () => {
setConfModal(false)
auth.addPhotoProfileUser({ img: url })
setTimeout(
() => window.location.reload(),
1000
);
}
return setUrl(url, uploadTask())})
}
)
}
const handleChange = (event) =>{
event.persist()
setFormValue(currentValue =>({
...currentValue,
[event.target.name]: event.target.value
}))
}
const handleChangeCreate = event =>{
setCreateRefSpace(event.currentTarget.value)
}
const handleChangeJoin = event =>{
setJoinRefSpace(event.currentTarget.value)
}
const handleImgChange = (event) => {
if (event.target.files[0]){
setImg(event.target.files[0])
}
}
const handleSubmit = async(event) => {
event.preventDefault()
setFormValue({hotelName: "", job: "", level: "", mood: ""})
firebase.updateIziProfile({username: user.displayName, hotelName: formValue.hotelName, job: formValue.job, level: formValue.level}).then(handleClose)
return db.collection("mySweetHotel")
.doc("country")
.collection("France")
.doc('collection')
.collection('business')
.doc('collection')
.collection('users')
.doc(username)
.update({
job: job,
category: level
})
}
const handleClose = () => setShowModal(false)
const handleShow = () => setShowModal(true)
const handleCloseUpdate = () => setList(false)
const handleShowUpdate = () => setList(true)
const hideDialog = () => {
setShowDialog(false)
}
useEffect(() => {
const iziUserOnAir2 = () => {
return db.collection("mySweetHotel")
.doc("country")
.collection("France")
.doc('collection')
.collection('business')
.doc('collection')
.collection('users')
.where("userId", "==", user.uid)
}
let unsubscribe = iziUserOnAir2().onSnapshot(function(snapshot) {
const snapInfo = []
snapshot.forEach(function(doc) {
snapInfo.push({
id: doc.id,
...doc.data()
})
});
console.log(snapInfo)
setInfo(snapInfo)
});
return unsubscribe
},[])
console.log(window.innerWidth)
return (
info.map(flow => (
<div className="global-container"
style={{ backgroundImage: user.photoURL ? `url(${user.photoURL})` : `url(${DefaultProfile})` }}>
<div className="profile-container">
<h1>
<div style={{color: "#5bc0de", fontWeight: "bold"}}>{flow.id}</div>
{ /*<div className="header-profile">
<img src={Tips} alt="tips" className="tips" />
{flow.tips} tips
<img src={Arrow} alt="arrow" style={{width: "1vw", cursor: "pointer", marginLeft: "1vw", transform: "rotate(0turn)"}} id="arrowTop" onClick={handleShowDetails} />
</div>*/}
</h1>
<ToggleDisplay show={showDetails}>
<div>
<div className="header-toggle-container">
<div>
<b>hotel</b><p className="profile-details">{flow.hotelName}</p>
</div>
<div>
<b>poste</b><p className="profile-details">{flow.job}</p>
</div>
<div>
<b>level</b><p className="profile-details">{flow.category}</p>
</div>
</div>
<Button variant="secondary" className="update-profile-button" onClick={handleShowUpdate}>Actualiser votre profil</Button>
</div>
</ToggleDisplay>
</div>
<div className="space-container">
<div className="space-box">
<div className="softSkin space-card"
onClick={handleWorkspace}>
<h2>Work Space</h2>
<h4 style={{color: "darkgoldenrod"}}>Hello, Karen</h4>
<img src={Fom} alt="Fom" className="white-fom-icon" />
</div>
</div>
<div className="space-box-shadow">
<div className="boomSkakalaka space-card-shadow"
onClick={()=>navigate('/izilife')}>
<h2>World Space</h2>
<h4 style={{color: "darkred"}}>Hell no, Karen</h4>
<img src={Fom} alt="Fom" className="black-fom-icon" />
</div>
</div>
<h2 id="dilema-sentence" className="dilema-sentence">Choisissez votre espace</h2>
</div>
<Modal show={list}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
onHide={handleCloseUpdate}
>
<Modal.Header closeButton className="bg-light">
<Modal.Title id="contained-modal-title-vcenter">
Modifier mon profil
</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className="update_modal_container">
<Form.Row>
<Form.Group controlId="description">
<Form.Label>Change d'hôtel</Form.Label>
<Form.Control type="text" placeholder={flow.hotelName} className="hotelName-input" value={formValue.hotelName} name="hotelName" onChange={handleChange} />
</Form.Group>
</Form.Row>
<Form.Row>
<Form.Group controlId="description">
<Form.Label>Change de <i>casquette</i></Form.Label><br/>
<select class="selectpicker" value={formValue.job} name="job" onChange={handleChange}
className="update-profile-select">
<option></option>
<option>Réceptionniste</option>
<option>Chef de Brigade</option>
<option>Chef de Réception</option>
<option>Assistant de direction</option>
<option>Head Manager</option>
</select>
</Form.Group>
</Form.Row>
<Form.Row>
<Form.Group controlId="description">
<Form.Label>Change de <i>level</i></Form.Label><br/>
<select class="selectpicker"defaultValue={flow.category} value={formValue.level} name="level" onChange={handleChange}
className="update-profile-select">
<option></option>
<option>Jeune Padawan</option>
<option>Je gère, tranquille</option>
<option>I'm a living Legend</option>
</select>
</Form.Group>
</Form.Row>
</div>
</Modal.Body>
<Modal.Footer>
<Button variant="outline-success" onClick={handleSubmit}>Modifier</Button>
</Modal.Footer>
</Modal>
<Avatar alt="user-profile-photo"
src={user.photoURL ? user.photoURL : DefaultProfile}
style={{
display: typeof window && window.innerWidth > 480 ? "none" : "flex",
position: "absolute",
top: "35vh",
left: "28vw",
width: "45%",
height: "25%",
filter: "grayscale(90%) drop-shadow(1px 1px 1px)",
zIndex: "10"
}}
onClick={() => navigate("/userPage")} />
<img src={AddPhotoURL} alt="add photoURL"
className="dilema-add-photo-icon" />
<OverlayTrigger
placement="top"
overlay={
<Tooltip id="title">
Ajouter/Changer la photo de votre profil
</Tooltip>
}>
<input type="file"
className="dilema-add-photo-input"
onChange={handleImgChange} />
</OverlayTrigger>
<div className="dilema-add-photo-input-mask">
</div>
{img &&
<Modal show={confModal}
size="sm"
aria-labelledby="contained-modal-title-vcenter"
centered
onHide={handleCloseUpdate}
>
<Modal.Body>
<p style={{textAlign: "center"}}>Etes-vous sûr.e de vouloir ajouter ou changer votre photo de profil ?</p>
</Modal.Body>
<Modal.Footer>
<div>
<Button size="sm" variant="success" style={{marginRight: "1vw"}} onClick={handleChangePhotoUrl}>Oui</Button>
<Button size="sm" variant="danger" onClick={() => setConfModal(false)}>Non</Button>
</div>
</Modal.Footer>
</Modal>}
</div>
))
)
}
export default Dilema |
from argparse import ArgumentParser
from typing import Any
from django.conf import settings
from django.core.management.base import CommandError
from zerver.lib.management import ZulipBaseCommand
from zerver.lib.send_email import send_custom_email
from zerver.models import Realm, UserProfile
class Command(ZulipBaseCommand):
help = """
Send a custom email with Zulip branding to the specified users.
Useful to send a notice to all users of a realm or server.
The From and Subject headers can be provided in the body of the Markdown
document used to generate the email, or on the command line."""
def add_arguments(self, parser: ArgumentParser) -> None:
parser.add_argument(
"--entire-server", action="store_true", help="Send to every user on the server."
)
parser.add_argument(
"--all-sponsored-org-admins",
action="store_true",
help="Send to all organization administrators of sponsored organizations.",
)
parser.add_argument(
"--markdown-template-path",
"--path",
required=True,
help="Path to a Markdown-format body for the email.",
)
parser.add_argument(
"--subject",
help="Subject for the email. It can be declared in Markdown file in headers",
)
parser.add_argument(
"--from-name",
help="From line for the email. It can be declared in Markdown file in headers",
)
parser.add_argument("--reply-to", help="Optional reply-to line for the email")
parser.add_argument(
"--admins-only", help="Send only to organization administrators", action="store_true"
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Prints emails of the recipients and text of the email.",
)
self.add_user_list_args(
parser,
help="Email addresses of user(s) to send emails to.",
all_users_help="Send to every user on the realm.",
)
self.add_realm_args(parser)
def handle(self, *args: Any, **options: str) -> None:
if options["entire_server"]:
users = UserProfile.objects.filter(
is_active=True, is_bot=False, is_mirror_dummy=False, realm__deactivated=False
)
elif options["all_sponsored_org_admins"]:
# Sends at most one copy to each email address, even if it
# is an administrator in several organizations.
sponsored_realms = Realm.objects.filter(
plan_type=Realm.STANDARD_FREE, deactivated=False
)
admin_roles = [UserProfile.ROLE_REALM_ADMINISTRATOR, UserProfile.ROLE_REALM_OWNER]
users = UserProfile.objects.filter(
is_active=True,
is_bot=False,
is_mirror_dummy=False,
role__in=admin_roles,
realm__deactivated=False,
realm__in=sponsored_realms,
).distinct("delivery_email")
else:
realm = self.get_realm(options)
try:
users = self.get_users(options, realm, is_bot=False)
except CommandError as error:
if str(error) == "You have to pass either -u/--users or -a/--all-users.":
raise CommandError(
"You have to pass -u/--users or -a/--all-users or --entire-server."
)
raise error
# Only email users who've agreed to the terms of service.
if settings.TOS_VERSION is not None:
users = users.exclude(tos_version=None)
send_custom_email(users, options)
if options["dry_run"]:
print("Would send the above email to:")
for user in users:
print(f" {user.delivery_email} ({user.realm.string_id})")
|
const express = require('express');
const { errors } = require('celebrate');
const cors = require('cors');
const routes = require('./routes');
const app = express();
app.use(cors());
app.use(express.json());
app.use(routes);
app.use(errors());
module.exports = app;
|
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUF 512
int factorial(int max) {
if(max <= 0) {
return 0;
} else if (max == 1) {
return 1;
} else {
return max * factorial(max - 1);
}
}
int main() {
int max;
printf("Please a number: ");
scanf("%d", &max);
printf("factorial(%d) -> %d\n", max, factorial(max));
}
|
ResourceLoader.pushRelativePaths([
"Animation.js",
"LineAnimation.js",
"AltAnimation.js",
"Animation.js",
"DiagonalAnimation.js",
"LineDownAnimation.js",
"LineLeftAnimation.js",
"LineRightAnimation.js",
"LineUpAnimation.js",
"RandomAnimation.js",
"Tree/_imports.js"
]);
|
// userAuthentication.js
// ------------------------------------------------------------------
//
// A module to do user authentication. It supports three different mechanisms,
// currently: fake, and local.
//
// This module could be extended by adding new functions and expanding the list of
// exports. Good candidates might be firebase auth, or Google Signin.
//
// created: Wed Jun 15 14:13:56 2016
// last saved: <2018-August-28 14:13:28>
(function (globalScope){
var request = require('request'),
crypto = require('crypto'),
ugConfig,
localUserDb;
function configureNoop(config) {
return Promise.resolve(config);
}
function alwaysAuthenticateSuccessfully(ctx) {
ctx.loginStatus = 200;
ctx.userInfo = {
picture : 'http://i.imgur.com/60rQbfy.png',
uuid : '6BAE464E-C76D-42F0-998B-C59517C13C4A',
user_id : ctx.credentials.username,
username : ctx.credentials.username,
email : ctx.credentials.username + '@example.com',
motto : 'Experience is what you get when you didn\'t get what you wanted.',
family_name : 'Williams',
given_name : 'Freda'
};
return Promise.resolve(ctx);
}
function joinPathElements() {
var re1 = new RegExp('^\\/|\\/$', 'g'),
elts = Array.prototype.slice.call(arguments);
return '/' + elts.map(function(element){
if ( ! element) {return '';}
return element.replace(re1,""); }).join('/');
}
function loadLocalUserDb(filename) {
localUserDb = require(joinPathElements(__dirname, filename));
if ( ! localUserDb) {
throw new Error("localUserDb cannot be loaded.");
}
}
function configureLocalAuth(config) {
// Read the usernames + passwords "user database" that is passed in, in config.
// This allows the "stored" credentials to be dynamically specified at init time.
if ( !config.localUserDb) {
throw new Error("there is no localUserDb configured.");
}
loadLocalUserDb(config.localUserDb);
return Promise.resolve(config);
}
function authenticateAgainstLocalUserDb(ctx) {
console.log('Authenticate against localDB');
if ( !ctx.credentials.username || !ctx.credentials.password) {
ctx.userInfo = null;
return ctx;
}
if ( !localUserDb) {
throw new Error("localUserDb is null.");
}
console.log('Authenticate %s/%s against localDB', ctx.credentials.username, ctx.credentials.password);
var storedRecord = localUserDb[ctx.credentials.username];
if (storedRecord && storedRecord.password) {
console.log('authenticateAgainstLocalUserDb: user has been found');
if (storedRecord.password == ctx.credentials.password) {
console.log('authenticateAgainstLocalUserDb: user is authentic');
var copy = shallowCopyObject(storedRecord);
delete(copy.password);
copy.email = ctx.credentials.username;
ctx.loginStatus = 200;
ctx.userInfo = copy;
}
else {
console.log('authenticateAgainstLocalUserDb: user is not authentic');
ctx.loginStatus = 401;
}
}
else {
ctx.loginStatus = 401;
}
return Promise.resolve(ctx);
}
function shallowCopyObject(obj) {
var copy = {};
if (null !== obj && typeof obj == "object") {
Object.keys(obj).forEach(function(attr){copy[attr] = obj[attr];});
}
return copy;
}
module.exports = {
fake : {
config: configureNoop,
authn: alwaysAuthenticateSuccessfully
},
local : {
config: configureLocalAuth,
authn: authenticateAgainstLocalUserDb
}
};
}(this));
|
//>>built
define("dijit/_editor/nls/th/commands",({"bold":"ตัวหนา","copy":"คัดลอก","cut":"ตัด","delete":"ลบ","indent":"เพิ่มการเยื้อง","insertHorizontalRule":"ไม้บรรทัดแนวนอน","insertOrderedList":"ลำดับเลข","insertUnorderedList":"หัวข้อย่อย","italic":"ตัวเอียง","justifyCenter":"จัดแนวกึ่งกลาง","justifyFull":"ชิดขอบ","justifyLeft":"จัดชิดซ้าย","justifyRight":"จัดชิดขวา","outdent":"ลดการเยื้อง","paste":"วาง","redo":"ทำซ้ำ","removeFormat":"ลบรูปแบบออก","selectAll":"เลือกทั้งหมด","strikethrough":"ขีดทับ","subscript":"ตัวห้อย","superscript":"ตัวยก","underline":"ขีดเส้นใต้","undo":"เลิกทำ","unlink":"ลบลิงก์ออก","createLink":"สร้างลิงก์","toggleDir":"สลับทิศทาง","insertImage":"แทรกรูปภาพ","insertTable":"แทรก/แก้ไขตาราง","toggleTableBorder":"สลับเส้นขอบตาราง","deleteTable":"ลบตาราง","tableProp":"คุณสมบัติตาราง","htmlToggle":"ซอร์ส HTML","foreColor":"สีพื้นหน้า","hiliteColor":"สีพื้นหลัง","plainFormatBlock":"ลักษณะย่อหน้า","formatBlock":"ลักษณะย่อหน้า","fontSize":"ขนาดฟอนต์","fontName":"ชื่อฟอนต์","tabIndent":"เยื้องแท็บ","fullScreen":"สลับจอภาพแบบเต็ม","viewSource":"ดูซอร์ส HTML","print":"พิมพ์","newPage":"หน้าใหม่","systemShortcut":"แอ็กชัน \"${0}\" ใช้งานได้เฉพาะกับเบราว์เซอร์ของคุณโดยใช้แป้นพิมพ์ลัด ใช้ ${1}","ctrlKey":"ctrl+${0}","appleKey":"⌘${0}"}));
|
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
import React, { Component } from 'react';
import styled from 'styled-components';
import { hsv } from 'd3-hsv';
import { canvasMargin, canvasRadius, clearCanvas, drawColorWheelIntoCanvasImage, eventCartesianPosition, } from './canvas_utils';
import { cartesian2hsv, generateColorWheel, hsv2cartesian, } from './color_wheel_utils';
import { diameter, limitByRadius, translateDiagonal, } from './math_utils';
var ColorWheel = (function (_super) {
__extends(ColorWheel, _super);
function ColorWheel() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.isMouseDragging = false;
_this.setColorWheelCanvasRef = function (element) {
_this.colorWheelCanvas = element;
};
_this.setValueCanvasRef = function (element) {
_this.valueCanvas = element;
};
_this.setCompositeCanvasRef = function (element) {
_this.compositeCanvas = element;
};
_this.setMarkerCanvasRef = function (element) {
_this.markerCanvas = element;
};
_this.mouseDown = function (event) {
_this.setMouseDragging(true);
var canvasCartesian = eventCartesianPosition(_this.colorWheelCanvas, event);
var position = limitByRadius(translateDiagonal(-canvasMargin, canvasCartesian), _this.radius);
_this.updateColor(position, _this.props.onColorChange);
};
_this.mouseMove = function (event) {
if (_this.isMouseDragging) {
var canvasCartesian = eventCartesianPosition(_this.colorWheelCanvas, event);
var position = limitByRadius(translateDiagonal(-canvasMargin, canvasCartesian), _this.radius);
_this.updateColor(position, _this.props.onColorChange);
}
};
_this.setMouseDragging = function (isDragging) {
_this.isMouseDragging = isDragging;
};
_this.drawValueLayer = function () {
clearCanvas(_this.valueCanvas);
var ctx = _this.valueCanvas.getContext('2d');
var centerX = _this.valueCanvas.width / 2;
var centerY = _this.valueCanvas.height / 2;
if (ctx) {
var _a = hsv(0, 0, _this.props.value).rgb(), r = _a.r, g = _a.g, b = _a.b;
ctx.beginPath();
ctx.arc(centerX, centerY, _this.radius, 0, 2 * Math.PI, false);
ctx.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = '#ffffff';
ctx.stroke();
}
};
_this.drawCompositeCanvas = function () {
clearCanvas(_this.compositeCanvas);
var ctx = _this.compositeCanvas.getContext('2d');
if (ctx) {
ctx.globalCompositeOperation = 'multiply';
ctx.drawImage(_this.colorWheelCanvas, 0, 0);
ctx.drawImage(_this.valueCanvas, 0, 0);
}
};
return _this;
}
ColorWheel.prototype.componentDidMount = function () {
this.drawWheel();
this.drawValueLayer();
this.drawCompositeCanvas();
this.drawMouseMarker();
};
ColorWheel.prototype.componentDidUpdate = function () {
this.drawValueLayer();
this.drawCompositeCanvas();
this.drawMouseMarker();
};
ColorWheel.prototype.render = function () {
return (React.createElement(ColorWheelWrapper, { size: this.props.size },
React.createElement(Canvas, { ref: this.setColorWheelCanvasRef, width: this.props.size, height: this.props.size }),
React.createElement(Canvas, { ref: this.setValueCanvasRef, width: this.props.size, height: this.props.size }),
React.createElement(Canvas, { ref: this.setCompositeCanvasRef, width: this.props.size, height: this.props.size }),
React.createElement(Canvas, { "data-testid": "mouse-marker", ref: this.setMarkerCanvasRef, width: this.props.size, height: this.props.size, onMouseDown: this.mouseDown, onMouseMove: this.mouseMove, onMouseUp: this.setMouseDragging.bind(this, false), onMouseLeave: this.setMouseDragging.bind(this, false) })));
};
Object.defineProperty(ColorWheel.prototype, "radius", {
get: function () {
return this.colorWheelCanvas
? canvasRadius(this.colorWheelCanvas, canvasMargin)
: 0;
},
enumerable: true,
configurable: true
});
ColorWheel.prototype.drawWheel = function () {
var ctx = this.colorWheelCanvas.getContext('2d');
if (!ctx)
return;
var image = this.getColorWheelImage();
if (image) {
ctx.putImageData(image, canvasMargin, canvasMargin);
}
ctx.beginPath();
ctx.arc(this.colorWheelCanvas.width / 2, this.colorWheelCanvas.width / 2, this.radius, 0, 2 * Math.PI, false);
ctx.lineWidth = 3;
ctx.strokeStyle = '#ffffff';
ctx.stroke();
};
ColorWheel.prototype.getColorWheelImage = function () {
var ctx = this.colorWheelCanvas.getContext('2d');
if (!this.colorWheelImage && ctx) {
var colorValue = 1;
this.colorWheelImage = ctx.createImageData(diameter(this.radius), diameter(this.radius));
drawColorWheelIntoCanvasImage(this.colorWheelImage.data, generateColorWheel(this.radius, colorValue));
}
return this.colorWheelImage;
};
ColorWheel.prototype.drawMouseMarker = function () {
clearCanvas(this.markerCanvas);
var canvasCartesian = hsv2cartesian(this.radius, {
h: this.props.hue,
s: this.props.saturation,
v: this.props.value,
});
var mousePosition = translateDiagonal(canvasMargin, canvasCartesian);
var ctx = this.markerCanvas.getContext('2d');
if (ctx && mousePosition) {
var mouseRadius = 4;
ctx.beginPath();
ctx.arc(mousePosition.x, mousePosition.y, mouseRadius, 0, 2 * Math.PI, false);
ctx.lineWidth = 3;
ctx.strokeStyle = '#FFFFFF';
ctx.stroke();
ctx.beginPath();
ctx.arc(mousePosition.x, mousePosition.y, mouseRadius - 1, 0, 2 * Math.PI, false);
ctx.lineWidth = 2;
ctx.strokeStyle = '#000000';
ctx.stroke();
}
};
ColorWheel.prototype.updateColor = function (position, callback) {
if (callback && position) {
var color = cartesian2hsv(this.props.value, this.radius, position);
var updateColorValues = { h: color.h, s: color.s };
callback(updateColorValues);
}
};
ColorWheel.defaultProps = {
hue: 0,
saturation: 1,
size: 100,
value: 1,
};
return ColorWheel;
}(Component));
export { ColorWheel };
var ColorWheelWrapper = styled.div.withConfig({ displayName: "ColorWheelWrapper", componentId: "sc-a42q5" })(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n position: relative;\n width: ", "px;\n height: ", "px;\n"], ["\n position: relative;\n width: ", "px;\n height: ", "px;\n"])), function (_a) {
var size = _a.size;
return size;
}, function (_a) {
var size = _a.size;
return size;
});
var Canvas = styled.canvas.withConfig({ displayName: "Canvas", componentId: "sc-xapbr" })(templateObject_2 || (templateObject_2 = __makeTemplateObject(["\n position: absolute;\n left: 0;\n top: 0;\n"], ["\n position: absolute;\n left: 0;\n top: 0;\n"])));
var templateObject_1, templateObject_2;
//# sourceMappingURL=ColorWheel.js.map |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI } from './uri.js';
import * as platform from './platform.js';
export var Schemas;
(function (Schemas) {
/**
* A schema that is used for models that exist in memory
* only and that have no correspondence on a server or such.
*/
Schemas.inMemory = 'inmemory';
/**
* A schema that is used for setting files
*/
Schemas.vscode = 'vscode';
/**
* A schema that is used for internal private files
*/
Schemas.internal = 'private';
/**
* A walk-through document.
*/
Schemas.walkThrough = 'walkThrough';
/**
* An embedded code snippet.
*/
Schemas.walkThroughSnippet = 'walkThroughSnippet';
Schemas.http = 'http';
Schemas.https = 'https';
Schemas.file = 'file';
Schemas.mailto = 'mailto';
Schemas.untitled = 'untitled';
Schemas.data = 'data';
Schemas.command = 'command';
Schemas.vscodeRemote = 'vscode-remote';
Schemas.vscodeRemoteResource = 'vscode-remote-resource';
Schemas.userData = 'vscode-userdata';
Schemas.vscodeCustomEditor = 'vscode-custom-editor';
Schemas.vscodeNotebook = 'vscode-notebook';
Schemas.vscodeNotebookCell = 'vscode-notebook-cell';
Schemas.vscodeNotebookCellMetadata = 'vscode-notebook-cell-metadata';
Schemas.vscodeSettings = 'vscode-settings';
Schemas.vscodeWorkspaceTrust = 'vscode-workspace-trust';
Schemas.webviewPanel = 'webview-panel';
/**
* Scheme used for loading the wrapper html and script in webviews.
*/
Schemas.vscodeWebview = 'vscode-webview';
/**
* Scheme used for loading resources inside of webviews.
*/
Schemas.vscodeWebviewResource = 'vscode-webview-resource';
/**
* Scheme used for extension pages
*/
Schemas.extension = 'extension';
/**
* Scheme used as a replacement of `file` scheme to load
* files with our custom protocol handler (desktop only).
*/
Schemas.vscodeFileResource = 'vscode-file';
})(Schemas || (Schemas = {}));
class RemoteAuthoritiesImpl {
constructor() {
this._hosts = Object.create(null);
this._ports = Object.create(null);
this._connectionTokens = Object.create(null);
this._preferredWebSchema = 'http';
this._delegate = null;
}
setPreferredWebSchema(schema) {
this._preferredWebSchema = schema;
}
rewrite(uri) {
if (this._delegate) {
return this._delegate(uri);
}
const authority = uri.authority;
let host = this._hosts[authority];
if (host && host.indexOf(':') !== -1) {
host = `[${host}]`;
}
const port = this._ports[authority];
const connectionToken = this._connectionTokens[authority];
let query = `path=${encodeURIComponent(uri.path)}`;
if (typeof connectionToken === 'string') {
query += `&tkn=${encodeURIComponent(connectionToken)}`;
}
return URI.from({
scheme: platform.isWeb ? this._preferredWebSchema : Schemas.vscodeRemoteResource,
authority: `${host}:${port}`,
path: `/vscode-remote-resource`,
query
});
}
}
export const RemoteAuthorities = new RemoteAuthoritiesImpl();
class FileAccessImpl {
constructor() {
this.FALLBACK_AUTHORITY = 'vscode-app';
}
asBrowserUri(uriOrModule, moduleIdToUrl, __forceCodeFileUri) {
const uri = this.toUri(uriOrModule, moduleIdToUrl);
// Handle remote URIs via `RemoteAuthorities`
if (uri.scheme === Schemas.vscodeRemote) {
return RemoteAuthorities.rewrite(uri);
}
// Only convert the URI if we are in a native context and it has `file:` scheme
// and we have explicitly enabled the conversion (sandbox, or ENABLE_VSCODE_BROWSER_CODE_LOADING)
if (platform.isNative && (__forceCodeFileUri || platform.isPreferringBrowserCodeLoad) && uri.scheme === Schemas.file) {
return uri.with({
scheme: Schemas.vscodeFileResource,
// We need to provide an authority here so that it can serve
// as origin for network and loading matters in chromium.
// If the URI is not coming with an authority already, we
// add our own
authority: uri.authority || this.FALLBACK_AUTHORITY,
query: null,
fragment: null
});
}
return uri;
}
toUri(uriOrModule, moduleIdToUrl) {
if (URI.isUri(uriOrModule)) {
return uriOrModule;
}
return URI.parse(moduleIdToUrl.toUrl(uriOrModule));
}
}
export const FileAccess = new FileAccessImpl();
|
# Copyright (C) 2022, Arijit Das.
# Code adapted from doctr and huggingface
# This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
from typing import Any, List, Union
import numpy as np
import torch
from torch import nn
from deepocr.models.preprocessor import PreProcessor
__all__ = ['DetectionPredictor']
class DetectionPredictor(nn.Module):
"""Implements an object able to localize text elements in a document
Args:
pre_processor: transform inputs for easier batched model inference
model: core detection architecture
"""
def __init__(
self,
pre_processor: PreProcessor,
model: nn.Module,
) -> None:
super().__init__()
self.pre_processor = pre_processor
self.model = model.eval()
@torch.no_grad()
def forward(
self,
pages: List[Union[np.ndarray, torch.Tensor]],
**kwargs: Any,
) -> List[np.ndarray]:
# Dimension check
if any(page.ndim != 3 for page in pages):
raise ValueError("incorrect input shape: all pages are expected to be multi-channel 2D images.")
processed_batches = self.pre_processor(pages)
_device = next(self.model.parameters()).device
predicted_batches = [
self.model(batch.to(device=_device), return_preds=True, **kwargs)['preds'] # type:ignore[operator]
for batch in processed_batches
]
return [pred for batch in predicted_batches for pred in batch]
|
/*
* Arm SCP/MCP Software
* Copyright (c) 2020, Arm Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Description:
* ROM firmware memory layout for the linker script.
*/
#ifndef FMW_MEMORY_H
#define FMW_MEMORY_H
#include "scp_mmap.h"
#include "scp_software_mmap.h"
#define FIRMWARE_MEM_MODE FWK_MEM_MODE_DUAL_REGION_RELOCATION
/*
* ROM memory
*/
#define FIRMWARE_MEM0_SIZE SCP_BOOT_ROM_SIZE
#define FIRMWARE_MEM0_BASE SCP_BOOT_ROM_BASE
/*
* RAM memory
*/
#define FIRMWARE_MEM1_SIZE SCP_DTC_RAM_SIZE
#define FIRMWARE_MEM1_BASE SCP_DTC_RAM_BASE
#define FIRMWARE_STACK_SIZE (1 * 1024)
#endif /* FMW_MEMORY_H */
|
//
// UIColor+LNHexString.h
// LNCategories
//
// Created by 童玉龙 on 2017/7/19.
// Copyright © 2017年 Lengain. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIColor (LNHexString)
+ (UIColor *)ln_colorWithHexString:(NSString *)color;
+ (UIColor *)ln_colorWithHexString:(NSString *)color alpha:(CGFloat)alpha;
@end
|
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const env = require('../config/prod.env')
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[hash].css'),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true,
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
// new OptimizeCSSPlugin({
// cssProcessorOptions: config.build.productionSourceMap
// ? { safe: true, map: { inline: false } }
// : { safe: true }
// }),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// keep module.id stable when vendor modules does not change
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// split vendor js into its own file
// new webpack.optimize.CommonsChunkPlugin({
// name: 'vendor',
// minChunks (module) {
// // any required modules inside node_modules are extracted to vendor
// return (
// module.resource &&
// /\.js$/.test(module.resource) &&
// module.resource.indexOf(
// path.join(__dirname, '../node_modules')
// ) === 0
// )
// }
// }),
// // extract webpack runtime and module manifest to its own file in order to
// // prevent vendor hash from being updated whenever app bundle is updated
// new webpack.optimize.CommonsChunkPlugin({
// name: 'manifest',
// minChunks: Infinity
// }),
// // This instance extracts shared chunks from code splitted chunks and bundles them
// // in a separate chunk, similar to the vendor chunk
// // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
// new webpack.optimize.CommonsChunkPlugin({
// name: 'app',
// async: 'vendor-async',
// children: true,
// minChunks: 3
// }),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
],
optimization: {
splitChunks: {
cacheGroups: {
commons: {
name: "commons",
chunks: "initial",
minChunks: 2
}
}
}
},
})
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
|
from functools import lru_cache
from host.models import PkeyModel
class AppSetting():
keys = ('public_key', 'private_key')
@classmethod
@lru_cache(maxsize=64)
def get(cls, name):
"""获取秘钥对"""
info = PkeyModel.objects.filter(name=name).first()
if not info:
raise KeyError(f'没有这个 {name!r} 秘钥对')
# 以元组格式,返回公私钥
return (info.private, info.public)
@classmethod
def set(cls, name, private_key, public_key, description=None):
"""保存秘钥对"""
PkeyModel.objects.update_or_create(name=name, defaults={
'private': private_key,
'public': public_key,
'description': description
})
|
#!/usr/bin/env python3
# @generated AUTOGENERATED file. Do not Change!
from dataclasses import dataclass
from datetime import datetime
from gql.gql.datetime_utils import DATETIME_FIELD
from gql.gql.graphql_client import GraphqlClient
from gql.gql.client import OperationException
from gql.gql.reporter import FailedOperationException
from functools import partial
from numbers import Number
from typing import Any, Callable, List, Mapping, Optional, Dict
from time import perf_counter
from dataclasses_json import DataClassJsonMixin
from ..fragment.equipment import EquipmentFragment, QUERY as EquipmentFragmentQuery
from ..input.equipment_filter import EquipmentFilterInput
QUERY: List[str] = EquipmentFragmentQuery + ["""
query EquipmentSearchQuery($filters: [EquipmentFilterInput!]!, $limit: Int) {
equipments(filterBy: $filters, first: $limit) {
edges {
node {
...EquipmentFragment
}
}
totalCount
}
}
"""]
@dataclass
class EquipmentSearchQuery(DataClassJsonMixin):
@dataclass
class EquipmentSearchQueryData(DataClassJsonMixin):
@dataclass
class EquipmentConnection(DataClassJsonMixin):
@dataclass
class EquipmentEdge(DataClassJsonMixin):
@dataclass
class Equipment(EquipmentFragment):
pass
node: Optional[Equipment]
edges: List[EquipmentEdge]
totalCount: int
equipments: EquipmentConnection
data: EquipmentSearchQueryData
@classmethod
# fmt: off
def execute(cls, client: GraphqlClient, filters: List[EquipmentFilterInput] = [], limit: Optional[int] = None) -> EquipmentSearchQueryData.EquipmentConnection:
# fmt: off
variables: Dict[str, Any] = {"filters": filters, "limit": limit}
try:
network_start = perf_counter()
response_text = client.call(''.join(set(QUERY)), variables=variables)
decode_start = perf_counter()
res = cls.from_json(response_text).data
decode_time = perf_counter() - decode_start
network_time = decode_start - network_start
client.reporter.log_successful_operation("EquipmentSearchQuery", variables, network_time, decode_time)
return res.equipments
except OperationException as e:
raise FailedOperationException(
client.reporter,
e.err_msg,
e.err_id,
"EquipmentSearchQuery",
variables,
)
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.20
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from kubernetes.client.configuration import Configuration
class V1AttachedVolume(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'device_path': 'str',
'name': 'str'
}
attribute_map = {
'device_path': 'devicePath',
'name': 'name'
}
def __init__(self, device_path=None, name=None, local_vars_configuration=None): # noqa: E501
"""V1AttachedVolume - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._device_path = None
self._name = None
self.discriminator = None
self.device_path = device_path
self.name = name
@property
def device_path(self):
"""Gets the device_path of this V1AttachedVolume. # noqa: E501
DevicePath represents the device path where the volume should be available # noqa: E501
:return: The device_path of this V1AttachedVolume. # noqa: E501
:rtype: str
"""
return self._device_path
@device_path.setter
def device_path(self, device_path):
"""Sets the device_path of this V1AttachedVolume.
DevicePath represents the device path where the volume should be available # noqa: E501
:param device_path: The device_path of this V1AttachedVolume. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and device_path is None: # noqa: E501
raise ValueError("Invalid value for `device_path`, must not be `None`") # noqa: E501
self._device_path = device_path
@property
def name(self):
"""Gets the name of this V1AttachedVolume. # noqa: E501
Name of the attached volume # noqa: E501
:return: The name of this V1AttachedVolume. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this V1AttachedVolume.
Name of the attached volume # noqa: E501
:param name: The name of this V1AttachedVolume. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and name is None: # noqa: E501
raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501
self._name = name
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1AttachedVolume):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1AttachedVolume):
return True
return self.to_dict() != other.to_dict()
|
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const RobustCalculator = require("./calculators/RobustCalculator");
const SimpleRateCalculator_1 = require("./calculators/SimpleRateCalculator");
__export(require("./FXService"));
__export(require("./FXRateCalculator"));
__export(require("./FXProvider"));
const CoinMarketCapProvider = require("./providers/CoinMarketCapProvider");
const OpenExchangeProvider = require("./providers/OpenExchangeProvider");
const YahooFXProvider = require("./providers/YahooFXProvider");
const CryptoProvider = require("./providers/CryptoProvider");
const FailoverProvider_1 = require("./providers/FailoverProvider");
const FailoverCalculator_1 = require("./calculators/FailoverCalculator");
exports.Providers = {
CoinMarketCapProvider,
OpenExchangeProvider,
YahooFXProvider,
CryptoProvider,
FailoverProvider: FailoverProvider_1.FailoverProvider
};
exports.Calculators = {
SimpleRateCalculator: SimpleRateCalculator_1.default,
RobustCalculator,
FailoverCalculator: FailoverCalculator_1.default
};
//# sourceMappingURL=index.js.map |
import { APP_SETTING } from "../../achievementsApp/config";
import {
DISPLAY_NAME_UPDATE_REQUEST,
EXTERNAL_PROFILE_REFRESH_REQUEST,
EXTERNAL_PROFILE_REMOVE_REQUEST,
EXTERNAL_PROFILE_UPDATE_REQUEST,
displayNameEditToggle,
displayNameUpdateFail,
displayNameUpdateSuccess,
externalProfileDialogHide,
externalProfileRefreshFail,
externalProfileRefreshRequest,
externalProfileRefreshSuccess,
externalProfileRemoveFail,
externalProfileRemoveSuccess,
externalProfileUpdateFail,
externalProfileUpdateSuccess,
accountChangeAdminStatus,
PROFILE_UPDATE_DATA_REQUEST,
profileUpdateDataFail,
profileUpdateDataSuccess,
ACCOUNT_OPEN,
accountFetchPaths,
FETCH_USER_DATA,
fetchUserDataFail,
INSPECT_PATH_AS_USER
} from "./actions";
import { accountService } from "../../services/account";
import { call, put, race, select, take, takeLatest } from "redux-saga/effects";
import { delay } from "redux-saga";
import { push } from "connected-react-router";
import { notificationShow } from "../Root/actions";
import {
getDynamicPathtitle,
GET_DYNAMIC_PATHTITLE,
SAVE_PROMO_CODE,
ROUTES_CHANGED
} from "../AppFrame/actions";
import download from "downloadjs";
function* signInHandler() {
const uid = yield select(state => state.firebase.auth.uid);
const promocode = yield select(state => state.appFrame.promocode);
try {
if (uid) {
if (promocode) {
yield call(accountService.savePromoCode, {
uid,
promocode,
type: SAVE_PROMO_CODE
});
}
const adminStatus = yield call(accountService.checkAdminStatus, uid);
yield call(accountService.authTimeUpdate, uid);
yield put(accountChangeAdminStatus(adminStatus));
} else {
yield put(accountChangeAdminStatus(false));
}
} catch (err) {
accountChangeAdminStatus(false, err.message);
}
}
function* accountOpenHandler(action) {
let uid = yield select(state => state.firebase.auth.uid);
if (!uid) {
yield take("@@reactReduxFirebase/LOGIN");
uid = yield select(state => state.firebase.auth.uid);
}
try {
const paths = yield call(accountService.fetchJoinedPaths, action.accountId);
if (!paths) {
yield put(notificationShow("Wrong user ID. Redirecting to your profile"));
yield put(push(`/profile/${uid}`));
} else {
yield put(accountFetchPaths(action.accountId, paths));
}
} catch (err) {
yield put(notificationShow(err.message));
}
}
function* inspectPathAsUserHandler(action) {
const user = yield select(state => state.firebase.data.users[action.userId]);
yield put(push(`/paths/${action.pathId}`));
yield take(GET_DYNAMIC_PATHTITLE);
yield put(getDynamicPathtitle(`Path (as ${user.displayName})`));
}
function* externalProfileUpdateRequestHandler(action) {
try {
let error = "";
const uid = yield select(
state => action.customUID || state.firebase.auth.uid
);
yield call(
accountService.addExternalProfile,
action.externalProfileType,
uid,
action.externalProfileId
);
yield put(
externalProfileRefreshRequest(
action.externalProfileId,
action.externalProfileType,
action.customUID
)
);
const { response, timedOut } = yield race({
response: call(
[accountService, accountService.watchProfileRefresh],
uid,
action.externalProfileType
),
timedOut: call(delay, APP_SETTING.defaultTimeout)
});
if (timedOut) {
error = "Profile refreshing timed out";
} else if (!response) {
error = "Invalid CodeCombat username provided";
}
if (error) {
yield put(
externalProfileUpdateFail(
action.externalProfileId,
action.externalProfileType,
error
)
);
return yield put(notificationShow(error));
}
yield put(
externalProfileUpdateSuccess(
action.externalProfileId,
action.externalProfileType
)
);
yield put(externalProfileDialogHide());
} catch (err) {
yield put(
externalProfileUpdateFail(
action.externalProfileId,
action.externalProfileType,
err.message
)
);
yield put(notificationShow(err.message));
}
}
function* externalProfileRefreshRequestHandler(action) {
try {
const uid = yield select(
state => action.customUID || state.firebase.auth.uid
);
yield call(
accountService.refreshAchievements,
action.externalProfileType,
uid,
action.externalProfileId
);
yield put(
notificationShow(
`Refreshing ${action.externalProfileType} Achievements...`
)
);
const result = yield race({
response: call(
[accountService, accountService.watchProfileRefresh],
uid,
action.externalProfileType
),
timedOut: call(delay, APP_SETTING.defaultTimeout)
});
if (result.timedOut) {
const error = "Profile refresh timed out";
yield put(
externalProfileRefreshFail(
action.externalProfileId,
action.externalProfileType,
error
)
);
return yield put(notificationShow(error));
}
if (result.response) {
yield put(
externalProfileRefreshSuccess(
action.externalProfileId,
action.externalProfileType
)
);
}
} catch (err) {
yield put(
externalProfileRefreshFail(
action.externalProfileId,
action.externalProfileType,
err.message
)
);
}
}
function* externalProfileRemoveRequestHandler(action) {
try {
const uid = yield select(state => state.firebase.auth.uid);
yield call(
accountService.removeExternalProfile,
action.externalProfileType,
uid
);
yield put(externalProfileRemoveSuccess(action.externalProfileType));
} catch (err) {
yield put(
externalProfileRemoveFail(action.externalProfileType, err.message)
);
}
}
function* profileUpdateDataRequestHandler(action) {
try {
const uid = yield select(state => state.firebase.auth.uid);
accountService.updateProfileData(
action.customUID || uid,
action.field,
action.data
);
yield put(
profileUpdateDataSuccess(
action.field,
action.data,
action.customUID || uid
)
);
} catch (err) {
yield put(profileUpdateDataFail(action.field, action.data, err.message));
yield put(notificationShow(err.message));
}
}
function* displayNameUpdateRequestHandler(action) {
const uid = yield select(state => state.firebase.auth.uid);
try {
yield call(accountService.updateDisplayName, uid, action.name);
yield put(displayNameUpdateSuccess());
yield put(displayNameEditToggle(false));
} catch (err) {
yield put(displayNameUpdateFail(err.message));
yield put(notificationShow(err.message));
}
}
function* fetchUserDataHandler() {
const uid = yield select(state => state.firebase.auth.uid);
try {
const userData = yield call(accountService.fetchUserJSON, uid);
download(
JSON.stringify(userData.data, null, 2),
"user-achievements.json",
"text/plain"
);
} catch (err) {
yield put(fetchUserDataFail(err.message));
}
}
function* routeChangeHandler(action){
try {
const uid = yield select(state => state.firebase.auth.uid);
const promocode = yield select(state => state.appFrame.promocode);
if (uid && promocode) {
yield call(accountService.saveNavigationChange, {
uid,
promocode,
pathName : action.pathName
});
}
} catch (err) {
// do nothing
}
}
export default [
function* watchSignIn() {
yield takeLatest("@@reactReduxFirebase/LOGIN", signInHandler);
},
function* watchAccountOpen() {
yield takeLatest(ACCOUNT_OPEN, accountOpenHandler);
},
function* watchInspectPathAsUser() {
yield takeLatest(INSPECT_PATH_AS_USER, inspectPathAsUserHandler);
},
function* watchExternalProfileUpdateRequest() {
yield takeLatest(
EXTERNAL_PROFILE_UPDATE_REQUEST,
externalProfileUpdateRequestHandler
);
},
function* watchExternalProfileRefreshRequest() {
yield takeLatest(
EXTERNAL_PROFILE_REFRESH_REQUEST,
externalProfileRefreshRequestHandler
);
},
function* watchExternalProfileRemoveRequest() {
yield takeLatest(
EXTERNAL_PROFILE_REMOVE_REQUEST,
externalProfileRemoveRequestHandler
);
},
function* watchProfileUpdateDataRequest() {
yield takeLatest(
PROFILE_UPDATE_DATA_REQUEST,
profileUpdateDataRequestHandler
);
},
function* watchDisplayNameUpdateRequest() {
yield takeLatest(
DISPLAY_NAME_UPDATE_REQUEST,
displayNameUpdateRequestHandler
);
},
function* watchFetchUserData() {
yield takeLatest(FETCH_USER_DATA, fetchUserDataHandler);
},
function* watchRouteChange(){
yield takeLatest(ROUTES_CHANGED, routeChangeHandler);
}
];
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.14.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes.client.models.v1alpha1_audit_sink_spec import V1alpha1AuditSinkSpec
class TestV1alpha1AuditSinkSpec(unittest.TestCase):
""" V1alpha1AuditSinkSpec unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV1alpha1AuditSinkSpec(self):
"""
Test V1alpha1AuditSinkSpec
"""
# FIXME: construct object with mandatory attributes with example values
#model = kubernetes.client.models.v1alpha1_audit_sink_spec.V1alpha1AuditSinkSpec()
pass
if __name__ == '__main__':
unittest.main()
|
//
// FKFlickrGroupsJoin.h
// FlickrKit
//
// Generated by FKAPIBuilder.
// Copyright (c) 2013 DevedUp Ltd. All rights reserved. http://www.devedup.com
//
// DO NOT MODIFY THIS FILE - IT IS MACHINE GENERATED
#import "FKFlickrAPIMethod.h"
typedef NS_ENUM(NSInteger, FKFlickrGroupsJoinError) {
FKFlickrGroupsJoinError_RequiredArgumentsMissing = 1, /* The group_id doesn't exist */
FKFlickrGroupsJoinError_GroupDoesNotExist = 2, /* The Group does not exist */
FKFlickrGroupsJoinError_GroupNotAvailabieToTheAccount = 3, /* The authed account does not have permission to view/join the group. */
FKFlickrGroupsJoinError_AccountIsAlreadyInThatGroup = 4, /* The authed account has previously joined this group */
FKFlickrGroupsJoinError_MembershipInGroupIsByInvitationOnly = 5, /* Use flickr.groups.joinRequest to contact the administrations for an invitation. */
FKFlickrGroupsJoinError_UserMustAcceptTheGroupRulesBeforeJoining = 6, /* The user must read and accept the rules before joining. Please see the accept_rules argument for this method. */
FKFlickrGroupsJoinError_AccountInMaximumNumberOfGroups = 10, /* The account is a member of the maximum number of groups. */
FKFlickrGroupsJoinError_UserUnableToJoin = 11, /* This user is unable to join this group. */
FKFlickrGroupsJoinError_SSLIsRequired = 95, /* SSL is required to access the Flickr API. */
FKFlickrGroupsJoinError_InvalidSignature = 96, /* The passed signature was invalid. */
FKFlickrGroupsJoinError_MissingSignature = 97, /* The call required signing but no signature was sent. */
FKFlickrGroupsJoinError_LoginFailedOrInvalidAuthToken = 98, /* The login details or auth token passed were invalid. */
FKFlickrGroupsJoinError_UserNotLoggedInOrInsufficientPermissions = 99, /* The method requires user authentication but the user was not logged in, or the authenticated method call did not have the required permissions. */
FKFlickrGroupsJoinError_InvalidAPIKey = 100, /* The API key passed was not valid or has expired. */
FKFlickrGroupsJoinError_ServiceCurrentlyUnavailable = 105, /* The requested service is temporarily unavailable. */
FKFlickrGroupsJoinError_WriteOperationFailed = 106, /* The requested operation failed due to a temporary issue. */
FKFlickrGroupsJoinError_FormatXXXNotFound = 111, /* The requested response format was not found. */
FKFlickrGroupsJoinError_MethodXXXNotFound = 112, /* The requested method was not found. */
FKFlickrGroupsJoinError_InvalidSOAPEnvelope = 114, /* The SOAP envelope send in the request could not be parsed. */
FKFlickrGroupsJoinError_InvalidXMLRPCMethodCall = 115, /* The XML-RPC request document could not be parsed. */
FKFlickrGroupsJoinError_BadURLFound = 116, /* One or more arguments contained a URL that has been used for abuse on Flickr. */
};
/*
Join a public group as a member.
*/
@interface FKFlickrGroupsJoin : NSObject <FKFlickrAPIMethod>
/* The NSID of the Group in question */
@property (nonatomic, copy) NSString *group_id; /* (Required) */
/* If the group has rules, they must be displayed to the user prior to joining. Passing a true value for this argument specifies that the application has displayed the group rules to the user, and that the user has agreed to them. (See flickr.groups.getInfo). */
@property (nonatomic, copy) NSString *accept_rules;
@end
|
from __future__ import division, absolute_import, print_function
import collections
import tempfile
import sys
import shutil
import warnings
import operator
import io
import itertools
import ctypes
import os
if sys.version_info[0] >= 3:
import builtins
else:
import __builtin__ as builtins
from decimal import Decimal
import numpy as np
from numpy.compat import asbytes, getexception, strchar, unicode, sixu
from test_print import in_foreign_locale
from numpy.core.multiarray_tests import (
test_neighborhood_iterator, test_neighborhood_iterator_oob,
test_pydatamem_seteventhook_start, test_pydatamem_seteventhook_end,
test_inplace_increment, get_buffer_info, test_as_c_array
)
from numpy.testing import (
TestCase, run_module_suite, assert_, assert_raises,
assert_equal, assert_almost_equal, assert_array_equal,
assert_array_almost_equal, assert_allclose,
assert_array_less, runstring, dec, SkipTest
)
# Need to test an object that does not fully implement math interface
from datetime import timedelta
if sys.version_info[:2] > (3, 2):
# In Python 3.3 the representation of empty shape, strides and sub-offsets
# is an empty tuple instead of None.
# http://docs.python.org/dev/whatsnew/3.3.html#api-changes
EMPTY = ()
else:
EMPTY = None
class TestFlags(TestCase):
def setUp(self):
self.a = np.arange(10)
def test_writeable(self):
mydict = locals()
self.a.flags.writeable = False
self.assertRaises(ValueError, runstring, 'self.a[0] = 3', mydict)
self.assertRaises(ValueError, runstring, 'self.a[0:1].itemset(3)', mydict)
self.a.flags.writeable = True
self.a[0] = 5
self.a[0] = 0
def test_otherflags(self):
assert_equal(self.a.flags.carray, True)
assert_equal(self.a.flags.farray, False)
assert_equal(self.a.flags.behaved, True)
assert_equal(self.a.flags.fnc, False)
assert_equal(self.a.flags.forc, True)
assert_equal(self.a.flags.owndata, True)
assert_equal(self.a.flags.writeable, True)
assert_equal(self.a.flags.aligned, True)
assert_equal(self.a.flags.updateifcopy, False)
def test_string_align(self):
a = np.zeros(4, dtype=np.dtype('|S4'))
assert_(a.flags.aligned)
# not power of two are accessed byte-wise and thus considered aligned
a = np.zeros(5, dtype=np.dtype('|S4'))
assert_(a.flags.aligned)
def test_void_align(self):
a = np.zeros(4, dtype=np.dtype([("a", "i4"), ("b", "i4")]))
assert_(a.flags.aligned)
class TestHash(TestCase):
# see #3793
def test_int(self):
for st, ut, s in [(np.int8, np.uint8, 8),
(np.int16, np.uint16, 16),
(np.int32, np.uint32, 32),
(np.int64, np.uint64, 64)]:
for i in range(1, s):
assert_equal(hash(st(-2**i)), hash(-2**i),
err_msg="%r: -2**%d" % (st, i))
assert_equal(hash(st(2**(i - 1))), hash(2**(i - 1)),
err_msg="%r: 2**%d" % (st, i - 1))
assert_equal(hash(st(2**i - 1)), hash(2**i - 1),
err_msg="%r: 2**%d - 1" % (st, i))
i = max(i - 1, 1)
assert_equal(hash(ut(2**(i - 1))), hash(2**(i - 1)),
err_msg="%r: 2**%d" % (ut, i - 1))
assert_equal(hash(ut(2**i - 1)), hash(2**i - 1),
err_msg="%r: 2**%d - 1" % (ut, i))
class TestAttributes(TestCase):
def setUp(self):
self.one = np.arange(10)
self.two = np.arange(20).reshape(4, 5)
self.three = np.arange(60, dtype=np.float64).reshape(2, 5, 6)
def test_attributes(self):
assert_equal(self.one.shape, (10,))
assert_equal(self.two.shape, (4, 5))
assert_equal(self.three.shape, (2, 5, 6))
self.three.shape = (10, 3, 2)
assert_equal(self.three.shape, (10, 3, 2))
self.three.shape = (2, 5, 6)
assert_equal(self.one.strides, (self.one.itemsize,))
num = self.two.itemsize
assert_equal(self.two.strides, (5*num, num))
num = self.three.itemsize
assert_equal(self.three.strides, (30*num, 6*num, num))
assert_equal(self.one.ndim, 1)
assert_equal(self.two.ndim, 2)
assert_equal(self.three.ndim, 3)
num = self.two.itemsize
assert_equal(self.two.size, 20)
assert_equal(self.two.nbytes, 20*num)
assert_equal(self.two.itemsize, self.two.dtype.itemsize)
assert_equal(self.two.base, np.arange(20))
def test_dtypeattr(self):
assert_equal(self.one.dtype, np.dtype(np.int_))
assert_equal(self.three.dtype, np.dtype(np.float_))
assert_equal(self.one.dtype.char, 'l')
assert_equal(self.three.dtype.char, 'd')
self.assertTrue(self.three.dtype.str[0] in '<>')
assert_equal(self.one.dtype.str[1], 'i')
assert_equal(self.three.dtype.str[1], 'f')
def test_int_subclassing(self):
# Regression test for https://github.com/numpy/numpy/pull/3526
numpy_int = np.int_(0)
if sys.version_info[0] >= 3:
# On Py3k int_ should not inherit from int, because it's not
# fixed-width anymore
assert_equal(isinstance(numpy_int, int), False)
else:
# Otherwise, it should inherit from int...
assert_equal(isinstance(numpy_int, int), True)
# ... and fast-path checks on C-API level should also work
from numpy.core.multiarray_tests import test_int_subclass
assert_equal(test_int_subclass(numpy_int), True)
def test_stridesattr(self):
x = self.one
def make_array(size, offset, strides):
return np.ndarray(size, buffer=x, dtype=int,
offset=offset*x.itemsize,
strides=strides*x.itemsize)
assert_equal(make_array(4, 4, -1), np.array([4, 3, 2, 1]))
self.assertRaises(ValueError, make_array, 4, 4, -2)
self.assertRaises(ValueError, make_array, 4, 2, -1)
self.assertRaises(ValueError, make_array, 8, 3, 1)
assert_equal(make_array(8, 3, 0), np.array([3]*8))
# Check behavior reported in gh-2503:
self.assertRaises(ValueError, make_array, (2, 3), 5, np.array([-2, -3]))
make_array(0, 0, 10)
def test_set_stridesattr(self):
x = self.one
def make_array(size, offset, strides):
try:
r = np.ndarray([size], dtype=int, buffer=x,
offset=offset*x.itemsize)
except:
raise RuntimeError(getexception())
r.strides = strides = strides*x.itemsize
return r
assert_equal(make_array(4, 4, -1), np.array([4, 3, 2, 1]))
assert_equal(make_array(7, 3, 1), np.array([3, 4, 5, 6, 7, 8, 9]))
self.assertRaises(ValueError, make_array, 4, 4, -2)
self.assertRaises(ValueError, make_array, 4, 2, -1)
self.assertRaises(RuntimeError, make_array, 8, 3, 1)
# Check that the true extent of the array is used.
# Test relies on as_strided base not exposing a buffer.
x = np.lib.stride_tricks.as_strided(np.arange(1), (10, 10), (0, 0))
def set_strides(arr, strides):
arr.strides = strides
self.assertRaises(ValueError, set_strides, x, (10*x.itemsize, x.itemsize))
# Test for offset calculations:
x = np.lib.stride_tricks.as_strided(np.arange(10, dtype=np.int8)[-1],
shape=(10,), strides=(-1,))
self.assertRaises(ValueError, set_strides, x[::-1], -1)
a = x[::-1]
a.strides = 1
a[::2].strides = 2
def test_fill(self):
for t in "?bhilqpBHILQPfdgFDGO":
x = np.empty((3, 2, 1), t)
y = np.empty((3, 2, 1), t)
x.fill(1)
y[...] = 1
assert_equal(x, y)
def test_fill_max_uint64(self):
x = np.empty((3, 2, 1), dtype=np.uint64)
y = np.empty((3, 2, 1), dtype=np.uint64)
value = 2**64 - 1
y[...] = value
x.fill(value)
assert_array_equal(x, y)
def test_fill_struct_array(self):
# Filling from a scalar
x = np.array([(0, 0.0), (1, 1.0)], dtype='i4,f8')
x.fill(x[0])
assert_equal(x['f1'][1], x['f1'][0])
# Filling from a tuple that can be converted
# to a scalar
x = np.zeros(2, dtype=[('a', 'f8'), ('b', 'i4')])
x.fill((3.5, -2))
assert_array_equal(x['a'], [3.5, 3.5])
assert_array_equal(x['b'], [-2, -2])
class TestArrayConstruction(TestCase):
def test_array(self):
d = np.ones(6)
r = np.array([d, d])
assert_equal(r, np.ones((2, 6)))
d = np.ones(6)
tgt = np.ones((2, 6))
r = np.array([d, d])
assert_equal(r, tgt)
tgt[1] = 2
r = np.array([d, d + 1])
assert_equal(r, tgt)
d = np.ones(6)
r = np.array([[d, d]])
assert_equal(r, np.ones((1, 2, 6)))
d = np.ones(6)
r = np.array([[d, d], [d, d]])
assert_equal(r, np.ones((2, 2, 6)))
d = np.ones((6, 6))
r = np.array([d, d])
assert_equal(r, np.ones((2, 6, 6)))
d = np.ones((6, ))
r = np.array([[d, d + 1], d + 2])
assert_equal(len(r), 2)
assert_equal(r[0], [d, d + 1])
assert_equal(r[1], d + 2)
tgt = np.ones((2, 3), dtype=np.bool)
tgt[0, 2] = False
tgt[1, 0:2] = False
r = np.array([[True, True, False], [False, False, True]])
assert_equal(r, tgt)
r = np.array([[True, False], [True, False], [False, True]])
assert_equal(r, tgt.T)
def test_array_empty(self):
assert_raises(TypeError, np.array)
def test_array_copy_false(self):
d = np.array([1, 2, 3])
e = np.array(d, copy=False)
d[1] = 3
assert_array_equal(e, [1, 3, 3])
e = np.array(d, copy=False, order='F')
d[1] = 4
assert_array_equal(e, [1, 4, 3])
e[2] = 7
assert_array_equal(d, [1, 4, 7])
def test_array_copy_true(self):
d = np.array([[1,2,3], [1, 2, 3]])
e = np.array(d, copy=True)
d[0, 1] = 3
e[0, 2] = -7
assert_array_equal(e, [[1, 2, -7], [1, 2, 3]])
assert_array_equal(d, [[1, 3, 3], [1, 2, 3]])
e = np.array(d, copy=True, order='F')
d[0, 1] = 5
e[0, 2] = 7
assert_array_equal(e, [[1, 3, 7], [1, 2, 3]])
assert_array_equal(d, [[1, 5, 3], [1,2,3]])
def test_array_cont(self):
d = np.ones(10)[::2]
assert_(np.ascontiguousarray(d).flags.c_contiguous)
assert_(np.ascontiguousarray(d).flags.f_contiguous)
assert_(np.asfortranarray(d).flags.c_contiguous)
assert_(np.asfortranarray(d).flags.f_contiguous)
d = np.ones((10, 10))[::2,::2]
assert_(np.ascontiguousarray(d).flags.c_contiguous)
assert_(np.asfortranarray(d).flags.f_contiguous)
class TestAssignment(TestCase):
def test_assignment_broadcasting(self):
a = np.arange(6).reshape(2, 3)
# Broadcasting the input to the output
a[...] = np.arange(3)
assert_equal(a, [[0, 1, 2], [0, 1, 2]])
a[...] = np.arange(2).reshape(2, 1)
assert_equal(a, [[0, 0, 0], [1, 1, 1]])
# For compatibility with <= 1.5, a limited version of broadcasting
# the output to the input.
#
# This behavior is inconsistent with NumPy broadcasting
# in general, because it only uses one of the two broadcasting
# rules (adding a new "1" dimension to the left of the shape),
# applied to the output instead of an input. In NumPy 2.0, this kind
# of broadcasting assignment will likely be disallowed.
a[...] = np.arange(6)[::-1].reshape(1, 2, 3)
assert_equal(a, [[5, 4, 3], [2, 1, 0]])
# The other type of broadcasting would require a reduction operation.
def assign(a, b):
a[...] = b
assert_raises(ValueError, assign, a, np.arange(12).reshape(2, 2, 3))
def test_assignment_errors(self):
# Address issue #2276
class C:
pass
a = np.zeros(1)
def assign(v):
a[0] = v
assert_raises((AttributeError, TypeError), assign, C())
assert_raises(ValueError, assign, [1])
class TestDtypedescr(TestCase):
def test_construction(self):
d1 = np.dtype('i4')
assert_equal(d1, np.dtype(np.int32))
d2 = np.dtype('f8')
assert_equal(d2, np.dtype(np.float64))
def test_byteorders(self):
self.assertNotEqual(np.dtype('<i4'), np.dtype('>i4'))
self.assertNotEqual(np.dtype([('a', '<i4')]), np.dtype([('a', '>i4')]))
class TestZeroRank(TestCase):
def setUp(self):
self.d = np.array(0), np.array('x', object)
def test_ellipsis_subscript(self):
a, b = self.d
self.assertEqual(a[...], 0)
self.assertEqual(b[...], 'x')
self.assertTrue(a[...].base is a) # `a[...] is a` in numpy <1.9.
self.assertTrue(b[...].base is b) # `b[...] is b` in numpy <1.9.
def test_empty_subscript(self):
a, b = self.d
self.assertEqual(a[()], 0)
self.assertEqual(b[()], 'x')
self.assertTrue(type(a[()]) is a.dtype.type)
self.assertTrue(type(b[()]) is str)
def test_invalid_subscript(self):
a, b = self.d
self.assertRaises(IndexError, lambda x: x[0], a)
self.assertRaises(IndexError, lambda x: x[0], b)
self.assertRaises(IndexError, lambda x: x[np.array([], int)], a)
self.assertRaises(IndexError, lambda x: x[np.array([], int)], b)
def test_ellipsis_subscript_assignment(self):
a, b = self.d
a[...] = 42
self.assertEqual(a, 42)
b[...] = ''
self.assertEqual(b.item(), '')
def test_empty_subscript_assignment(self):
a, b = self.d
a[()] = 42
self.assertEqual(a, 42)
b[()] = ''
self.assertEqual(b.item(), '')
def test_invalid_subscript_assignment(self):
a, b = self.d
def assign(x, i, v):
x[i] = v
self.assertRaises(IndexError, assign, a, 0, 42)
self.assertRaises(IndexError, assign, b, 0, '')
self.assertRaises(ValueError, assign, a, (), '')
def test_newaxis(self):
a, b = self.d
self.assertEqual(a[np.newaxis].shape, (1,))
self.assertEqual(a[..., np.newaxis].shape, (1,))
self.assertEqual(a[np.newaxis, ...].shape, (1,))
self.assertEqual(a[..., np.newaxis].shape, (1,))
self.assertEqual(a[np.newaxis, ..., np.newaxis].shape, (1, 1))
self.assertEqual(a[..., np.newaxis, np.newaxis].shape, (1, 1))
self.assertEqual(a[np.newaxis, np.newaxis, ...].shape, (1, 1))
self.assertEqual(a[(np.newaxis,)*10].shape, (1,)*10)
def test_invalid_newaxis(self):
a, b = self.d
def subscript(x, i):
x[i]
self.assertRaises(IndexError, subscript, a, (np.newaxis, 0))
self.assertRaises(IndexError, subscript, a, (np.newaxis,)*50)
def test_constructor(self):
x = np.ndarray(())
x[()] = 5
self.assertEqual(x[()], 5)
y = np.ndarray((), buffer=x)
y[()] = 6
self.assertEqual(x[()], 6)
def test_output(self):
x = np.array(2)
self.assertRaises(ValueError, np.add, x, [1], x)
class TestScalarIndexing(TestCase):
def setUp(self):
self.d = np.array([0, 1])[0]
def test_ellipsis_subscript(self):
a = self.d
self.assertEqual(a[...], 0)
self.assertEqual(a[...].shape, ())
def test_empty_subscript(self):
a = self.d
self.assertEqual(a[()], 0)
self.assertEqual(a[()].shape, ())
def test_invalid_subscript(self):
a = self.d
self.assertRaises(IndexError, lambda x: x[0], a)
self.assertRaises(IndexError, lambda x: x[np.array([], int)], a)
def test_invalid_subscript_assignment(self):
a = self.d
def assign(x, i, v):
x[i] = v
self.assertRaises(TypeError, assign, a, 0, 42)
def test_newaxis(self):
a = self.d
self.assertEqual(a[np.newaxis].shape, (1,))
self.assertEqual(a[..., np.newaxis].shape, (1,))
self.assertEqual(a[np.newaxis, ...].shape, (1,))
self.assertEqual(a[..., np.newaxis].shape, (1,))
self.assertEqual(a[np.newaxis, ..., np.newaxis].shape, (1, 1))
self.assertEqual(a[..., np.newaxis, np.newaxis].shape, (1, 1))
self.assertEqual(a[np.newaxis, np.newaxis, ...].shape, (1, 1))
self.assertEqual(a[(np.newaxis,)*10].shape, (1,)*10)
def test_invalid_newaxis(self):
a = self.d
def subscript(x, i):
x[i]
self.assertRaises(IndexError, subscript, a, (np.newaxis, 0))
self.assertRaises(IndexError, subscript, a, (np.newaxis,)*50)
def test_overlapping_assignment(self):
# With positive strides
a = np.arange(4)
a[:-1] = a[1:]
assert_equal(a, [1, 2, 3, 3])
a = np.arange(4)
a[1:] = a[:-1]
assert_equal(a, [0, 0, 1, 2])
# With positive and negative strides
a = np.arange(4)
a[:] = a[::-1]
assert_equal(a, [3, 2, 1, 0])
a = np.arange(6).reshape(2, 3)
a[::-1,:] = a[:, ::-1]
assert_equal(a, [[5, 4, 3], [2, 1, 0]])
a = np.arange(6).reshape(2, 3)
a[::-1, ::-1] = a[:, ::-1]
assert_equal(a, [[3, 4, 5], [0, 1, 2]])
# With just one element overlapping
a = np.arange(5)
a[:3] = a[2:]
assert_equal(a, [2, 3, 4, 3, 4])
a = np.arange(5)
a[2:] = a[:3]
assert_equal(a, [0, 1, 0, 1, 2])
a = np.arange(5)
a[2::-1] = a[2:]
assert_equal(a, [4, 3, 2, 3, 4])
a = np.arange(5)
a[2:] = a[2::-1]
assert_equal(a, [0, 1, 2, 1, 0])
a = np.arange(5)
a[2::-1] = a[:1:-1]
assert_equal(a, [2, 3, 4, 3, 4])
a = np.arange(5)
a[:1:-1] = a[2::-1]
assert_equal(a, [0, 1, 0, 1, 2])
class TestCreation(TestCase):
def test_from_attribute(self):
class x(object):
def __array__(self, dtype=None):
pass
self.assertRaises(ValueError, np.array, x())
def test_from_string(self):
types = np.typecodes['AllInteger'] + np.typecodes['Float']
nstr = ['123', '123']
result = np.array([123, 123], dtype=int)
for type in types:
msg = 'String conversion for %s' % type
assert_equal(np.array(nstr, dtype=type), result, err_msg=msg)
def test_void(self):
arr = np.array([], dtype='V')
assert_equal(arr.dtype.kind, 'V')
def test_zeros(self):
types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
for dt in types:
d = np.zeros((13,), dtype=dt)
assert_equal(np.count_nonzero(d), 0)
# true for ieee floats
assert_equal(d.sum(), 0)
assert_(not d.any())
d = np.zeros(2, dtype='(2,4)i4')
assert_equal(np.count_nonzero(d), 0)
assert_equal(d.sum(), 0)
assert_(not d.any())
d = np.zeros(2, dtype='4i4')
assert_equal(np.count_nonzero(d), 0)
assert_equal(d.sum(), 0)
assert_(not d.any())
d = np.zeros(2, dtype='(2,4)i4, (2,4)i4')
assert_equal(np.count_nonzero(d), 0)
@dec.slow
def test_zeros_big(self):
# test big array as they might be allocated different by the system
types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
for dt in types:
d = np.zeros((30 * 1024**2,), dtype=dt)
assert_(not d.any())
# This test can fail on 32-bit systems due to insufficient
# contiguous memory. Deallocating the previous array increases the
# chance of success.
del(d)
def test_zeros_obj(self):
# test initialization from PyLong(0)
d = np.zeros((13,), dtype=object)
assert_array_equal(d, [0] * 13)
assert_equal(np.count_nonzero(d), 0)
def test_zeros_obj_obj(self):
d = np.zeros(10, dtype=[('k', object, 2)])
assert_array_equal(d['k'], 0)
def test_zeros_like_like_zeros(self):
# test zeros_like returns the same as zeros
for c in np.typecodes['All']:
if c == 'V':
continue
d = np.zeros((3,3), dtype=c)
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
# explicitly check some special cases
d = np.zeros((3,3), dtype='S5')
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
d = np.zeros((3,3), dtype='U5')
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
d = np.zeros((3,3), dtype='<i4')
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
d = np.zeros((3,3), dtype='>i4')
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
d = np.zeros((3,3), dtype='<M8[s]')
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
d = np.zeros((3,3), dtype='>M8[s]')
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
d = np.zeros((3,3), dtype='f4,f4')
assert_array_equal(np.zeros_like(d), d)
assert_equal(np.zeros_like(d).dtype, d.dtype)
def test_empty_unicode(self):
# don't throw decode errors on garbage memory
for i in range(5, 100, 5):
d = np.empty(i, dtype='U')
str(d)
def test_sequence_non_homogenous(self):
assert_equal(np.array([4, 2**80]).dtype, np.object)
assert_equal(np.array([4, 2**80, 4]).dtype, np.object)
assert_equal(np.array([2**80, 4]).dtype, np.object)
assert_equal(np.array([2**80] * 3).dtype, np.object)
assert_equal(np.array([[1, 1],[1j, 1j]]).dtype, np.complex)
assert_equal(np.array([[1j, 1j],[1, 1]]).dtype, np.complex)
assert_equal(np.array([[1, 1, 1],[1, 1j, 1.], [1, 1, 1]]).dtype, np.complex)
@dec.skipif(sys.version_info[0] >= 3)
def test_sequence_long(self):
assert_equal(np.array([long(4), long(4)]).dtype, np.long)
assert_equal(np.array([long(4), 2**80]).dtype, np.object)
assert_equal(np.array([long(4), 2**80, long(4)]).dtype, np.object)
assert_equal(np.array([2**80, long(4)]).dtype, np.object)
def test_non_sequence_sequence(self):
"""Should not segfault.
Class Fail breaks the sequence protocol for new style classes, i.e.,
those derived from object. Class Map is a mapping type indicated by
raising a ValueError. At some point we may raise a warning instead
of an error in the Fail case.
"""
class Fail(object):
def __len__(self):
return 1
def __getitem__(self, index):
raise ValueError()
class Map(object):
def __len__(self):
return 1
def __getitem__(self, index):
raise KeyError()
a = np.array([Map()])
assert_(a.shape == (1,))
assert_(a.dtype == np.dtype(object))
assert_raises(ValueError, np.array, [Fail()])
def test_no_len_object_type(self):
# gh-5100, want object array from iterable object without len()
class Point2:
def __init__(self):
pass
def __getitem__(self, ind):
if ind in [0, 1]:
return ind
else:
raise IndexError()
d = np.array([Point2(), Point2(), Point2()])
assert_equal(d.dtype, np.dtype(object))
def test_false_len_sequence(self):
# gh-7264, segfault for this example
class C:
def __getitem__(self, i):
raise IndexError
def __len__(self):
return 42
assert_raises(ValueError, np.array, C()) # segfault?
def test_failed_len_sequence(self):
# gh-7393
class A(object):
def __init__(self, data):
self._data = data
def __getitem__(self, item):
return type(self)(self._data[item])
def __len__(self):
return len(self._data)
# len(d) should give 3, but len(d[0]) will fail
d = A([1,2,3])
assert_equal(len(np.array(d)), 3)
def test_array_too_big(self):
# Test that array creation succeeds for arrays addressable by intp
# on the byte level and fails for too large arrays.
buf = np.zeros(100)
max_bytes = np.iinfo(np.intp).max
for dtype in ["intp", "S20", "b"]:
dtype = np.dtype(dtype)
itemsize = dtype.itemsize
np.ndarray(buffer=buf, strides=(0,),
shape=(max_bytes//itemsize,), dtype=dtype)
assert_raises(ValueError, np.ndarray, buffer=buf, strides=(0,),
shape=(max_bytes//itemsize + 1,), dtype=dtype)
class TestStructured(TestCase):
def test_subarray_field_access(self):
a = np.zeros((3, 5), dtype=[('a', ('i4', (2, 2)))])
a['a'] = np.arange(60).reshape(3, 5, 2, 2)
# Since the subarray is always in C-order, a transpose
# does not swap the subarray:
assert_array_equal(a.T['a'], a['a'].transpose(1, 0, 2, 3))
# In Fortran order, the subarray gets appended
# like in all other cases, not prepended as a special case
b = a.copy(order='F')
assert_equal(a['a'].shape, b['a'].shape)
assert_equal(a.T['a'].shape, a.T.copy()['a'].shape)
def test_subarray_comparison(self):
# Check that comparisons between record arrays with
# multi-dimensional field types work properly
a = np.rec.fromrecords(
[([1, 2, 3], 'a', [[1, 2], [3, 4]]), ([3, 3, 3], 'b', [[0, 0], [0, 0]])],
dtype=[('a', ('f4', 3)), ('b', np.object), ('c', ('i4', (2, 2)))])
b = a.copy()
assert_equal(a == b, [True, True])
assert_equal(a != b, [False, False])
b[1].b = 'c'
assert_equal(a == b, [True, False])
assert_equal(a != b, [False, True])
for i in range(3):
b[0].a = a[0].a
b[0].a[i] = 5
assert_equal(a == b, [False, False])
assert_equal(a != b, [True, True])
for i in range(2):
for j in range(2):
b = a.copy()
b[0].c[i, j] = 10
assert_equal(a == b, [False, True])
assert_equal(a != b, [True, False])
# Check that broadcasting with a subarray works
a = np.array([[(0,)], [(1,)]], dtype=[('a', 'f8')])
b = np.array([(0,), (0,), (1,)], dtype=[('a', 'f8')])
assert_equal(a == b, [[True, True, False], [False, False, True]])
assert_equal(b == a, [[True, True, False], [False, False, True]])
a = np.array([[(0,)], [(1,)]], dtype=[('a', 'f8', (1,))])
b = np.array([(0,), (0,), (1,)], dtype=[('a', 'f8', (1,))])
assert_equal(a == b, [[True, True, False], [False, False, True]])
assert_equal(b == a, [[True, True, False], [False, False, True]])
a = np.array([[([0, 0],)], [([1, 1],)]], dtype=[('a', 'f8', (2,))])
b = np.array([([0, 0],), ([0, 1],), ([1, 1],)], dtype=[('a', 'f8', (2,))])
assert_equal(a == b, [[True, False, False], [False, False, True]])
assert_equal(b == a, [[True, False, False], [False, False, True]])
# Check that broadcasting Fortran-style arrays with a subarray work
a = np.array([[([0, 0],)], [([1, 1],)]], dtype=[('a', 'f8', (2,))], order='F')
b = np.array([([0, 0],), ([0, 1],), ([1, 1],)], dtype=[('a', 'f8', (2,))])
assert_equal(a == b, [[True, False, False], [False, False, True]])
assert_equal(b == a, [[True, False, False], [False, False, True]])
# Check that incompatible sub-array shapes don't result to broadcasting
x = np.zeros((1,), dtype=[('a', ('f4', (1, 2))), ('b', 'i1')])
y = np.zeros((1,), dtype=[('a', ('f4', (2,))), ('b', 'i1')])
# This comparison invokes deprecated behaviour, and will probably
# start raising an error eventually. What we really care about in this
# test is just that it doesn't return True.
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
assert_equal(x == y, False)
x = np.zeros((1,), dtype=[('a', ('f4', (2, 1))), ('b', 'i1')])
y = np.zeros((1,), dtype=[('a', ('f4', (2,))), ('b', 'i1')])
# This comparison invokes deprecated behaviour, and will probably
# start raising an error eventually. What we really care about in this
# test is just that it doesn't return True.
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
assert_equal(x == y, False)
# Check that structured arrays that are different only in
# byte-order work
a = np.array([(5, 42), (10, 1)], dtype=[('a', '>i8'), ('b', '<f8')])
b = np.array([(5, 43), (10, 1)], dtype=[('a', '<i8'), ('b', '>f8')])
assert_equal(a == b, [False, True])
def test_casting(self):
# Check that casting a structured array to change its byte order
# works
a = np.array([(1,)], dtype=[('a', '<i4')])
assert_(np.can_cast(a.dtype, [('a', '>i4')], casting='unsafe'))
b = a.astype([('a', '>i4')])
assert_equal(b, a.byteswap().newbyteorder())
assert_equal(a['a'][0], b['a'][0])
# Check that equality comparison works on structured arrays if
# they are 'equiv'-castable
a = np.array([(5, 42), (10, 1)], dtype=[('a', '>i4'), ('b', '<f8')])
b = np.array([(42, 5), (1, 10)], dtype=[('b', '>f8'), ('a', '<i4')])
assert_(np.can_cast(a.dtype, b.dtype, casting='equiv'))
assert_equal(a == b, [True, True])
# Check that 'equiv' casting can reorder fields and change byte
# order
assert_(np.can_cast(a.dtype, b.dtype, casting='equiv'))
c = a.astype(b.dtype, casting='equiv')
assert_equal(a == c, [True, True])
# Check that 'safe' casting can change byte order and up-cast
# fields
t = [('a', '<i8'), ('b', '>f8')]
assert_(np.can_cast(a.dtype, t, casting='safe'))
c = a.astype(t, casting='safe')
assert_equal((c == np.array([(5, 42), (10, 1)], dtype=t)),
[True, True])
# Check that 'same_kind' casting can change byte order and
# change field widths within a "kind"
t = [('a', '<i4'), ('b', '>f4')]
assert_(np.can_cast(a.dtype, t, casting='same_kind'))
c = a.astype(t, casting='same_kind')
assert_equal((c == np.array([(5, 42), (10, 1)], dtype=t)),
[True, True])
# Check that casting fails if the casting rule should fail on
# any of the fields
t = [('a', '>i8'), ('b', '<f4')]
assert_(not np.can_cast(a.dtype, t, casting='safe'))
assert_raises(TypeError, a.astype, t, casting='safe')
t = [('a', '>i2'), ('b', '<f8')]
assert_(not np.can_cast(a.dtype, t, casting='equiv'))
assert_raises(TypeError, a.astype, t, casting='equiv')
t = [('a', '>i8'), ('b', '<i2')]
assert_(not np.can_cast(a.dtype, t, casting='same_kind'))
assert_raises(TypeError, a.astype, t, casting='same_kind')
assert_(not np.can_cast(a.dtype, b.dtype, casting='no'))
assert_raises(TypeError, a.astype, b.dtype, casting='no')
# Check that non-'unsafe' casting can't change the set of field names
for casting in ['no', 'safe', 'equiv', 'same_kind']:
t = [('a', '>i4')]
assert_(not np.can_cast(a.dtype, t, casting=casting))
t = [('a', '>i4'), ('b', '<f8'), ('c', 'i4')]
assert_(not np.can_cast(a.dtype, t, casting=casting))
def test_objview(self):
# https://github.com/numpy/numpy/issues/3286
a = np.array([], dtype=[('a', 'f'), ('b', 'f'), ('c', 'O')])
a[['a', 'b']] # TypeError?
# https://github.com/numpy/numpy/issues/3253
dat2 = np.zeros(3, [('A', 'i'), ('B', '|O')])
dat2[['B', 'A']] # TypeError?
def test_setfield(self):
# https://github.com/numpy/numpy/issues/3126
struct_dt = np.dtype([('elem', 'i4', 5),])
dt = np.dtype([('field', 'i4', 10),('struct', struct_dt)])
x = np.zeros(1, dt)
x[0]['field'] = np.ones(10, dtype='i4')
x[0]['struct'] = np.ones(1, dtype=struct_dt)
assert_equal(x[0]['field'], np.ones(10, dtype='i4'))
def test_setfield_object(self):
# make sure object field assignment with ndarray value
# on void scalar mimics setitem behavior
b = np.zeros(1, dtype=[('x', 'O')])
# next line should work identically to b['x'][0] = np.arange(3)
b[0]['x'] = np.arange(3)
assert_equal(b[0]['x'], np.arange(3))
# check that broadcasting check still works
c = np.zeros(1, dtype=[('x', 'O', 5)])
def testassign():
c[0]['x'] = np.arange(3)
assert_raises(ValueError, testassign)
class TestBool(TestCase):
def test_test_interning(self):
a0 = np.bool_(0)
b0 = np.bool_(False)
self.assertTrue(a0 is b0)
a1 = np.bool_(1)
b1 = np.bool_(True)
self.assertTrue(a1 is b1)
self.assertTrue(np.array([True])[0] is a1)
self.assertTrue(np.array(True)[()] is a1)
def test_sum(self):
d = np.ones(101, dtype=np.bool)
assert_equal(d.sum(), d.size)
assert_equal(d[::2].sum(), d[::2].size)
assert_equal(d[::-2].sum(), d[::-2].size)
d = np.frombuffer(b'\xff\xff' * 100, dtype=bool)
assert_equal(d.sum(), d.size)
assert_equal(d[::2].sum(), d[::2].size)
assert_equal(d[::-2].sum(), d[::-2].size)
def check_count_nonzero(self, power, length):
powers = [2 ** i for i in range(length)]
for i in range(2**power):
l = [(i & x) != 0 for x in powers]
a = np.array(l, dtype=np.bool)
c = builtins.sum(l)
self.assertEqual(np.count_nonzero(a), c)
av = a.view(np.uint8)
av *= 3
self.assertEqual(np.count_nonzero(a), c)
av *= 4
self.assertEqual(np.count_nonzero(a), c)
av[av != 0] = 0xFF
self.assertEqual(np.count_nonzero(a), c)
def test_count_nonzero(self):
# check all 12 bit combinations in a length 17 array
# covers most cases of the 16 byte unrolled code
self.check_count_nonzero(12, 17)
@dec.slow
def test_count_nonzero_all(self):
# check all combinations in a length 17 array
# covers all cases of the 16 byte unrolled code
self.check_count_nonzero(17, 17)
def test_count_nonzero_unaligned(self):
# prevent mistakes as e.g. gh-4060
for o in range(7):
a = np.zeros((18,), dtype=np.bool)[o+1:]
a[:o] = True
self.assertEqual(np.count_nonzero(a), builtins.sum(a.tolist()))
a = np.ones((18,), dtype=np.bool)[o+1:]
a[:o] = False
self.assertEqual(np.count_nonzero(a), builtins.sum(a.tolist()))
class TestMethods(TestCase):
def test_compress(self):
tgt = [[5, 6, 7, 8, 9]]
arr = np.arange(10).reshape(2, 5)
out = arr.compress([0, 1], axis=0)
assert_equal(out, tgt)
tgt = [[1, 3], [6, 8]]
out = arr.compress([0, 1, 0, 1, 0], axis=1)
assert_equal(out, tgt)
tgt = [[1], [6]]
arr = np.arange(10).reshape(2, 5)
out = arr.compress([0, 1], axis=1)
assert_equal(out, tgt)
arr = np.arange(10).reshape(2, 5)
out = arr.compress([0, 1])
assert_equal(out, 1)
def test_choose(self):
x = 2*np.ones((3,), dtype=int)
y = 3*np.ones((3,), dtype=int)
x2 = 2*np.ones((2, 3), dtype=int)
y2 = 3*np.ones((2, 3), dtype=int)
ind = np.array([0, 0, 1])
A = ind.choose((x, y))
assert_equal(A, [2, 2, 3])
A = ind.choose((x2, y2))
assert_equal(A, [[2, 2, 3], [2, 2, 3]])
A = ind.choose((x, y2))
assert_equal(A, [[2, 2, 3], [2, 2, 3]])
def test_prod(self):
ba = [1, 2, 10, 11, 6, 5, 4]
ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
for ctype in [np.int16, np.uint16, np.int32, np.uint32,
np.float32, np.float64, np.complex64, np.complex128]:
a = np.array(ba, ctype)
a2 = np.array(ba2, ctype)
if ctype in ['1', 'b']:
self.assertRaises(ArithmeticError, a.prod)
self.assertRaises(ArithmeticError, a2.prod, axis=1)
else:
assert_equal(a.prod(axis=0), 26400)
assert_array_equal(a2.prod(axis=0),
np.array([50, 36, 84, 180], ctype))
assert_array_equal(a2.prod(axis=-1),
np.array([24, 1890, 600], ctype))
def test_repeat(self):
m = np.array([1, 2, 3, 4, 5, 6])
m_rect = m.reshape((2, 3))
A = m.repeat([1, 3, 2, 1, 1, 2])
assert_equal(A, [1, 2, 2, 2, 3,
3, 4, 5, 6, 6])
A = m.repeat(2)
assert_equal(A, [1, 1, 2, 2, 3, 3,
4, 4, 5, 5, 6, 6])
A = m_rect.repeat([2, 1], axis=0)
assert_equal(A, [[1, 2, 3],
[1, 2, 3],
[4, 5, 6]])
A = m_rect.repeat([1, 3, 2], axis=1)
assert_equal(A, [[1, 2, 2, 2, 3, 3],
[4, 5, 5, 5, 6, 6]])
A = m_rect.repeat(2, axis=0)
assert_equal(A, [[1, 2, 3],
[1, 2, 3],
[4, 5, 6],
[4, 5, 6]])
A = m_rect.repeat(2, axis=1)
assert_equal(A, [[1, 1, 2, 2, 3, 3],
[4, 4, 5, 5, 6, 6]])
def test_reshape(self):
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
tgt = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]
assert_equal(arr.reshape(2, 6), tgt)
tgt = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
assert_equal(arr.reshape(3, 4), tgt)
tgt = [[1, 10, 8, 6], [4, 2, 11, 9], [7, 5, 3, 12]]
assert_equal(arr.reshape((3, 4), order='F'), tgt)
tgt = [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
assert_equal(arr.T.reshape((3, 4), order='C'), tgt)
def test_round(self):
def check_round(arr, expected, *round_args):
assert_equal(arr.round(*round_args), expected)
# With output array
out = np.zeros_like(arr)
res = arr.round(*round_args, out=out)
assert_equal(out, expected)
assert_equal(out, res)
check_round(np.array([1.2, 1.5]), [1, 2])
check_round(np.array(1.5), 2)
check_round(np.array([12.2, 15.5]), [10, 20], -1)
check_round(np.array([12.15, 15.51]), [12.2, 15.5], 1)
# Complex rounding
check_round(np.array([4.5 + 1.5j]), [4 + 2j])
check_round(np.array([12.5 + 15.5j]), [10 + 20j], -1)
def test_squeeze(self):
a = np.array([[[1], [2], [3]]])
assert_equal(a.squeeze(), [1, 2, 3])
assert_equal(a.squeeze(axis=(0,)), [[1], [2], [3]])
assert_raises(ValueError, a.squeeze, axis=(1,))
assert_equal(a.squeeze(axis=(2,)), [[1, 2, 3]])
def test_transpose(self):
a = np.array([[1, 2], [3, 4]])
assert_equal(a.transpose(), [[1, 3], [2, 4]])
self.assertRaises(ValueError, lambda: a.transpose(0))
self.assertRaises(ValueError, lambda: a.transpose(0, 0))
self.assertRaises(ValueError, lambda: a.transpose(0, 1, 2))
def test_sort(self):
# test ordering for floats and complex containing nans. It is only
# necessary to check the less-than comparison, so sorts that
# only follow the insertion sort path are sufficient. We only
# test doubles and complex doubles as the logic is the same.
# check doubles
msg = "Test real sort order with nans"
a = np.array([np.nan, 1, 0])
b = np.sort(a)
assert_equal(b, a[::-1], msg)
# check complex
msg = "Test complex sort order with nans"
a = np.zeros(9, dtype=np.complex128)
a.real += [np.nan, np.nan, np.nan, 1, 0, 1, 1, 0, 0]
a.imag += [np.nan, 1, 0, np.nan, np.nan, 1, 0, 1, 0]
b = np.sort(a)
assert_equal(b, a[::-1], msg)
# all c scalar sorts use the same code with different types
# so it suffices to run a quick check with one type. The number
# of sorted items must be greater than ~50 to check the actual
# algorithm because quick and merge sort fall over to insertion
# sort for small arrays.
a = np.arange(101)
b = a[::-1].copy()
for kind in ['q', 'm', 'h']:
msg = "scalar sort, kind=%s" % kind
c = a.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
c = b.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
# test complex sorts. These use the same code as the scalars
# but the compare function differs.
ai = a*1j + 1
bi = b*1j + 1
for kind in ['q', 'm', 'h']:
msg = "complex sort, real part == 1, kind=%s" % kind
c = ai.copy()
c.sort(kind=kind)
assert_equal(c, ai, msg)
c = bi.copy()
c.sort(kind=kind)
assert_equal(c, ai, msg)
ai = a + 1j
bi = b + 1j
for kind in ['q', 'm', 'h']:
msg = "complex sort, imag part == 1, kind=%s" % kind
c = ai.copy()
c.sort(kind=kind)
assert_equal(c, ai, msg)
c = bi.copy()
c.sort(kind=kind)
assert_equal(c, ai, msg)
# test sorting of complex arrays requiring byte-swapping, gh-5441
for endianess in '<>':
for dt in np.typecodes['Complex']:
arr = np.array([1+3.j, 2+2.j, 3+1.j], dtype=endianess + dt)
c = arr.copy()
c.sort()
msg = 'byte-swapped complex sort, dtype={0}'.format(dt)
assert_equal(c, arr, msg)
# test string sorts.
s = 'aaaaaaaa'
a = np.array([s + chr(i) for i in range(101)])
b = a[::-1].copy()
for kind in ['q', 'm', 'h']:
msg = "string sort, kind=%s" % kind
c = a.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
c = b.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
# test unicode sorts.
s = 'aaaaaaaa'
a = np.array([s + chr(i) for i in range(101)], dtype=np.unicode)
b = a[::-1].copy()
for kind in ['q', 'm', 'h']:
msg = "unicode sort, kind=%s" % kind
c = a.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
c = b.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
# test object array sorts.
a = np.empty((101,), dtype=np.object)
a[:] = list(range(101))
b = a[::-1]
for kind in ['q', 'h', 'm']:
msg = "object sort, kind=%s" % kind
c = a.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
c = b.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
# test record array sorts.
dt = np.dtype([('f', float), ('i', int)])
a = np.array([(i, i) for i in range(101)], dtype=dt)
b = a[::-1]
for kind in ['q', 'h', 'm']:
msg = "object sort, kind=%s" % kind
c = a.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
c = b.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
# test datetime64 sorts.
a = np.arange(0, 101, dtype='datetime64[D]')
b = a[::-1]
for kind in ['q', 'h', 'm']:
msg = "datetime64 sort, kind=%s" % kind
c = a.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
c = b.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
# test timedelta64 sorts.
a = np.arange(0, 101, dtype='timedelta64[D]')
b = a[::-1]
for kind in ['q', 'h', 'm']:
msg = "timedelta64 sort, kind=%s" % kind
c = a.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
c = b.copy()
c.sort(kind=kind)
assert_equal(c, a, msg)
# check axis handling. This should be the same for all type
# specific sorts, so we only check it for one type and one kind
a = np.array([[3, 2], [1, 0]])
b = np.array([[1, 0], [3, 2]])
c = np.array([[2, 3], [0, 1]])
d = a.copy()
d.sort(axis=0)
assert_equal(d, b, "test sort with axis=0")
d = a.copy()
d.sort(axis=1)
assert_equal(d, c, "test sort with axis=1")
d = a.copy()
d.sort()
assert_equal(d, c, "test sort with default axis")
# check axis handling for multidimensional empty arrays
a = np.array([])
a.shape = (3, 2, 1, 0)
for axis in range(-a.ndim, a.ndim):
msg = 'test empty array sort with axis={0}'.format(axis)
assert_equal(np.sort(a, axis=axis), a, msg)
msg = 'test empty array sort with axis=None'
assert_equal(np.sort(a, axis=None), a.ravel(), msg)
def test_copy(self):
def assert_fortran(arr):
assert_(arr.flags.fortran)
assert_(arr.flags.f_contiguous)
assert_(not arr.flags.c_contiguous)
def assert_c(arr):
assert_(not arr.flags.fortran)
assert_(not arr.flags.f_contiguous)
assert_(arr.flags.c_contiguous)
a = np.empty((2, 2), order='F')
# Test copying a Fortran array
assert_c(a.copy())
assert_c(a.copy('C'))
assert_fortran(a.copy('F'))
assert_fortran(a.copy('A'))
# Now test starting with a C array.
a = np.empty((2, 2), order='C')
assert_c(a.copy())
assert_c(a.copy('C'))
assert_fortran(a.copy('F'))
assert_c(a.copy('A'))
def test_sort_order(self):
# Test sorting an array with fields
x1 = np.array([21, 32, 14])
x2 = np.array(['my', 'first', 'name'])
x3 = np.array([3.1, 4.5, 6.2])
r = np.rec.fromarrays([x1, x2, x3], names='id,word,number')
r.sort(order=['id'])
assert_equal(r.id, np.array([14, 21, 32]))
assert_equal(r.word, np.array(['name', 'my', 'first']))
assert_equal(r.number, np.array([6.2, 3.1, 4.5]))
r.sort(order=['word'])
assert_equal(r.id, np.array([32, 21, 14]))
assert_equal(r.word, np.array(['first', 'my', 'name']))
assert_equal(r.number, np.array([4.5, 3.1, 6.2]))
r.sort(order=['number'])
assert_equal(r.id, np.array([21, 32, 14]))
assert_equal(r.word, np.array(['my', 'first', 'name']))
assert_equal(r.number, np.array([3.1, 4.5, 6.2]))
if sys.byteorder == 'little':
strtype = '>i2'
else:
strtype = '<i2'
mydtype = [('name', strchar + '5'), ('col2', strtype)]
r = np.array([('a', 1), ('b', 255), ('c', 3), ('d', 258)],
dtype=mydtype)
r.sort(order='col2')
assert_equal(r['col2'], [1, 3, 255, 258])
assert_equal(r, np.array([('a', 1), ('c', 3), ('b', 255), ('d', 258)],
dtype=mydtype))
def test_argsort(self):
# all c scalar argsorts use the same code with different types
# so it suffices to run a quick check with one type. The number
# of sorted items must be greater than ~50 to check the actual
# algorithm because quick and merge sort fall over to insertion
# sort for small arrays.
a = np.arange(101)
b = a[::-1].copy()
for kind in ['q', 'm', 'h']:
msg = "scalar argsort, kind=%s" % kind
assert_equal(a.copy().argsort(kind=kind), a, msg)
assert_equal(b.copy().argsort(kind=kind), b, msg)
# test complex argsorts. These use the same code as the scalars
# but the compare function differs.
ai = a*1j + 1
bi = b*1j + 1
for kind in ['q', 'm', 'h']:
msg = "complex argsort, kind=%s" % kind
assert_equal(ai.copy().argsort(kind=kind), a, msg)
assert_equal(bi.copy().argsort(kind=kind), b, msg)
ai = a + 1j
bi = b + 1j
for kind in ['q', 'm', 'h']:
msg = "complex argsort, kind=%s" % kind
assert_equal(ai.copy().argsort(kind=kind), a, msg)
assert_equal(bi.copy().argsort(kind=kind), b, msg)
# test argsort of complex arrays requiring byte-swapping, gh-5441
for endianess in '<>':
for dt in np.typecodes['Complex']:
arr = np.array([1+3.j, 2+2.j, 3+1.j], dtype=endianess + dt)
msg = 'byte-swapped complex argsort, dtype={0}'.format(dt)
assert_equal(arr.argsort(),
np.arange(len(arr), dtype=np.intp), msg)
# test string argsorts.
s = 'aaaaaaaa'
a = np.array([s + chr(i) for i in range(101)])
b = a[::-1].copy()
r = np.arange(101)
rr = r[::-1]
for kind in ['q', 'm', 'h']:
msg = "string argsort, kind=%s" % kind
assert_equal(a.copy().argsort(kind=kind), r, msg)
assert_equal(b.copy().argsort(kind=kind), rr, msg)
# test unicode argsorts.
s = 'aaaaaaaa'
a = np.array([s + chr(i) for i in range(101)], dtype=np.unicode)
b = a[::-1]
r = np.arange(101)
rr = r[::-1]
for kind in ['q', 'm', 'h']:
msg = "unicode argsort, kind=%s" % kind
assert_equal(a.copy().argsort(kind=kind), r, msg)
assert_equal(b.copy().argsort(kind=kind), rr, msg)
# test object array argsorts.
a = np.empty((101,), dtype=np.object)
a[:] = list(range(101))
b = a[::-1]
r = np.arange(101)
rr = r[::-1]
for kind in ['q', 'm', 'h']:
msg = "object argsort, kind=%s" % kind
assert_equal(a.copy().argsort(kind=kind), r, msg)
assert_equal(b.copy().argsort(kind=kind), rr, msg)
# test structured array argsorts.
dt = np.dtype([('f', float), ('i', int)])
a = np.array([(i, i) for i in range(101)], dtype=dt)
b = a[::-1]
r = np.arange(101)
rr = r[::-1]
for kind in ['q', 'm', 'h']:
msg = "structured array argsort, kind=%s" % kind
assert_equal(a.copy().argsort(kind=kind), r, msg)
assert_equal(b.copy().argsort(kind=kind), rr, msg)
# test datetime64 argsorts.
a = np.arange(0, 101, dtype='datetime64[D]')
b = a[::-1]
r = np.arange(101)
rr = r[::-1]
for kind in ['q', 'h', 'm']:
msg = "datetime64 argsort, kind=%s" % kind
assert_equal(a.copy().argsort(kind=kind), r, msg)
assert_equal(b.copy().argsort(kind=kind), rr, msg)
# test timedelta64 argsorts.
a = np.arange(0, 101, dtype='timedelta64[D]')
b = a[::-1]
r = np.arange(101)
rr = r[::-1]
for kind in ['q', 'h', 'm']:
msg = "timedelta64 argsort, kind=%s" % kind
assert_equal(a.copy().argsort(kind=kind), r, msg)
assert_equal(b.copy().argsort(kind=kind), rr, msg)
# check axis handling. This should be the same for all type
# specific argsorts, so we only check it for one type and one kind
a = np.array([[3, 2], [1, 0]])
b = np.array([[1, 1], [0, 0]])
c = np.array([[1, 0], [1, 0]])
assert_equal(a.copy().argsort(axis=0), b)
assert_equal(a.copy().argsort(axis=1), c)
assert_equal(a.copy().argsort(), c)
# check axis handling for multidimensional empty arrays
a = np.array([])
a.shape = (3, 2, 1, 0)
for axis in range(-a.ndim, a.ndim):
msg = 'test empty array argsort with axis={0}'.format(axis)
assert_equal(np.argsort(a, axis=axis),
np.zeros_like(a, dtype=np.intp), msg)
msg = 'test empty array argsort with axis=None'
assert_equal(np.argsort(a, axis=None),
np.zeros_like(a.ravel(), dtype=np.intp), msg)
# check that stable argsorts are stable
r = np.arange(100)
# scalars
a = np.zeros(100)
assert_equal(a.argsort(kind='m'), r)
# complex
a = np.zeros(100, dtype=np.complex)
assert_equal(a.argsort(kind='m'), r)
# string
a = np.array(['aaaaaaaaa' for i in range(100)])
assert_equal(a.argsort(kind='m'), r)
# unicode
a = np.array(['aaaaaaaaa' for i in range(100)], dtype=np.unicode)
assert_equal(a.argsort(kind='m'), r)
def test_sort_unicode_kind(self):
d = np.arange(10)
k = b'\xc3\xa4'.decode("UTF8")
assert_raises(ValueError, d.sort, kind=k)
assert_raises(ValueError, d.argsort, kind=k)
def test_searchsorted(self):
# test for floats and complex containing nans. The logic is the
# same for all float types so only test double types for now.
# The search sorted routines use the compare functions for the
# array type, so this checks if that is consistent with the sort
# order.
# check double
a = np.array([0, 1, np.nan])
msg = "Test real searchsorted with nans, side='l'"
b = a.searchsorted(a, side='l')
assert_equal(b, np.arange(3), msg)
msg = "Test real searchsorted with nans, side='r'"
b = a.searchsorted(a, side='r')
assert_equal(b, np.arange(1, 4), msg)
# check double complex
a = np.zeros(9, dtype=np.complex128)
a.real += [0, 0, 1, 1, 0, 1, np.nan, np.nan, np.nan]
a.imag += [0, 1, 0, 1, np.nan, np.nan, 0, 1, np.nan]
msg = "Test complex searchsorted with nans, side='l'"
b = a.searchsorted(a, side='l')
assert_equal(b, np.arange(9), msg)
msg = "Test complex searchsorted with nans, side='r'"
b = a.searchsorted(a, side='r')
assert_equal(b, np.arange(1, 10), msg)
msg = "Test searchsorted with little endian, side='l'"
a = np.array([0, 128], dtype='<i4')
b = a.searchsorted(np.array(128, dtype='<i4'))
assert_equal(b, 1, msg)
msg = "Test searchsorted with big endian, side='l'"
a = np.array([0, 128], dtype='>i4')
b = a.searchsorted(np.array(128, dtype='>i4'))
assert_equal(b, 1, msg)
# Check 0 elements
a = np.ones(0)
b = a.searchsorted([0, 1, 2], 'l')
assert_equal(b, [0, 0, 0])
b = a.searchsorted([0, 1, 2], 'r')
assert_equal(b, [0, 0, 0])
a = np.ones(1)
# Check 1 element
b = a.searchsorted([0, 1, 2], 'l')
assert_equal(b, [0, 0, 1])
b = a.searchsorted([0, 1, 2], 'r')
assert_equal(b, [0, 1, 1])
# Check all elements equal
a = np.ones(2)
b = a.searchsorted([0, 1, 2], 'l')
assert_equal(b, [0, 0, 2])
b = a.searchsorted([0, 1, 2], 'r')
assert_equal(b, [0, 2, 2])
# Test searching unaligned array
a = np.arange(10)
aligned = np.empty(a.itemsize * a.size + 1, 'uint8')
unaligned = aligned[1:].view(a.dtype)
unaligned[:] = a
# Test searching unaligned array
b = unaligned.searchsorted(a, 'l')
assert_equal(b, a)
b = unaligned.searchsorted(a, 'r')
assert_equal(b, a + 1)
# Test searching for unaligned keys
b = a.searchsorted(unaligned, 'l')
assert_equal(b, a)
b = a.searchsorted(unaligned, 'r')
assert_equal(b, a + 1)
# Test smart resetting of binsearch indices
a = np.arange(5)
b = a.searchsorted([6, 5, 4], 'l')
assert_equal(b, [5, 5, 4])
b = a.searchsorted([6, 5, 4], 'r')
assert_equal(b, [5, 5, 5])
# Test all type specific binary search functions
types = ''.join((np.typecodes['AllInteger'], np.typecodes['AllFloat'],
np.typecodes['Datetime'], '?O'))
for dt in types:
if dt == 'M':
dt = 'M8[D]'
if dt == '?':
a = np.arange(2, dtype=dt)
out = np.arange(2)
else:
a = np.arange(0, 5, dtype=dt)
out = np.arange(5)
b = a.searchsorted(a, 'l')
assert_equal(b, out)
b = a.searchsorted(a, 'r')
assert_equal(b, out + 1)
def test_searchsorted_unicode(self):
# Test searchsorted on unicode strings.
# 1.6.1 contained a string length miscalculation in
# arraytypes.c.src:UNICODE_compare() which manifested as
# incorrect/inconsistent results from searchsorted.
a = np.array(['P:\\20x_dapi_cy3\\20x_dapi_cy3_20100185_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100186_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100187_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100189_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100190_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100191_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100192_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100193_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100194_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100195_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100196_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100197_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100198_1',
'P:\\20x_dapi_cy3\\20x_dapi_cy3_20100199_1'],
dtype=np.unicode)
ind = np.arange(len(a))
assert_equal([a.searchsorted(v, 'left') for v in a], ind)
assert_equal([a.searchsorted(v, 'right') for v in a], ind + 1)
assert_equal([a.searchsorted(a[i], 'left') for i in ind], ind)
assert_equal([a.searchsorted(a[i], 'right') for i in ind], ind + 1)
def test_searchsorted_with_sorter(self):
a = np.array([5, 2, 1, 3, 4])
s = np.argsort(a)
assert_raises(TypeError, np.searchsorted, a, 0, sorter=(1, (2, 3)))
assert_raises(TypeError, np.searchsorted, a, 0, sorter=[1.1])
assert_raises(ValueError, np.searchsorted, a, 0, sorter=[1, 2, 3, 4])
assert_raises(ValueError, np.searchsorted, a, 0, sorter=[1, 2, 3, 4, 5, 6])
# bounds check
assert_raises(ValueError, np.searchsorted, a, 4, sorter=[0, 1, 2, 3, 5])
assert_raises(ValueError, np.searchsorted, a, 0, sorter=[-1, 0, 1, 2, 3])
assert_raises(ValueError, np.searchsorted, a, 0, sorter=[4, 0, -1, 2, 3])
a = np.random.rand(300)
s = a.argsort()
b = np.sort(a)
k = np.linspace(0, 1, 20)
assert_equal(b.searchsorted(k), a.searchsorted(k, sorter=s))
a = np.array([0, 1, 2, 3, 5]*20)
s = a.argsort()
k = [0, 1, 2, 3, 5]
expected = [0, 20, 40, 60, 80]
assert_equal(a.searchsorted(k, side='l', sorter=s), expected)
expected = [20, 40, 60, 80, 100]
assert_equal(a.searchsorted(k, side='r', sorter=s), expected)
# Test searching unaligned array
keys = np.arange(10)
a = keys.copy()
np.random.shuffle(s)
s = a.argsort()
aligned = np.empty(a.itemsize * a.size + 1, 'uint8')
unaligned = aligned[1:].view(a.dtype)
# Test searching unaligned array
unaligned[:] = a
b = unaligned.searchsorted(keys, 'l', s)
assert_equal(b, keys)
b = unaligned.searchsorted(keys, 'r', s)
assert_equal(b, keys + 1)
# Test searching for unaligned keys
unaligned[:] = keys
b = a.searchsorted(unaligned, 'l', s)
assert_equal(b, keys)
b = a.searchsorted(unaligned, 'r', s)
assert_equal(b, keys + 1)
# Test all type specific indirect binary search functions
types = ''.join((np.typecodes['AllInteger'], np.typecodes['AllFloat'],
np.typecodes['Datetime'], '?O'))
for dt in types:
if dt == 'M':
dt = 'M8[D]'
if dt == '?':
a = np.array([1, 0], dtype=dt)
# We want the sorter array to be of a type that is different
# from np.intp in all platforms, to check for #4698
s = np.array([1, 0], dtype=np.int16)
out = np.array([1, 0])
else:
a = np.array([3, 4, 1, 2, 0], dtype=dt)
# We want the sorter array to be of a type that is different
# from np.intp in all platforms, to check for #4698
s = np.array([4, 2, 3, 0, 1], dtype=np.int16)
out = np.array([3, 4, 1, 2, 0], dtype=np.intp)
b = a.searchsorted(a, 'l', s)
assert_equal(b, out)
b = a.searchsorted(a, 'r', s)
assert_equal(b, out + 1)
# Test non-contiguous sorter array
a = np.array([3, 4, 1, 2, 0])
srt = np.empty((10,), dtype=np.intp)
srt[1::2] = -1
srt[::2] = [4, 2, 3, 0, 1]
s = srt[::2]
out = np.array([3, 4, 1, 2, 0], dtype=np.intp)
b = a.searchsorted(a, 'l', s)
assert_equal(b, out)
b = a.searchsorted(a, 'r', s)
assert_equal(b, out + 1)
def test_searchsorted_return_type(self):
# Functions returning indices should always return base ndarrays
class A(np.ndarray):
pass
a = np.arange(5).view(A)
b = np.arange(1, 3).view(A)
s = np.arange(5).view(A)
assert_(not isinstance(a.searchsorted(b, 'l'), A))
assert_(not isinstance(a.searchsorted(b, 'r'), A))
assert_(not isinstance(a.searchsorted(b, 'l', s), A))
assert_(not isinstance(a.searchsorted(b, 'r', s), A))
def test_argpartition_out_of_range(self):
# Test out of range values in kth raise an error, gh-5469
d = np.arange(10)
assert_raises(ValueError, d.argpartition, 10)
assert_raises(ValueError, d.argpartition, -11)
# Test also for generic type argpartition, which uses sorting
# and used to not bound check kth
d_obj = np.arange(10, dtype=object)
assert_raises(ValueError, d_obj.argpartition, 10)
assert_raises(ValueError, d_obj.argpartition, -11)
def test_partition_out_of_range(self):
# Test out of range values in kth raise an error, gh-5469
d = np.arange(10)
assert_raises(ValueError, d.partition, 10)
assert_raises(ValueError, d.partition, -11)
# Test also for generic type partition, which uses sorting
# and used to not bound check kth
d_obj = np.arange(10, dtype=object)
assert_raises(ValueError, d_obj.partition, 10)
assert_raises(ValueError, d_obj.partition, -11)
def test_partition_empty_array(self):
# check axis handling for multidimensional empty arrays
a = np.array([])
a.shape = (3, 2, 1, 0)
for axis in range(-a.ndim, a.ndim):
msg = 'test empty array partition with axis={0}'.format(axis)
assert_equal(np.partition(a, 0, axis=axis), a, msg)
msg = 'test empty array partition with axis=None'
assert_equal(np.partition(a, 0, axis=None), a.ravel(), msg)
def test_argpartition_empty_array(self):
# check axis handling for multidimensional empty arrays
a = np.array([])
a.shape = (3, 2, 1, 0)
for axis in range(-a.ndim, a.ndim):
msg = 'test empty array argpartition with axis={0}'.format(axis)
assert_equal(np.partition(a, 0, axis=axis),
np.zeros_like(a, dtype=np.intp), msg)
msg = 'test empty array argpartition with axis=None'
assert_equal(np.partition(a, 0, axis=None),
np.zeros_like(a.ravel(), dtype=np.intp), msg)
def test_partition(self):
d = np.arange(10)
assert_raises(TypeError, np.partition, d, 2, kind=1)
assert_raises(ValueError, np.partition, d, 2, kind="nonsense")
assert_raises(ValueError, np.argpartition, d, 2, kind="nonsense")
assert_raises(ValueError, d.partition, 2, axis=0, kind="nonsense")
assert_raises(ValueError, d.argpartition, 2, axis=0, kind="nonsense")
for k in ("introselect",):
d = np.array([])
assert_array_equal(np.partition(d, 0, kind=k), d)
assert_array_equal(np.argpartition(d, 0, kind=k), d)
d = np.ones(1)
assert_array_equal(np.partition(d, 0, kind=k)[0], d)
assert_array_equal(d[np.argpartition(d, 0, kind=k)],
np.partition(d, 0, kind=k))
# kth not modified
kth = np.array([30, 15, 5])
okth = kth.copy()
np.partition(np.arange(40), kth)
assert_array_equal(kth, okth)
for r in ([2, 1], [1, 2], [1, 1]):
d = np.array(r)
tgt = np.sort(d)
assert_array_equal(np.partition(d, 0, kind=k)[0], tgt[0])
assert_array_equal(np.partition(d, 1, kind=k)[1], tgt[1])
assert_array_equal(d[np.argpartition(d, 0, kind=k)],
np.partition(d, 0, kind=k))
assert_array_equal(d[np.argpartition(d, 1, kind=k)],
np.partition(d, 1, kind=k))
for i in range(d.size):
d[i:].partition(0, kind=k)
assert_array_equal(d, tgt)
for r in ([3, 2, 1], [1, 2, 3], [2, 1, 3], [2, 3, 1],
[1, 1, 1], [1, 2, 2], [2, 2, 1], [1, 2, 1]):
d = np.array(r)
tgt = np.sort(d)
assert_array_equal(np.partition(d, 0, kind=k)[0], tgt[0])
assert_array_equal(np.partition(d, 1, kind=k)[1], tgt[1])
assert_array_equal(np.partition(d, 2, kind=k)[2], tgt[2])
assert_array_equal(d[np.argpartition(d, 0, kind=k)],
np.partition(d, 0, kind=k))
assert_array_equal(d[np.argpartition(d, 1, kind=k)],
np.partition(d, 1, kind=k))
assert_array_equal(d[np.argpartition(d, 2, kind=k)],
np.partition(d, 2, kind=k))
for i in range(d.size):
d[i:].partition(0, kind=k)
assert_array_equal(d, tgt)
d = np.ones(50)
assert_array_equal(np.partition(d, 0, kind=k), d)
assert_array_equal(d[np.argpartition(d, 0, kind=k)],
np.partition(d, 0, kind=k))
# sorted
d = np.arange(49)
self.assertEqual(np.partition(d, 5, kind=k)[5], 5)
self.assertEqual(np.partition(d, 15, kind=k)[15], 15)
assert_array_equal(d[np.argpartition(d, 5, kind=k)],
np.partition(d, 5, kind=k))
assert_array_equal(d[np.argpartition(d, 15, kind=k)],
np.partition(d, 15, kind=k))
# rsorted
d = np.arange(47)[::-1]
self.assertEqual(np.partition(d, 6, kind=k)[6], 6)
self.assertEqual(np.partition(d, 16, kind=k)[16], 16)
assert_array_equal(d[np.argpartition(d, 6, kind=k)],
np.partition(d, 6, kind=k))
assert_array_equal(d[np.argpartition(d, 16, kind=k)],
np.partition(d, 16, kind=k))
assert_array_equal(np.partition(d, -6, kind=k),
np.partition(d, 41, kind=k))
assert_array_equal(np.partition(d, -16, kind=k),
np.partition(d, 31, kind=k))
assert_array_equal(d[np.argpartition(d, -6, kind=k)],
np.partition(d, 41, kind=k))
# median of 3 killer, O(n^2) on pure median 3 pivot quickselect
# exercises the median of median of 5 code used to keep O(n)
d = np.arange(1000000)
x = np.roll(d, d.size // 2)
mid = x.size // 2 + 1
assert_equal(np.partition(x, mid)[mid], mid)
d = np.arange(1000001)
x = np.roll(d, d.size // 2 + 1)
mid = x.size // 2 + 1
assert_equal(np.partition(x, mid)[mid], mid)
# max
d = np.ones(10)
d[1] = 4
assert_equal(np.partition(d, (2, -1))[-1], 4)
assert_equal(np.partition(d, (2, -1))[2], 1)
assert_equal(d[np.argpartition(d, (2, -1))][-1], 4)
assert_equal(d[np.argpartition(d, (2, -1))][2], 1)
d[1] = np.nan
assert_(np.isnan(d[np.argpartition(d, (2, -1))][-1]))
assert_(np.isnan(np.partition(d, (2, -1))[-1]))
# equal elements
d = np.arange(47) % 7
tgt = np.sort(np.arange(47) % 7)
np.random.shuffle(d)
for i in range(d.size):
self.assertEqual(np.partition(d, i, kind=k)[i], tgt[i])
assert_array_equal(d[np.argpartition(d, 6, kind=k)],
np.partition(d, 6, kind=k))
assert_array_equal(d[np.argpartition(d, 16, kind=k)],
np.partition(d, 16, kind=k))
for i in range(d.size):
d[i:].partition(0, kind=k)
assert_array_equal(d, tgt)
d = np.array([0, 1, 2, 3, 4, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 9])
kth = [0, 3, 19, 20]
assert_equal(np.partition(d, kth, kind=k)[kth], (0, 3, 7, 7))
assert_equal(d[np.argpartition(d, kth, kind=k)][kth], (0, 3, 7, 7))
d = np.array([2, 1])
d.partition(0, kind=k)
assert_raises(ValueError, d.partition, 2)
assert_raises(ValueError, d.partition, 3, axis=1)
assert_raises(ValueError, np.partition, d, 2)
assert_raises(ValueError, np.partition, d, 2, axis=1)
assert_raises(ValueError, d.argpartition, 2)
assert_raises(ValueError, d.argpartition, 3, axis=1)
assert_raises(ValueError, np.argpartition, d, 2)
assert_raises(ValueError, np.argpartition, d, 2, axis=1)
d = np.arange(10).reshape((2, 5))
d.partition(1, axis=0, kind=k)
d.partition(4, axis=1, kind=k)
np.partition(d, 1, axis=0, kind=k)
np.partition(d, 4, axis=1, kind=k)
np.partition(d, 1, axis=None, kind=k)
np.partition(d, 9, axis=None, kind=k)
d.argpartition(1, axis=0, kind=k)
d.argpartition(4, axis=1, kind=k)
np.argpartition(d, 1, axis=0, kind=k)
np.argpartition(d, 4, axis=1, kind=k)
np.argpartition(d, 1, axis=None, kind=k)
np.argpartition(d, 9, axis=None, kind=k)
assert_raises(ValueError, d.partition, 2, axis=0)
assert_raises(ValueError, d.partition, 11, axis=1)
assert_raises(TypeError, d.partition, 2, axis=None)
assert_raises(ValueError, np.partition, d, 9, axis=1)
assert_raises(ValueError, np.partition, d, 11, axis=None)
assert_raises(ValueError, d.argpartition, 2, axis=0)
assert_raises(ValueError, d.argpartition, 11, axis=1)
assert_raises(ValueError, np.argpartition, d, 9, axis=1)
assert_raises(ValueError, np.argpartition, d, 11, axis=None)
td = [(dt, s) for dt in [np.int32, np.float32, np.complex64]
for s in (9, 16)]
for dt, s in td:
aae = assert_array_equal
at = self.assertTrue
d = np.arange(s, dtype=dt)
np.random.shuffle(d)
d1 = np.tile(np.arange(s, dtype=dt), (4, 1))
map(np.random.shuffle, d1)
d0 = np.transpose(d1)
for i in range(d.size):
p = np.partition(d, i, kind=k)
self.assertEqual(p[i], i)
# all before are smaller
assert_array_less(p[:i], p[i])
# all after are larger
assert_array_less(p[i], p[i + 1:])
aae(p, d[np.argpartition(d, i, kind=k)])
p = np.partition(d1, i, axis=1, kind=k)
aae(p[:, i], np.array([i] * d1.shape[0], dtype=dt))
# array_less does not seem to work right
at((p[:, :i].T <= p[:, i]).all(),
msg="%d: %r <= %r" % (i, p[:, i], p[:, :i].T))
at((p[:, i + 1:].T > p[:, i]).all(),
msg="%d: %r < %r" % (i, p[:, i], p[:, i + 1:].T))
aae(p, d1[np.arange(d1.shape[0])[:, None],
np.argpartition(d1, i, axis=1, kind=k)])
p = np.partition(d0, i, axis=0, kind=k)
aae(p[i, :], np.array([i] * d1.shape[0], dtype=dt))
# array_less does not seem to work right
at((p[:i, :] <= p[i, :]).all(),
msg="%d: %r <= %r" % (i, p[i, :], p[:i, :]))
at((p[i + 1:, :] > p[i, :]).all(),
msg="%d: %r < %r" % (i, p[i, :], p[:, i + 1:]))
aae(p, d0[np.argpartition(d0, i, axis=0, kind=k),
np.arange(d0.shape[1])[None, :]])
# check inplace
dc = d.copy()
dc.partition(i, kind=k)
assert_equal(dc, np.partition(d, i, kind=k))
dc = d0.copy()
dc.partition(i, axis=0, kind=k)
assert_equal(dc, np.partition(d0, i, axis=0, kind=k))
dc = d1.copy()
dc.partition(i, axis=1, kind=k)
assert_equal(dc, np.partition(d1, i, axis=1, kind=k))
def assert_partitioned(self, d, kth):
prev = 0
for k in np.sort(kth):
assert_array_less(d[prev:k], d[k], err_msg='kth %d' % k)
assert_((d[k:] >= d[k]).all(),
msg="kth %d, %r not greater equal %d" % (k, d[k:], d[k]))
prev = k + 1
def test_partition_iterative(self):
d = np.arange(17)
kth = (0, 1, 2, 429, 231)
assert_raises(ValueError, d.partition, kth)
assert_raises(ValueError, d.argpartition, kth)
d = np.arange(10).reshape((2, 5))
assert_raises(ValueError, d.partition, kth, axis=0)
assert_raises(ValueError, d.partition, kth, axis=1)
assert_raises(ValueError, np.partition, d, kth, axis=1)
assert_raises(ValueError, np.partition, d, kth, axis=None)
d = np.array([3, 4, 2, 1])
p = np.partition(d, (0, 3))
self.assert_partitioned(p, (0, 3))
self.assert_partitioned(d[np.argpartition(d, (0, 3))], (0, 3))
assert_array_equal(p, np.partition(d, (-3, -1)))
assert_array_equal(p, d[np.argpartition(d, (-3, -1))])
d = np.arange(17)
np.random.shuffle(d)
d.partition(range(d.size))
assert_array_equal(np.arange(17), d)
np.random.shuffle(d)
assert_array_equal(np.arange(17), d[d.argpartition(range(d.size))])
# test unsorted kth
d = np.arange(17)
np.random.shuffle(d)
keys = np.array([1, 3, 8, -2])
np.random.shuffle(d)
p = np.partition(d, keys)
self.assert_partitioned(p, keys)
p = d[np.argpartition(d, keys)]
self.assert_partitioned(p, keys)
np.random.shuffle(keys)
assert_array_equal(np.partition(d, keys), p)
assert_array_equal(d[np.argpartition(d, keys)], p)
# equal kth
d = np.arange(20)[::-1]
self.assert_partitioned(np.partition(d, [5]*4), [5])
self.assert_partitioned(np.partition(d, [5]*4 + [6, 13]),
[5]*4 + [6, 13])
self.assert_partitioned(d[np.argpartition(d, [5]*4)], [5])
self.assert_partitioned(d[np.argpartition(d, [5]*4 + [6, 13])],
[5]*4 + [6, 13])
d = np.arange(12)
np.random.shuffle(d)
d1 = np.tile(np.arange(12), (4, 1))
map(np.random.shuffle, d1)
d0 = np.transpose(d1)
kth = (1, 6, 7, -1)
p = np.partition(d1, kth, axis=1)
pa = d1[np.arange(d1.shape[0])[:, None],
d1.argpartition(kth, axis=1)]
assert_array_equal(p, pa)
for i in range(d1.shape[0]):
self.assert_partitioned(p[i,:], kth)
p = np.partition(d0, kth, axis=0)
pa = d0[np.argpartition(d0, kth, axis=0),
np.arange(d0.shape[1])[None,:]]
assert_array_equal(p, pa)
for i in range(d0.shape[1]):
self.assert_partitioned(p[:, i], kth)
def test_partition_cdtype(self):
d = np.array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
('Lancelot', 1.9, 38)],
dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
tgt = np.sort(d, order=['age', 'height'])
assert_array_equal(np.partition(d, range(d.size),
order=['age', 'height']),
tgt)
assert_array_equal(d[np.argpartition(d, range(d.size),
order=['age', 'height'])],
tgt)
for k in range(d.size):
assert_equal(np.partition(d, k, order=['age', 'height'])[k],
tgt[k])
assert_equal(d[np.argpartition(d, k, order=['age', 'height'])][k],
tgt[k])
d = np.array(['Galahad', 'Arthur', 'zebra', 'Lancelot'])
tgt = np.sort(d)
assert_array_equal(np.partition(d, range(d.size)), tgt)
for k in range(d.size):
assert_equal(np.partition(d, k)[k], tgt[k])
assert_equal(d[np.argpartition(d, k)][k], tgt[k])
def test_partition_unicode_kind(self):
d = np.arange(10)
k = b'\xc3\xa4'.decode("UTF8")
assert_raises(ValueError, d.partition, 2, kind=k)
assert_raises(ValueError, d.argpartition, 2, kind=k)
def test_partition_fuzz(self):
# a few rounds of random data testing
for j in range(10, 30):
for i in range(1, j - 2):
d = np.arange(j)
np.random.shuffle(d)
d = d % np.random.randint(2, 30)
idx = np.random.randint(d.size)
kth = [0, idx, i, i + 1]
tgt = np.sort(d)[kth]
assert_array_equal(np.partition(d, kth)[kth], tgt,
err_msg="data: %r\n kth: %r" % (d, kth))
def test_argpartition_gh5524(self):
# A test for functionality of argpartition on lists.
d = [6,7,3,2,9,0]
p = np.argpartition(d,1)
self.assert_partitioned(np.array(d)[p],[1])
def test_flatten(self):
x0 = np.array([[1, 2, 3], [4, 5, 6]], np.int32)
x1 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], np.int32)
y0 = np.array([1, 2, 3, 4, 5, 6], np.int32)
y0f = np.array([1, 4, 2, 5, 3, 6], np.int32)
y1 = np.array([1, 2, 3, 4, 5, 6, 7, 8], np.int32)
y1f = np.array([1, 5, 3, 7, 2, 6, 4, 8], np.int32)
assert_equal(x0.flatten(), y0)
assert_equal(x0.flatten('F'), y0f)
assert_equal(x0.flatten('F'), x0.T.flatten())
assert_equal(x1.flatten(), y1)
assert_equal(x1.flatten('F'), y1f)
assert_equal(x1.flatten('F'), x1.T.flatten())
def test_dot(self):
a = np.array([[1, 0], [0, 1]])
b = np.array([[0, 1], [1, 0]])
c = np.array([[9, 1], [1, -9]])
d = np.arange(24).reshape(4, 6)
ddt = np.array(
[[ 55, 145, 235, 325],
[ 145, 451, 757, 1063],
[ 235, 757, 1279, 1801],
[ 325, 1063, 1801, 2539]]
)
dtd = np.array(
[[504, 540, 576, 612, 648, 684],
[540, 580, 620, 660, 700, 740],
[576, 620, 664, 708, 752, 796],
[612, 660, 708, 756, 804, 852],
[648, 700, 752, 804, 856, 908],
[684, 740, 796, 852, 908, 964]]
)
# gemm vs syrk optimizations
for et in [np.float32, np.float64, np.complex64, np.complex128]:
eaf = a.astype(et)
assert_equal(np.dot(eaf, eaf), eaf)
assert_equal(np.dot(eaf.T, eaf), eaf)
assert_equal(np.dot(eaf, eaf.T), eaf)
assert_equal(np.dot(eaf.T, eaf.T), eaf)
assert_equal(np.dot(eaf.T.copy(), eaf), eaf)
assert_equal(np.dot(eaf, eaf.T.copy()), eaf)
assert_equal(np.dot(eaf.T.copy(), eaf.T.copy()), eaf)
# syrk validations
for et in [np.float32, np.float64, np.complex64, np.complex128]:
eaf = a.astype(et)
ebf = b.astype(et)
assert_equal(np.dot(ebf, ebf), eaf)
assert_equal(np.dot(ebf.T, ebf), eaf)
assert_equal(np.dot(ebf, ebf.T), eaf)
assert_equal(np.dot(ebf.T, ebf.T), eaf)
# syrk - different shape, stride, and view validations
for et in [np.float32, np.float64, np.complex64, np.complex128]:
edf = d.astype(et)
assert_equal(
np.dot(edf[::-1, :], edf.T),
np.dot(edf[::-1, :].copy(), edf.T.copy())
)
assert_equal(
np.dot(edf[:, ::-1], edf.T),
np.dot(edf[:, ::-1].copy(), edf.T.copy())
)
assert_equal(
np.dot(edf, edf[::-1, :].T),
np.dot(edf, edf[::-1, :].T.copy())
)
assert_equal(
np.dot(edf, edf[:, ::-1].T),
np.dot(edf, edf[:, ::-1].T.copy())
)
assert_equal(
np.dot(edf[:edf.shape[0] // 2, :], edf[::2, :].T),
np.dot(edf[:edf.shape[0] // 2, :].copy(), edf[::2, :].T.copy())
)
assert_equal(
np.dot(edf[::2, :], edf[:edf.shape[0] // 2, :].T),
np.dot(edf[::2, :].copy(), edf[:edf.shape[0] // 2, :].T.copy())
)
# syrk - different shape
for et in [np.float32, np.float64, np.complex64, np.complex128]:
edf = d.astype(et)
eddtf = ddt.astype(et)
edtdf = dtd.astype(et)
assert_equal(np.dot(edf, edf.T), eddtf)
assert_equal(np.dot(edf.T, edf), edtdf)
# function versus methods
assert_equal(np.dot(a, b), a.dot(b))
assert_equal(np.dot(np.dot(a, b), c), a.dot(b).dot(c))
# test passing in an output array
c = np.zeros_like(a)
a.dot(b, c)
assert_equal(c, np.dot(a, b))
# test keyword args
c = np.zeros_like(a)
a.dot(b=b, out=c)
assert_equal(c, np.dot(a, b))
def test_dot_override(self):
# 2016-01-29: NUMPY_UFUNC_DISABLED
return
class A(object):
def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
return "A"
class B(object):
def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
return NotImplemented
a = A()
b = B()
c = np.array([[1]])
assert_equal(np.dot(a, b), "A")
assert_equal(c.dot(a), "A")
assert_raises(TypeError, np.dot, b, c)
assert_raises(TypeError, c.dot, b)
def test_dot_type_mismatch(self):
c = 1.
A = np.array((1,1), dtype='i,i')
assert_raises(TypeError, np.dot, c, A)
assert_raises(TypeError, np.dot, A, c)
def test_diagonal(self):
a = np.arange(12).reshape((3, 4))
assert_equal(a.diagonal(), [0, 5, 10])
assert_equal(a.diagonal(0), [0, 5, 10])
assert_equal(a.diagonal(1), [1, 6, 11])
assert_equal(a.diagonal(-1), [4, 9])
b = np.arange(8).reshape((2, 2, 2))
assert_equal(b.diagonal(), [[0, 6], [1, 7]])
assert_equal(b.diagonal(0), [[0, 6], [1, 7]])
assert_equal(b.diagonal(1), [[2], [3]])
assert_equal(b.diagonal(-1), [[4], [5]])
assert_raises(ValueError, b.diagonal, axis1=0, axis2=0)
assert_equal(b.diagonal(0, 1, 2), [[0, 3], [4, 7]])
assert_equal(b.diagonal(0, 0, 1), [[0, 6], [1, 7]])
assert_equal(b.diagonal(offset=1, axis1=0, axis2=2), [[1], [3]])
# Order of axis argument doesn't matter:
assert_equal(b.diagonal(0, 2, 1), [[0, 3], [4, 7]])
def test_diagonal_view_notwriteable(self):
# this test is only for 1.9, the diagonal view will be
# writeable in 1.10.
a = np.eye(3).diagonal()
assert_(not a.flags.writeable)
assert_(not a.flags.owndata)
a = np.diagonal(np.eye(3))
assert_(not a.flags.writeable)
assert_(not a.flags.owndata)
a = np.diag(np.eye(3))
assert_(not a.flags.writeable)
assert_(not a.flags.owndata)
def test_diagonal_memleak(self):
# Regression test for a bug that crept in at one point
a = np.zeros((100, 100))
assert_(sys.getrefcount(a) < 50)
for i in range(100):
a.diagonal()
assert_(sys.getrefcount(a) < 50)
def test_trace(self):
a = np.arange(12).reshape((3, 4))
assert_equal(a.trace(), 15)
assert_equal(a.trace(0), 15)
assert_equal(a.trace(1), 18)
assert_equal(a.trace(-1), 13)
b = np.arange(8).reshape((2, 2, 2))
assert_equal(b.trace(), [6, 8])
assert_equal(b.trace(0), [6, 8])
assert_equal(b.trace(1), [2, 3])
assert_equal(b.trace(-1), [4, 5])
assert_equal(b.trace(0, 0, 1), [6, 8])
assert_equal(b.trace(0, 0, 2), [5, 9])
assert_equal(b.trace(0, 1, 2), [3, 11])
assert_equal(b.trace(offset=1, axis1=0, axis2=2), [1, 3])
def test_trace_subclass(self):
# The class would need to overwrite trace to ensure single-element
# output also has the right subclass.
class MyArray(np.ndarray):
pass
b = np.arange(8).reshape((2, 2, 2)).view(MyArray)
t = b.trace()
assert isinstance(t, MyArray)
def test_put(self):
icodes = np.typecodes['AllInteger']
fcodes = np.typecodes['AllFloat']
for dt in icodes + fcodes + 'O':
tgt = np.array([0, 1, 0, 3, 0, 5], dtype=dt)
# test 1-d
a = np.zeros(6, dtype=dt)
a.put([1, 3, 5], [1, 3, 5])
assert_equal(a, tgt)
# test 2-d
a = np.zeros((2, 3), dtype=dt)
a.put([1, 3, 5], [1, 3, 5])
assert_equal(a, tgt.reshape(2, 3))
for dt in '?':
tgt = np.array([False, True, False, True, False, True], dtype=dt)
# test 1-d
a = np.zeros(6, dtype=dt)
a.put([1, 3, 5], [True]*3)
assert_equal(a, tgt)
# test 2-d
a = np.zeros((2, 3), dtype=dt)
a.put([1, 3, 5], [True]*3)
assert_equal(a, tgt.reshape(2, 3))
# check must be writeable
a = np.zeros(6)
a.flags.writeable = False
assert_raises(ValueError, a.put, [1, 3, 5], [1, 3, 5])
# when calling np.put, make sure a
# TypeError is raised if the object
# isn't an ndarray
bad_array = [1, 2, 3]
assert_raises(TypeError, np.put, bad_array, [0, 2], 5)
def test_ravel(self):
a = np.array([[0, 1], [2, 3]])
assert_equal(a.ravel(), [0, 1, 2, 3])
assert_(not a.ravel().flags.owndata)
assert_equal(a.ravel('F'), [0, 2, 1, 3])
assert_equal(a.ravel(order='C'), [0, 1, 2, 3])
assert_equal(a.ravel(order='F'), [0, 2, 1, 3])
assert_equal(a.ravel(order='A'), [0, 1, 2, 3])
assert_(not a.ravel(order='A').flags.owndata)
assert_equal(a.ravel(order='K'), [0, 1, 2, 3])
assert_(not a.ravel(order='K').flags.owndata)
assert_equal(a.ravel(), a.reshape(-1))
a = np.array([[0, 1], [2, 3]], order='F')
assert_equal(a.ravel(), [0, 1, 2, 3])
assert_equal(a.ravel(order='A'), [0, 2, 1, 3])
assert_equal(a.ravel(order='K'), [0, 2, 1, 3])
assert_(not a.ravel(order='A').flags.owndata)
assert_(not a.ravel(order='K').flags.owndata)
assert_equal(a.ravel(), a.reshape(-1))
assert_equal(a.ravel(order='A'), a.reshape(-1, order='A'))
a = np.array([[0, 1], [2, 3]])[::-1, :]
assert_equal(a.ravel(), [2, 3, 0, 1])
assert_equal(a.ravel(order='C'), [2, 3, 0, 1])
assert_equal(a.ravel(order='F'), [2, 0, 3, 1])
assert_equal(a.ravel(order='A'), [2, 3, 0, 1])
# 'K' doesn't reverse the axes of negative strides
assert_equal(a.ravel(order='K'), [2, 3, 0, 1])
assert_(a.ravel(order='K').flags.owndata)
# Test simple 1-d copy behaviour:
a = np.arange(10)[::2]
assert_(a.ravel('K').flags.owndata)
assert_(a.ravel('C').flags.owndata)
assert_(a.ravel('F').flags.owndata)
# Not contiguous and 1-sized axis with non matching stride
a = np.arange(2**3 * 2)[::2]
a = a.reshape(2, 1, 2, 2).swapaxes(-1, -2)
strides = list(a.strides)
strides[1] = 123
a.strides = strides
assert_(a.ravel(order='K').flags.owndata)
assert_equal(a.ravel('K'), np.arange(0, 15, 2))
# contiguous and 1-sized axis with non matching stride works:
a = np.arange(2**3)
a = a.reshape(2, 1, 2, 2).swapaxes(-1, -2)
strides = list(a.strides)
strides[1] = 123
a.strides = strides
assert_(np.may_share_memory(a.ravel(order='K'), a))
assert_equal(a.ravel(order='K'), np.arange(2**3))
# Test negative strides (not very interesting since non-contiguous):
a = np.arange(4)[::-1].reshape(2, 2)
assert_(a.ravel(order='C').flags.owndata)
assert_(a.ravel(order='K').flags.owndata)
assert_equal(a.ravel('C'), [3, 2, 1, 0])
assert_equal(a.ravel('K'), [3, 2, 1, 0])
# 1-element tidy strides test (NPY_RELAXED_STRIDES_CHECKING):
a = np.array([[1]])
a.strides = (123, 432)
# If the stride is not 8, NPY_RELAXED_STRIDES_CHECKING is messing
# them up on purpose:
if np.ones(1).strides == (8,):
assert_(np.may_share_memory(a.ravel('K'), a))
assert_equal(a.ravel('K').strides, (a.dtype.itemsize,))
for order in ('C', 'F', 'A', 'K'):
# 0-d corner case:
a = np.array(0)
assert_equal(a.ravel(order), [0])
assert_(np.may_share_memory(a.ravel(order), a))
# Test that certain non-inplace ravels work right (mostly) for 'K':
b = np.arange(2**4 * 2)[::2].reshape(2, 2, 2, 2)
a = b[..., ::2]
assert_equal(a.ravel('K'), [0, 4, 8, 12, 16, 20, 24, 28])
assert_equal(a.ravel('C'), [0, 4, 8, 12, 16, 20, 24, 28])
assert_equal(a.ravel('A'), [0, 4, 8, 12, 16, 20, 24, 28])
assert_equal(a.ravel('F'), [0, 16, 8, 24, 4, 20, 12, 28])
a = b[::2, ...]
assert_equal(a.ravel('K'), [0, 2, 4, 6, 8, 10, 12, 14])
assert_equal(a.ravel('C'), [0, 2, 4, 6, 8, 10, 12, 14])
assert_equal(a.ravel('A'), [0, 2, 4, 6, 8, 10, 12, 14])
assert_equal(a.ravel('F'), [0, 8, 4, 12, 2, 10, 6, 14])
def test_ravel_subclass(self):
class ArraySubclass(np.ndarray):
pass
a = np.arange(10).view(ArraySubclass)
assert_(isinstance(a.ravel('C'), ArraySubclass))
assert_(isinstance(a.ravel('F'), ArraySubclass))
assert_(isinstance(a.ravel('A'), ArraySubclass))
assert_(isinstance(a.ravel('K'), ArraySubclass))
a = np.arange(10)[::2].view(ArraySubclass)
assert_(isinstance(a.ravel('C'), ArraySubclass))
assert_(isinstance(a.ravel('F'), ArraySubclass))
assert_(isinstance(a.ravel('A'), ArraySubclass))
assert_(isinstance(a.ravel('K'), ArraySubclass))
def test_swapaxes(self):
a = np.arange(1*2*3*4).reshape(1, 2, 3, 4).copy()
idx = np.indices(a.shape)
assert_(a.flags['OWNDATA'])
b = a.copy()
# check exceptions
assert_raises(ValueError, a.swapaxes, -5, 0)
assert_raises(ValueError, a.swapaxes, 4, 0)
assert_raises(ValueError, a.swapaxes, 0, -5)
assert_raises(ValueError, a.swapaxes, 0, 4)
for i in range(-4, 4):
for j in range(-4, 4):
for k, src in enumerate((a, b)):
c = src.swapaxes(i, j)
# check shape
shape = list(src.shape)
shape[i] = src.shape[j]
shape[j] = src.shape[i]
assert_equal(c.shape, shape, str((i, j, k)))
# check array contents
i0, i1, i2, i3 = [dim-1 for dim in c.shape]
j0, j1, j2, j3 = [dim-1 for dim in src.shape]
assert_equal(src[idx[j0], idx[j1], idx[j2], idx[j3]],
c[idx[i0], idx[i1], idx[i2], idx[i3]],
str((i, j, k)))
# check a view is always returned, gh-5260
assert_(not c.flags['OWNDATA'], str((i, j, k)))
# check on non-contiguous input array
if k == 1:
b = c
def test_conjugate(self):
a = np.array([1-1j, 1+1j, 23+23.0j])
ac = a.conj()
assert_equal(a.real, ac.real)
assert_equal(a.imag, -ac.imag)
assert_equal(ac, a.conjugate())
assert_equal(ac, np.conjugate(a))
a = np.array([1-1j, 1+1j, 23+23.0j], 'F')
ac = a.conj()
assert_equal(a.real, ac.real)
assert_equal(a.imag, -ac.imag)
assert_equal(ac, a.conjugate())
assert_equal(ac, np.conjugate(a))
a = np.array([1, 2, 3])
ac = a.conj()
assert_equal(a, ac)
assert_equal(ac, a.conjugate())
assert_equal(ac, np.conjugate(a))
a = np.array([1.0, 2.0, 3.0])
ac = a.conj()
assert_equal(a, ac)
assert_equal(ac, a.conjugate())
assert_equal(ac, np.conjugate(a))
a = np.array([1-1j, 1+1j, 1, 2.0], object)
ac = a.conj()
assert_equal(ac, [k.conjugate() for k in a])
assert_equal(ac, a.conjugate())
assert_equal(ac, np.conjugate(a))
a = np.array([1-1j, 1, 2.0, 'f'], object)
assert_raises(AttributeError, lambda: a.conj())
assert_raises(AttributeError, lambda: a.conjugate())
def test__complex__(self):
dtypes = ['i1', 'i2', 'i4', 'i8',
'u1', 'u2', 'u4', 'u8',
'f', 'd', 'g', 'F', 'D', 'G',
'?', 'O']
for dt in dtypes:
a = np.array(7, dtype=dt)
b = np.array([7], dtype=dt)
c = np.array([[[[[7]]]]], dtype=dt)
msg = 'dtype: {0}'.format(dt)
ap = complex(a)
assert_equal(ap, a, msg)
bp = complex(b)
assert_equal(bp, b, msg)
cp = complex(c)
assert_equal(cp, c, msg)
def test__complex__should_not_work(self):
dtypes = ['i1', 'i2', 'i4', 'i8',
'u1', 'u2', 'u4', 'u8',
'f', 'd', 'g', 'F', 'D', 'G',
'?', 'O']
for dt in dtypes:
a = np.array([1, 2, 3], dtype=dt)
assert_raises(TypeError, complex, a)
dt = np.dtype([('a', 'f8'), ('b', 'i1')])
b = np.array((1.0, 3), dtype=dt)
assert_raises(TypeError, complex, b)
c = np.array([(1.0, 3), (2e-3, 7)], dtype=dt)
assert_raises(TypeError, complex, c)
d = np.array('1+1j')
assert_raises(TypeError, complex, d)
e = np.array(['1+1j'], 'U')
assert_raises(TypeError, complex, e)
class TestBinop(object):
def test_inplace(self):
# test refcount 1 inplace conversion
assert_array_almost_equal(np.array([0.5]) * np.array([1.0, 2.0]),
[0.5, 1.0])
d = np.array([0.5, 0.5])[::2]
assert_array_almost_equal(d * (d * np.array([1.0, 2.0])),
[0.25, 0.5])
a = np.array([0.5])
b = np.array([0.5])
c = a + b
c = a - b
c = a * b
c = a / b
assert_equal(a, b)
assert_almost_equal(c, 1.)
c = a + b * 2. / b * a - a / b
assert_equal(a, b)
assert_equal(c, 0.5)
# true divide
a = np.array([5])
b = np.array([3])
c = (a * a) / b
assert_almost_equal(c, 25 / 3)
assert_equal(a, 5)
assert_equal(b, 3)
def test_extension_incref_elide(self):
# test extension (e.g. cython) calling PyNumber_* slots without
# increasing the reference counts
#
# def incref_elide(a):
# d = input.copy() # refcount 1
# return d, d + d # PyNumber_Add without increasing refcount
from numpy.core.multiarray_tests import incref_elide
d = np.ones(5)
orig, res = incref_elide(d)
# the return original should not be changed to an inplace operation
assert_array_equal(orig, d)
assert_array_equal(res, d + d)
def test_extension_incref_elide_stack(self):
# scanning if the refcount == 1 object is on the python stack to check
# that we are called directly from python is flawed as object may still
# be above the stack pointer and we have no access to the top of it
#
# def incref_elide_l(d):
# return l[4] + l[4] # PyNumber_Add without increasing refcount
from numpy.core.multiarray_tests import incref_elide_l
# padding with 1 makes sure the object on the stack is not overwriten
l = [1, 1, 1, 1, np.ones(5)]
res = incref_elide_l(l)
# the return original should not be changed to an inplace operation
assert_array_equal(l[4], np.ones(5))
assert_array_equal(res, l[4] + l[4])
def test_ufunc_override_rop_precedence(self):
# 2016-01-29: NUMPY_UFUNC_DISABLED
return
# Check that __rmul__ and other right-hand operations have
# precedence over __numpy_ufunc__
ops = {
'__add__': ('__radd__', np.add, True),
'__sub__': ('__rsub__', np.subtract, True),
'__mul__': ('__rmul__', np.multiply, True),
'__truediv__': ('__rtruediv__', np.true_divide, True),
'__floordiv__': ('__rfloordiv__', np.floor_divide, True),
'__mod__': ('__rmod__', np.remainder, True),
'__divmod__': ('__rdivmod__', None, False),
'__pow__': ('__rpow__', np.power, True),
'__lshift__': ('__rlshift__', np.left_shift, True),
'__rshift__': ('__rrshift__', np.right_shift, True),
'__and__': ('__rand__', np.bitwise_and, True),
'__xor__': ('__rxor__', np.bitwise_xor, True),
'__or__': ('__ror__', np.bitwise_or, True),
'__ge__': ('__le__', np.less_equal, False),
'__gt__': ('__lt__', np.less, False),
'__le__': ('__ge__', np.greater_equal, False),
'__lt__': ('__gt__', np.greater, False),
'__eq__': ('__eq__', np.equal, False),
'__ne__': ('__ne__', np.not_equal, False),
}
class OtherNdarraySubclass(np.ndarray):
pass
class OtherNdarraySubclassWithOverride(np.ndarray):
def __numpy_ufunc__(self, *a, **kw):
raise AssertionError(("__numpy_ufunc__ %r %r shouldn't have "
"been called!") % (a, kw))
def check(op_name, ndsubclass):
rop_name, np_op, has_iop = ops[op_name]
if has_iop:
iop_name = '__i' + op_name[2:]
iop = getattr(operator, iop_name)
if op_name == "__divmod__":
op = divmod
else:
op = getattr(operator, op_name)
# Dummy class
def __init__(self, *a, **kw):
pass
def __numpy_ufunc__(self, *a, **kw):
raise AssertionError(("__numpy_ufunc__ %r %r shouldn't have "
"been called!") % (a, kw))
def __op__(self, *other):
return "op"
def __rop__(self, *other):
return "rop"
if ndsubclass:
bases = (np.ndarray,)
else:
bases = (object,)
dct = {'__init__': __init__,
'__numpy_ufunc__': __numpy_ufunc__,
op_name: __op__}
if op_name != rop_name:
dct[rop_name] = __rop__
cls = type("Rop" + rop_name, bases, dct)
# Check behavior against both bare ndarray objects and a
# ndarray subclasses with and without their own override
obj = cls((1,), buffer=np.ones(1,))
arr_objs = [np.array([1]),
np.array([2]).view(OtherNdarraySubclass),
np.array([3]).view(OtherNdarraySubclassWithOverride),
]
for arr in arr_objs:
err_msg = "%r %r" % (op_name, arr,)
# Check that ndarray op gives up if it sees a non-subclass
if not isinstance(obj, arr.__class__):
assert_equal(getattr(arr, op_name)(obj),
NotImplemented, err_msg=err_msg)
# Check that the Python binops have priority
assert_equal(op(obj, arr), "op", err_msg=err_msg)
if op_name == rop_name:
assert_equal(op(arr, obj), "op", err_msg=err_msg)
else:
assert_equal(op(arr, obj), "rop", err_msg=err_msg)
# Check that Python binops have priority also for in-place ops
if has_iop:
assert_equal(getattr(arr, iop_name)(obj),
NotImplemented, err_msg=err_msg)
if op_name != "__pow__":
# inplace pow requires the other object to be
# integer-like?
assert_equal(iop(arr, obj), "rop", err_msg=err_msg)
# Check that ufunc call __numpy_ufunc__ normally
if np_op is not None:
assert_raises(AssertionError, np_op, arr, obj,
err_msg=err_msg)
assert_raises(AssertionError, np_op, obj, arr,
err_msg=err_msg)
# Check all binary operations
for op_name in sorted(ops.keys()):
yield check, op_name, True
yield check, op_name, False
def test_ufunc_override_rop_simple(self):
# 2016-01-29: NUMPY_UFUNC_DISABLED
return
# Check parts of the binary op overriding behavior in an
# explicit test case that is easier to understand.
class SomeClass(object):
def __numpy_ufunc__(self, *a, **kw):
return "ufunc"
def __mul__(self, other):
return 123
def __rmul__(self, other):
return 321
def __rsub__(self, other):
return "no subs for me"
def __gt__(self, other):
return "yep"
def __lt__(self, other):
return "nope"
class SomeClass2(SomeClass, np.ndarray):
def __numpy_ufunc__(self, ufunc, method, i, inputs, **kw):
if ufunc is np.multiply or ufunc is np.bitwise_and:
return "ufunc"
else:
inputs = list(inputs)
if i < len(inputs):
inputs[i] = np.asarray(self)
func = getattr(ufunc, method)
if ('out' in kw) and (kw['out'] is not None):
kw['out'] = np.asarray(kw['out'])
r = func(*inputs, **kw)
x = self.__class__(r.shape, dtype=r.dtype)
x[...] = r
return x
class SomeClass3(SomeClass2):
def __rsub__(self, other):
return "sub for me"
arr = np.array([0])
obj = SomeClass()
obj2 = SomeClass2((1,), dtype=np.int_)
obj2[0] = 9
obj3 = SomeClass3((1,), dtype=np.int_)
obj3[0] = 4
# obj is first, so should get to define outcome.
assert_equal(obj * arr, 123)
# obj is second, but has __numpy_ufunc__ and defines __rmul__.
assert_equal(arr * obj, 321)
# obj is second, but has __numpy_ufunc__ and defines __rsub__.
assert_equal(arr - obj, "no subs for me")
# obj is second, but has __numpy_ufunc__ and defines __lt__.
assert_equal(arr > obj, "nope")
# obj is second, but has __numpy_ufunc__ and defines __gt__.
assert_equal(arr < obj, "yep")
# Called as a ufunc, obj.__numpy_ufunc__ is used.
assert_equal(np.multiply(arr, obj), "ufunc")
# obj is second, but has __numpy_ufunc__ and defines __rmul__.
arr *= obj
assert_equal(arr, 321)
# obj2 is an ndarray subclass, so CPython takes care of the same rules.
assert_equal(obj2 * arr, 123)
assert_equal(arr * obj2, 321)
assert_equal(arr - obj2, "no subs for me")
assert_equal(arr > obj2, "nope")
assert_equal(arr < obj2, "yep")
# Called as a ufunc, obj2.__numpy_ufunc__ is called.
assert_equal(np.multiply(arr, obj2), "ufunc")
# Also when the method is not overridden.
assert_equal(arr & obj2, "ufunc")
arr *= obj2
assert_equal(arr, 321)
obj2 += 33
assert_equal(obj2[0], 42)
assert_equal(obj2.sum(), 42)
assert_(isinstance(obj2, SomeClass2))
# Obj3 is subclass that defines __rsub__. CPython calls it.
assert_equal(arr - obj3, "sub for me")
assert_equal(obj2 - obj3, "sub for me")
# obj3 is a subclass that defines __rmul__. CPython calls it.
assert_equal(arr * obj3, 321)
# But not here, since obj3.__rmul__ is obj2.__rmul__.
assert_equal(obj2 * obj3, 123)
# And of course, here obj3.__mul__ should be called.
assert_equal(obj3 * obj2, 123)
# obj3 defines __numpy_ufunc__ but obj3.__radd__ is obj2.__radd__.
# (and both are just ndarray.__radd__); see #4815.
res = obj2 + obj3
assert_equal(res, 46)
assert_(isinstance(res, SomeClass2))
# Since obj3 is a subclass, it should have precedence, like CPython
# would give, even though obj2 has __numpy_ufunc__ and __radd__.
# See gh-4815 and gh-5747.
res = obj3 + obj2
assert_equal(res, 46)
assert_(isinstance(res, SomeClass3))
def test_ufunc_override_normalize_signature(self):
# 2016-01-29: NUMPY_UFUNC_DISABLED
return
# gh-5674
class SomeClass(object):
def __numpy_ufunc__(self, ufunc, method, i, inputs, **kw):
return kw
a = SomeClass()
kw = np.add(a, [1])
assert_('sig' not in kw and 'signature' not in kw)
kw = np.add(a, [1], sig='ii->i')
assert_('sig' not in kw and 'signature' in kw)
assert_equal(kw['signature'], 'ii->i')
kw = np.add(a, [1], signature='ii->i')
assert_('sig' not in kw and 'signature' in kw)
assert_equal(kw['signature'], 'ii->i')
def test_numpy_ufunc_index(self):
# 2016-01-29: NUMPY_UFUNC_DISABLED
return
# Check that index is set appropriately, also if only an output
# is passed on (latter is another regression tests for github bug 4753)
class CheckIndex(object):
def __numpy_ufunc__(self, ufunc, method, i, inputs, **kw):
return i
a = CheckIndex()
dummy = np.arange(2.)
# 1 input, 1 output
assert_equal(np.sin(a), 0)
assert_equal(np.sin(dummy, a), 1)
assert_equal(np.sin(dummy, out=a), 1)
assert_equal(np.sin(dummy, out=(a,)), 1)
assert_equal(np.sin(a, a), 0)
assert_equal(np.sin(a, out=a), 0)
assert_equal(np.sin(a, out=(a,)), 0)
# 1 input, 2 outputs
assert_equal(np.modf(dummy, a), 1)
assert_equal(np.modf(dummy, None, a), 2)
assert_equal(np.modf(dummy, dummy, a), 2)
assert_equal(np.modf(dummy, out=a), 1)
assert_equal(np.modf(dummy, out=(a,)), 1)
assert_equal(np.modf(dummy, out=(a, None)), 1)
assert_equal(np.modf(dummy, out=(a, dummy)), 1)
assert_equal(np.modf(dummy, out=(None, a)), 2)
assert_equal(np.modf(dummy, out=(dummy, a)), 2)
assert_equal(np.modf(a, out=(dummy, a)), 0)
# 2 inputs, 1 output
assert_equal(np.add(a, dummy), 0)
assert_equal(np.add(dummy, a), 1)
assert_equal(np.add(dummy, dummy, a), 2)
assert_equal(np.add(dummy, a, a), 1)
assert_equal(np.add(dummy, dummy, out=a), 2)
assert_equal(np.add(dummy, dummy, out=(a,)), 2)
assert_equal(np.add(a, dummy, out=a), 0)
def test_out_override(self):
# 2016-01-29: NUMPY_UFUNC_DISABLED
return
# regression test for github bug 4753
class OutClass(np.ndarray):
def __numpy_ufunc__(self, ufunc, method, i, inputs, **kw):
if 'out' in kw:
tmp_kw = kw.copy()
tmp_kw.pop('out')
func = getattr(ufunc, method)
kw['out'][...] = func(*inputs, **tmp_kw)
A = np.array([0]).view(OutClass)
B = np.array([5])
C = np.array([6])
np.multiply(C, B, A)
assert_equal(A[0], 30)
assert_(isinstance(A, OutClass))
A[0] = 0
np.multiply(C, B, out=A)
assert_equal(A[0], 30)
assert_(isinstance(A, OutClass))
class TestCAPI(TestCase):
def test_IsPythonScalar(self):
from numpy.core.multiarray_tests import IsPythonScalar
assert_(IsPythonScalar(b'foobar'))
assert_(IsPythonScalar(1))
assert_(IsPythonScalar(2**80))
assert_(IsPythonScalar(2.))
assert_(IsPythonScalar("a"))
class TestSubscripting(TestCase):
def test_test_zero_rank(self):
x = np.array([1, 2, 3])
self.assertTrue(isinstance(x[0], np.int_))
if sys.version_info[0] < 3:
self.assertTrue(isinstance(x[0], int))
self.assertTrue(type(x[0, ...]) is np.ndarray)
class TestPickling(TestCase):
def test_roundtrip(self):
import pickle
carray = np.array([[2, 9], [7, 0], [3, 8]])
DATA = [
carray,
np.transpose(carray),
np.array([('xxx', 1, 2.0)], dtype=[('a', (str, 3)), ('b', int),
('c', float)])
]
for a in DATA:
assert_equal(a, pickle.loads(a.dumps()), err_msg="%r" % a)
def _loads(self, obj):
if sys.version_info[0] >= 3:
return np.loads(obj, encoding='latin1')
else:
return np.loads(obj)
# version 0 pickles, using protocol=2 to pickle
# version 0 doesn't have a version field
def test_version0_int8(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02i1K\x00K\x01\x87Rq\x05(U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x04\x01\x02\x03\x04tb.'
a = np.array([1, 2, 3, 4], dtype=np.int8)
p = self._loads(asbytes(s))
assert_equal(a, p)
def test_version0_float32(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02f4K\x00K\x01\x87Rq\x05(U\x01<NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x10\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@tb.'
a = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32)
p = self._loads(asbytes(s))
assert_equal(a, p)
def test_version0_object(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x02\x85cnumpy\ndtype\nq\x04U\x02O8K\x00K\x01\x87Rq\x05(U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89]q\x06(}q\x07U\x01aK\x01s}q\x08U\x01bK\x02setb.'
a = np.array([{'a': 1}, {'b': 2}])
p = self._loads(asbytes(s))
assert_equal(a, p)
# version 1 pickles, using protocol=2 to pickle
def test_version1_int8(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x01K\x04\x85cnumpy\ndtype\nq\x04U\x02i1K\x00K\x01\x87Rq\x05(K\x01U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x04\x01\x02\x03\x04tb.'
a = np.array([1, 2, 3, 4], dtype=np.int8)
p = self._loads(asbytes(s))
assert_equal(a, p)
def test_version1_float32(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x01K\x04\x85cnumpy\ndtype\nq\x04U\x02f4K\x00K\x01\x87Rq\x05(K\x01U\x01<NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x10\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@tb.'
a = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32)
p = self._loads(asbytes(s))
assert_equal(a, p)
def test_version1_object(self):
s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x01K\x02\x85cnumpy\ndtype\nq\x04U\x02O8K\x00K\x01\x87Rq\x05(K\x01U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89]q\x06(}q\x07U\x01aK\x01s}q\x08U\x01bK\x02setb.'
a = np.array([{'a': 1}, {'b': 2}])
p = self._loads(asbytes(s))
assert_equal(a, p)
def test_subarray_int_shape(self):
s = "cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\np7\n(S'V6'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nN(S'a'\np12\ng3\ntp13\n(dp14\ng12\n(g7\n(S'V4'\np15\nI0\nI1\ntp16\nRp17\n(I3\nS'|'\np18\n(g7\n(S'i1'\np19\nI0\nI1\ntp20\nRp21\n(I3\nS'|'\np22\nNNNI-1\nI-1\nI0\ntp23\nb(I2\nI2\ntp24\ntp25\nNNI4\nI1\nI0\ntp26\nbI0\ntp27\nsg3\n(g7\n(S'V2'\np28\nI0\nI1\ntp29\nRp30\n(I3\nS'|'\np31\n(g21\nI2\ntp32\nNNI2\nI1\nI0\ntp33\nbI4\ntp34\nsI6\nI1\nI0\ntp35\nbI00\nS'\\x01\\x01\\x01\\x01\\x01\\x02'\np36\ntp37\nb."
a = np.array([(1, (1, 2))], dtype=[('a', 'i1', (2, 2)), ('b', 'i1', 2)])
p = self._loads(asbytes(s))
assert_equal(a, p)
class TestFancyIndexing(TestCase):
def test_list(self):
x = np.ones((1, 1))
x[:, [0]] = 2.0
assert_array_equal(x, np.array([[2.0]]))
x = np.ones((1, 1, 1))
x[:, :, [0]] = 2.0
assert_array_equal(x, np.array([[[2.0]]]))
def test_tuple(self):
x = np.ones((1, 1))
x[:, (0,)] = 2.0
assert_array_equal(x, np.array([[2.0]]))
x = np.ones((1, 1, 1))
x[:, :, (0,)] = 2.0
assert_array_equal(x, np.array([[[2.0]]]))
def test_mask(self):
x = np.array([1, 2, 3, 4])
m = np.array([0, 1, 0, 0], bool)
assert_array_equal(x[m], np.array([2]))
def test_mask2(self):
x = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
m = np.array([0, 1], bool)
m2 = np.array([[0, 1, 0, 0], [1, 0, 0, 0]], bool)
m3 = np.array([[0, 1, 0, 0], [0, 0, 0, 0]], bool)
assert_array_equal(x[m], np.array([[5, 6, 7, 8]]))
assert_array_equal(x[m2], np.array([2, 5]))
assert_array_equal(x[m3], np.array([2]))
def test_assign_mask(self):
x = np.array([1, 2, 3, 4])
m = np.array([0, 1, 0, 0], bool)
x[m] = 5
assert_array_equal(x, np.array([1, 5, 3, 4]))
def test_assign_mask2(self):
xorig = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
m = np.array([0, 1], bool)
m2 = np.array([[0, 1, 0, 0], [1, 0, 0, 0]], bool)
m3 = np.array([[0, 1, 0, 0], [0, 0, 0, 0]], bool)
x = xorig.copy()
x[m] = 10
assert_array_equal(x, np.array([[1, 2, 3, 4], [10, 10, 10, 10]]))
x = xorig.copy()
x[m2] = 10
assert_array_equal(x, np.array([[1, 10, 3, 4], [10, 6, 7, 8]]))
x = xorig.copy()
x[m3] = 10
assert_array_equal(x, np.array([[1, 10, 3, 4], [5, 6, 7, 8]]))
class TestStringCompare(TestCase):
def test_string(self):
g1 = np.array(["This", "is", "example"])
g2 = np.array(["This", "was", "example"])
assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 >= g2, [g1[i] >= g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0, 1, 2]])
def test_mixed(self):
g1 = np.array(["spam", "spa", "spammer", "and eggs"])
g2 = "spam"
assert_array_equal(g1 == g2, [x == g2 for x in g1])
assert_array_equal(g1 != g2, [x != g2 for x in g1])
assert_array_equal(g1 < g2, [x < g2 for x in g1])
assert_array_equal(g1 > g2, [x > g2 for x in g1])
assert_array_equal(g1 <= g2, [x <= g2 for x in g1])
assert_array_equal(g1 >= g2, [x >= g2 for x in g1])
def test_unicode(self):
g1 = np.array([sixu("This"), sixu("is"), sixu("example")])
g2 = np.array([sixu("This"), sixu("was"), sixu("example")])
assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 >= g2, [g1[i] >= g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0, 1, 2]])
assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0, 1, 2]])
class TestArgmax(TestCase):
nan_arr = [
([0, 1, 2, 3, np.nan], 4),
([0, 1, 2, np.nan, 3], 3),
([np.nan, 0, 1, 2, 3], 0),
([np.nan, 0, np.nan, 2, 3], 0),
([0, 1, 2, 3, complex(0, np.nan)], 4),
([0, 1, 2, 3, complex(np.nan, 0)], 4),
([0, 1, 2, complex(np.nan, 0), 3], 3),
([0, 1, 2, complex(0, np.nan), 3], 3),
([complex(0, np.nan), 0, 1, 2, 3], 0),
([complex(np.nan, np.nan), 0, 1, 2, 3], 0),
([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, 1)], 0),
([complex(np.nan, np.nan), complex(np.nan, 2), complex(np.nan, 1)], 0),
([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, np.nan)], 0),
([complex(0, 0), complex(0, 2), complex(0, 1)], 1),
([complex(1, 0), complex(0, 2), complex(0, 1)], 0),
([complex(1, 0), complex(0, 2), complex(1, 1)], 2),
([np.datetime64('1923-04-14T12:43:12'),
np.datetime64('1994-06-21T14:43:15'),
np.datetime64('2001-10-15T04:10:32'),
np.datetime64('1995-11-25T16:02:16'),
np.datetime64('2005-01-04T03:14:12'),
np.datetime64('2041-12-03T14:05:03')], 5),
([np.datetime64('1935-09-14T04:40:11'),
np.datetime64('1949-10-12T12:32:11'),
np.datetime64('2010-01-03T05:14:12'),
np.datetime64('2015-11-20T12:20:59'),
np.datetime64('1932-09-23T10:10:13'),
np.datetime64('2014-10-10T03:50:30')], 3),
# Assorted tests with NaTs
([np.datetime64('NaT'),
np.datetime64('NaT'),
np.datetime64('2010-01-03T05:14:12'),
np.datetime64('NaT'),
np.datetime64('2015-09-23T10:10:13'),
np.datetime64('1932-10-10T03:50:30')], 4),
([np.datetime64('2059-03-14T12:43:12'),
np.datetime64('1996-09-21T14:43:15'),
np.datetime64('NaT'),
np.datetime64('2022-12-25T16:02:16'),
np.datetime64('1963-10-04T03:14:12'),
np.datetime64('2013-05-08T18:15:23')], 0),
([np.timedelta64(2, 's'),
np.timedelta64(1, 's'),
np.timedelta64('NaT', 's'),
np.timedelta64(3, 's')], 3),
([np.timedelta64('NaT', 's')] * 3, 0),
([timedelta(days=5, seconds=14), timedelta(days=2, seconds=35),
timedelta(days=-1, seconds=23)], 0),
([timedelta(days=1, seconds=43), timedelta(days=10, seconds=5),
timedelta(days=5, seconds=14)], 1),
([timedelta(days=10, seconds=24), timedelta(days=10, seconds=5),
timedelta(days=10, seconds=43)], 2),
([False, False, False, False, True], 4),
([False, False, False, True, False], 3),
([True, False, False, False, False], 0),
([True, False, True, False, False], 0),
]
def test_all(self):
a = np.random.normal(0, 1, (4, 5, 6, 7, 8))
for i in range(a.ndim):
amax = a.max(i)
aargmax = a.argmax(i)
axes = list(range(a.ndim))
axes.remove(i)
assert_(np.all(amax == aargmax.choose(*a.transpose(i,*axes))))
def test_combinations(self):
for arr, pos in self.nan_arr:
assert_equal(np.argmax(arr), pos, err_msg="%r" % arr)
assert_equal(arr[np.argmax(arr)], np.max(arr), err_msg="%r" % arr)
def test_output_shape(self):
# see also gh-616
a = np.ones((10, 5))
# Check some simple shape mismatches
out = np.ones(11, dtype=np.int_)
assert_raises(ValueError, a.argmax, -1, out)
out = np.ones((2, 5), dtype=np.int_)
assert_raises(ValueError, a.argmax, -1, out)
# these could be relaxed possibly (used to allow even the previous)
out = np.ones((1, 10), dtype=np.int_)
assert_raises(ValueError, a.argmax, -1, out)
out = np.ones(10, dtype=np.int_)
a.argmax(-1, out=out)
assert_equal(out, a.argmax(-1))
def test_argmax_unicode(self):
d = np.zeros(6031, dtype='<U9')
d[5942] = "as"
assert_equal(d.argmax(), 5942)
def test_np_vs_ndarray(self):
# make sure both ndarray.argmax and numpy.argmax support out/axis args
a = np.random.normal(size=(2,3))
# check positional args
out1 = np.zeros(2, dtype=int)
out2 = np.zeros(2, dtype=int)
assert_equal(a.argmax(1, out1), np.argmax(a, 1, out2))
assert_equal(out1, out2)
# check keyword args
out1 = np.zeros(3, dtype=int)
out2 = np.zeros(3, dtype=int)
assert_equal(a.argmax(out=out1, axis=0), np.argmax(a, out=out2, axis=0))
assert_equal(out1, out2)
def test_object_argmax_with_NULLs(self):
# See gh-6032
a = np.empty(4, dtype='O')
ctypes.memset(a.ctypes.data, 0, a.nbytes)
assert_equal(a.argmax(), 0)
a[3] = 10
assert_equal(a.argmax(), 3)
a[1] = 30
assert_equal(a.argmax(), 1)
class TestArgmin(TestCase):
nan_arr = [
([0, 1, 2, 3, np.nan], 4),
([0, 1, 2, np.nan, 3], 3),
([np.nan, 0, 1, 2, 3], 0),
([np.nan, 0, np.nan, 2, 3], 0),
([0, 1, 2, 3, complex(0, np.nan)], 4),
([0, 1, 2, 3, complex(np.nan, 0)], 4),
([0, 1, 2, complex(np.nan, 0), 3], 3),
([0, 1, 2, complex(0, np.nan), 3], 3),
([complex(0, np.nan), 0, 1, 2, 3], 0),
([complex(np.nan, np.nan), 0, 1, 2, 3], 0),
([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, 1)], 0),
([complex(np.nan, np.nan), complex(np.nan, 2), complex(np.nan, 1)], 0),
([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, np.nan)], 0),
([complex(0, 0), complex(0, 2), complex(0, 1)], 0),
([complex(1, 0), complex(0, 2), complex(0, 1)], 2),
([complex(1, 0), complex(0, 2), complex(1, 1)], 1),
([np.datetime64('1923-04-14T12:43:12'),
np.datetime64('1994-06-21T14:43:15'),
np.datetime64('2001-10-15T04:10:32'),
np.datetime64('1995-11-25T16:02:16'),
np.datetime64('2005-01-04T03:14:12'),
np.datetime64('2041-12-03T14:05:03')], 0),
([np.datetime64('1935-09-14T04:40:11'),
np.datetime64('1949-10-12T12:32:11'),
np.datetime64('2010-01-03T05:14:12'),
np.datetime64('2014-11-20T12:20:59'),
np.datetime64('2015-09-23T10:10:13'),
np.datetime64('1932-10-10T03:50:30')], 5),
# Assorted tests with NaTs
([np.datetime64('NaT'),
np.datetime64('NaT'),
np.datetime64('2010-01-03T05:14:12'),
np.datetime64('NaT'),
np.datetime64('2015-09-23T10:10:13'),
np.datetime64('1932-10-10T03:50:30')], 5),
([np.datetime64('2059-03-14T12:43:12'),
np.datetime64('1996-09-21T14:43:15'),
np.datetime64('NaT'),
np.datetime64('2022-12-25T16:02:16'),
np.datetime64('1963-10-04T03:14:12'),
np.datetime64('2013-05-08T18:15:23')], 4),
([np.timedelta64(2, 's'),
np.timedelta64(1, 's'),
np.timedelta64('NaT', 's'),
np.timedelta64(3, 's')], 1),
([np.timedelta64('NaT', 's')] * 3, 0),
([timedelta(days=5, seconds=14), timedelta(days=2, seconds=35),
timedelta(days=-1, seconds=23)], 2),
([timedelta(days=1, seconds=43), timedelta(days=10, seconds=5),
timedelta(days=5, seconds=14)], 0),
([timedelta(days=10, seconds=24), timedelta(days=10, seconds=5),
timedelta(days=10, seconds=43)], 1),
([True, True, True, True, False], 4),
([True, True, True, False, True], 3),
([False, True, True, True, True], 0),
([False, True, False, True, True], 0),
]
def test_all(self):
a = np.random.normal(0, 1, (4, 5, 6, 7, 8))
for i in range(a.ndim):
amin = a.min(i)
aargmin = a.argmin(i)
axes = list(range(a.ndim))
axes.remove(i)
assert_(np.all(amin == aargmin.choose(*a.transpose(i,*axes))))
def test_combinations(self):
for arr, pos in self.nan_arr:
assert_equal(np.argmin(arr), pos, err_msg="%r" % arr)
assert_equal(arr[np.argmin(arr)], np.min(arr), err_msg="%r" % arr)
def test_minimum_signed_integers(self):
a = np.array([1, -2**7, -2**7 + 1], dtype=np.int8)
assert_equal(np.argmin(a), 1)
a = np.array([1, -2**15, -2**15 + 1], dtype=np.int16)
assert_equal(np.argmin(a), 1)
a = np.array([1, -2**31, -2**31 + 1], dtype=np.int32)
assert_equal(np.argmin(a), 1)
a = np.array([1, -2**63, -2**63 + 1], dtype=np.int64)
assert_equal(np.argmin(a), 1)
def test_output_shape(self):
# see also gh-616
a = np.ones((10, 5))
# Check some simple shape mismatches
out = np.ones(11, dtype=np.int_)
assert_raises(ValueError, a.argmin, -1, out)
out = np.ones((2, 5), dtype=np.int_)
assert_raises(ValueError, a.argmin, -1, out)
# these could be relaxed possibly (used to allow even the previous)
out = np.ones((1, 10), dtype=np.int_)
assert_raises(ValueError, a.argmin, -1, out)
out = np.ones(10, dtype=np.int_)
a.argmin(-1, out=out)
assert_equal(out, a.argmin(-1))
def test_argmin_unicode(self):
d = np.ones(6031, dtype='<U9')
d[6001] = "0"
assert_equal(d.argmin(), 6001)
def test_np_vs_ndarray(self):
# make sure both ndarray.argmin and numpy.argmin support out/axis args
a = np.random.normal(size=(2, 3))
# check positional args
out1 = np.zeros(2, dtype=int)
out2 = np.ones(2, dtype=int)
assert_equal(a.argmin(1, out1), np.argmin(a, 1, out2))
assert_equal(out1, out2)
# check keyword args
out1 = np.zeros(3, dtype=int)
out2 = np.ones(3, dtype=int)
assert_equal(a.argmin(out=out1, axis=0), np.argmin(a, out=out2, axis=0))
assert_equal(out1, out2)
def test_object_argmin_with_NULLs(self):
# See gh-6032
a = np.empty(4, dtype='O')
ctypes.memset(a.ctypes.data, 0, a.nbytes)
assert_equal(a.argmin(), 0)
a[3] = 30
assert_equal(a.argmin(), 3)
a[1] = 10
assert_equal(a.argmin(), 1)
class TestMinMax(TestCase):
def test_scalar(self):
assert_raises(ValueError, np.amax, 1, 1)
assert_raises(ValueError, np.amin, 1, 1)
assert_equal(np.amax(1, axis=0), 1)
assert_equal(np.amin(1, axis=0), 1)
assert_equal(np.amax(1, axis=None), 1)
assert_equal(np.amin(1, axis=None), 1)
def test_axis(self):
assert_raises(ValueError, np.amax, [1, 2, 3], 1000)
assert_equal(np.amax([[1, 2, 3]], axis=1), 3)
def test_datetime(self):
# NaTs are ignored
for dtype in ('m8[s]', 'm8[Y]'):
a = np.arange(10).astype(dtype)
a[3] = 'NaT'
assert_equal(np.amin(a), a[0])
assert_equal(np.amax(a), a[9])
a[0] = 'NaT'
assert_equal(np.amin(a), a[1])
assert_equal(np.amax(a), a[9])
a.fill('NaT')
assert_equal(np.amin(a), a[0])
assert_equal(np.amax(a), a[0])
class TestNewaxis(TestCase):
def test_basic(self):
sk = np.array([0, -0.1, 0.1])
res = 250*sk[:, np.newaxis]
assert_almost_equal(res.ravel(), 250*sk)
class TestClip(TestCase):
def _check_range(self, x, cmin, cmax):
assert_(np.all(x >= cmin))
assert_(np.all(x <= cmax))
def _clip_type(self, type_group, array_max,
clip_min, clip_max, inplace=False,
expected_min=None, expected_max=None):
if expected_min is None:
expected_min = clip_min
if expected_max is None:
expected_max = clip_max
for T in np.sctypes[type_group]:
if sys.byteorder == 'little':
byte_orders = ['=', '>']
else:
byte_orders = ['<', '=']
for byteorder in byte_orders:
dtype = np.dtype(T).newbyteorder(byteorder)
x = (np.random.random(1000) * array_max).astype(dtype)
if inplace:
x.clip(clip_min, clip_max, x)
else:
x = x.clip(clip_min, clip_max)
byteorder = '='
if x.dtype.byteorder == '|':
byteorder = '|'
assert_equal(x.dtype.byteorder, byteorder)
self._check_range(x, expected_min, expected_max)
return x
def test_basic(self):
for inplace in [False, True]:
self._clip_type(
'float', 1024, -12.8, 100.2, inplace=inplace)
self._clip_type(
'float', 1024, 0, 0, inplace=inplace)
self._clip_type(
'int', 1024, -120, 100.5, inplace=inplace)
self._clip_type(
'int', 1024, 0, 0, inplace=inplace)
self._clip_type(
'uint', 1024, 0, 0, inplace=inplace)
self._clip_type(
'uint', 1024, -120, 100, inplace=inplace, expected_min=0)
def test_record_array(self):
rec = np.array([(-5, 2.0, 3.0), (5.0, 4.0, 3.0)],
dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])
y = rec['x'].clip(-0.3, 0.5)
self._check_range(y, -0.3, 0.5)
def test_max_or_min(self):
val = np.array([0, 1, 2, 3, 4, 5, 6, 7])
x = val.clip(3)
assert_(np.all(x >= 3))
x = val.clip(min=3)
assert_(np.all(x >= 3))
x = val.clip(max=4)
assert_(np.all(x <= 4))
class TestCompress(TestCase):
def test_axis(self):
tgt = [[5, 6, 7, 8, 9]]
arr = np.arange(10).reshape(2, 5)
out = np.compress([0, 1], arr, axis=0)
assert_equal(out, tgt)
tgt = [[1, 3], [6, 8]]
out = np.compress([0, 1, 0, 1, 0], arr, axis=1)
assert_equal(out, tgt)
def test_truncate(self):
tgt = [[1], [6]]
arr = np.arange(10).reshape(2, 5)
out = np.compress([0, 1], arr, axis=1)
assert_equal(out, tgt)
def test_flatten(self):
arr = np.arange(10).reshape(2, 5)
out = np.compress([0, 1], arr)
assert_equal(out, 1)
class TestPutmask(object):
def tst_basic(self, x, T, mask, val):
np.putmask(x, mask, val)
assert_(np.all(x[mask] == T(val)))
assert_(x.dtype == T)
def test_ip_types(self):
unchecked_types = [str, unicode, np.void, object]
x = np.random.random(1000)*100
mask = x < 40
for val in [-100, 0, 15]:
for types in np.sctypes.values():
for T in types:
if T not in unchecked_types:
yield self.tst_basic, x.copy().astype(T), T, mask, val
def test_mask_size(self):
assert_raises(ValueError, np.putmask, np.array([1, 2, 3]), [True], 5)
def tst_byteorder(self, dtype):
x = np.array([1, 2, 3], dtype)
np.putmask(x, [True, False, True], -1)
assert_array_equal(x, [-1, 2, -1])
def test_ip_byteorder(self):
for dtype in ('>i4', '<i4'):
yield self.tst_byteorder, dtype
def test_record_array(self):
# Note mixed byteorder.
rec = np.array([(-5, 2.0, 3.0), (5.0, 4.0, 3.0)],
dtype=[('x', '<f8'), ('y', '>f8'), ('z', '<f8')])
np.putmask(rec['x'], [True, False], 10)
assert_array_equal(rec['x'], [10, 5])
assert_array_equal(rec['y'], [2, 4])
assert_array_equal(rec['z'], [3, 3])
np.putmask(rec['y'], [True, False], 11)
assert_array_equal(rec['x'], [10, 5])
assert_array_equal(rec['y'], [11, 4])
assert_array_equal(rec['z'], [3, 3])
class TestTake(object):
def tst_basic(self, x):
ind = list(range(x.shape[0]))
assert_array_equal(x.take(ind, axis=0), x)
def test_ip_types(self):
unchecked_types = [str, unicode, np.void, object]
x = np.random.random(24)*100
x.shape = 2, 3, 4
for types in np.sctypes.values():
for T in types:
if T not in unchecked_types:
yield self.tst_basic, x.copy().astype(T)
def test_raise(self):
x = np.random.random(24)*100
x.shape = 2, 3, 4
assert_raises(IndexError, x.take, [0, 1, 2], axis=0)
assert_raises(IndexError, x.take, [-3], axis=0)
assert_array_equal(x.take([-1], axis=0)[0], x[1])
def test_clip(self):
x = np.random.random(24)*100
x.shape = 2, 3, 4
assert_array_equal(x.take([-1], axis=0, mode='clip')[0], x[0])
assert_array_equal(x.take([2], axis=0, mode='clip')[0], x[1])
def test_wrap(self):
x = np.random.random(24)*100
x.shape = 2, 3, 4
assert_array_equal(x.take([-1], axis=0, mode='wrap')[0], x[1])
assert_array_equal(x.take([2], axis=0, mode='wrap')[0], x[0])
assert_array_equal(x.take([3], axis=0, mode='wrap')[0], x[1])
def tst_byteorder(self, dtype):
x = np.array([1, 2, 3], dtype)
assert_array_equal(x.take([0, 2, 1]), [1, 3, 2])
def test_ip_byteorder(self):
for dtype in ('>i4', '<i4'):
yield self.tst_byteorder, dtype
def test_record_array(self):
# Note mixed byteorder.
rec = np.array([(-5, 2.0, 3.0), (5.0, 4.0, 3.0)],
dtype=[('x', '<f8'), ('y', '>f8'), ('z', '<f8')])
rec1 = rec.take([1])
assert_(rec1['x'] == 5.0 and rec1['y'] == 4.0)
class TestLexsort(TestCase):
def test_basic(self):
a = [1, 2, 1, 3, 1, 5]
b = [0, 4, 5, 6, 2, 3]
idx = np.lexsort((b, a))
expected_idx = np.array([0, 4, 2, 1, 3, 5])
assert_array_equal(idx, expected_idx)
x = np.vstack((b, a))
idx = np.lexsort(x)
assert_array_equal(idx, expected_idx)
assert_array_equal(x[1][idx], np.sort(x[1]))
def test_datetime(self):
a = np.array([0,0,0], dtype='datetime64[D]')
b = np.array([2,1,0], dtype='datetime64[D]')
idx = np.lexsort((b, a))
expected_idx = np.array([2, 1, 0])
assert_array_equal(idx, expected_idx)
a = np.array([0,0,0], dtype='timedelta64[D]')
b = np.array([2,1,0], dtype='timedelta64[D]')
idx = np.lexsort((b, a))
expected_idx = np.array([2, 1, 0])
assert_array_equal(idx, expected_idx)
def test_object(self): # gh-6312
a = np.random.choice(10, 1000)
b = np.random.choice(['abc', 'xy', 'wz', 'efghi', 'qwst', 'x'], 1000)
for u in a, b:
left = np.lexsort((u.astype('O'),))
right = np.argsort(u, kind='mergesort')
assert_array_equal(left, right)
for u, v in (a, b), (b, a):
idx = np.lexsort((u, v))
assert_array_equal(idx, np.lexsort((u.astype('O'), v)))
assert_array_equal(idx, np.lexsort((u, v.astype('O'))))
u, v = np.array(u, dtype='object'), np.array(v, dtype='object')
assert_array_equal(idx, np.lexsort((u, v)))
class TestIO(object):
"""Test tofile, fromfile, tobytes, and fromstring"""
def setUp(self):
shape = (2, 4, 3)
rand = np.random.random
self.x = rand(shape) + rand(shape).astype(np.complex)*1j
self.x[0,:, 1] = [np.nan, np.inf, -np.inf, np.nan]
self.dtype = self.x.dtype
self.tempdir = tempfile.mkdtemp()
self.filename = tempfile.mktemp(dir=self.tempdir)
def tearDown(self):
shutil.rmtree(self.tempdir)
def test_nofile(self):
# this should probably be supported as a file
# but for now test for proper errors
b = io.BytesIO()
assert_raises(IOError, np.fromfile, b, np.uint8, 80)
d = np.ones(7)
assert_raises(IOError, lambda x: x.tofile(b), d)
def test_bool_fromstring(self):
v = np.array([True, False, True, False], dtype=np.bool_)
y = np.fromstring('1 0 -2.3 0.0', sep=' ', dtype=np.bool_)
assert_array_equal(v, y)
def test_uint64_fromstring(self):
d = np.fromstring("9923372036854775807 104783749223640",
dtype=np.uint64, sep=' ')
e = np.array([9923372036854775807, 104783749223640], dtype=np.uint64)
assert_array_equal(d, e)
def test_int64_fromstring(self):
d = np.fromstring("-25041670086757 104783749223640",
dtype=np.int64, sep=' ')
e = np.array([-25041670086757, 104783749223640], dtype=np.int64)
assert_array_equal(d, e)
def test_empty_files_binary(self):
f = open(self.filename, 'w')
f.close()
y = np.fromfile(self.filename)
assert_(y.size == 0, "Array not empty")
def test_empty_files_text(self):
f = open(self.filename, 'w')
f.close()
y = np.fromfile(self.filename, sep=" ")
assert_(y.size == 0, "Array not empty")
def test_roundtrip_file(self):
f = open(self.filename, 'wb')
self.x.tofile(f)
f.close()
# NB. doesn't work with flush+seek, due to use of C stdio
f = open(self.filename, 'rb')
y = np.fromfile(f, dtype=self.dtype)
f.close()
assert_array_equal(y, self.x.flat)
def test_roundtrip_filename(self):
self.x.tofile(self.filename)
y = np.fromfile(self.filename, dtype=self.dtype)
assert_array_equal(y, self.x.flat)
def test_roundtrip_binary_str(self):
s = self.x.tobytes()
y = np.fromstring(s, dtype=self.dtype)
assert_array_equal(y, self.x.flat)
s = self.x.tobytes('F')
y = np.fromstring(s, dtype=self.dtype)
assert_array_equal(y, self.x.flatten('F'))
def test_roundtrip_str(self):
x = self.x.real.ravel()
s = "@".join(map(str, x))
y = np.fromstring(s, sep="@")
# NB. str imbues less precision
nan_mask = ~np.isfinite(x)
assert_array_equal(x[nan_mask], y[nan_mask])
assert_array_almost_equal(x[~nan_mask], y[~nan_mask], decimal=5)
def test_roundtrip_repr(self):
x = self.x.real.ravel()
s = "@".join(map(repr, x))
y = np.fromstring(s, sep="@")
assert_array_equal(x, y)
def test_unbuffered_fromfile(self):
# gh-6246
self.x.tofile(self.filename)
def fail(*args, **kwargs):
raise io.IOError('Can not tell or seek')
f = io.open(self.filename, 'rb', buffering=0)
f.seek = fail
f.tell = fail
y = np.fromfile(self.filename, dtype=self.dtype)
assert_array_equal(y, self.x.flat)
def test_largish_file(self):
# check the fallocate path on files > 16MB
d = np.zeros(4 * 1024 ** 2)
d.tofile(self.filename)
assert_equal(os.path.getsize(self.filename), d.nbytes)
assert_array_equal(d, np.fromfile(self.filename))
# check offset
with open(self.filename, "r+b") as f:
f.seek(d.nbytes)
d.tofile(f)
assert_equal(os.path.getsize(self.filename), d.nbytes * 2)
def test_file_position_after_fromfile(self):
# gh-4118
sizes = [io.DEFAULT_BUFFER_SIZE//8,
io.DEFAULT_BUFFER_SIZE,
io.DEFAULT_BUFFER_SIZE*8]
for size in sizes:
f = open(self.filename, 'wb')
f.seek(size-1)
f.write(b'\0')
f.close()
for mode in ['rb', 'r+b']:
err_msg = "%d %s" % (size, mode)
f = open(self.filename, mode)
f.read(2)
np.fromfile(f, dtype=np.float64, count=1)
pos = f.tell()
f.close()
assert_equal(pos, 10, err_msg=err_msg)
def test_file_position_after_tofile(self):
# gh-4118
sizes = [io.DEFAULT_BUFFER_SIZE//8,
io.DEFAULT_BUFFER_SIZE,
io.DEFAULT_BUFFER_SIZE*8]
for size in sizes:
err_msg = "%d" % (size,)
f = open(self.filename, 'wb')
f.seek(size-1)
f.write(b'\0')
f.seek(10)
f.write(b'12')
np.array([0], dtype=np.float64).tofile(f)
pos = f.tell()
f.close()
assert_equal(pos, 10 + 2 + 8, err_msg=err_msg)
f = open(self.filename, 'r+b')
f.read(2)
f.seek(0, 1) # seek between read&write required by ANSI C
np.array([0], dtype=np.float64).tofile(f)
pos = f.tell()
f.close()
assert_equal(pos, 10, err_msg=err_msg)
def _check_from(self, s, value, **kw):
y = np.fromstring(asbytes(s), **kw)
assert_array_equal(y, value)
f = open(self.filename, 'wb')
f.write(asbytes(s))
f.close()
y = np.fromfile(self.filename, **kw)
assert_array_equal(y, value)
def test_nan(self):
self._check_from(
"nan +nan -nan NaN nan(foo) +NaN(BAR) -NAN(q_u_u_x_)",
[np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
sep=' ')
def test_inf(self):
self._check_from(
"inf +inf -inf infinity -Infinity iNfInItY -inF",
[np.inf, np.inf, -np.inf, np.inf, -np.inf, np.inf, -np.inf],
sep=' ')
def test_numbers(self):
self._check_from("1.234 -1.234 .3 .3e55 -123133.1231e+133",
[1.234, -1.234, .3, .3e55, -123133.1231e+133], sep=' ')
def test_binary(self):
self._check_from('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@',
np.array([1, 2, 3, 4]),
dtype='<f4')
@dec.slow # takes > 1 minute on mechanical hard drive
def test_big_binary(self):
"""Test workarounds for 32-bit limited fwrite, fseek, and ftell
calls in windows. These normally would hang doing something like this.
See http://projects.scipy.org/numpy/ticket/1660"""
if sys.platform != 'win32':
return
try:
# before workarounds, only up to 2**32-1 worked
fourgbplus = 2**32 + 2**16
testbytes = np.arange(8, dtype=np.int8)
n = len(testbytes)
flike = tempfile.NamedTemporaryFile()
f = flike.file
np.tile(testbytes, fourgbplus // testbytes.nbytes).tofile(f)
flike.seek(0)
a = np.fromfile(f, dtype=np.int8)
flike.close()
assert_(len(a) == fourgbplus)
# check only start and end for speed:
assert_((a[:n] == testbytes).all())
assert_((a[-n:] == testbytes).all())
except (MemoryError, ValueError):
pass
def test_string(self):
self._check_from('1,2,3,4', [1., 2., 3., 4.], sep=',')
def test_counted_string(self):
self._check_from('1,2,3,4', [1., 2., 3., 4.], count=4, sep=',')
self._check_from('1,2,3,4', [1., 2., 3.], count=3, sep=',')
self._check_from('1,2,3,4', [1., 2., 3., 4.], count=-1, sep=',')
def test_string_with_ws(self):
self._check_from('1 2 3 4 ', [1, 2, 3, 4], dtype=int, sep=' ')
def test_counted_string_with_ws(self):
self._check_from('1 2 3 4 ', [1, 2, 3], count=3, dtype=int,
sep=' ')
def test_ascii(self):
self._check_from('1 , 2 , 3 , 4', [1., 2., 3., 4.], sep=',')
self._check_from('1,2,3,4', [1., 2., 3., 4.], dtype=float, sep=',')
def test_malformed(self):
self._check_from('1.234 1,234', [1.234, 1.], sep=' ')
def test_long_sep(self):
self._check_from('1_x_3_x_4_x_5', [1, 3, 4, 5], sep='_x_')
def test_dtype(self):
v = np.array([1, 2, 3, 4], dtype=np.int_)
self._check_from('1,2,3,4', v, sep=',', dtype=np.int_)
def test_dtype_bool(self):
# can't use _check_from because fromstring can't handle True/False
v = np.array([True, False, True, False], dtype=np.bool_)
s = '1,0,-2.3,0'
f = open(self.filename, 'wb')
f.write(asbytes(s))
f.close()
y = np.fromfile(self.filename, sep=',', dtype=np.bool_)
assert_(y.dtype == '?')
assert_array_equal(y, v)
def test_tofile_sep(self):
x = np.array([1.51, 2, 3.51, 4], dtype=float)
f = open(self.filename, 'w')
x.tofile(f, sep=',')
f.close()
f = open(self.filename, 'r')
s = f.read()
f.close()
#assert_equal(s, '1.51,2.0,3.51,4.0')
y = np.array([float(p) for p in s.split(',')])
assert_array_equal(x,y)
def test_tofile_format(self):
x = np.array([1.51, 2, 3.51, 4], dtype=float)
f = open(self.filename, 'w')
x.tofile(f, sep=',', format='%.2f')
f.close()
f = open(self.filename, 'r')
s = f.read()
f.close()
assert_equal(s, '1.51,2.00,3.51,4.00')
def test_locale(self):
in_foreign_locale(self.test_numbers)()
in_foreign_locale(self.test_nan)()
in_foreign_locale(self.test_inf)()
in_foreign_locale(self.test_counted_string)()
in_foreign_locale(self.test_ascii)()
in_foreign_locale(self.test_malformed)()
in_foreign_locale(self.test_tofile_sep)()
in_foreign_locale(self.test_tofile_format)()
class TestFromBuffer(object):
def tst_basic(self, buffer, expected, kwargs):
assert_array_equal(np.frombuffer(buffer,**kwargs), expected)
def test_ip_basic(self):
for byteorder in ['<', '>']:
for dtype in [float, int, np.complex]:
dt = np.dtype(dtype).newbyteorder(byteorder)
x = (np.random.random((4, 7))*5).astype(dt)
buf = x.tobytes()
yield self.tst_basic, buf, x.flat, {'dtype':dt}
def test_empty(self):
yield self.tst_basic, asbytes(''), np.array([]), {}
class TestFlat(TestCase):
def setUp(self):
a0 = np.arange(20.0)
a = a0.reshape(4, 5)
a0.shape = (4, 5)
a.flags.writeable = False
self.a = a
self.b = a[::2, ::2]
self.a0 = a0
self.b0 = a0[::2, ::2]
def test_contiguous(self):
testpassed = False
try:
self.a.flat[12] = 100.0
except ValueError:
testpassed = True
assert_(testpassed)
assert_(self.a.flat[12] == 12.0)
def test_discontiguous(self):
testpassed = False
try:
self.b.flat[4] = 100.0
except ValueError:
testpassed = True
assert_(testpassed)
assert_(self.b.flat[4] == 12.0)
def test___array__(self):
c = self.a.flat.__array__()
d = self.b.flat.__array__()
e = self.a0.flat.__array__()
f = self.b0.flat.__array__()
assert_(c.flags.writeable is False)
assert_(d.flags.writeable is False)
assert_(e.flags.writeable is True)
assert_(f.flags.writeable is True)
assert_(c.flags.updateifcopy is False)
assert_(d.flags.updateifcopy is False)
assert_(e.flags.updateifcopy is False)
assert_(f.flags.updateifcopy is True)
assert_(f.base is self.b0)
class TestResize(TestCase):
def test_basic(self):
x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
x.resize((5, 5))
assert_array_equal(x.flat[:9],
np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).flat)
assert_array_equal(x[9:].flat, 0)
def test_check_reference(self):
x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
y = x
self.assertRaises(ValueError, x.resize, (5, 1))
del y # avoid pyflakes unused variable warning.
def test_int_shape(self):
x = np.eye(3)
x.resize(3)
assert_array_equal(x, np.eye(3)[0,:])
def test_none_shape(self):
x = np.eye(3)
x.resize(None)
assert_array_equal(x, np.eye(3))
x.resize()
assert_array_equal(x, np.eye(3))
def test_invalid_arguements(self):
self.assertRaises(TypeError, np.eye(3).resize, 'hi')
self.assertRaises(ValueError, np.eye(3).resize, -1)
self.assertRaises(TypeError, np.eye(3).resize, order=1)
self.assertRaises(TypeError, np.eye(3).resize, refcheck='hi')
def test_freeform_shape(self):
x = np.eye(3)
x.resize(3, 2, 1)
assert_(x.shape == (3, 2, 1))
def test_zeros_appended(self):
x = np.eye(3)
x.resize(2, 3, 3)
assert_array_equal(x[0], np.eye(3))
assert_array_equal(x[1], np.zeros((3, 3)))
def test_obj_obj(self):
# check memory is initialized on resize, gh-4857
a = np.ones(10, dtype=[('k', object, 2)])
a.resize(15,)
assert_equal(a.shape, (15,))
assert_array_equal(a['k'][-5:], 0)
assert_array_equal(a['k'][:-5], 1)
class TestRecord(TestCase):
def test_field_rename(self):
dt = np.dtype([('f', float), ('i', int)])
dt.names = ['p', 'q']
assert_equal(dt.names, ['p', 'q'])
def test_multiple_field_name_occurrence(self):
def test_assign():
dtype = np.dtype([("A", "f8"), ("B", "f8"), ("A", "f8")])
# Error raised when multiple fields have the same name
assert_raises(ValueError, test_assign)
if sys.version_info[0] >= 3:
def test_bytes_fields(self):
# Bytes are not allowed in field names and not recognized in titles
# on Py3
assert_raises(TypeError, np.dtype, [(asbytes('a'), int)])
assert_raises(TypeError, np.dtype, [(('b', asbytes('a')), int)])
dt = np.dtype([((asbytes('a'), 'b'), int)])
assert_raises(ValueError, dt.__getitem__, asbytes('a'))
x = np.array([(1,), (2,), (3,)], dtype=dt)
assert_raises(IndexError, x.__getitem__, asbytes('a'))
y = x[0]
assert_raises(IndexError, y.__getitem__, asbytes('a'))
def test_multiple_field_name_unicode(self):
def test_assign_unicode():
dt = np.dtype([("\u20B9", "f8"),
("B", "f8"),
("\u20B9", "f8")])
# Error raised when multiple fields have the same name(unicode included)
assert_raises(ValueError, test_assign_unicode)
else:
def test_unicode_field_titles(self):
# Unicode field titles are added to field dict on Py2
title = unicode('b')
dt = np.dtype([((title, 'a'), int)])
dt[title]
dt['a']
x = np.array([(1,), (2,), (3,)], dtype=dt)
x[title]
x['a']
y = x[0]
y[title]
y['a']
def test_unicode_field_names(self):
# Unicode field names are not allowed on Py2
title = unicode('b')
assert_raises(TypeError, np.dtype, [(title, int)])
assert_raises(TypeError, np.dtype, [(('a', title), int)])
def test_field_names(self):
# Test unicode and 8-bit / byte strings can be used
a = np.zeros((1,), dtype=[('f1', 'i4'),
('f2', 'i4'),
('f3', [('sf1', 'i4')])])
is_py3 = sys.version_info[0] >= 3
if is_py3:
funcs = (str,)
# byte string indexing fails gracefully
assert_raises(IndexError, a.__setitem__, asbytes('f1'), 1)
assert_raises(IndexError, a.__getitem__, asbytes('f1'))
assert_raises(IndexError, a['f1'].__setitem__, asbytes('sf1'), 1)
assert_raises(IndexError, a['f1'].__getitem__, asbytes('sf1'))
else:
funcs = (str, unicode)
for func in funcs:
b = a.copy()
fn1 = func('f1')
b[fn1] = 1
assert_equal(b[fn1], 1)
fnn = func('not at all')
assert_raises(ValueError, b.__setitem__, fnn, 1)
assert_raises(ValueError, b.__getitem__, fnn)
b[0][fn1] = 2
assert_equal(b[fn1], 2)
# Subfield
assert_raises(ValueError, b[0].__setitem__, fnn, 1)
assert_raises(ValueError, b[0].__getitem__, fnn)
# Subfield
fn3 = func('f3')
sfn1 = func('sf1')
b[fn3][sfn1] = 1
assert_equal(b[fn3][sfn1], 1)
assert_raises(ValueError, b[fn3].__setitem__, fnn, 1)
assert_raises(ValueError, b[fn3].__getitem__, fnn)
# multiple subfields
fn2 = func('f2')
b[fn2] = 3
assert_equal(b[['f1', 'f2']][0].tolist(), (2, 3))
assert_equal(b[['f2', 'f1']][0].tolist(), (3, 2))
assert_equal(b[['f1', 'f3']][0].tolist(), (2, (1,)))
# view of subfield view/copy
assert_equal(b[['f1', 'f2']][0].view(('i4', 2)).tolist(), (2, 3))
assert_equal(b[['f2', 'f1']][0].view(('i4', 2)).tolist(), (3, 2))
view_dtype = [('f1', 'i4'), ('f3', [('', 'i4')])]
assert_equal(b[['f1', 'f3']][0].view(view_dtype).tolist(), (2, (1,)))
# non-ascii unicode field indexing is well behaved
if not is_py3:
raise SkipTest('non ascii unicode field indexing skipped; '
'raises segfault on python 2.x')
else:
assert_raises(ValueError, a.__setitem__, sixu('\u03e0'), 1)
assert_raises(ValueError, a.__getitem__, sixu('\u03e0'))
def test_field_names_deprecation(self):
def collect_warnings(f, *args, **kwargs):
with warnings.catch_warnings(record=True) as log:
warnings.simplefilter("always")
f(*args, **kwargs)
return [w.category for w in log]
a = np.zeros((1,), dtype=[('f1', 'i4'),
('f2', 'i4'),
('f3', [('sf1', 'i4')])])
a['f1'][0] = 1
a['f2'][0] = 2
a['f3'][0] = (3,)
b = np.zeros((1,), dtype=[('f1', 'i4'),
('f2', 'i4'),
('f3', [('sf1', 'i4')])])
b['f1'][0] = 1
b['f2'][0] = 2
b['f3'][0] = (3,)
# All the different functions raise a warning, but not an error, and
# 'a' is not modified:
assert_equal(collect_warnings(a[['f1', 'f2']].__setitem__, 0, (10, 20)),
[FutureWarning])
assert_equal(a, b)
# Views also warn
subset = a[['f1', 'f2']]
subset_view = subset.view()
assert_equal(collect_warnings(subset_view['f1'].__setitem__, 0, 10),
[FutureWarning])
# But the write goes through:
assert_equal(subset['f1'][0], 10)
# Only one warning per multiple field indexing, though (even if there
# are multiple views involved):
assert_equal(collect_warnings(subset['f1'].__setitem__, 0, 10), [])
def test_record_hash(self):
a = np.array([(1, 2), (1, 2)], dtype='i1,i2')
a.flags.writeable = False
b = np.array([(1, 2), (3, 4)], dtype=[('num1', 'i1'), ('num2', 'i2')])
b.flags.writeable = False
c = np.array([(1, 2), (3, 4)], dtype='i1,i2')
c.flags.writeable = False
self.assertTrue(hash(a[0]) == hash(a[1]))
self.assertTrue(hash(a[0]) == hash(b[0]))
self.assertTrue(hash(a[0]) != hash(b[1]))
self.assertTrue(hash(c[0]) == hash(a[0]) and c[0] == a[0])
def test_record_no_hash(self):
a = np.array([(1, 2), (1, 2)], dtype='i1,i2')
self.assertRaises(TypeError, hash, a[0])
def test_empty_structure_creation(self):
# make sure these do not raise errors (gh-5631)
np.array([()], dtype={'names': [], 'formats': [],
'offsets': [], 'itemsize': 12})
np.array([(), (), (), (), ()], dtype={'names': [], 'formats': [],
'offsets': [], 'itemsize': 12})
class TestView(TestCase):
def test_basic(self):
x = np.array([(1, 2, 3, 4), (5, 6, 7, 8)],
dtype=[('r', np.int8), ('g', np.int8),
('b', np.int8), ('a', np.int8)])
# We must be specific about the endianness here:
y = x.view(dtype='<i4')
# ... and again without the keyword.
z = x.view('<i4')
assert_array_equal(y, z)
assert_array_equal(y, [67305985, 134678021])
def _mean(a, **args):
return a.mean(**args)
def _var(a, **args):
return a.var(**args)
def _std(a, **args):
return a.std(**args)
class TestStats(TestCase):
funcs = [_mean, _var, _std]
def setUp(self):
np.random.seed(range(3))
self.rmat = np.random.random((4, 5))
self.cmat = self.rmat + 1j * self.rmat
self.omat = np.array([Decimal(repr(r)) for r in self.rmat.flat])
self.omat = self.omat.reshape(4, 5)
def test_keepdims(self):
mat = np.eye(3)
for f in self.funcs:
for axis in [0, 1]:
res = f(mat, axis=axis, keepdims=True)
assert_(res.ndim == mat.ndim)
assert_(res.shape[axis] == 1)
for axis in [None]:
res = f(mat, axis=axis, keepdims=True)
assert_(res.shape == (1, 1))
def test_out(self):
mat = np.eye(3)
for f in self.funcs:
out = np.zeros(3)
tgt = f(mat, axis=1)
res = f(mat, axis=1, out=out)
assert_almost_equal(res, out)
assert_almost_equal(res, tgt)
out = np.empty(2)
assert_raises(ValueError, f, mat, axis=1, out=out)
out = np.empty((2, 2))
assert_raises(ValueError, f, mat, axis=1, out=out)
def test_dtype_from_input(self):
icodes = np.typecodes['AllInteger']
fcodes = np.typecodes['AllFloat']
# object type
for f in self.funcs:
mat = np.array([[Decimal(1)]*3]*3)
tgt = mat.dtype.type
res = f(mat, axis=1).dtype.type
assert_(res is tgt)
# scalar case
res = type(f(mat, axis=None))
assert_(res is Decimal)
# integer types
for f in self.funcs:
for c in icodes:
mat = np.eye(3, dtype=c)
tgt = np.float64
res = f(mat, axis=1).dtype.type
assert_(res is tgt)
# scalar case
res = f(mat, axis=None).dtype.type
assert_(res is tgt)
# mean for float types
for f in [_mean]:
for c in fcodes:
mat = np.eye(3, dtype=c)
tgt = mat.dtype.type
res = f(mat, axis=1).dtype.type
assert_(res is tgt)
# scalar case
res = f(mat, axis=None).dtype.type
assert_(res is tgt)
# var, std for float types
for f in [_var, _std]:
for c in fcodes:
mat = np.eye(3, dtype=c)
# deal with complex types
tgt = mat.real.dtype.type
res = f(mat, axis=1).dtype.type
assert_(res is tgt)
# scalar case
res = f(mat, axis=None).dtype.type
assert_(res is tgt)
def test_dtype_from_dtype(self):
mat = np.eye(3)
# stats for integer types
# FIXME:
# this needs definition as there are lots places along the line
# where type casting may take place.
# for f in self.funcs:
# for c in np.typecodes['AllInteger']:
# tgt = np.dtype(c).type
# res = f(mat, axis=1, dtype=c).dtype.type
# assert_(res is tgt)
# # scalar case
# res = f(mat, axis=None, dtype=c).dtype.type
# assert_(res is tgt)
# stats for float types
for f in self.funcs:
for c in np.typecodes['AllFloat']:
tgt = np.dtype(c).type
res = f(mat, axis=1, dtype=c).dtype.type
assert_(res is tgt)
# scalar case
res = f(mat, axis=None, dtype=c).dtype.type
assert_(res is tgt)
def test_ddof(self):
for f in [_var]:
for ddof in range(3):
dim = self.rmat.shape[1]
tgt = f(self.rmat, axis=1) * dim
res = f(self.rmat, axis=1, ddof=ddof) * (dim - ddof)
for f in [_std]:
for ddof in range(3):
dim = self.rmat.shape[1]
tgt = f(self.rmat, axis=1) * np.sqrt(dim)
res = f(self.rmat, axis=1, ddof=ddof) * np.sqrt(dim - ddof)
assert_almost_equal(res, tgt)
assert_almost_equal(res, tgt)
def test_ddof_too_big(self):
dim = self.rmat.shape[1]
for f in [_var, _std]:
for ddof in range(dim, dim + 2):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
res = f(self.rmat, axis=1, ddof=ddof)
assert_(not (res < 0).any())
assert_(len(w) > 0)
assert_(issubclass(w[0].category, RuntimeWarning))
def test_empty(self):
A = np.zeros((0, 3))
for f in self.funcs:
for axis in [0, None]:
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
assert_(np.isnan(f(A, axis=axis)).all())
assert_(len(w) > 0)
assert_(issubclass(w[0].category, RuntimeWarning))
for axis in [1]:
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
assert_equal(f(A, axis=axis), np.zeros([]))
def test_mean_values(self):
for mat in [self.rmat, self.cmat, self.omat]:
for axis in [0, 1]:
tgt = mat.sum(axis=axis)
res = _mean(mat, axis=axis) * mat.shape[axis]
assert_almost_equal(res, tgt)
for axis in [None]:
tgt = mat.sum(axis=axis)
res = _mean(mat, axis=axis) * np.prod(mat.shape)
assert_almost_equal(res, tgt)
def test_var_values(self):
for mat in [self.rmat, self.cmat, self.omat]:
for axis in [0, 1, None]:
msqr = _mean(mat * mat.conj(), axis=axis)
mean = _mean(mat, axis=axis)
tgt = msqr - mean * mean.conjugate()
res = _var(mat, axis=axis)
assert_almost_equal(res, tgt)
def test_std_values(self):
for mat in [self.rmat, self.cmat, self.omat]:
for axis in [0, 1, None]:
tgt = np.sqrt(_var(mat, axis=axis))
res = _std(mat, axis=axis)
assert_almost_equal(res, tgt)
def test_subclass(self):
class TestArray(np.ndarray):
def __new__(cls, data, info):
result = np.array(data)
result = result.view(cls)
result.info = info
return result
def __array_finalize__(self, obj):
self.info = getattr(obj, "info", '')
dat = TestArray([[1, 2, 3, 4], [5, 6, 7, 8]], 'jubba')
res = dat.mean(1)
assert_(res.info == dat.info)
res = dat.std(1)
assert_(res.info == dat.info)
res = dat.var(1)
assert_(res.info == dat.info)
class TestVdot(TestCase):
def test_basic(self):
dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
dt_complex = np.typecodes['Complex']
# test real
a = np.eye(3)
for dt in dt_numeric + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test complex
a = np.eye(3) * 1j
for dt in dt_complex + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test boolean
b = np.eye(3, dtype=np.bool)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), True)
def test_vdot_array_order(self):
a = np.array([[1, 2], [3, 4]], order='C')
b = np.array([[1, 2], [3, 4]], order='F')
res = np.vdot(a, a)
# integer arrays are exact
assert_equal(np.vdot(a, b), res)
assert_equal(np.vdot(b, a), res)
assert_equal(np.vdot(b, b), res)
def test_vdot_uncontiguous(self):
for size in [2, 1000]:
# Different sizes match different branches in vdot.
a = np.zeros((size, 2, 2))
b = np.zeros((size, 2, 2))
a[:, 0, 0] = np.arange(size)
b[:, 0, 0] = np.arange(size) + 1
# Make a and b uncontiguous:
a = a[..., 0]
b = b[..., 0]
assert_equal(np.vdot(a, b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy()),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy(), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy('F'), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy('F')),
np.vdot(a.flatten(), b.flatten()))
class TestDot(TestCase):
def setUp(self):
np.random.seed(128)
self.A = np.random.rand(4, 2)
self.b1 = np.random.rand(2, 1)
self.b2 = np.random.rand(2)
self.b3 = np.random.rand(1, 2)
self.b4 = np.random.rand(4)
self.N = 7
def test_dotmatmat(self):
A = self.A
res = np.dot(A.transpose(), A)
tgt = np.array([[1.45046013, 0.86323640],
[0.86323640, 0.84934569]])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotmatvec(self):
A, b1 = self.A, self.b1
res = np.dot(A, b1)
tgt = np.array([[0.32114320], [0.04889721],
[0.15696029], [0.33612621]])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotmatvec2(self):
A, b2 = self.A, self.b2
res = np.dot(A, b2)
tgt = np.array([0.29677940, 0.04518649, 0.14468333, 0.31039293])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotvecmat(self):
A, b4 = self.A, self.b4
res = np.dot(b4, A)
tgt = np.array([1.23495091, 1.12222648])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotvecmat2(self):
b3, A = self.b3, self.A
res = np.dot(b3, A.transpose())
tgt = np.array([[0.58793804, 0.08957460, 0.30605758, 0.62716383]])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotvecmat3(self):
A, b4 = self.A, self.b4
res = np.dot(A.transpose(), b4)
tgt = np.array([1.23495091, 1.12222648])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotvecvecouter(self):
b1, b3 = self.b1, self.b3
res = np.dot(b1, b3)
tgt = np.array([[0.20128610, 0.08400440], [0.07190947, 0.03001058]])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotvecvecinner(self):
b1, b3 = self.b1, self.b3
res = np.dot(b3, b1)
tgt = np.array([[ 0.23129668]])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotcolumnvect1(self):
b1 = np.ones((3, 1))
b2 = [5.3]
res = np.dot(b1, b2)
tgt = np.array([5.3, 5.3, 5.3])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotcolumnvect2(self):
b1 = np.ones((3, 1)).transpose()
b2 = [6.2]
res = np.dot(b2, b1)
tgt = np.array([6.2, 6.2, 6.2])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotvecscalar(self):
np.random.seed(100)
b1 = np.random.rand(1, 1)
b2 = np.random.rand(1, 4)
res = np.dot(b1, b2)
tgt = np.array([[0.15126730, 0.23068496, 0.45905553, 0.00256425]])
assert_almost_equal(res, tgt, decimal=self.N)
def test_dotvecscalar2(self):
np.random.seed(100)
b1 = np.random.rand(4, 1)
b2 = np.random.rand(1, 1)
res = np.dot(b1, b2)
tgt = np.array([[0.00256425],[0.00131359],[0.00200324],[ 0.00398638]])
assert_almost_equal(res, tgt, decimal=self.N)
def test_all(self):
dims = [(), (1,), (1, 1)]
dout = [(), (1,), (1, 1), (1,), (), (1,), (1, 1), (1,), (1, 1)]
for dim, (dim1, dim2) in zip(dout, itertools.product(dims, dims)):
b1 = np.zeros(dim1)
b2 = np.zeros(dim2)
res = np.dot(b1, b2)
tgt = np.zeros(dim)
assert_(res.shape == tgt.shape)
assert_almost_equal(res, tgt, decimal=self.N)
def test_vecobject(self):
class Vec(object):
def __init__(self, sequence=None):
if sequence is None:
sequence = []
self.array = np.array(sequence)
def __add__(self, other):
out = Vec()
out.array = self.array + other.array
return out
def __sub__(self, other):
out = Vec()
out.array = self.array - other.array
return out
def __mul__(self, other): # with scalar
out = Vec(self.array.copy())
out.array *= other
return out
def __rmul__(self, other):
return self*other
U_non_cont = np.transpose([[1., 1.], [1., 2.]])
U_cont = np.ascontiguousarray(U_non_cont)
x = np.array([Vec([1., 0.]), Vec([0., 1.])])
zeros = np.array([Vec([0., 0.]), Vec([0., 0.])])
zeros_test = np.dot(U_cont, x) - np.dot(U_non_cont, x)
assert_equal(zeros[0].array, zeros_test[0].array)
assert_equal(zeros[1].array, zeros_test[1].array)
def test_dot_2args(self):
from numpy.core.multiarray import dot
a = np.array([[1, 2], [3, 4]], dtype=float)
b = np.array([[1, 0], [1, 1]], dtype=float)
c = np.array([[3, 2], [7, 4]], dtype=float)
d = dot(a, b)
assert_allclose(c, d)
def test_dot_3args(self):
from numpy.core.multiarray import dot
np.random.seed(22)
f = np.random.random_sample((1024, 16))
v = np.random.random_sample((16, 32))
r = np.empty((1024, 32))
for i in range(12):
dot(f, v, r)
assert_equal(sys.getrefcount(r), 2)
r2 = dot(f, v, out=None)
assert_array_equal(r2, r)
assert_(r is dot(f, v, out=r))
v = v[:, 0].copy() # v.shape == (16,)
r = r[:, 0].copy() # r.shape == (1024,)
r2 = dot(f, v)
assert_(r is dot(f, v, r))
assert_array_equal(r2, r)
def test_dot_3args_errors(self):
from numpy.core.multiarray import dot
np.random.seed(22)
f = np.random.random_sample((1024, 16))
v = np.random.random_sample((16, 32))
r = np.empty((1024, 31))
assert_raises(ValueError, dot, f, v, r)
r = np.empty((1024,))
assert_raises(ValueError, dot, f, v, r)
r = np.empty((32,))
assert_raises(ValueError, dot, f, v, r)
r = np.empty((32, 1024))
assert_raises(ValueError, dot, f, v, r)
assert_raises(ValueError, dot, f, v, r.T)
r = np.empty((1024, 64))
assert_raises(ValueError, dot, f, v, r[:, ::2])
assert_raises(ValueError, dot, f, v, r[:, :32])
r = np.empty((1024, 32), dtype=np.float32)
assert_raises(ValueError, dot, f, v, r)
r = np.empty((1024, 32), dtype=int)
assert_raises(ValueError, dot, f, v, r)
def test_dot_array_order(self):
a = np.array([[1, 2], [3, 4]], order='C')
b = np.array([[1, 2], [3, 4]], order='F')
res = np.dot(a, a)
# integer arrays are exact
assert_equal(np.dot(a, b), res)
assert_equal(np.dot(b, a), res)
assert_equal(np.dot(b, b), res)
def test_dot_scalar_and_matrix_of_objects(self):
# Ticket #2469
arr = np.matrix([1, 2], dtype=object)
desired = np.matrix([[3, 6]], dtype=object)
assert_equal(np.dot(arr, 3), desired)
assert_equal(np.dot(3, arr), desired)
def test_accelerate_framework_sgemv_fix(self):
def aligned_array(shape, align, dtype, order='C'):
d = dtype(0)
N = np.prod(shape)
tmp = np.zeros(N * d.nbytes + align, dtype=np.uint8)
address = tmp.__array_interface__["data"][0]
for offset in range(align):
if (address + offset) % align == 0:
break
tmp = tmp[offset:offset+N*d.nbytes].view(dtype=dtype)
return tmp.reshape(shape, order=order)
def as_aligned(arr, align, dtype, order='C'):
aligned = aligned_array(arr.shape, align, dtype, order)
aligned[:] = arr[:]
return aligned
def assert_dot_close(A, X, desired):
assert_allclose(np.dot(A, X), desired, rtol=1e-5, atol=1e-7)
m = aligned_array(100, 15, np.float32)
s = aligned_array((100, 100), 15, np.float32)
np.dot(s, m) # this will always segfault if the bug is present
testdata = itertools.product((15,32), (10000,), (200,89), ('C','F'))
for align, m, n, a_order in testdata:
# Calculation in double precision
A_d = np.random.rand(m, n)
X_d = np.random.rand(n)
desired = np.dot(A_d, X_d)
# Calculation with aligned single precision
A_f = as_aligned(A_d, align, np.float32, order=a_order)
X_f = as_aligned(X_d, align, np.float32)
assert_dot_close(A_f, X_f, desired)
# Strided A rows
A_d_2 = A_d[::2]
desired = np.dot(A_d_2, X_d)
A_f_2 = A_f[::2]
assert_dot_close(A_f_2, X_f, desired)
# Strided A columns, strided X vector
A_d_22 = A_d_2[:, ::2]
X_d_2 = X_d[::2]
desired = np.dot(A_d_22, X_d_2)
A_f_22 = A_f_2[:, ::2]
X_f_2 = X_f[::2]
assert_dot_close(A_f_22, X_f_2, desired)
# Check the strides are as expected
if a_order == 'F':
assert_equal(A_f_22.strides, (8, 8 * m))
else:
assert_equal(A_f_22.strides, (8 * n, 8))
assert_equal(X_f_2.strides, (8,))
# Strides in A rows + cols only
X_f_2c = as_aligned(X_f_2, align, np.float32)
assert_dot_close(A_f_22, X_f_2c, desired)
# Strides just in A cols
A_d_12 = A_d[:, ::2]
desired = np.dot(A_d_12, X_d_2)
A_f_12 = A_f[:, ::2]
assert_dot_close(A_f_12, X_f_2c, desired)
# Strides in A cols and X
assert_dot_close(A_f_12, X_f_2, desired)
class MatmulCommon():
"""Common tests for '@' operator and numpy.matmul.
Do not derive from TestCase to avoid nose running it.
"""
# Should work with these types. Will want to add
# "O" at some point
types = "?bhilqBHILQefdgFDG"
def test_exceptions(self):
dims = [
((1,), (2,)), # mismatched vector vector
((2, 1,), (2,)), # mismatched matrix vector
((2,), (1, 2)), # mismatched vector matrix
((1, 2), (3, 1)), # mismatched matrix matrix
((1,), ()), # vector scalar
((), (1)), # scalar vector
((1, 1), ()), # matrix scalar
((), (1, 1)), # scalar matrix
((2, 2, 1), (3, 1, 2)), # cannot broadcast
]
for dt, (dm1, dm2) in itertools.product(self.types, dims):
a = np.ones(dm1, dtype=dt)
b = np.ones(dm2, dtype=dt)
assert_raises(ValueError, self.matmul, a, b)
def test_shapes(self):
dims = [
((1, 1), (2, 1, 1)), # broadcast first argument
((2, 1, 1), (1, 1)), # broadcast second argument
((2, 1, 1), (2, 1, 1)), # matrix stack sizes match
]
for dt, (dm1, dm2) in itertools.product(self.types, dims):
a = np.ones(dm1, dtype=dt)
b = np.ones(dm2, dtype=dt)
res = self.matmul(a, b)
assert_(res.shape == (2, 1, 1))
# vector vector returns scalars.
for dt in self.types:
a = np.ones((2,), dtype=dt)
b = np.ones((2,), dtype=dt)
c = self.matmul(a, b)
assert_(np.array(c).shape == ())
def test_result_types(self):
mat = np.ones((1,1))
vec = np.ones((1,))
for dt in self.types:
m = mat.astype(dt)
v = vec.astype(dt)
for arg in [(m, v), (v, m), (m, m)]:
res = self.matmul(*arg)
assert_(res.dtype == dt)
# vector vector returns scalars
res = self.matmul(v, v)
assert_(type(res) is np.dtype(dt).type)
def test_vector_vector_values(self):
vec = np.array([1, 2])
tgt = 5
for dt in self.types[1:]:
v1 = vec.astype(dt)
res = self.matmul(v1, v1)
assert_equal(res, tgt)
# boolean type
vec = np.array([True, True], dtype='?')
res = self.matmul(vec, vec)
assert_equal(res, True)
def test_vector_matrix_values(self):
vec = np.array([1, 2])
mat1 = np.array([[1, 2], [3, 4]])
mat2 = np.stack([mat1]*2, axis=0)
tgt1 = np.array([7, 10])
tgt2 = np.stack([tgt1]*2, axis=0)
for dt in self.types[1:]:
v = vec.astype(dt)
m1 = mat1.astype(dt)
m2 = mat2.astype(dt)
res = self.matmul(v, m1)
assert_equal(res, tgt1)
res = self.matmul(v, m2)
assert_equal(res, tgt2)
# boolean type
vec = np.array([True, False])
mat1 = np.array([[True, False], [False, True]])
mat2 = np.stack([mat1]*2, axis=0)
tgt1 = np.array([True, False])
tgt2 = np.stack([tgt1]*2, axis=0)
res = self.matmul(vec, mat1)
assert_equal(res, tgt1)
res = self.matmul(vec, mat2)
assert_equal(res, tgt2)
def test_matrix_vector_values(self):
vec = np.array([1, 2])
mat1 = np.array([[1, 2], [3, 4]])
mat2 = np.stack([mat1]*2, axis=0)
tgt1 = np.array([5, 11])
tgt2 = np.stack([tgt1]*2, axis=0)
for dt in self.types[1:]:
v = vec.astype(dt)
m1 = mat1.astype(dt)
m2 = mat2.astype(dt)
res = self.matmul(m1, v)
assert_equal(res, tgt1)
res = self.matmul(m2, v)
assert_equal(res, tgt2)
# boolean type
vec = np.array([True, False])
mat1 = np.array([[True, False], [False, True]])
mat2 = np.stack([mat1]*2, axis=0)
tgt1 = np.array([True, False])
tgt2 = np.stack([tgt1]*2, axis=0)
res = self.matmul(vec, mat1)
assert_equal(res, tgt1)
res = self.matmul(vec, mat2)
assert_equal(res, tgt2)
def test_matrix_matrix_values(self):
mat1 = np.array([[1, 2], [3, 4]])
mat2 = np.array([[1, 0], [1, 1]])
mat12 = np.stack([mat1, mat2], axis=0)
mat21 = np.stack([mat2, mat1], axis=0)
tgt11 = np.array([[7, 10], [15, 22]])
tgt12 = np.array([[3, 2], [7, 4]])
tgt21 = np.array([[1, 2], [4, 6]])
tgt12_21 = np.stack([tgt12, tgt21], axis=0)
tgt11_12 = np.stack((tgt11, tgt12), axis=0)
tgt11_21 = np.stack((tgt11, tgt21), axis=0)
for dt in self.types[1:]:
m1 = mat1.astype(dt)
m2 = mat2.astype(dt)
m12 = mat12.astype(dt)
m21 = mat21.astype(dt)
# matrix @ matrix
res = self.matmul(m1, m2)
assert_equal(res, tgt12)
res = self.matmul(m2, m1)
assert_equal(res, tgt21)
# stacked @ matrix
res = self.matmul(m12, m1)
assert_equal(res, tgt11_21)
# matrix @ stacked
res = self.matmul(m1, m12)
assert_equal(res, tgt11_12)
# stacked @ stacked
res = self.matmul(m12, m21)
assert_equal(res, tgt12_21)
# boolean type
m1 = np.array([[1, 1], [0, 0]], dtype=np.bool_)
m2 = np.array([[1, 0], [1, 1]], dtype=np.bool_)
m12 = np.stack([m1, m2], axis=0)
m21 = np.stack([m2, m1], axis=0)
tgt11 = m1
tgt12 = m1
tgt21 = np.array([[1, 1], [1, 1]], dtype=np.bool_)
tgt12_21 = np.stack([tgt12, tgt21], axis=0)
tgt11_12 = np.stack((tgt11, tgt12), axis=0)
tgt11_21 = np.stack((tgt11, tgt21), axis=0)
# matrix @ matrix
res = self.matmul(m1, m2)
assert_equal(res, tgt12)
res = self.matmul(m2, m1)
assert_equal(res, tgt21)
# stacked @ matrix
res = self.matmul(m12, m1)
assert_equal(res, tgt11_21)
# matrix @ stacked
res = self.matmul(m1, m12)
assert_equal(res, tgt11_12)
# stacked @ stacked
res = self.matmul(m12, m21)
assert_equal(res, tgt12_21)
def test_numpy_ufunc_override(self):
# 2016-01-29: NUMPY_UFUNC_DISABLED
return
class A(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(cls)
def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
return "A"
class B(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(cls)
def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
return NotImplemented
a = A([1, 2])
b = B([1, 2])
c = np.ones(2)
assert_equal(self.matmul(a, b), "A")
assert_equal(self.matmul(b, a), "A")
assert_raises(TypeError, self.matmul, b, c)
class TestMatmul(MatmulCommon, TestCase):
matmul = np.matmul
def test_out_arg(self):
a = np.ones((2, 2), dtype=np.float)
b = np.ones((2, 2), dtype=np.float)
tgt = np.full((2,2), 2, dtype=np.float)
# test as positional argument
msg = "out positional argument"
out = np.zeros((2, 2), dtype=np.float)
self.matmul(a, b, out)
assert_array_equal(out, tgt, err_msg=msg)
# test as keyword argument
msg = "out keyword argument"
out = np.zeros((2, 2), dtype=np.float)
self.matmul(a, b, out=out)
assert_array_equal(out, tgt, err_msg=msg)
# test out with not allowed type cast (safe casting)
# einsum and cblas raise different error types, so
# use Exception.
msg = "out argument with illegal cast"
out = np.zeros((2, 2), dtype=np.int32)
assert_raises(Exception, self.matmul, a, b, out=out)
# skip following tests for now, cblas does not allow non-contiguous
# outputs and consistency with dot would require same type,
# dimensions, subtype, and c_contiguous.
# test out with allowed type cast
# msg = "out argument with allowed cast"
# out = np.zeros((2, 2), dtype=np.complex128)
# self.matmul(a, b, out=out)
# assert_array_equal(out, tgt, err_msg=msg)
# test out non-contiguous
# msg = "out argument with non-contiguous layout"
# c = np.zeros((2, 2, 2), dtype=np.float)
# self.matmul(a, b, out=c[..., 0])
# assert_array_equal(c, tgt, err_msg=msg)
if sys.version_info[:2] >= (3, 5):
class TestMatmulOperator(MatmulCommon, TestCase):
import operator
matmul = operator.matmul
def test_array_priority_override(self):
class A(object):
__array_priority__ = 1000
def __matmul__(self, other):
return "A"
def __rmatmul__(self, other):
return "A"
a = A()
b = np.ones(2)
assert_equal(self.matmul(a, b), "A")
assert_equal(self.matmul(b, a), "A")
def test_matmul_inplace():
# It would be nice to support in-place matmul eventually, but for now
# we don't have a working implementation, so better just to error out
# and nudge people to writing "a = a @ b".
a = np.eye(3)
b = np.eye(3)
assert_raises(TypeError, a.__imatmul__, b)
import operator
assert_raises(TypeError, operator.imatmul, a, b)
# we avoid writing the token `exec` so as not to crash python 2's
# parser
exec_ = getattr(builtins, "exec")
assert_raises(TypeError, exec_, "a @= b", globals(), locals())
class TestInner(TestCase):
def test_inner_type_mismatch(self):
c = 1.
A = np.array((1,1), dtype='i,i')
assert_raises(TypeError, np.inner, c, A)
assert_raises(TypeError, np.inner, A, c)
def test_inner_scalar_and_vector(self):
for dt in np.typecodes['AllInteger'] + np.typecodes['AllFloat'] + '?':
sca = np.array(3, dtype=dt)[()]
vec = np.array([1, 2], dtype=dt)
desired = np.array([3, 6], dtype=dt)
assert_equal(np.inner(vec, sca), desired)
assert_equal(np.inner(sca, vec), desired)
def test_inner_scalar_and_matrix(self):
for dt in np.typecodes['AllInteger'] + np.typecodes['AllFloat'] + '?':
sca = np.array(3, dtype=dt)[()]
arr = np.matrix([[1, 2], [3, 4]], dtype=dt)
desired = np.matrix([[3, 6], [9, 12]], dtype=dt)
assert_equal(np.inner(arr, sca), desired)
assert_equal(np.inner(sca, arr), desired)
def test_inner_scalar_and_matrix_of_objects(self):
# Ticket #4482
arr = np.matrix([1, 2], dtype=object)
desired = np.matrix([[3, 6]], dtype=object)
assert_equal(np.inner(arr, 3), desired)
assert_equal(np.inner(3, arr), desired)
def test_vecself(self):
# Ticket 844.
# Inner product of a vector with itself segfaults or give
# meaningless result
a = np.zeros(shape=(1, 80), dtype=np.float64)
p = np.inner(a, a)
assert_almost_equal(p, 0, decimal=14)
def test_inner_product_with_various_contiguities(self):
# github issue 6532
for dt in np.typecodes['AllInteger'] + np.typecodes['AllFloat'] + '?':
# check an inner product involving a matrix transpose
A = np.array([[1, 2], [3, 4]], dtype=dt)
B = np.array([[1, 3], [2, 4]], dtype=dt)
C = np.array([1, 1], dtype=dt)
desired = np.array([4, 6], dtype=dt)
assert_equal(np.inner(A.T, C), desired)
assert_equal(np.inner(C, A.T), desired)
assert_equal(np.inner(B, C), desired)
assert_equal(np.inner(C, B), desired)
# check a matrix product
desired = np.array([[7, 10], [15, 22]], dtype=dt)
assert_equal(np.inner(A, B), desired)
# check the syrk vs. gemm paths
desired = np.array([[5, 11], [11, 25]], dtype=dt)
assert_equal(np.inner(A, A), desired)
assert_equal(np.inner(A, A.copy()), desired)
# check an inner product involving an aliased and reversed view
a = np.arange(5).astype(dt)
b = a[::-1]
desired = np.array(10, dtype=dt).item()
assert_equal(np.inner(b, a), desired)
def test_3d_tensor(self):
for dt in np.typecodes['AllInteger'] + np.typecodes['AllFloat'] + '?':
a = np.arange(24).reshape(2,3,4).astype(dt)
b = np.arange(24, 48).reshape(2,3,4).astype(dt)
desired = np.array(
[[[[ 158, 182, 206],
[ 230, 254, 278]],
[[ 566, 654, 742],
[ 830, 918, 1006]],
[[ 974, 1126, 1278],
[1430, 1582, 1734]]],
[[[1382, 1598, 1814],
[2030, 2246, 2462]],
[[1790, 2070, 2350],
[2630, 2910, 3190]],
[[2198, 2542, 2886],
[3230, 3574, 3918]]]],
dtype=dt
)
assert_equal(np.inner(a, b), desired)
assert_equal(np.inner(b, a).transpose(2,3,0,1), desired)
class TestSummarization(TestCase):
def test_1d(self):
A = np.arange(1001)
strA = '[ 0 1 2 ..., 998 999 1000]'
assert_(str(A) == strA)
reprA = 'array([ 0, 1, 2, ..., 998, 999, 1000])'
assert_(repr(A) == reprA)
def test_2d(self):
A = np.arange(1002).reshape(2, 501)
strA = '[[ 0 1 2 ..., 498 499 500]\n' \
' [ 501 502 503 ..., 999 1000 1001]]'
assert_(str(A) == strA)
reprA = 'array([[ 0, 1, 2, ..., 498, 499, 500],\n' \
' [ 501, 502, 503, ..., 999, 1000, 1001]])'
assert_(repr(A) == reprA)
class TestAlen(TestCase):
def test_basic(self):
m = np.array([1, 2, 3])
self.assertEqual(np.alen(m), 3)
m = np.array([[1, 2, 3], [4, 5, 7]])
self.assertEqual(np.alen(m), 2)
m = [1, 2, 3]
self.assertEqual(np.alen(m), 3)
m = [[1, 2, 3], [4, 5, 7]]
self.assertEqual(np.alen(m), 2)
def test_singleton(self):
self.assertEqual(np.alen(5), 1)
class TestChoose(TestCase):
def setUp(self):
self.x = 2*np.ones((3,), dtype=int)
self.y = 3*np.ones((3,), dtype=int)
self.x2 = 2*np.ones((2, 3), dtype=int)
self.y2 = 3*np.ones((2, 3), dtype=int)
self.ind = [0, 0, 1]
def test_basic(self):
A = np.choose(self.ind, (self.x, self.y))
assert_equal(A, [2, 2, 3])
def test_broadcast1(self):
A = np.choose(self.ind, (self.x2, self.y2))
assert_equal(A, [[2, 2, 3], [2, 2, 3]])
def test_broadcast2(self):
A = np.choose(self.ind, (self.x, self.y2))
assert_equal(A, [[2, 2, 3], [2, 2, 3]])
class TestRepeat(TestCase):
def setUp(self):
self.m = np.array([1, 2, 3, 4, 5, 6])
self.m_rect = self.m.reshape((2, 3))
def test_basic(self):
A = np.repeat(self.m, [1, 3, 2, 1, 1, 2])
assert_equal(A, [1, 2, 2, 2, 3,
3, 4, 5, 6, 6])
def test_broadcast1(self):
A = np.repeat(self.m, 2)
assert_equal(A, [1, 1, 2, 2, 3, 3,
4, 4, 5, 5, 6, 6])
def test_axis_spec(self):
A = np.repeat(self.m_rect, [2, 1], axis=0)
assert_equal(A, [[1, 2, 3],
[1, 2, 3],
[4, 5, 6]])
A = np.repeat(self.m_rect, [1, 3, 2], axis=1)
assert_equal(A, [[1, 2, 2, 2, 3, 3],
[4, 5, 5, 5, 6, 6]])
def test_broadcast2(self):
A = np.repeat(self.m_rect, 2, axis=0)
assert_equal(A, [[1, 2, 3],
[1, 2, 3],
[4, 5, 6],
[4, 5, 6]])
A = np.repeat(self.m_rect, 2, axis=1)
assert_equal(A, [[1, 1, 2, 2, 3, 3],
[4, 4, 5, 5, 6, 6]])
# TODO: test for multidimensional
NEIGH_MODE = {'zero': 0, 'one': 1, 'constant': 2, 'circular': 3, 'mirror': 4}
class TestNeighborhoodIter(TestCase):
# Simple, 2d tests
def _test_simple2d(self, dt):
# Test zero and one padding for simple data type
x = np.array([[0, 1], [2, 3]], dtype=dt)
r = [np.array([[0, 0, 0], [0, 0, 1]], dtype=dt),
np.array([[0, 0, 0], [0, 1, 0]], dtype=dt),
np.array([[0, 0, 1], [0, 2, 3]], dtype=dt),
np.array([[0, 1, 0], [2, 3, 0]], dtype=dt)]
l = test_neighborhood_iterator(x, [-1, 0, -1, 1], x[0],
NEIGH_MODE['zero'])
assert_array_equal(l, r)
r = [np.array([[1, 1, 1], [1, 0, 1]], dtype=dt),
np.array([[1, 1, 1], [0, 1, 1]], dtype=dt),
np.array([[1, 0, 1], [1, 2, 3]], dtype=dt),
np.array([[0, 1, 1], [2, 3, 1]], dtype=dt)]
l = test_neighborhood_iterator(x, [-1, 0, -1, 1], x[0],
NEIGH_MODE['one'])
assert_array_equal(l, r)
r = [np.array([[4, 4, 4], [4, 0, 1]], dtype=dt),
np.array([[4, 4, 4], [0, 1, 4]], dtype=dt),
np.array([[4, 0, 1], [4, 2, 3]], dtype=dt),
np.array([[0, 1, 4], [2, 3, 4]], dtype=dt)]
l = test_neighborhood_iterator(x, [-1, 0, -1, 1], 4,
NEIGH_MODE['constant'])
assert_array_equal(l, r)
def test_simple2d(self):
self._test_simple2d(np.float)
def test_simple2d_object(self):
self._test_simple2d(Decimal)
def _test_mirror2d(self, dt):
x = np.array([[0, 1], [2, 3]], dtype=dt)
r = [np.array([[0, 0, 1], [0, 0, 1]], dtype=dt),
np.array([[0, 1, 1], [0, 1, 1]], dtype=dt),
np.array([[0, 0, 1], [2, 2, 3]], dtype=dt),
np.array([[0, 1, 1], [2, 3, 3]], dtype=dt)]
l = test_neighborhood_iterator(x, [-1, 0, -1, 1], x[0],
NEIGH_MODE['mirror'])
assert_array_equal(l, r)
def test_mirror2d(self):
self._test_mirror2d(np.float)
def test_mirror2d_object(self):
self._test_mirror2d(Decimal)
# Simple, 1d tests
def _test_simple(self, dt):
# Test padding with constant values
x = np.linspace(1, 5, 5).astype(dt)
r = [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 0]]
l = test_neighborhood_iterator(x, [-1, 1], x[0], NEIGH_MODE['zero'])
assert_array_equal(l, r)
r = [[1, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 1]]
l = test_neighborhood_iterator(x, [-1, 1], x[0], NEIGH_MODE['one'])
assert_array_equal(l, r)
r = [[x[4], 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, x[4]]]
l = test_neighborhood_iterator(x, [-1, 1], x[4], NEIGH_MODE['constant'])
assert_array_equal(l, r)
def test_simple_float(self):
self._test_simple(np.float)
def test_simple_object(self):
self._test_simple(Decimal)
# Test mirror modes
def _test_mirror(self, dt):
x = np.linspace(1, 5, 5).astype(dt)
r = np.array([[2, 1, 1, 2, 3], [1, 1, 2, 3, 4], [1, 2, 3, 4, 5],
[2, 3, 4, 5, 5], [3, 4, 5, 5, 4]], dtype=dt)
l = test_neighborhood_iterator(x, [-2, 2], x[1], NEIGH_MODE['mirror'])
self.assertTrue([i.dtype == dt for i in l])
assert_array_equal(l, r)
def test_mirror(self):
self._test_mirror(np.float)
def test_mirror_object(self):
self._test_mirror(Decimal)
# Circular mode
def _test_circular(self, dt):
x = np.linspace(1, 5, 5).astype(dt)
r = np.array([[4, 5, 1, 2, 3], [5, 1, 2, 3, 4], [1, 2, 3, 4, 5],
[2, 3, 4, 5, 1], [3, 4, 5, 1, 2]], dtype=dt)
l = test_neighborhood_iterator(x, [-2, 2], x[0], NEIGH_MODE['circular'])
assert_array_equal(l, r)
def test_circular(self):
self._test_circular(np.float)
def test_circular_object(self):
self._test_circular(Decimal)
# Test stacking neighborhood iterators
class TestStackedNeighborhoodIter(TestCase):
# Simple, 1d test: stacking 2 constant-padded neigh iterators
def test_simple_const(self):
dt = np.float64
# Test zero and one padding for simple data type
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([0], dtype=dt),
np.array([0], dtype=dt),
np.array([1], dtype=dt),
np.array([2], dtype=dt),
np.array([3], dtype=dt),
np.array([0], dtype=dt),
np.array([0], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-2, 4], NEIGH_MODE['zero'],
[0, 0], NEIGH_MODE['zero'])
assert_array_equal(l, r)
r = [np.array([1, 0, 1], dtype=dt),
np.array([0, 1, 2], dtype=dt),
np.array([1, 2, 3], dtype=dt),
np.array([2, 3, 0], dtype=dt),
np.array([3, 0, 1], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'],
[-1, 1], NEIGH_MODE['one'])
assert_array_equal(l, r)
# 2nd simple, 1d test: stacking 2 neigh iterators, mixing const padding and
# mirror padding
def test_simple_mirror(self):
dt = np.float64
# Stacking zero on top of mirror
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([0, 1, 1], dtype=dt),
np.array([1, 1, 2], dtype=dt),
np.array([1, 2, 3], dtype=dt),
np.array([2, 3, 3], dtype=dt),
np.array([3, 3, 0], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['mirror'],
[-1, 1], NEIGH_MODE['zero'])
assert_array_equal(l, r)
# Stacking mirror on top of zero
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([1, 0, 0], dtype=dt),
np.array([0, 0, 1], dtype=dt),
np.array([0, 1, 2], dtype=dt),
np.array([1, 2, 3], dtype=dt),
np.array([2, 3, 0], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'],
[-2, 0], NEIGH_MODE['mirror'])
assert_array_equal(l, r)
# Stacking mirror on top of zero: 2nd
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([0, 1, 2], dtype=dt),
np.array([1, 2, 3], dtype=dt),
np.array([2, 3, 0], dtype=dt),
np.array([3, 0, 0], dtype=dt),
np.array([0, 0, 3], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'],
[0, 2], NEIGH_MODE['mirror'])
assert_array_equal(l, r)
# Stacking mirror on top of zero: 3rd
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([1, 0, 0, 1, 2], dtype=dt),
np.array([0, 0, 1, 2, 3], dtype=dt),
np.array([0, 1, 2, 3, 0], dtype=dt),
np.array([1, 2, 3, 0, 0], dtype=dt),
np.array([2, 3, 0, 0, 3], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'],
[-2, 2], NEIGH_MODE['mirror'])
assert_array_equal(l, r)
# 3rd simple, 1d test: stacking 2 neigh iterators, mixing const padding and
# circular padding
def test_simple_circular(self):
dt = np.float64
# Stacking zero on top of mirror
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([0, 3, 1], dtype=dt),
np.array([3, 1, 2], dtype=dt),
np.array([1, 2, 3], dtype=dt),
np.array([2, 3, 1], dtype=dt),
np.array([3, 1, 0], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['circular'],
[-1, 1], NEIGH_MODE['zero'])
assert_array_equal(l, r)
# Stacking mirror on top of zero
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([3, 0, 0], dtype=dt),
np.array([0, 0, 1], dtype=dt),
np.array([0, 1, 2], dtype=dt),
np.array([1, 2, 3], dtype=dt),
np.array([2, 3, 0], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'],
[-2, 0], NEIGH_MODE['circular'])
assert_array_equal(l, r)
# Stacking mirror on top of zero: 2nd
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([0, 1, 2], dtype=dt),
np.array([1, 2, 3], dtype=dt),
np.array([2, 3, 0], dtype=dt),
np.array([3, 0, 0], dtype=dt),
np.array([0, 0, 1], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'],
[0, 2], NEIGH_MODE['circular'])
assert_array_equal(l, r)
# Stacking mirror on top of zero: 3rd
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([3, 0, 0, 1, 2], dtype=dt),
np.array([0, 0, 1, 2, 3], dtype=dt),
np.array([0, 1, 2, 3, 0], dtype=dt),
np.array([1, 2, 3, 0, 0], dtype=dt),
np.array([2, 3, 0, 0, 1], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'],
[-2, 2], NEIGH_MODE['circular'])
assert_array_equal(l, r)
# 4th simple, 1d test: stacking 2 neigh iterators, but with lower iterator
# being strictly within the array
def test_simple_strict_within(self):
dt = np.float64
# Stacking zero on top of zero, first neighborhood strictly inside the
# array
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([1, 2, 3, 0], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [1, 1], NEIGH_MODE['zero'],
[-1, 2], NEIGH_MODE['zero'])
assert_array_equal(l, r)
# Stacking mirror on top of zero, first neighborhood strictly inside the
# array
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([1, 2, 3, 3], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [1, 1], NEIGH_MODE['zero'],
[-1, 2], NEIGH_MODE['mirror'])
assert_array_equal(l, r)
# Stacking mirror on top of zero, first neighborhood strictly inside the
# array
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([1, 2, 3, 1], dtype=dt)]
l = test_neighborhood_iterator_oob(x, [1, 1], NEIGH_MODE['zero'],
[-1, 2], NEIGH_MODE['circular'])
assert_array_equal(l, r)
class TestWarnings(object):
def test_complex_warning(self):
x = np.array([1, 2])
y = np.array([1-2j, 1+2j])
with warnings.catch_warnings():
warnings.simplefilter("error", np.ComplexWarning)
assert_raises(np.ComplexWarning, x.__setitem__, slice(None), y)
assert_equal(x, [1, 2])
class TestMinScalarType(object):
def test_usigned_shortshort(self):
dt = np.min_scalar_type(2**8-1)
wanted = np.dtype('uint8')
assert_equal(wanted, dt)
def test_usigned_short(self):
dt = np.min_scalar_type(2**16-1)
wanted = np.dtype('uint16')
assert_equal(wanted, dt)
def test_usigned_int(self):
dt = np.min_scalar_type(2**32-1)
wanted = np.dtype('uint32')
assert_equal(wanted, dt)
def test_usigned_longlong(self):
dt = np.min_scalar_type(2**63-1)
wanted = np.dtype('uint64')
assert_equal(wanted, dt)
def test_object(self):
dt = np.min_scalar_type(2**64)
wanted = np.dtype('O')
assert_equal(wanted, dt)
if sys.version_info[:2] == (2, 6):
from numpy.core.multiarray import memorysimpleview as memoryview
from numpy.core._internal import _dtype_from_pep3118
class TestPEP3118Dtype(object):
def _check(self, spec, wanted):
dt = np.dtype(wanted)
if isinstance(wanted, list) and isinstance(wanted[-1], tuple):
if wanted[-1][0] == '':
names = list(dt.names)
names[-1] = ''
dt.names = tuple(names)
assert_equal(_dtype_from_pep3118(spec), dt,
err_msg="spec %r != dtype %r" % (spec, wanted))
def test_native_padding(self):
align = np.dtype('i').alignment
for j in range(8):
if j == 0:
s = 'bi'
else:
s = 'b%dxi' % j
self._check('@'+s, {'f0': ('i1', 0),
'f1': ('i', align*(1 + j//align))})
self._check('='+s, {'f0': ('i1', 0),
'f1': ('i', 1+j)})
def test_native_padding_2(self):
# Native padding should work also for structs and sub-arrays
self._check('x3T{xi}', {'f0': (({'f0': ('i', 4)}, (3,)), 4)})
self._check('^x3T{xi}', {'f0': (({'f0': ('i', 1)}, (3,)), 1)})
def test_trailing_padding(self):
# Trailing padding should be included, *and*, the item size
# should match the alignment if in aligned mode
align = np.dtype('i').alignment
def VV(n):
return 'V%d' % (align*(1 + (n-1)//align))
self._check('ix', [('f0', 'i'), ('', VV(1))])
self._check('ixx', [('f0', 'i'), ('', VV(2))])
self._check('ixxx', [('f0', 'i'), ('', VV(3))])
self._check('ixxxx', [('f0', 'i'), ('', VV(4))])
self._check('i7x', [('f0', 'i'), ('', VV(7))])
self._check('^ix', [('f0', 'i'), ('', 'V1')])
self._check('^ixx', [('f0', 'i'), ('', 'V2')])
self._check('^ixxx', [('f0', 'i'), ('', 'V3')])
self._check('^ixxxx', [('f0', 'i'), ('', 'V4')])
self._check('^i7x', [('f0', 'i'), ('', 'V7')])
def test_native_padding_3(self):
dt = np.dtype(
[('a', 'b'), ('b', 'i'),
('sub', np.dtype('b,i')), ('c', 'i')],
align=True)
self._check("T{b:a:xxxi:b:T{b:f0:=i:f1:}:sub:xxxi:c:}", dt)
dt = np.dtype(
[('a', 'b'), ('b', 'i'), ('c', 'b'), ('d', 'b'),
('e', 'b'), ('sub', np.dtype('b,i', align=True))])
self._check("T{b:a:=i:b:b:c:b:d:b:e:T{b:f0:xxxi:f1:}:sub:}", dt)
def test_padding_with_array_inside_struct(self):
dt = np.dtype(
[('a', 'b'), ('b', 'i'), ('c', 'b', (3,)),
('d', 'i')],
align=True)
self._check("T{b:a:xxxi:b:3b:c:xi:d:}", dt)
def test_byteorder_inside_struct(self):
# The byte order after @T{=i} should be '=', not '@'.
# Check this by noting the absence of native alignment.
self._check('@T{^i}xi', {'f0': ({'f0': ('i', 0)}, 0),
'f1': ('i', 5)})
def test_intra_padding(self):
# Natively aligned sub-arrays may require some internal padding
align = np.dtype('i').alignment
def VV(n):
return 'V%d' % (align*(1 + (n-1)//align))
self._check('(3)T{ix}', ({'f0': ('i', 0), '': (VV(1), 4)}, (3,)))
class TestNewBufferProtocol(object):
def _check_roundtrip(self, obj):
obj = np.asarray(obj)
x = memoryview(obj)
y = np.asarray(x)
y2 = np.array(x)
assert_(not y.flags.owndata)
assert_(y2.flags.owndata)
assert_equal(y.dtype, obj.dtype)
assert_equal(y.shape, obj.shape)
assert_array_equal(obj, y)
assert_equal(y2.dtype, obj.dtype)
assert_equal(y2.shape, obj.shape)
assert_array_equal(obj, y2)
def test_roundtrip(self):
x = np.array([1, 2, 3, 4, 5], dtype='i4')
self._check_roundtrip(x)
x = np.array([[1, 2], [3, 4]], dtype=np.float64)
self._check_roundtrip(x)
x = np.zeros((3, 3, 3), dtype=np.float32)[:, 0,:]
self._check_roundtrip(x)
dt = [('a', 'b'),
('b', 'h'),
('c', 'i'),
('d', 'l'),
('dx', 'q'),
('e', 'B'),
('f', 'H'),
('g', 'I'),
('h', 'L'),
('hx', 'Q'),
('i', np.single),
('j', np.double),
('k', np.longdouble),
('ix', np.csingle),
('jx', np.cdouble),
('kx', np.clongdouble),
('l', 'S4'),
('m', 'U4'),
('n', 'V3'),
('o', '?'),
('p', np.half),
]
x = np.array(
[(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
asbytes('aaaa'), 'bbbb', asbytes('xxx'), True, 1.0)],
dtype=dt)
self._check_roundtrip(x)
x = np.array(([[1, 2], [3, 4]],), dtype=[('a', (int, (2, 2)))])
self._check_roundtrip(x)
x = np.array([1, 2, 3], dtype='>i2')
self._check_roundtrip(x)
x = np.array([1, 2, 3], dtype='<i2')
self._check_roundtrip(x)
x = np.array([1, 2, 3], dtype='>i4')
self._check_roundtrip(x)
x = np.array([1, 2, 3], dtype='<i4')
self._check_roundtrip(x)
# check long long can be represented as non-native
x = np.array([1, 2, 3], dtype='>q')
self._check_roundtrip(x)
# Native-only data types can be passed through the buffer interface
# only in native byte order
if sys.byteorder == 'little':
x = np.array([1, 2, 3], dtype='>g')
assert_raises(ValueError, self._check_roundtrip, x)
x = np.array([1, 2, 3], dtype='<g')
self._check_roundtrip(x)
else:
x = np.array([1, 2, 3], dtype='>g')
self._check_roundtrip(x)
x = np.array([1, 2, 3], dtype='<g')
assert_raises(ValueError, self._check_roundtrip, x)
def test_roundtrip_half(self):
half_list = [
1.0,
-2.0,
6.5504 * 10**4, # (max half precision)
2**-14, # ~= 6.10352 * 10**-5 (minimum positive normal)
2**-24, # ~= 5.96046 * 10**-8 (minimum strictly positive subnormal)
0.0,
-0.0,
float('+inf'),
float('-inf'),
0.333251953125, # ~= 1/3
]
x = np.array(half_list, dtype='>e')
self._check_roundtrip(x)
x = np.array(half_list, dtype='<e')
self._check_roundtrip(x)
def test_roundtrip_single_types(self):
for typ in np.typeDict.values():
dtype = np.dtype(typ)
if dtype.char in 'Mm':
# datetimes cannot be used in buffers
continue
if dtype.char == 'V':
# skip void
continue
x = np.zeros(4, dtype=dtype)
self._check_roundtrip(x)
if dtype.char not in 'qQgG':
dt = dtype.newbyteorder('<')
x = np.zeros(4, dtype=dt)
self._check_roundtrip(x)
dt = dtype.newbyteorder('>')
x = np.zeros(4, dtype=dt)
self._check_roundtrip(x)
def test_roundtrip_scalar(self):
# Issue #4015.
self._check_roundtrip(0)
def test_export_simple_1d(self):
x = np.array([1, 2, 3, 4, 5], dtype='i')
y = memoryview(x)
assert_equal(y.format, 'i')
assert_equal(y.shape, (5,))
assert_equal(y.ndim, 1)
assert_equal(y.strides, (4,))
assert_equal(y.suboffsets, EMPTY)
assert_equal(y.itemsize, 4)
def test_export_simple_nd(self):
x = np.array([[1, 2], [3, 4]], dtype=np.float64)
y = memoryview(x)
assert_equal(y.format, 'd')
assert_equal(y.shape, (2, 2))
assert_equal(y.ndim, 2)
assert_equal(y.strides, (16, 8))
assert_equal(y.suboffsets, EMPTY)
assert_equal(y.itemsize, 8)
def test_export_discontiguous(self):
x = np.zeros((3, 3, 3), dtype=np.float32)[:, 0,:]
y = memoryview(x)
assert_equal(y.format, 'f')
assert_equal(y.shape, (3, 3))
assert_equal(y.ndim, 2)
assert_equal(y.strides, (36, 4))
assert_equal(y.suboffsets, EMPTY)
assert_equal(y.itemsize, 4)
def test_export_record(self):
dt = [('a', 'b'),
('b', 'h'),
('c', 'i'),
('d', 'l'),
('dx', 'q'),
('e', 'B'),
('f', 'H'),
('g', 'I'),
('h', 'L'),
('hx', 'Q'),
('i', np.single),
('j', np.double),
('k', np.longdouble),
('ix', np.csingle),
('jx', np.cdouble),
('kx', np.clongdouble),
('l', 'S4'),
('m', 'U4'),
('n', 'V3'),
('o', '?'),
('p', np.half),
]
x = np.array(
[(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
asbytes('aaaa'), 'bbbb', asbytes(' '), True, 1.0)],
dtype=dt)
y = memoryview(x)
assert_equal(y.shape, (1,))
assert_equal(y.ndim, 1)
assert_equal(y.suboffsets, EMPTY)
sz = sum([np.dtype(b).itemsize for a, b in dt])
if np.dtype('l').itemsize == 4:
assert_equal(y.format, 'T{b:a:=h:b:i:c:l:d:q:dx:B:e:@H:f:=I:g:L:h:Q:hx:f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:@e:p:}')
else:
assert_equal(y.format, 'T{b:a:=h:b:i:c:q:d:q:dx:B:e:@H:f:=I:g:Q:h:Q:hx:f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:@e:p:}')
# Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides
if not (np.ones(1).strides[0] == np.iinfo(np.intp).max):
assert_equal(y.strides, (sz,))
assert_equal(y.itemsize, sz)
def test_export_subarray(self):
x = np.array(([[1, 2], [3, 4]],), dtype=[('a', ('i', (2, 2)))])
y = memoryview(x)
assert_equal(y.format, 'T{(2,2)i:a:}')
assert_equal(y.shape, EMPTY)
assert_equal(y.ndim, 0)
assert_equal(y.strides, EMPTY)
assert_equal(y.suboffsets, EMPTY)
assert_equal(y.itemsize, 16)
def test_export_endian(self):
x = np.array([1, 2, 3], dtype='>i')
y = memoryview(x)
if sys.byteorder == 'little':
assert_equal(y.format, '>i')
else:
assert_equal(y.format, 'i')
x = np.array([1, 2, 3], dtype='<i')
y = memoryview(x)
if sys.byteorder == 'little':
assert_equal(y.format, 'i')
else:
assert_equal(y.format, '<i')
def test_export_flags(self):
# Check SIMPLE flag, see also gh-3613 (exception should be BufferError)
assert_raises(ValueError, get_buffer_info, np.arange(5)[::2], ('SIMPLE',))
def test_padding(self):
for j in range(8):
x = np.array([(1,), (2,)], dtype={'f0': (int, j)})
self._check_roundtrip(x)
def test_reference_leak(self):
count_1 = sys.getrefcount(np.core._internal)
a = np.zeros(4)
b = memoryview(a)
c = np.asarray(b)
count_2 = sys.getrefcount(np.core._internal)
assert_equal(count_1, count_2)
del c # avoid pyflakes unused variable warning.
def test_padded_struct_array(self):
dt1 = np.dtype(
[('a', 'b'), ('b', 'i'), ('sub', np.dtype('b,i')), ('c', 'i')],
align=True)
x1 = np.arange(dt1.itemsize, dtype=np.int8).view(dt1)
self._check_roundtrip(x1)
dt2 = np.dtype(
[('a', 'b'), ('b', 'i'), ('c', 'b', (3,)), ('d', 'i')],
align=True)
x2 = np.arange(dt2.itemsize, dtype=np.int8).view(dt2)
self._check_roundtrip(x2)
dt3 = np.dtype(
[('a', 'b'), ('b', 'i'), ('c', 'b'), ('d', 'b'),
('e', 'b'), ('sub', np.dtype('b,i', align=True))])
x3 = np.arange(dt3.itemsize, dtype=np.int8).view(dt3)
self._check_roundtrip(x3)
def test_relaxed_strides(self):
# Test that relaxed strides are converted to non-relaxed
c = np.ones((1, 10, 10), dtype='i8')
# Check for NPY_RELAXED_STRIDES_CHECKING:
if np.ones((10, 1), order="C").flags.f_contiguous:
c.strides = (-1, 80, 8)
assert_(memoryview(c).strides == (800, 80, 8))
# Writing C-contiguous data to a BytesIO buffer should work
fd = io.BytesIO()
fd.write(c.data)
fortran = c.T
assert_(memoryview(fortran).strides == (8, 80, 800))
arr = np.ones((1, 10))
if arr.flags.f_contiguous:
shape, strides = get_buffer_info(arr, ['F_CONTIGUOUS'])
assert_(strides[0] == 8)
arr = np.ones((10, 1), order='F')
shape, strides = get_buffer_info(arr, ['C_CONTIGUOUS'])
assert_(strides[-1] == 8)
class TestArrayAttributeDeletion(object):
def test_multiarray_writable_attributes_deletion(self):
"""ticket #2046, should not seqfault, raise AttributeError"""
a = np.ones(2)
attr = ['shape', 'strides', 'data', 'dtype', 'real', 'imag', 'flat']
for s in attr:
assert_raises(AttributeError, delattr, a, s)
def test_multiarray_not_writable_attributes_deletion(self):
a = np.ones(2)
attr = ["ndim", "flags", "itemsize", "size", "nbytes", "base",
"ctypes", "T", "__array_interface__", "__array_struct__",
"__array_priority__", "__array_finalize__"]
for s in attr:
assert_raises(AttributeError, delattr, a, s)
def test_multiarray_flags_writable_attribute_deletion(self):
a = np.ones(2).flags
attr = ['updateifcopy', 'aligned', 'writeable']
for s in attr:
assert_raises(AttributeError, delattr, a, s)
def test_multiarray_flags_not_writable_attribute_deletion(self):
a = np.ones(2).flags
attr = ["contiguous", "c_contiguous", "f_contiguous", "fortran",
"owndata", "fnc", "forc", "behaved", "carray", "farray",
"num"]
for s in attr:
assert_raises(AttributeError, delattr, a, s)
def test_array_interface():
# Test scalar coercion within the array interface
class Foo(object):
def __init__(self, value):
self.value = value
self.iface = {'typestr': '=f8'}
def __float__(self):
return float(self.value)
@property
def __array_interface__(self):
return self.iface
f = Foo(0.5)
assert_equal(np.array(f), 0.5)
assert_equal(np.array([f]), [0.5])
assert_equal(np.array([f, f]), [0.5, 0.5])
assert_equal(np.array(f).dtype, np.dtype('=f8'))
# Test various shape definitions
f.iface['shape'] = ()
assert_equal(np.array(f), 0.5)
f.iface['shape'] = None
assert_raises(TypeError, np.array, f)
f.iface['shape'] = (1, 1)
assert_equal(np.array(f), [[0.5]])
f.iface['shape'] = (2,)
assert_raises(ValueError, np.array, f)
# test scalar with no shape
class ArrayLike(object):
array = np.array(1)
__array_interface__ = array.__array_interface__
assert_equal(np.array(ArrayLike()), 1)
def test_array_interface_itemsize():
# See gh-6361
my_dtype = np.dtype({'names': ['A', 'B'], 'formats': ['f4', 'f4'],
'offsets': [0, 8], 'itemsize': 16})
a = np.ones(10, dtype=my_dtype)
descr_t = np.dtype(a.__array_interface__['descr'])
typestr_t = np.dtype(a.__array_interface__['typestr'])
assert_equal(descr_t.itemsize, typestr_t.itemsize)
def test_flat_element_deletion():
it = np.ones(3).flat
try:
del it[1]
del it[1:2]
except TypeError:
pass
except:
raise AssertionError
def test_scalar_element_deletion():
a = np.zeros(2, dtype=[('x', 'int'), ('y', 'int')])
assert_raises(ValueError, a[0].__delitem__, 'x')
class TestMemEventHook(TestCase):
def test_mem_seteventhook(self):
# The actual tests are within the C code in
# multiarray/multiarray_tests.c.src
test_pydatamem_seteventhook_start()
# force an allocation and free of a numpy array
# needs to be larger then limit of small memory cacher in ctors.c
a = np.zeros(1000)
del a
test_pydatamem_seteventhook_end()
class TestMapIter(TestCase):
def test_mapiter(self):
# The actual tests are within the C code in
# multiarray/multiarray_tests.c.src
a = np.arange(12).reshape((3, 4)).astype(float)
index = ([1, 1, 2, 0],
[0, 0, 2, 3])
vals = [50, 50, 30, 16]
test_inplace_increment(a, index, vals)
assert_equal(a, [[0.00, 1., 2.0, 19.],
[104., 5., 6.0, 7.0],
[8.00, 9., 40., 11.]])
b = np.arange(6).astype(float)
index = (np.array([1, 2, 0]),)
vals = [50, 4, 100.1]
test_inplace_increment(b, index, vals)
assert_equal(b, [100.1, 51., 6., 3., 4., 5.])
class TestAsCArray(TestCase):
def test_1darray(self):
array = np.arange(24, dtype=np.double)
from_c = test_as_c_array(array, 3)
assert_equal(array[3], from_c)
def test_2darray(self):
array = np.arange(24, dtype=np.double).reshape(3, 8)
from_c = test_as_c_array(array, 2, 4)
assert_equal(array[2, 4], from_c)
def test_3darray(self):
array = np.arange(24, dtype=np.double).reshape(2, 3, 4)
from_c = test_as_c_array(array, 1, 2, 3)
assert_equal(array[1, 2, 3], from_c)
class TestConversion(TestCase):
def test_array_scalar_relational_operation(self):
# All integer
for dt1 in np.typecodes['AllInteger']:
assert_(1 > np.array(0, dtype=dt1), "type %s failed" % (dt1,))
assert_(not 1 < np.array(0, dtype=dt1), "type %s failed" % (dt1,))
for dt2 in np.typecodes['AllInteger']:
assert_(np.array(1, dtype=dt1) > np.array(0, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
assert_(not np.array(1, dtype=dt1) < np.array(0, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
# Unsigned integers
for dt1 in 'BHILQP':
assert_(-1 < np.array(1, dtype=dt1), "type %s failed" % (dt1,))
assert_(not -1 > np.array(1, dtype=dt1), "type %s failed" % (dt1,))
assert_(-1 != np.array(1, dtype=dt1), "type %s failed" % (dt1,))
# Unsigned vs signed
for dt2 in 'bhilqp':
assert_(np.array(1, dtype=dt1) > np.array(-1, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
assert_(not np.array(1, dtype=dt1) < np.array(-1, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
assert_(np.array(1, dtype=dt1) != np.array(-1, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
# Signed integers and floats
for dt1 in 'bhlqp' + np.typecodes['Float']:
assert_(1 > np.array(-1, dtype=dt1), "type %s failed" % (dt1,))
assert_(not 1 < np.array(-1, dtype=dt1), "type %s failed" % (dt1,))
assert_(-1 == np.array(-1, dtype=dt1), "type %s failed" % (dt1,))
for dt2 in 'bhlqp' + np.typecodes['Float']:
assert_(np.array(1, dtype=dt1) > np.array(-1, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
assert_(not np.array(1, dtype=dt1) < np.array(-1, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
assert_(np.array(-1, dtype=dt1) == np.array(-1, dtype=dt2),
"type %s and %s failed" % (dt1, dt2))
class TestWhere(TestCase):
def test_basic(self):
dts = [np.bool, np.int16, np.int32, np.int64, np.double, np.complex128,
np.longdouble, np.clongdouble]
for dt in dts:
c = np.ones(53, dtype=np.bool)
assert_equal(np.where( c, dt(0), dt(1)), dt(0))
assert_equal(np.where(~c, dt(0), dt(1)), dt(1))
assert_equal(np.where(True, dt(0), dt(1)), dt(0))
assert_equal(np.where(False, dt(0), dt(1)), dt(1))
d = np.ones_like(c).astype(dt)
e = np.zeros_like(d)
r = d.astype(dt)
c[7] = False
r[7] = e[7]
assert_equal(np.where(c, e, e), e)
assert_equal(np.where(c, d, e), r)
assert_equal(np.where(c, d, e[0]), r)
assert_equal(np.where(c, d[0], e), r)
assert_equal(np.where(c[::2], d[::2], e[::2]), r[::2])
assert_equal(np.where(c[1::2], d[1::2], e[1::2]), r[1::2])
assert_equal(np.where(c[::3], d[::3], e[::3]), r[::3])
assert_equal(np.where(c[1::3], d[1::3], e[1::3]), r[1::3])
assert_equal(np.where(c[::-2], d[::-2], e[::-2]), r[::-2])
assert_equal(np.where(c[::-3], d[::-3], e[::-3]), r[::-3])
assert_equal(np.where(c[1::-3], d[1::-3], e[1::-3]), r[1::-3])
def test_exotic(self):
# object
assert_array_equal(np.where(True, None, None), np.array(None))
# zero sized
m = np.array([], dtype=bool).reshape(0, 3)
b = np.array([], dtype=np.float64).reshape(0, 3)
assert_array_equal(np.where(m, 0, b), np.array([]).reshape(0, 3))
# object cast
d = np.array([-1.34, -0.16, -0.54, -0.31, -0.08, -0.95, 0.000, 0.313,
0.547, -0.18, 0.876, 0.236, 1.969, 0.310, 0.699, 1.013,
1.267, 0.229, -1.39, 0.487])
nan = float('NaN')
e = np.array(['5z', '0l', nan, 'Wz', nan, nan, 'Xq', 'cs', nan, nan,
'QN', nan, nan, 'Fd', nan, nan, 'kp', nan, '36', 'i1'],
dtype=object)
m = np.array([0, 0, 1, 0, 1, 1, 0, 0, 1, 1,
0, 1, 1, 0, 1, 1, 0, 1, 0, 0], dtype=bool)
r = e[:]
r[np.where(m)] = d[np.where(m)]
assert_array_equal(np.where(m, d, e), r)
r = e[:]
r[np.where(~m)] = d[np.where(~m)]
assert_array_equal(np.where(m, e, d), r)
assert_array_equal(np.where(m, e, e), e)
# minimal dtype result with NaN scalar (e.g required by pandas)
d = np.array([1., 2.], dtype=np.float32)
e = float('NaN')
assert_equal(np.where(True, d, e).dtype, np.float32)
e = float('Infinity')
assert_equal(np.where(True, d, e).dtype, np.float32)
e = float('-Infinity')
assert_equal(np.where(True, d, e).dtype, np.float32)
# also check upcast
e = float(1e150)
assert_equal(np.where(True, d, e).dtype, np.float64)
def test_ndim(self):
c = [True, False]
a = np.zeros((2, 25))
b = np.ones((2, 25))
r = np.where(np.array(c)[:,np.newaxis], a, b)
assert_array_equal(r[0], a[0])
assert_array_equal(r[1], b[0])
a = a.T
b = b.T
r = np.where(c, a, b)
assert_array_equal(r[:,0], a[:,0])
assert_array_equal(r[:,1], b[:,0])
def test_dtype_mix(self):
c = np.array([False, True, False, False, False, False, True, False,
False, False, True, False])
a = np.uint32(1)
b = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.],
dtype=np.float64)
r = np.array([5., 1., 3., 2., -1., -4., 1., -10., 10., 1., 1., 3.],
dtype=np.float64)
assert_equal(np.where(c, a, b), r)
a = a.astype(np.float32)
b = b.astype(np.int64)
assert_equal(np.where(c, a, b), r)
# non bool mask
c = c.astype(np.int)
c[c != 0] = 34242324
assert_equal(np.where(c, a, b), r)
# invert
tmpmask = c != 0
c[c == 0] = 41247212
c[tmpmask] = 0
assert_equal(np.where(c, b, a), r)
def test_foreign(self):
c = np.array([False, True, False, False, False, False, True, False,
False, False, True, False])
r = np.array([5., 1., 3., 2., -1., -4., 1., -10., 10., 1., 1., 3.],
dtype=np.float64)
a = np.ones(1, dtype='>i4')
b = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.],
dtype=np.float64)
assert_equal(np.where(c, a, b), r)
b = b.astype('>f8')
assert_equal(np.where(c, a, b), r)
a = a.astype('<i4')
assert_equal(np.where(c, a, b), r)
c = c.astype('>i4')
assert_equal(np.where(c, a, b), r)
def test_error(self):
c = [True, True]
a = np.ones((4, 5))
b = np.ones((5, 5))
assert_raises(ValueError, np.where, c, a, a)
assert_raises(ValueError, np.where, c[0], a, b)
def test_string(self):
# gh-4778 check strings are properly filled with nulls
a = np.array("abc")
b = np.array("x" * 753)
assert_equal(np.where(True, a, b), "abc")
assert_equal(np.where(False, b, a), "abc")
# check native datatype sized strings
a = np.array("abcd")
b = np.array("x" * 8)
assert_equal(np.where(True, a, b), "abcd")
assert_equal(np.where(False, b, a), "abcd")
class TestSizeOf(TestCase):
def test_empty_array(self):
x = np.array([])
assert_(sys.getsizeof(x) > 0)
def check_array(self, dtype):
elem_size = dtype(0).itemsize
for length in [10, 50, 100, 500]:
x = np.arange(length, dtype=dtype)
assert_(sys.getsizeof(x) > length * elem_size)
def test_array_int32(self):
self.check_array(np.int32)
def test_array_int64(self):
self.check_array(np.int64)
def test_array_float32(self):
self.check_array(np.float32)
def test_array_float64(self):
self.check_array(np.float64)
def test_view(self):
d = np.ones(100)
assert_(sys.getsizeof(d[...]) < sys.getsizeof(d))
def test_reshape(self):
d = np.ones(100)
assert_(sys.getsizeof(d) < sys.getsizeof(d.reshape(100, 1, 1).copy()))
def test_resize(self):
d = np.ones(100)
old = sys.getsizeof(d)
d.resize(50)
assert_(old > sys.getsizeof(d))
d.resize(150)
assert_(old < sys.getsizeof(d))
def test_error(self):
d = np.ones(100)
assert_raises(TypeError, d.__sizeof__, "a")
class TestHashing(TestCase):
def test_arrays_not_hashable(self):
x = np.ones(3)
assert_raises(TypeError, hash, x)
def test_collections_hashable(self):
x = np.array([])
self.assertFalse(isinstance(x, collections.Hashable))
class TestArrayPriority(TestCase):
# This will go away when __array_priority__ is settled, meanwhile
# it serves to check unintended changes.
op = operator
binary_ops = [
op.pow, op.add, op.sub, op.mul, op.floordiv, op.truediv, op.mod,
op.and_, op.or_, op.xor, op.lshift, op.rshift, op.mod, op.gt,
op.ge, op.lt, op.le, op.ne, op.eq
]
if sys.version_info[0] < 3:
binary_ops.append(op.div)
class Foo(np.ndarray):
__array_priority__ = 100.
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(cls)
class Bar(np.ndarray):
__array_priority__ = 101.
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(cls)
class Other(object):
__array_priority__ = 1000.
def _all(self, other):
return self.__class__()
__add__ = __radd__ = _all
__sub__ = __rsub__ = _all
__mul__ = __rmul__ = _all
__pow__ = __rpow__ = _all
__div__ = __rdiv__ = _all
__mod__ = __rmod__ = _all
__truediv__ = __rtruediv__ = _all
__floordiv__ = __rfloordiv__ = _all
__and__ = __rand__ = _all
__xor__ = __rxor__ = _all
__or__ = __ror__ = _all
__lshift__ = __rlshift__ = _all
__rshift__ = __rrshift__ = _all
__eq__ = _all
__ne__ = _all
__gt__ = _all
__ge__ = _all
__lt__ = _all
__le__ = _all
def test_ndarray_subclass(self):
a = np.array([1, 2])
b = self.Bar([1, 2])
for f in self.binary_ops:
msg = repr(f)
assert_(isinstance(f(a, b), self.Bar), msg)
assert_(isinstance(f(b, a), self.Bar), msg)
def test_ndarray_other(self):
a = np.array([1, 2])
b = self.Other()
for f in self.binary_ops:
msg = repr(f)
assert_(isinstance(f(a, b), self.Other), msg)
assert_(isinstance(f(b, a), self.Other), msg)
def test_subclass_subclass(self):
a = self.Foo([1, 2])
b = self.Bar([1, 2])
for f in self.binary_ops:
msg = repr(f)
assert_(isinstance(f(a, b), self.Bar), msg)
assert_(isinstance(f(b, a), self.Bar), msg)
def test_subclass_other(self):
a = self.Foo([1, 2])
b = self.Other()
for f in self.binary_ops:
msg = repr(f)
assert_(isinstance(f(a, b), self.Other), msg)
assert_(isinstance(f(b, a), self.Other), msg)
class TestBytestringArrayNonzero(TestCase):
def test_empty_bstring_array_is_falsey(self):
self.assertFalse(np.array([''], dtype=np.str))
def test_whitespace_bstring_array_is_falsey(self):
a = np.array(['spam'], dtype=np.str)
a[0] = ' \0\0'
self.assertFalse(a)
def test_all_null_bstring_array_is_falsey(self):
a = np.array(['spam'], dtype=np.str)
a[0] = '\0\0\0\0'
self.assertFalse(a)
def test_null_inside_bstring_array_is_truthy(self):
a = np.array(['spam'], dtype=np.str)
a[0] = ' \0 \0'
self.assertTrue(a)
class TestUnicodeArrayNonzero(TestCase):
def test_empty_ustring_array_is_falsey(self):
self.assertFalse(np.array([''], dtype=np.unicode))
def test_whitespace_ustring_array_is_falsey(self):
a = np.array(['eggs'], dtype=np.unicode)
a[0] = ' \0\0'
self.assertFalse(a)
def test_all_null_ustring_array_is_falsey(self):
a = np.array(['eggs'], dtype=np.unicode)
a[0] = '\0\0\0\0'
self.assertFalse(a)
def test_null_inside_ustring_array_is_truthy(self):
a = np.array(['eggs'], dtype=np.unicode)
a[0] = ' \0 \0'
self.assertTrue(a)
def test_orderconverter_with_nonASCII_unicode_ordering():
# gh-7475
a = np.arange(5)
assert_raises(ValueError, a.flatten, order=u'\xe2')
if __name__ == "__main__":
run_module_suite()
|
import events from '../events';
import { createElement } from '../utils/elements';
const UzPause = {
begin: false,
timeStart: 0,
timeEnd: 5000,
isPlaying: false,
trackingTimer: null,
timeTemp: 0,
setup() {
UzPause.ready.call(this);
},
ready() {
const player = this;
// Listen fragment buffered
const pauseText = createElement('div', { class: this.config.classNames.pauseText });
pauseText.style.display = 'none';
const content = document.createTextNode('Continue playing');
pauseText.appendChild(content);
player.elements.container.appendChild(pauseText);
player.on(events.ENDED, event => {
console.log('ended');
console.log(event);
});
player.on(events.PAUSE, event => {
console.log('pause');
console.log(event);
clearTimeout(UzPause.trackingTimer);
pauseText.style.display = '';
UzPause.timeStart = UzPause.timeStart + (Date.now() - UzPause.timeTemp);
});
player.on(events.PLAY, event => {
pauseText.style.display = 'none';
if (UzPause.begin === false) {
console.log('first started');
UzPause.begin = true;
UzPause.timeStart = 0;
}
UzPause.timeTemp = Date.now();
const leftTime = UzPause.timeEnd - UzPause.timeStart;
console.log('leftTIme', leftTime);
if (leftTime > 0) {
UzPause.trackingTimer = setTimeout(() => {
console.log('tracking time', player.elements.buttons);
player.elements.buttons.play[0].click();
}, leftTime);
}
});
},
tracking() {
console.log('tracking', this);
},
};
export default UzPause;
|
/* eslint-env jest */
test('test', () => {})
|
import React from "react";
import PropTypes from "prop-types";
import { AboutPageTemplate } from "../../templates/about-page";
const AboutPagePreview = ({ entry, widgetFor }) => (
<AboutPageTemplate
title={entry.getIn(["data", "title"])}
content={widgetFor("body")}
/>
);
AboutPagePreview.propTypes = {
entry: PropTypes.shape({
getIn: PropTypes.func,
}),
widgetFor: PropTypes.func,
};
export default AboutPagePreview;
|
/*jshint maxlen:10000000 */
export default {"faq.html": "\u003Cul class=\"nav-pills\"\u003E\n \u003Cli\u003E\u003Ca class=\"active\" href=\"/faq\"\u003EFAQ\u003C/a\u003E\u003C/li\u003E\n \u003Cli\u003E\u003Ca href=\"/tos\"\u003ETerms of Service\u003C/a\u003E\u003C/li\u003E\n \u003Cli\u003E\u003Ca href=\"/privacy\"\u003EPrivacy\u003C/a\u003E\u003C/li\u003E\n\u003C/ul\u003E\n\n\n\n\u003Cdiv id=\"civilized\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#civilized\"\u003EThis is a Civilized Place for Public Discussion\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n Please treat this discussion forum with the same respect you would a public park. We, too, are a shared community resource \u0026mdash; a place to share skills, knowledge and interests through ongoing conversation.\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n \u003Cp\u003E\n These are not hard and fast rules, merely aids to the human judgment of our community. Use these guidelines to keep this a clean, well-lighted place for civilized public discourse.\n \u003C/p\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"improve\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#improve\"\u003EImprove the Discussion\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n Help us make this a great place for discussion by always working to improve the discussion in some way, however small. If you are not sure your post adds to the discussion or might detract from its usefulness, think over what you want to say and try again later.\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n \u003Cp\u003E\n The topics discussed here matter to us, and we want you to act as if they matter to you, too. Be respectful of the topics and the people discussing them, even if you disagree with some of what is being said.\n \u003C/p\u003E\n \u003Cp\u003E\n One way to improve the discussion is by discovering ones that are already happening. Please spend some time browsing the topics here before replying or starting your own, and you’ll have a better chance of meeting others who share your interests.\n \u003C/p\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"agreeable\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#agreeable\"\u003EBe Agreeable, Even When You Disagree\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n You may wish to respond to something by disagreeing with it. That’s fine. But, remember to \u003Cem\u003Ecriticize ideas, not people\u003C/em\u003E.\n Please avoid:\n \u003Cul\u003E\n \u003Cli\u003EName-calling.\u003C/li\u003E\n \u003Cli\u003EAd hominem attacks.\u003C/li\u003E\n \u003Cli\u003EResponding to a post’s tone instead of its actual content.\u003C/li\u003E\n \u003Cli\u003EKnee-jerk contradiction.\u003C/li\u003E\n \u003C/ul\u003E\n\u003Cdiv class=\"more\"\u003E\n \u003Cp\u003E\n Instead, provide reasoned counter-arguments that improve the conversation.\n \u003C/p\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"participate\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#participate\"\u003EYour Participation Counts\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n The conversations we have here set the tone for everyone. Help us influence the future of this community by choosing to engage in discussions that make this forum an interesting place to be \u0026mdash; and avoiding those that do not.\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n \u003Cp\u003E\n Discourse provides tools that enable the community to collectively identify the best (and worst) contributions: favorites, bookmarks, likes, flags, replies, edits, and so forth. Use these tools to improve your own experience, and everyone else’s, too.\n \u003C/p\u003E\n \u003Cp\u003E\n Let’s try to leave our park better than we found it.\n \u003C/p\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"flag-problems\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#flag-problems\"\u003EIf You See a Problem, Flag It\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n Moderators have special authority; they are responsible for this forum. But so are you. With your help, moderators can be community facilitators, not just janitors or police.\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n \u003Cp\u003E\n When you see bad behavior, don’t reply. It encourages the bad behavior by acknowledging it, consumes your energy, and wastes everyone’s time. \u003Ci\u003EJust flag it\u003C/i\u003E. If enough flags accrue, action will be taken, either automatically or by moderator intervention.\n \u003C/p\u003E\n \u003Cp\u003E\n In order to maintain our community, moderators reserve the right to remove any content and any user account for any reason at any time. Moderators do not preview new posts in any way; the moderators and site operators take no responsibility for any content posted by the community.\n \u003C/p\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"be-civil\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#be-civil\"\u003EAlways Be Civil\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n Nothing sabotages a healthy conversation like rudeness:\n \u003Cul\u003E\n \u003Cli\u003EBe civil. Don’t post anything that a reasonable person would consider offensive, abusive, or hate speech.\u003C/li\u003E\n \u003Cli\u003EKeep it clean. Don’t post anything obscene or sexually explicit.\u003C/li\u003E\n \u003Cli\u003ERespect each other. Don’t harass or grief anyone,\n impersonate people, or expose their private information.\u003C/li\u003E\n \u003Cli\u003ERespect our forum. Don’t post spam or otherwise vandalize the forum.\u003C/li\u003E\n \u003C/ul\u003E\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n \u003Cp\u003E\n These are not concrete terms with precise definitions \u0026mdash; avoid\n even the \u003Ci\u003Eappearance\u003C/i\u003E of any of these things. If you’re unsure, ask yourself how you would feel if your post was featured on the front page of the New York Times.\n \u003C/p\u003E\n \u003Cp\u003E\n This is a public forum, and search engines index these discussions. Keep the language, links, and images safe for family and friends.\n \u003C/p\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"keep-tidy\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#keep-tidy\"\u003EKeep It Tidy\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n Make the effort to put things in the right place, so that we can spend more time discussing and less cleaning up. So:\n \u003Cul\u003E\n \u003Cli\u003EDon’t start a topic in the wrong category.\u003C/li\u003E\n \u003Cli\u003EDon’t cross-post the same thing in multiple topics.\u003C/li\u003E\n \u003Cli\u003EDon’t post no-content replies.\u003C/li\u003E\n \u003Cli\u003EDon’t divert a topic by changing it midstream.\u003C/li\u003E\n \u003Cli\u003EDon’t sign your posts \u0026mdash; every post has your profile information attached to it.\u003C/li\u003E\n \u003C/ul\u003E\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n \u003Cp\u003E\n Rather than posting “+1” or “Agreed”, use the Like button. Rather than taking an existing topic in a radically different direction, use Reply as a New Topic.\n \u003C/p\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"stealing\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#stealing\"\u003EPost Only Your Own Stuff\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n You may not post anything digital that belongs to someone else without permission. You may not post descriptions of, links to, or methods for stealing someone’s intellectual property (software, video, audio, images), or for breaking any other law.\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"tos\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#tos\"\u003ETerms of Service\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n Yes, legalese is boring, but we must protect ourselves \u0026ndash; and by extension, you and your data \u0026ndash; against unfriendly folks. We have a \u003Ca href=\"/tos\"\u003ETerms of Service\u003C/a\u003E describing your (and our) behavior and rights related to content, privacy, and laws. To use this service, you must agree to abide by our \u003Ca href=\"/tos\"\u003ETOS\u003C/a\u003E.\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n\u003C/div\u003E\n\n",
"tos.html": "\u003Cul class=\"nav-pills\"\u003E\n \u003Cli\u003E\u003Ca href=\"/faq\"\u003EFAQ\u003C/a\u003E\u003C/li\u003E\n \u003Cli\u003E\u003Ca class=\"active\" href=\"/tos\"\u003ETerms of Service\u003C/a\u003E\u003C/li\u003E\n \u003Cli\u003E\u003Ca href=\"/privacy\"\u003EPrivacy\u003C/a\u003E\u003C/li\u003E\n\u003C/ul\u003E\n\n\u003Cp\u003E\n The following terms and conditions govern all use of the discourse.org website and all content, services and products available at or through the website, including, but not limited to, discourse.org Forum Software, discourse.org Support Forums and the discourse.org Hosting service (“Hosting”), (taken together, the Website). The Website is owned and operated by Civilized Discourse Construction Kit, Inc. (“CDCK”). The Website is offered subject to your acceptance without modification of all of the terms and conditions contained herein and all other operating rules, policies (including, without limitation, discourse.org’s \u003Ca href=\"/privacy\"\u003EPrivacy Policy\u003C/a\u003E and \u003Ca href=\"/faq\"\u003ECommunity Guidelines\u003C/a\u003E) and procedures that may be published from time to time on this Site by CDCK (collectively, the “Agreement”).\n\u003C/p\u003E\n\n\u003Cp\u003E\n Please read this Agreement carefully before accessing or using the Website. By accessing or using any part of the web site, you agree to become bound by the terms and conditions of this agreement. If you do not agree to all the terms and conditions of this agreement, then you may not access the Website or use any services. If these terms and conditions are considered an offer by CDCK, acceptance is expressly limited to these terms. The Website is available only to individuals who are at least 13 years old.\n\u003C/p\u003E\n\n\u003Cdiv id=\"1\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#1\"\u003E1. Your discourse.org Account\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n If you create an account on the Website, you are responsible for maintaining the security of your account and you are fully responsible for all activities that occur under the account. You must immediately notify CDCK of any unauthorized uses of your account or any other breaches of security. CDCK will not be liable for any acts or omissions by you, including any damages of any kind incurred as a result of such acts or omissions.\n\u003C/p\u003E\n\n\u003Cdiv id=\"2\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#2\"\u003E2. Responsibility of Contributors\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003EIf you post material to the Website, post links on the Website, or otherwise make (or allow any third party to make) material available by means of the Website (any such material, “Content”), You are entirely responsible for the content of, and any harm resulting from, that Content. That is the case regardless of whether the Content in question constitutes text, graphics, an audio file, or computer software. By making Content available, you represent and warrant that:\n\u003C/p\u003E\n\u003Cul\u003E\n \u003Cli\u003Ethe downloading, copying and use of the Content will not infringe the proprietary rights, including but not limited to the copyright, patent, trademark or trade secret rights, of any third party;\u003C/li\u003E\n \u003Cli\u003Eif your employer has rights to intellectual property you create, you have either (i) received permission from your employer to post or make available the Content, including but not limited to any software, or (ii) secured from your employer a waiver as to all rights in or to the Content;\u003C/li\u003E\n \u003Cli\u003Eyou have fully complied with any third-party licenses relating to the Content, and have done all things necessary to successfully pass through to end users any required terms;\u003C/li\u003E\n \u003Cli\u003Ethe Content does not contain or install any viruses, worms, malware, Trojan horses or other harmful or destructive content;\u003C/li\u003E\n \u003Cli\u003Ethe Content is not spam, is not machine- or randomly-generated, and does not contain unethical or unwanted commercial content designed to drive traffic to third party sites or boost the search engine rankings of third party sites, or to further unlawful acts (such as phishing) or mislead recipients as to the source of the material (such as spoofing);\u003C/li\u003E\n \u003Cli\u003Ethe Content is not pornographic, does not contain threats or incite violence, and does not violate the privacy or publicity rights of any third party;\u003C/li\u003E\n \u003Cli\u003Eyour content is not getting advertised via unwanted electronic messages such as spam links on newsgroups, email lists, blogs and web sites, and similar unsolicited promotional methods;\u003C/li\u003E\n \u003Cli\u003Eyour content is not named in a manner that misleads your readers into thinking that you are another person or company; and\u003C/li\u003E\n \u003Cli\u003Eyou have, in the case of Content that includes computer code, accurately categorized and/or described the type, nature, uses and effects of the materials, whether requested to do so by CDCK or otherwise.\u003C/li\u003E\n\u003C/ul\u003E\n\n\u003Cdiv id=\"3\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#3\"\u003E3. User Content License\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003EUser contributions are licensed under a \u003Ca href=\"http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_US\" rel=\"nofollow\"\u003ECreative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License\u003C/a\u003E. Without limiting any of those representations or warranties, CDCK has the right (though not the obligation) to, in CDCK’s sole discretion (i) refuse or remove any content that, in CDCK’s reasonable opinion, violates any CDCK policy or is in any way harmful or objectionable, or (ii) terminate or deny access to and use of the Website to any individual or entity for any reason, in CDCK’s sole discretion. CDCK will have no obligation to provide a refund of any amounts previously paid.\u003C/p\u003E\n\n\u003Cdiv id=\"4\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#4\"\u003E4. Payment and Renewal\u003C/a\u003E\u003C/h2\u003E\n\u003Ch3\u003EGeneral Terms\u003C/h3\u003E\n\u003Cp\u003E\n Optional paid services or upgrades may be available on the Website. When utilizing an optional paid service or upgrade, you agree to pay CDCK the monthly or annual subscription fees indicated. Payments will be charged on a pre-pay basis on the day you begin utilizing the service or upgrade and will cover the use of that service or upgrade for a monthly or annual subscription period as indicated. These fees are not refundable.\n\u003C/p\u003E\n\u003Ch3\u003EAutomatic Renewal\u003C/h3\u003E\n\u003Cp\u003EUnless you notify CDCK before the end of the applicable subscription period that you want to cancel a service or upgrade, your subscription will automatically renew and you authorize us to collect the then-applicable annual or monthly subscription fee (as well as any taxes) using any credit card or other payment mechanism we have on record for you. Subscriptions can be canceled at any time.\n\u003C/p\u003E\n\n\u003Cdiv id=\"5\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#5\"\u003E5. Services\u003C/a\u003E\u003C/h2\u003E\n\u003Ch3\u003EHosting, Support Services\u003C/h3\u003E\n\u003Cp\u003EOptional Hosting and Support services may be provided by CDCK under the terms and conditions for each such service. By signing up for a Hosting/Support or Support services account, you agree to abide by such terms and conditions.\n\u003C/p\u003E\n\n\u003Cdiv id=\"6\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#6\"\u003E6. Responsibility of Website Visitors\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n CDCK has not reviewed, and cannot review, all of the material, including computer software, posted to the Website, and cannot therefore be responsible for that material’s content, use or effects. By operating the Website, CDCK does not represent or imply that it endorses the material there posted, or that it believes such material to be accurate, useful or non-harmful. You are responsible for taking precautions as necessary to protect yourself and your computer systems from viruses, worms, Trojan horses, and other harmful or destructive content. The Website may contain content that is offensive, indecent, or otherwise objectionable, as well as content containing technical inaccuracies, typographical mistakes, and other errors. The Website may also contain material that violates the privacy or publicity rights, or infringes the intellectual property and other proprietary rights, of third parties, or the downloading, copying or use of which is subject to additional terms and conditions, stated or unstated. CDCK disclaims any responsibility for any harm resulting from the use by visitors of the Website, or from any downloading by those visitors of content there posted.\n\u003C/p\u003E\n\n\u003Cdiv id=\"7\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#7\"\u003E7. Content Posted on Other Websites\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003EWe have not reviewed, and cannot review, all of the material, including computer software, made available through the websites and webpages to which discourse.org links, and that link to discourse.org. CDCK does not have any control over those non-discourse.org websites and webpages, and is not responsible for their contents or their use. By linking to a non-discourse.org website or webpage, CDCK does not represent or imply that it endorses such website or webpage. You are responsible for taking precautions as necessary to protect yourself and your computer systems from viruses, worms, Trojan horses, and other harmful or destructive content. CDCK disclaims any responsibility for any harm resulting from your use of non-discourse.org websites and webpages.\n\u003C/p\u003E\n\n\u003Cdiv id=\"8\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#8\"\u003E8. Copyright Infringement and DMCA Policy\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n As CDCK asks others to respect its intellectual property rights, it respects the intellectual property rights of others. If you believe that material located on or linked to by discourse.org violates your copyright, and if this website resides in the USA, you are encouraged to notify CDCK in accordance with CDCK’s \u003Ca href=\"http://en.wikipedia.org/wiki/Digital_Millennium_Copyright_Act\"\u003EDigital Millennium Copyright Act\u003C/a\u003E (“DMCA”) Policy. CDCK will respond to all such notices, including as required or appropriate by removing the infringing material or disabling all links to the infringing material. CDCK will terminate a visitor’s access to and use of the Website if, under appropriate circumstances, the visitor is determined to be a repeat infringer of the copyrights or other intellectual property rights of CDCK or others. In the case of such termination, CDCK will have no obligation to provide a refund of any amounts previously paid to CDCK.\n\u003C/p\u003E\n\n\u003Cdiv id=\"9\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#9\"\u003E9. Intellectual Property\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n This Agreement does not transfer from CDCK to you any CDCK or third party intellectual property, and all right, title and interest in and to such property will remain (as between the parties) solely with CDCK. CDCK, discourse.org, the discourse.org logo, and all other trademarks, service marks, graphics and logos used in connection with discourse.org, or the Website are trademarks or registered trademarks of CDCK or CDCK’s licensors. Other trademarks, service marks, graphics and logos used in connection with the Website may be the trademarks of other third parties. Your use of the Website grants you no right or license to reproduce or otherwise use any CDCK or third-party trademarks.\n\u003C/p\u003E\n\n\u003Cdiv id=\"10\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#10\"\u003E10. Advertisements\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003ECDCK reserves the right to display advertisements on your content unless you have purchased an Ad-free Upgrade or a Services account.\u003C/p\u003E\n\n\u003Cdiv id=\"11\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#11\"\u003E11. Attribution\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003ECDCK reserves the right to display attribution links such as ‘Powered by discourse.org,’ theme author, and font attribution in your content footer or toolbar. Footer credits and the discourse.org toolbar may not be removed regardless of upgrades purchased.\u003C/p\u003E\n\n\u003Cdiv id=\"12\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#12\"\u003E12. Changes\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\nCDCK reserves the right, at its sole discretion, to modify or replace any part of this Agreement. It is your responsibility to check this Agreement periodically for changes. Your continued use of or access to the Website following the posting of any changes to this Agreement constitutes acceptance of those changes. CDCK may also, in the future, offer new services and/or features through the Website (including, the release of new tools and resources). Such new features and/or services shall be subject to the terms and conditions of this Agreement.\n\u003C/p\u003E\n\n\u003Cdiv id=\"13\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#13\"\u003E13. Termination\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\nCDCK may terminate your access to all or any part of the Website at any time, with or without cause, with or without notice, effective immediately. If you wish to terminate this Agreement or your discourse.org account (if you have one), you may simply discontinue using the Website. All provisions of this Agreement which by their nature should survive termination shall survive termination, including, without limitation, ownership provisions, warranty disclaimers, indemnity and limitations of liability.\n\u003C/p\u003E\n\n\u003Cdiv id=\"14\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#14\"\u003E14. Disclaimer of Warranties\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\nThe Website is provided “as is”. CDCK and its suppliers and licensors hereby disclaim all warranties of any kind, express or implied, including, without limitation, the warranties of merchantability, fitness for a particular purpose and non-infringement. Neither CDCK nor its suppliers and licensors, makes any warranty that the Website will be error free or that cess thereto will be continuous or uninterrupted. If you’re actually reading this, here’s \u003Ca href=\"http://www.newyorker.com/online/blogs/shouts/2012/12/the-hundred-best-lists-of-all-time.html\"\u003Ea treat\u003C/a\u003E. You understand that you download from, or otherwise obtain content or services through, the Website at your own discretion and risk.\n\u003C/p\u003E\n\n\u003Cdiv id=\"15\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#15\"\u003E15. Limitation of Liability\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\nIn no event will CDCK, or its suppliers or licensors, be liable with respect to any subject matter of this agreement under any contract, negligence, strict liability or other legal or equitable theory for: (i) any special, incidental or consequential damages; (ii) the cost of procurement for substitute products or services; (iii) for interruption of use or loss or corruption of data; or (iv) for any amounts that exceed the fees paid by you to CDCK under this agreement during the twelve (12) month period prior to the cause of action. CDCK shall have no liability for any failure or delay due to matters beyond their reasonable control. The foregoing shall not apply to the extent prohibited by applicable law.\n\u003C/p\u003E\n\n\u003Cdiv id=\"16\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#16\"\u003E16. General Representation and Warranty\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\nYou represent and warrant that (i) your use of the Website will be in strict accordance with the CDCK \u003Ca href=\"/privacy\"\u003EPrivacy Policy\u003C/a\u003E, \u003Ca href=\"/faq\"\u003ECommunity Guidelines\u003C/a\u003E, with this Agreement and with all applicable laws and regulations (including without limitation any local laws or regulations in your country, state, city, or other governmental area, regarding online conduct and acceptable content, and including all applicable laws regarding the transmission of technical data exported from the country in which this website resides or the country in which you reside) and (ii) your use of the Website will not infringe or misappropriate the intellectual property rights of any third party.\n\u003C/p\u003E\n\n\u003Cdiv id=\"17\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#17\"\u003E17. Indemnification\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\nYou agree to indemnify and hold harmless CDCK, its contractors, and its licensors, and their respective directors, officers, employees and agents from and against any and all claims and expenses, including attorneys’ fees, arising out of your use of the Website, including but not limited to your violation of this Agreement.\n\u003C/p\u003E\n\n\u003Cdiv id=\"18\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#18\"\u003E18. Miscellaneous\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003EThis Agreement constitutes the entire agreement between CDCK and you concerning the subject matter hereof, and they may only be modified by a written amendment signed by an authorized executive of CDCK, or by the posting by CDCK of a revised version. Except to the extent applicable law, if any, provides otherwise, this Agreement, any access to or use of the Website will be governed by the laws of the state of California, U.S.A., excluding its conflict of law provisions, and the proper venue for any disputes arising out of or relating to any of the same will be the state and federal courts located in San Francisco County, California. Except for claims for injunctive or equitable relief or claims regarding intellectual property rights (which may be brought in any competent court without the posting of a bond), any dispute arising under this Agreement shall be finally settled in accordance with the Comprehensive Arbitration Rules of the Judicial Arbitration and Mediation Service, Inc. (“JAMS”) by three arbitrators appointed in accordance with such Rules. The arbitration shall take place in San Francisco, California, in the English language and the arbitral decision may be enforced in any court. The prevailing party in any action or proceeding to enforce this Agreement shall be entitled to costs and attorneys’ fees. If any part of this Agreement is held invalid or unenforceable, that part will be construed to reflect the parties’ original intent, and the remaining portions will remain in full force and effect. A waiver by either party of any term or condition of this Agreement or any breach thereof, in any one instance, will not waive such term or condition or any subsequent breach thereof. You may assign your rights under this Agreement to any party that consents to, and agrees to be bound by, its terms and conditions; CDCK may assign its rights under this Agreement without condition. This Agreement will be binding upon and will inure to the benefit of the parties, their successors and permitted assigns.\u003C/p\u003E\n\n\u003Cp\u003E\n This document is CC-BY-SA. It was last updated May 31, 2013.\u003Cbr/\u003E\n Originally adapted from the \u003Ca href=\"http://en.wordpress.com/tos/\"\u003EWordPress Terms of Service\u003C/a\u003E.\n\u003C/p\u003E\n",
"privacy.html": "\u003Cul class=\"nav-pills\"\u003E\n \u003Cli\u003E\u003Ca href=\"/faq\"\u003EFAQ\u003C/a\u003E\u003C/li\u003E\n \u003Cli\u003E\u003Ca href=\"/tos\"\u003ETerms of Service\u003C/a\u003E\u003C/li\u003E\n \u003Cli\u003E\u003Ca class=\"active\" href=\"/privacy\"\u003EPrivacy\u003C/a\u003E\u003C/li\u003E\n\u003C/ul\u003E\n\n\n\n\u003Cdiv id=\"collect\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#collect\"\u003EWhat information do we collect?\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\nWe collect information from you when you register on our site and gather data when you participate in the forum by reading, writing, and evaluating the content shared here.\n\u003C/p\u003E\n\n\u003Cp\u003E\n When registering on our site, you may be asked to enter your name and e-mail address. You may, however, visit our site without registering. Your e-mail address will be verified by an email containing a unique link. If that link is visited, we know that you control the e-mail address.\n\u003C/p\u003E\n\n\u003Cp\u003E\n When registered and posting, we record the IP address that the post originated from. We also may retain server logs which include the IP address of every request to our server.\n\u003C/p\u003E\n\n\u003Cdiv id=\"use\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#use\"\u003EWhat do we use your information for?\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003EAny of the information we collect from you may be used in one of the following ways:\u003C/p\u003E\n\u003Cul\u003E\n \u003Cli\u003ETo personalize your experience \u0026mdash; your information helps us to better respond to your individual needs.\u003C/li\u003E\n \u003Cli\u003ETo improve our site \u0026mdash; we continually strive to improve our site offerings based on the information and feedback we receive from you.\u003C/li\u003E\n \u003Cli\u003ETo improve customer service \u0026mdash; your information helps us to more effectively respond to your customer service requests and support needs.\u003C/li\u003E\n \u003Cli\u003ETo send periodic emails \u0026mdash; The email address you provide may be used to send you information, notifications that you request about changes to topics or in response to your user name, respond to inquiries, and/or other requests or questions.\u003C/li\u003E\n\u003C/ul\u003E\n\n\u003Cdiv id=\"protect\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#use\"\u003EHow do we protect your information?\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n We implement a variety of security measures to maintain the safety of your personal information when you enter, submit, or access your personal information.\n\u003C/p\u003E\n\n\u003Cdiv id=\"data-retention\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#data-retention\"\u003EWhat is your data retention policy?\u003C/a\u003E\u003C/h2\u003E\n\n\u003Cp\u003E\n We will make a good faith effort to:\n\u003C/p\u003E\n\u003Cul\u003E\n \u003Cli\u003ERetain server logs containing the IP address of all requests to this server no more than 90 days.\u003C/li\u003E\n \u003Cli\u003ERetain the IP addresses associated with registered users and their posts no more than 5 years.\u003C/li\u003E\n\u003C/ul\u003E\n\u003C/p\u003E\n\n\n\u003Cdiv id=\"cookies\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#cookies\"\u003EDo we use cookies?\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n Yes. Cookies are small files that a site or its service provider transfers to your computer's hard drive through your Web browser (if you allow). These cookies enable the site to recognize your browser and, if you have a registered account, associate it with your registered account.\n\u003C/p\u003E\n\n\u003Cp\u003E\n We use cookies to understand and save your preferences for future visits and compile aggregate data about site traffic and site interaction so that we can offer better site experiences and tools in the future. We may contract with third-party service providers to assist us in better understanding our site visitors. These service providers are not permitted to use the information collected on our behalf except to help us conduct and improve our business.\n\u003C/p\u003E\n\n\u003Cdiv id=\"disclose\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#disclose\"\u003EDo we disclose any information to outside parties?\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\nWe do not sell, trade, or otherwise transfer to outside parties your personally identifiable information. This does not include trusted third parties who assist us in operating our site, conducting our business, or servicing you, so long as those parties agree to keep this information confidential. We may also release your information when we believe release is appropriate to comply with the law, enforce our site policies, or protect ours or others rights, property, or safety. However, non-personally identifiable visitor information may be provided to other parties for marketing, advertising, or other uses.\n\u003C/p\u003E\n\n\u003Cdiv id=\"third-party\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#third-party\"\u003EThird party links\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n Occasionally, at our discretion, we may include or offer third party products or services on our site. These third party sites have separate and independent privacy policies. We therefore have no responsibility or liability for the content and activities of these linked sites. Nonetheless, we seek to protect the integrity of our site and welcome any feedback about these sites.\n\u003C/p\u003E\n\n\u003Cdiv id=\"coppa\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#coppa\"\u003EChildren's Online Privacy Protection Act Compliance\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\nOur site, products and services are all directed to people who are at least 13 years old or older. If this server is in the USA, and you are under the age of 13, per the requirements of COPPA (\u003Ca href=\"http://en.wikipedia.org/wiki/Children's_Online_Privacy_Protection_Act\"\u003EChildren's Online Privacy Protection Act\u003C/a\u003E), do not use this site.\n\u003C/p\u003E\n\n\u003Cdiv id=\"online\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#online\"\u003EOnline Privacy Policy Only\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\nThis online privacy policy applies only to information collected through our site and not to information collected offline.\n\u003C/p\u003E\n\n\u003Cdiv id=\"consent\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#consent\"\u003EYour Consent\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\nBy using our site, you consent to our web site privacy policy.\n\u003C/p\u003E\n\n\u003Cdiv id=\"changes\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#changes\"\u003EChanges to our Privacy Policy\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\nIf we decide to change our privacy policy, we will post those changes on this page.\n\u003C/p\u003E\n\n\u003Cp\u003E\n This document is CC-BY-SA. It was last updated May 31, 2013.\n\u003C/p\u003E\n\n",
"guidelines.html": "\u003Cul class=\"nav-pills\"\u003E\n \u003Cli\u003E\u003Ca class=\"active\" href=\"/faq\"\u003EFAQ\u003C/a\u003E\u003C/li\u003E\n \u003Cli\u003E\u003Ca href=\"/tos\"\u003ETerms of Service\u003C/a\u003E\u003C/li\u003E\n \u003Cli\u003E\u003Ca href=\"/privacy\"\u003EPrivacy\u003C/a\u003E\u003C/li\u003E\n\u003C/ul\u003E\n\n\n\n\u003Cdiv id=\"civilized\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#civilized\"\u003EThis is a Civilized Place for Public Discussion\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n Please treat this discussion forum with the same respect you would a public park. We, too, are a shared community resource \u0026mdash; a place to share skills, knowledge and interests through ongoing conversation.\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n \u003Cp\u003E\n These are not hard and fast rules, merely aids to the human judgment of our community. Use these guidelines to keep this a clean, well-lighted place for civilized public discourse.\n \u003C/p\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"improve\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#improve\"\u003EImprove the Discussion\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n Help us make this a great place for discussion by always working to improve the discussion in some way, however small. If you are not sure your post adds to the discussion or might detract from its usefulness, think over what you want to say and try again later.\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n \u003Cp\u003E\n The topics discussed here matter to us, and we want you to act as if they matter to you, too. Be respectful of the topics and the people discussing them, even if you disagree with some of what is being said.\n \u003C/p\u003E\n \u003Cp\u003E\n One way to improve the discussion is by discovering ones that are already happening. Please spend some time browsing the topics here before replying or starting your own, and you’ll have a better chance of meeting others who share your interests.\n \u003C/p\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"agreeable\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#agreeable\"\u003EBe Agreeable, Even When You Disagree\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n You may wish to respond to something by disagreeing with it. That’s fine. But, remember to \u003Cem\u003Ecriticize ideas, not people\u003C/em\u003E.\n Please avoid:\n \u003Cul\u003E\n \u003Cli\u003EName-calling.\u003C/li\u003E\n \u003Cli\u003EAd hominem attacks.\u003C/li\u003E\n \u003Cli\u003EResponding to a post’s tone instead of its actual content.\u003C/li\u003E\n \u003Cli\u003EKnee-jerk contradiction.\u003C/li\u003E\n \u003C/ul\u003E\n\u003Cdiv class=\"more\"\u003E\n \u003Cp\u003E\n Instead, provide reasoned counter-arguments that improve the conversation.\n \u003C/p\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"participate\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#participate\"\u003EYour Participation Counts\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n The conversations we have here set the tone for everyone. Help us influence the future of this community by choosing to engage in discussions that make this forum an interesting place to be \u0026mdash; and avoiding those that do not.\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n \u003Cp\u003E\n Discourse provides tools that enable the community to collectively identify the best (and worst) contributions: favorites, bookmarks, likes, flags, replies, edits, and so forth. Use these tools to improve your own experience, and everyone else’s, too.\n \u003C/p\u003E\n \u003Cp\u003E\n Let’s try to leave our park better than we found it.\n \u003C/p\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"flag-problems\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#flag-problems\"\u003EIf You See a Problem, Flag It\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n Moderators have special authority; they are responsible for this forum. But so are you. With your help, moderators can be community facilitators, not just janitors or police.\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n \u003Cp\u003E\n When you see bad behavior, don’t reply. It encourages the bad behavior by acknowledging it, consumes your energy, and wastes everyone’s time. \u003Ci\u003EJust flag it\u003C/i\u003E. If enough flags accrue, action will be taken, either automatically or by moderator intervention.\n \u003C/p\u003E\n \u003Cp\u003E\n In order to maintain our community, moderators reserve the right to remove any content and any user account for any reason at any time. Moderators do not preview new posts in any way; the moderators and site operators take no responsibility for any content posted by the community.\n \u003C/p\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"be-civil\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#be-civil\"\u003EAlways Be Civil\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n Nothing sabotages a healthy conversation like rudeness:\n \u003Cul\u003E\n \u003Cli\u003EBe civil. Don’t post anything that a reasonable person would consider offensive, abusive, or hate speech.\u003C/li\u003E\n \u003Cli\u003EKeep it clean. Don’t post anything obscene or sexually explicit.\u003C/li\u003E\n \u003Cli\u003ERespect each other. Don’t harass or grief anyone,\n impersonate people, or expose their private information.\u003C/li\u003E\n \u003Cli\u003ERespect our forum. Don’t post spam or otherwise vandalize the forum.\u003C/li\u003E\n \u003C/ul\u003E\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n \u003Cp\u003E\n These are not concrete terms with precise definitions \u0026mdash; avoid\n even the \u003Ci\u003Eappearance\u003C/i\u003E of any of these things. If you’re unsure, ask yourself how you would feel if your post was featured on the front page of the New York Times.\n \u003C/p\u003E\n \u003Cp\u003E\n This is a public forum, and search engines index these discussions. Keep the language, links, and images safe for family and friends.\n \u003C/p\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"keep-tidy\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#keep-tidy\"\u003EKeep It Tidy\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n Make the effort to put things in the right place, so that we can spend more time discussing and less cleaning up. So:\n \u003Cul\u003E\n \u003Cli\u003EDon’t start a topic in the wrong category.\u003C/li\u003E\n \u003Cli\u003EDon’t cross-post the same thing in multiple topics.\u003C/li\u003E\n \u003Cli\u003EDon’t post no-content replies.\u003C/li\u003E\n \u003Cli\u003EDon’t divert a topic by changing it midstream.\u003C/li\u003E\n \u003Cli\u003EDon’t sign your posts \u0026mdash; every post has your profile information attached to it.\u003C/li\u003E\n \u003C/ul\u003E\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n \u003Cp\u003E\n Rather than posting “+1” or “Agreed”, use the Like button. Rather than taking an existing topic in a radically different direction, use Reply as a New Topic.\n \u003C/p\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"stealing\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#stealing\"\u003EPost Only Your Own Stuff\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n You may not post anything digital that belongs to someone else without permission. You may not post descriptions of, links to, or methods for stealing someone’s intellectual property (software, video, audio, images), or for breaking any other law.\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n\u003C/div\u003E\n\n\u003Cdiv id=\"tos\"\u003E\u003C/div\u003E\n\u003Ch2\u003E\u003Ca href=\"#tos\"\u003ETerms of Service\u003C/a\u003E\u003C/h2\u003E\n\u003Cp\u003E\n Yes, legalese is boring, but we must protect ourselves \u0026ndash; and by extension, you and your data \u0026ndash; against unfriendly folks. We have a \u003Ca href=\"/tos\"\u003ETerms of Service\u003C/a\u003E describing your (and our) behavior and rights related to content, privacy, and laws. To use this service, you must agree to abide by our \u003Ca href=\"/tos\"\u003ETOS\u003C/a\u003E.\n\u003C/p\u003E\n\u003Cdiv class=\"more\"\u003E\n\u003C/div\u003E\n\n"}
|
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
export class ListBoxItem extends Component {
static defaultProps = {
option: null,
label: null,
selected: false,
onClick: null,
onTouchEnd: null,
template: null
}
static propTypes = {
option: PropTypes.any,
label: PropTypes.string,
selected: PropTypes.bool,
onClick: PropTypes.func,
onTouchEnd: PropTypes.func,
template: PropTypes.func
}
constructor() {
super();
this.onClick = this.onClick.bind(this);
this.onTouchEnd = this.onTouchEnd.bind(this);
}
onClick(event) {
if(this.props.onClick) {
this.props.onClick({
originalEvent: event,
option: this.props.option
});
}
event.preventDefault();
}
onTouchEnd(event) {
if(this.props.onTouchEnd) {
this.props.onTouchEnd({
originalEvent: event,
option: this.props.option
});
}
}
render() {
let className = classNames('p-listbox-item', {'p-highlight': this.props.selected});
let content = this.props.template ? this.props.template(this.props.option) : this.props.label;
return (
<li className={className} onClick={this.onClick} onTouchEnd={this.onTouchEnd}>
{content}
</li>
);
}
} |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
module.exports = [
'$q',
'camAPI',
function($q, camAPI) {
var decisionDefinitionService = camAPI.resource('decision-definition');
var drdService = camAPI.resource('drd');
var drds, decisions;
var defaultParams = {
latestVersion: true,
sortBy: 'name',
sortOrder: 'asc',
firstResult: 0,
maxResults: 50
};
function getDecisions(params) {
return decisionDefinitionService
.list(Object.assign({}, defaultParams, params))
.then(function(result) {
decisions = result;
if (drds) result = connectDrdsToDecisionDefinitions(drds, result);
return result;
});
}
function getDrds(params) {
return drdService
.list(Object.assign({}, defaultParams, params))
.then(function(result) {
drds = result;
if (decisions)
result = connectDrdsToDecisionDefinitions(drds, result);
return result;
});
}
function getDecisionsLists(decParams, drdParams) {
var decisionsProm = decisionDefinitionService.list(
Object.assign({}, defaultParams, decParams)
);
var decisionsCountProm = decisionDefinitionService.count({
latestVersion: true
});
var drdsProm = drdService.list(
Object.assign({}, defaultParams, drdParams)
);
var drdsCountProm = drdService.count({
latestVersion: true
});
return $q
.all({
decisions: decisionsProm,
decisionsCount: decisionsCountProm,
drds: drdsProm,
drdsCount: drdsCountProm
})
.then(function(results) {
drds = results.drds;
decisions = results.decisions;
decisions = results.decisions = connectDrdsToDecisionDefinitions(
results.drds,
results.decisions
);
results.drdsCount = results.drdsCount.count;
return results;
})
.catch(function() {});
}
function connectDrdsToDecisionDefinitions(drds, decisions) {
return decisions.map(function(decision) {
if (decision.decisionRequirementsDefinitionId) {
decision.drd = findDrdById(
drds,
decision.decisionRequirementsDefinitionId
) || {
key: decision.decisionRequirementsDefinitionKey,
id: decision.decisionRequirementsDefinitionId
};
}
return decision;
});
}
function findDrdById(drds, id) {
return drds.filter(function(drd) {
return drd.id === id;
})[0];
}
return {
getDecisionsLists: getDecisionsLists,
getDecisions: getDecisions,
getDrds: getDrds
};
}
];
|
from apps.configuration.editions.technologies_2018 import Technologies
from apps.configuration.models import Configuration, Translation, Value, Key, \
Questiongroup, Category
def run():
Technologies(
key=Key, value=Value, questiongroup=Questiongroup,
category=Category, configuration=Configuration, translation=Translation
).run_operations()
|
var gulp = require('gulp');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var rev = require('gulp-rev');
var revCollector = require('gulp-rev-collector');
var revDel = require('gulp-rev-delete-original');
var jsonmin = require('gulp-jsonminify');
var watch = require('gulp-watch');
var merge = require('merge-stream');
var runSequence = require('run-sequence');
var vinyl = require('vinyl-paths');
var del = require('del');
var errorHandler = require('gulp-error-handle');
var notifier = require('node-notifier');
var gutil = require('gulp-util');
var through = require('through2');
var pre = require('preprocess');
var logError = function(err) {
notifier.notify({
title: 'Error Occured...',
message: err.toString(),
timeout: 10
});
gutil.log(gutil.colors.red(err));
gutil.log(gutil.colors.red(err.stack));
this.emit('end');
};
var strToUnicode = function() {
var toUnicode = function(s) {
return s.replace(/([\u4E00-\u9FA5]|[\uFE30-\uFFA0])/g, function(s){
return '\\u' + s.charCodeAt(0).toString(16);
});
};
return through.obj(function(file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
return cb();
}
var content = pre.preprocess(file.contents.toString(), {});
content = toUnicode(content);
file.contents = new Buffer(content);
this.push(file);
cb();
});
};
gulp.task('delete', function() {
var delFolder = gulp.src('./{css,image}')
.pipe(errorHandler(logError))
.pipe(vinyl(del));
var delJson = gulp.src('./channel_list_data.json')
.pipe(errorHandler(logError))
.pipe(vinyl(del));
return merge(delFolder, delJson);
});
gulp.task('moveFile', ['delete'], function() {
return gulp.src('./src/**/*')
.pipe(errorHandler(logError))
.pipe(gulp.dest('./'));
});
gulp.task('cssnano', ['moveFile'], function() {
return gulp.src("./css/**/*.css")
.pipe(errorHandler(logError))
.pipe(cssnano({
browsers: ['last 2 versions'],
reduceIdents: false,
zindex: false // 關閉z-index 設定
}))
.pipe(gulp.dest("./css"));
});
gulp.task('imagemin', ['moveFile'], function() {
return gulp.src('./image/**/*.{jpg,png,svg}')
.pipe(errorHandler(logError))
.pipe(imagemin([
imagemin.gifsicle({ interlaced: true }), // gif無損轉換為漸進式。
imagemin.jpegtran({ progressive: true }), // jpg無損失轉換為漸進式
imagemin.optipng({ optimizationLevel: 5 }), // 設定png優化等級,共有0~7級
imagemin.svgo({
plugins: [
{ removeXMLProcInst: true }, // 刪除XML處理指令
{ removeEmptyAttrs: true }, // 刪除空的屬性
{ removeHiddenElems: true }, // 刪除隱藏的元素
{ removeEmptyText: true }, // 刪除空的文本元素
{ removeEmptyContainers: true }, // 刪除空的容器元素
{ removeUnusedNS: true }, // 刪除未使用的名稱空間聲明
{ removeUselessStrokeAndFill: true }, // 刪除無用stroke和fillattrs
{ cleanupIDs: true } // 刪除未使用的和縮小使用的ID
]
})
]))
.pipe(gulp.dest('./image'));
});
gulp.task('chinese2unicode', ['moveFile'], function() {
return gulp.src('./channel_list_data.json')
.pipe(errorHandler(logError))
.pipe(strToUnicode())
.pipe(jsonmin())
.pipe(gulp.dest('./'));
});
gulp.task('rev', ['cssnano', 'imagemin', 'chinese2unicode'], function() {
return gulp.src(
["./{css,image}/**/*"], { base: "./" }
)
.pipe(errorHandler(logError))
.pipe(rev())
.pipe(revDel())
.pipe(gulp.dest("./"))
.pipe(rev.manifest())
.pipe(gulp.dest("./"));
});
gulp.task('revCollectorCss', ['rev'], function() {
return revCollectorFile = gulp.src([
"./rev-manifest.json",
"./css/**/*.css"
])
.pipe(errorHandler(logError))
.pipe(revCollector())
.pipe(gulp.dest("./css"));
});
gulp.task('revCollectorJson', ['rev'], function() {
return revCollectorFile = gulp.src([
"./rev-manifest.json",
"./channel_list_data.json"
])
.pipe(errorHandler(logError))
.pipe(revCollector())
.pipe(gulp.dest("./"));
});
gulp.task('watch', ['revCollectorCss', 'revCollectorJson'], function() {
var isRunning = false;
var watchRunnable = null;
var printComplete = function() {
console.log("All Task Complete...");
};
printComplete();
return watch("./src/**/*", function() {
var run = function() {
isRunning = true;
runSequence(["revCollectorCss", 'revCollectorJson'], function() {
isRunning = false;
printComplete();
});
};
var check = function() {
clearTimeout(watchRunnable);
watchRunnable = setTimeout(function() {
if (isRunning) {
check();
} else {
run();
}
}, 500);
};
if (isRunning) {
check();
} else {
run();
}
});
});
gulp.task('default', ['revCollectorCss', 'revCollectorJson']); |
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
from datadog_api_client.v2.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
)
def lazy_import():
from datadog_api_client.v2.model.application_key_response_included_item import ApplicationKeyResponseIncludedItem
from datadog_api_client.v2.model.full_application_key import FullApplicationKey
globals()["ApplicationKeyResponseIncludedItem"] = ApplicationKeyResponseIncludedItem
globals()["FullApplicationKey"] = FullApplicationKey
class ApplicationKeyResponse(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {}
validations = {}
additional_properties_type = None
_nullable = False
@cached_property
def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
lazy_import()
return {
"data": (FullApplicationKey,), # noqa: E501
"included": ([ApplicationKeyResponseIncludedItem],), # noqa: E501
}
discriminator = None
attribute_map = {
"data": "data", # noqa: E501
"included": "included", # noqa: E501
}
read_only_vars = {}
_composed_schemas = {}
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs): # noqa: E501
"""ApplicationKeyResponse - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
data (FullApplicationKey): [optional] # noqa: E501
included ([ApplicationKeyResponseIncludedItem]): Array of objects related to the application key.. [optional] # noqa: E501
"""
super().__init__(kwargs)
self._check_pos_args(args)
@classmethod
@convert_js_args_to_python_args
def _from_openapi_data(cls, *args, **kwargs): # noqa: E501
"""Helper creating a new instance from a response."""
self = super(ApplicationKeyResponse, cls)._from_openapi_data(kwargs)
self._check_pos_args(args)
return self
|
import {html, PolymerElement} from '@polymer/polymer/polymer-element.js';
/**
* `ipfs-response`
* A web component that records the response time from multiple IPFS endpoints
*
* @customElement
* @polymer
* @demo demo/index.html
*/
class IpfsResponse extends PolymerElement {
static get template() {
return html`
<style>
:host {
display: block;
}
input {
width: 100%;
outline: none;
height: 40px;
border-radius: 2px;
background: #F0F1F3;
border: 1px solid #C9CCD0;
border-radius: 4px;
text-indent: 15px;
font-size: 15px;
margin-bottom:15px;
margin-top:5px;
}
input:focus {
background-color: white;
}
.button{
background-image: linear-gradient(-180deg, #FEFFFF 0%, #F3F4F5 100%);
border: 1px solid #D2D3D5;
border-radius: 4px;
cursor: pointer;
text-transform: uppercase;
font-size: 13px;
color: #585D6B;
font-weight:600;
}
label {
margin-bottom:10px;
}
</style>
<template is="dom-if" if="{{debug}}">
<label for="fileToFetch">File to Fetch: </label>
<input type="text" id="fileToFetch" value="{{fileToFetch::input}}" >
<label for="endPoints">Public IPFS End Points: </label>
<input type="text" id="endPoints" value="{{endPoints::input}}" >
<label for="timeOut">Timeout: </label>
<input type="text" id="timeOut" value="{{timeOut::input}}" >
<label for="retryAttempts">Retry Attempts: </label>
<input type="text" id="retryAttempts" value="{{retryAttempts::input}}" >
<label for="retryCount">Retry Count: </label>
<input type="text" id="retryCount" value="{{retryCount::input}}" >
<label for="delayLower">Delay Lower: </label>
<input type="text" id="delayLower" value="{{delayLower::input}}" >
<label for="delayUpper">Delay Upper: </label>
<input type="text" id="delayUpper" value="{{delayUpper::input}}" >
<label for="startTime">Start Time: </label>
<input type="text" id="startTime" value="{{startTime::input}}" >
<label for="response">Response: </label>
<input type="text" id="response" value="{{response::input}}" >
<label for="endTime">End Time: </label>
<input type="text" id="endTime" value="{{endTime::input}}" >
<label for="responseTime">Response Time: </label>
<input type="text" id="responseTime" value="{{responseTime::input}}" >
<input type="submit" value="Start" class="button" on-click="_start">
</template>
`;
}
static get properties() {
return {
endPoints: {
type: Array,
value: ['https://ipfs.io/ipfs/', 'https://ipfs.infura.io'],
},
timeOut: {
type: Number,
value: 3000
},
retryAttempts: {
type: Number,
value: 10
},
retryCount: {
type: Number,
value: 0
},
fileToFetch: {
type: String,
value: 'QmXoypizjW3WknFiJnKLwHCnL72vedxjQkDDP1mXWo6uco/I/m/Alan_Schaaf.jpg'
},
delayLower: {
type: Number,
value: 3000
},
delayUpper: {
type: Number,
value: 4000
},
response: {
type: String,
value: ''
},
debug: {
type: Boolean,
value: false
},
startTime: {
type: Number,
},
endTime: {
type: Number,
},
responseTime: {
type: Number,
},
};
}
_start(){
if (!this.startTime) this.startTime = performance.now();
if(this.response === '' && this.retryCount < this.retryAttempts && this.retryCount === 0){
this._callIpfs()
}
}
_retry(){
// this._randomDelay()
// .then((random) => {
// setTimeout(() => {
// this.retryCount++
// this._launchTimer()
// }, random);
// })
}
_randomDelay(){
return new Promise((resolve, reject) => {
try {
resolve(Math.floor(Math.random() * this.delayUpper) + this.delayLower );
}
catch(error) {
reject(error);
}
})
}
_callIpfs(){
fetch(this.endPoints[0] + this.fileToFetch)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => {
this.response = reader.result;
this.endTime = performance.now();
this.responseTime = this.endTime - this.startTime;
resolve(reader.result);
}
reader.onerror = reject
reader.readAsDataURL(blob)
}))
}
} window.customElements.define('ipfs-response', IpfsResponse);
|
import time
def test_flow_tracking_stats(api, utils):
config = api.config()
api._enable_flow_tracking(True)
# ports
config.ports.port(name="p1", location=utils.settings.ports[0])
config.ports.port(name="p2", location=utils.settings.ports[1])
config.ports.port(name="p3", location=utils.settings.ports[2])
config.ports.port(name="p4", location=utils.settings.ports[3])
layer1 = config.layer1.layer1()[-1]
layer1.port_names = [port.name for port in config.ports]
layer1.speed = "speed_100_gbps"
layer1.media = "copper"
layer1.name = "test"
d1, d2, d3, d4 = (
config.devices.device(container_name="p1", name="Device1")
.device(container_name="p2", name="Device2")
.device(container_name="p3", name="Device3")
.device(container_name="p4", name="Device4")
)
# device1
d1.ethernet.name = "Eth1"
d1.ethernet.mac = "00:02:00:00:00:11"
d1.ethernet.ipv4.name = "IPv41"
d1.ethernet.ipv4.address = "10.10.10.1"
d1.ethernet.ipv4.prefix = 32
d1.ethernet.ipv4.gateway = "10.10.10.2"
# device2
d2.ethernet.name = "Eth2"
d2.ethernet.mac = "00:02:00:00:00:12"
d2.ethernet.ipv4.name = "IPv42"
d2.ethernet.ipv4.address = "10.10.10.2"
d2.ethernet.ipv4.prefix = 32
d2.ethernet.ipv4.gateway = "10.10.10.1"
# device3
d3.ethernet.name = "Eth3"
d3.ethernet.mac = "00:02:00:00:00:13"
d3.ethernet.ipv4.name = "IPv43"
d3.ethernet.ipv4.address = "20.20.20.1"
d3.ethernet.ipv4.prefix = 32
d3.ethernet.ipv4.gateway = "20.20.20.2"
# device4
d4.ethernet.name = "Eth4"
d4.ethernet.mac = "00:02:00:00:00:14"
d4.ethernet.ipv4.name = "IPv44"
d4.ethernet.ipv4.address = "20.20.20.2"
d4.ethernet.ipv4.prefix = 32
d4.ethernet.ipv4.gateway = "20.20.20.1"
# traffic
config.flows.flow(name="Full Mesh Traffic")
flow = config.flows[-1]
flow.metrics.enable = True
flow.metrics.loss = True
endpoints = [device.name for device in config.devices]
flow.tx_rx.device.tx_names = endpoints
flow.tx_rx.device.rx_names = endpoints
flow.packet.ethernet().ipv4().udp()
flow.packet[1]
flow.size.fixed = 128
flow.duration.fixed_packets.packets = 10000
flow.rate.percentage = 1
api.set_config(config)
# start traffic
ts = api.transmit_state()
ts.state = ts.START
api.set_transmit_state(ts)
# check stats
time.sleep(5)
config = api.get_config()
request = api.metrics_request()
request.choice = request.FLOW
results = api.get_metrics(request).flow_metrics
assert len(results) == 12
|
"""
eZmax API Definition (Full)
This API expose all the functionnalities for the eZmax and eZsign applications. # noqa: E501
The version of the OpenAPI document: 1.1.7
Contact: [email protected]
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import eZmaxApi
from eZmaxApi.model.ezsigntemplatesignature_create_object_v1_response_m_payload import EzsigntemplatesignatureCreateObjectV1ResponseMPayload
class TestEzsigntemplatesignatureCreateObjectV1ResponseMPayload(unittest.TestCase):
"""EzsigntemplatesignatureCreateObjectV1ResponseMPayload unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testEzsigntemplatesignatureCreateObjectV1ResponseMPayload(self):
"""Test EzsigntemplatesignatureCreateObjectV1ResponseMPayload"""
# FIXME: construct object with mandatory attributes with example values
# model = EzsigntemplatesignatureCreateObjectV1ResponseMPayload() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
webpackJsonp([3],Array(46).concat([function(e,o,a){"use strict";var t=a(51),r=a.n(t),i=a(128),n=a(70),s="",d={file:{},download:{}},u=i.a,l=function(){p(),f(),window.plugins&&(window.plugins.file=d.file,window.plugins.downloads=d.download)},c=function(){document.addEventListener("deviceready",l,!1)},p=function(){d.file.checkDir=function(e,o,a){/^\//.test(o)&&console.error("directory cannot start with /");try{var t=e+o;window.resolveLocalFileSystemURL(t,function(e){!0===e.isDirectory?a(e):(console.error("input is not a directory"),a(void 0))},function(e){console.error(i.b[e.code]),a(void 0)})}catch(e){console.error(i.b[e.code]),a(void 0)}},d.file.checkFile=function(e,o,a){/^\//.test(o)&&console.error("directory cannot start with /");try{var t=e+o;window.resolveLocalFileSystemURL(t,function(e){!0===e.isFile?a(e):(console.error("input is not a file"),a(void 0))},function(e){console.error(i.b[e.code]),a(void 0)})}catch(e){console.error(i.b[e.code]),a(void 0)}},d.file.createDir=function(e,o,a,t){/^\//.test(o)&&console.error("directory cannot start with /"),a=!a;var r={create:!0,exclusive:a};try{window.resolveLocalFileSystemURL(e,function(e){e.getDirectory(o,r,function(e){t(e)},function(e){console.error(i.b[e.code]),t(void 0)})},function(e){console.error(i.b[e.code]),t(void 0)})}catch(e){console.error(i.b[e.code]),t(void 0)}},d.file.createFile=function(e,o,a){},d.file.removeDir=function(e,o){},d.file.removeFile=function(e,o,a){/^\//.test(o)&&console.log("file-name cannot start with /");try{window.resolveLocalFileSystemURL(e,function(e){e.getFile(o,{create:!1},function(e){e.remove(function(){a({success:!0,fileRemoved:e})},function(e){console.error(i.b[e.code]),a({success:!1})})},function(e){console.error(i.b[e.code]),a({success:!1})})},function(e){console.error(i.b[e.code]),a({success:!1})})}catch(e){console.error(i.b[e.code]),a({success:!1})}},d.file.removeRecursively=function(e,o){},d.file.writeFile=function(e,o,a,t){},d.file.writeExistingFile=function(e,o,a){},d.file.readAsText=function(e,o){},d.file.readAsDataURL=function(e,o){},d.file.readAsBinaryString=function(e,o){},d.file.readAsArrayBuffer=function(e,o){},d.file.moveFile=function(e,o,a,t,r){t=t||o,(/^\//.test(o)||/^\//.test(t))&&console.error("file-name cannot start with /");try{window.resolveLocalFileSystemURL(e,function(e){e.getFile(o,{create:!1},function(e){window.resolveLocalFileSystemURL(a,function(o){e.moveTo(o,t,function(e){r(e)},function(e){r(void 0)})},function(e){r(void 0)})},function(e){r(void 0)})},function(e){r(void 0)})}catch(e){r(void 0)}},d.file.moveDir=function(e,o,a,t){},d.file.copyDir=function(e,o,a,t){},d.file.copyFile=function(e,o,a,t){},d.file.bytesToSize=function(e){if(void 0===e||0===e)return"0 B";var o=["B","KB","MB","GB"],a=Math.floor(Math.log(e)/Math.log(1024));return(e/Math.pow(1024,a)).toPrecision(3)+" "+o[a]}},f=function(){d.download=function(){var e={debug:"false"},o=[],t=void 0,l="",c="",p="",f="",m=function(){return o.some(function(e){return e.status===i.c.DOWNLOADING})},b=function(e){var a=o[e];return o.splice(e,1),a},h=function(e){for(var a=0;a<o.length&&o[a].resourceId!==e;a++);return a>=o.length?void 0:b(a)},v=function(e){return void 0===e?o.find(function(e){return e.status===i.c.NO_START||e.status===i.c.WAITING}):o.find(function(o){return o.resourceId===e})},w=function(e,a,t,i,n,s){var d={success:!0,data:{resId:void 0}};try{if(void 0===v(e)){var l=r()({},u);l.resourceId=e,l.resourceDownloadUrl=a,l.resourceIndex=t,l.belongsCourseId=i,l.resourceFile=n,l.resourceName=s,o.push(l)}else d.success=!1;void 0!==e&&(d.data.resId=e),setTimeout(function(){P(d.data.resId)},300)}catch(e){d.success=!1}window.cordova.fireWindowEvent("download.pushed",d),window.cordova.fireWindowEvent("download.list.saved",{})},y=function(e){d.file.checkDir(s,"video",function(o){void 0===o?d.file.createDir(s,"video",!1,function(o){o.isDirectory&&(c=o.toURL().replace("file://","")+f,console.log("create targetPath:"+c),e())}):o.isDirectory&&(c=o.toURL().replace("file://","")+f,e())})},g=function(e){d.file.checkFile(s+"video/",e,function(o){t.resourceTargetPath=void 0!==o?"video/"+e:"",window.cordova.fireWindowEvent("download.list.saved",{})})},k=function(){if(o.length>0)for(var e=0;e<o.length;e++)o[e].status!==i.c.NO_START&&o[e].status!==i.c.DOWNLOADING||(o[e].status=i.c.WAITING,L(o[e].resourceId))},T=function(e,o,a,r,n){d.file.checkFile(s+"video/",r,function(u){if(void 0===u){if(!m()){t.status=i.c.DOWNLOADING;var l=(new Date).getTime(),c=0;window.plugins.download.start(e,o,n,function(o){window.plugins.download.progress(e,n,function(e){if(void 0!==e.data.error)return void d.file.removeFile(s+"video",a,function(e){});void 0===e.data||!1!==e.data.isCompletd&&"false"!==e.data.isCompletd?d.file.moveFile(s+"video",a,s+"video",r,function(e){window.cordova.fireWindowEvent("download.complete",{success:!0,data:{resId:t.resourceId}}),t.status=i.c.COMPLETE,g(r),setTimeout(function(){P()},300)}):(c=(new Date).getTime())-l>=200&&(l=c,t.speed=e.data.speed,t.loaded=e.data.loaded,t.fileSize=e.data.total,window.cordova.fireWindowEvent("download.progress",{success:!0,data:{resId:t.resourceId,speed:e.data.speed,loaded:e.data.loaded,total:e.data.total,disk:{free:e.data.freeDisk,total:e.data.totalDisk}}}),window.cordova.fireWindowEvent("download.list.saved",{}))})})}}else window.cordova.fireWindowEvent("download.complete",{success:!0,data:{resId:t.resourceId}}),t.status=i.c.COMPLETE,g(r),setTimeout(function(){P()},300)})},P=function(o){if(void 0!==o||!m()){void 0!==o&&k();var a={success:!0,data:{resId:void 0}};try{if(void 0===(t=v(o)))return a.success=!1,void window.cordova.fireWindowEvent("download.started",a);l=t.resourceDownloadUrl,p=t.resourceFile,f=p+".tmp",I(function(){y(function(){T(l,c,f,p,e)})}),a.data.resId=o}catch(e){a.success=!1}window.cordova.fireWindowEvent("download.started",a)}},L=function(o){if(void 0!==o){var a={success:!0,data:{resId:void 0}};try{var t=D(o);void 0!==t&&t.status===i.c.DOWNLOADING&&(t.status=i.c.PAUSE),window.plugins.download.pause(t.resourceDownloadUrl,e,function(e){setTimeout(function(){P(),a.data.resId=o,window.cordova.fireWindowEvent("download.list.saved",{})},300)})}catch(e){a.success=!1}finally{window.cordova.fireWindowEvent("download.paused",a)}}},S=function(o){if(void 0!==o){var a={success:!0,data:{resId:void 0}};try{var r=h(o);window.plugins.download.abort(r.resourceDownloadUrl,e,function(e){var o=r.resourceTargetPath.substring(r.resourceTargetPath.lastIndexOf("/")+1);I(function(){d.file.removeFile(s+"video",o,function(e){e.success})}),void 0!==t&&o.resourceId===t.resourceId&&setTimeout(function(){P()},300)}),a.data.resId=o}catch(e){a.success=!1}window.cordova.fireWindowEvent("download.aborted",a),window.cordova.fireWindowEvent("download.list.saved",{})}},C=function(){I(function(){var e={success:!0,data:{resList:[]}};try{if(o.length>0)for(var a=0;a<o.length;a++)e.data.resList.push({courseId:o[a].belongsCourseId,resId:o[a].resourceId,resName:o[a].resourceName,resTargetPath:s+o[a].resourceTargetPath,resDownloadPath:o[a].resourceDownloadUrl,resStatus:o[a].status,resLoaded:d.file.bytesToSize(o[a].loaded),resFileSize:d.file.bytesToSize(o[a].fileSize),resLoadedSource:o[a].loaded,resFileSizeSource:o[a].fileSize})}catch(o){e.success=!1}window.cordova.fireWindowEvent("download.list",e)})},j=function(){a.i(n.a)("download.wifi.download",!0)},E=function(){a.i(n.a)("download.wifi.download",!1)},N=function(){return void 0===JSON.parse(a.i(n.b)("download.wifi.download"))&&j(),JSON.parse(a.i(n.b)("download.wifi.download"))},D=function(e){return v(e)},R=function(e){var o=D(e);if(void 0!==s&&""!==s||I(function(){}),void 0!==o&&o.resourceId===e)return{courseId:o.belongsCourseId,resId:o.resourceId,resTargetPath:s+o.resourceTargetPath,resDownloadPath:o.resourceDownloadUrl,resStatus:o.status,resLoaded:d.file.bytesToSize(o.loaded),resFileSize:d.file.bytesToSize(o.fileSize)}},I=function(e){var o=window.device.platform;"Android"===o?s=window.cordova.file.externalDataDirectory:"iOS"===o&&(s=window.cordova.file.documentsDirectory+"NoCloud/"),e()};window.addEventListener("download.list.saved",function(e){a.i(n.a)("download_list",o),C()});return function(){var e=a.i(n.b)("download_list"),t=JSON.parse(e);if(null!==t)for(var s=0;s<t.length;s++){var d=r()({},t[s]);d.speed="0",0!==t[s].loaded&&t[s].loaded===t[s].fileSize?d.status=i.c.COMPLETE:d.status=t[s].status,d.status===i.c.DOWNLOADING?d.status=i.c.PAUSE:d.status=t[s].status,o.push(d)}}(),{push:function(e,o,a,t,r){return w(e,o,a,t,r)},start:function(e){P(e)},pause:function(e){L(e)},abort:function(e){S(e)},list:function(){C()},enableWifiDownload:function(){j()},disableWifiDownload:function(){E()},isEnableWifiDownload:function(){return N()},getResource:function(e){return R(e)}}}()};o.a={init:c}},,function(e,o){},function(e,o){},function(e,o){},,,,,,,,,,,,,,,,,,,,function(e,o,a){"use strict";a.d(o,"a",function(){return l}),a.d(o,"b",function(){return c});var t=a(148),r=a.n(t),i=a(149),n=a.n(i),s=a(143),d=a.n(s),u=a(197),l=(a.n(u),function(e,o){e&&("string"!=typeof o&&(o=d()(o)),window.localStorage.setItem(e,o))}),c=function(e){if(e)return window.localStorage.getItem(e)};!function(){function e(o){r()(this,e),this.IOSVersion="v1.0.2",this.ANDROIDVersion="v1.0.2"}n()(e,[{key:"platforms",value:function(){var e=navigator.userAgent;return e.indexOf("Android")>-1||e.indexOf("Adr")>-1?(this.platform="Android",this.platform):(this.platform="IOS",this.platform)}}])}()},function(e,o,a){"use strict";a.d(o,"b",function(){return t}),a.d(o,"a",function(){return r});var t="OPEN_IS_LOGIN",r="OPEN_ISLOADING"},,,,,,,,,,,,,,,,,,,,function(e,o){},,,,,,,,,,,,,,,,,,,,function(e,o){!function(e,o){var a=e.documentElement,t="orientationchange"in window?"orientationchange":"resize",r=function(){var e=a.clientWidth;e&&(a.style.fontSize=e/320*20+"px")};e.addEventListener&&(o.addEventListener(t,r,!1),e.addEventListener("DOMContentLoaded",r,!1))}(document,window)},function(e,o,a){"use strict";a(21).default.filter("dateFormatTime",function(e){if(e)return e.substring(0,10)})},function(e,o,a){"use strict";var t=a(21),r=a(277),i=a(129),n=function(e){return a.e(1).then(function(){return e(a(314))}.bind(null,a)).catch(a.oe)},s=function(e){return a.e(0).then(function(){return e(a(315))}.bind(null,a)).catch(a.oe)};t.default.use(r.a);var d=new r.a({routes:[{path:"/",redirect:"/home"},{path:"/index.html",redirect:"/oces/"},{path:"/login",name:"login",component:n},{path:"/home",name:"home",component:s,meta:{requireAuth:!0},children:[]}],mode:i.a});d.beforeEach(function(e,o,a){window.mtj&&(o.name&&window.mtj.pageviewEndWithName(o.name,function(){console.log("Success mtj.pageviewEndWithName")},function(){console.log("Error mtj.pageviewEndWithName")}),window.mtj.pageviewStartWithName(e.name,function(){console.log("Success mtj.pageviewStartWithName")},function(){console.log("Error mtj.pageviewStartWithName")})),window.StatusBar&&(window.StatusBar.overlaysWebView(!1),window.StatusBar.styleDefault(!0)),a()}),o.a=d},function(e,o,a){"use strict";var t=a(21),r=a(109),i=a(138),n=a(131),s=a(132),d=a(139),u=a(135);t.default.use(r.b),o.a=new r.b.Store({state:d.a,mutations:i.a,getters:s.a,actions:n.a,modules:{oces:u.a}})},,,,,,,,,function(e,o,a){function t(e){a(194)}var r=a(47)(a(141),a(275),t,null,null);e.exports=r.exports},,,,,function(e,o,a){"use strict";a.d(o,"a",function(){return i}),a.d(o,"c",function(){return t}),a.d(o,"b",function(){return r});var t={NO_START:"no_start",WAITING:"waiting",DOWNLOADING:"downloading",PAUSE:"pause",COMPLETE:"complete"},r={1:"NOT_FOUND_ERR",2:"SECURITY_ERR",3:"ABORT_ERR",4:"NOT_READABLE_ERR",5:"ENCODING_ERR",6:"NO_MODIFICATION_ALLOWED_ERR",7:"INVALID_STATE_ERR",8:"SYNTAX_ERR",9:"INVALID_MODIFICATION_ERR",10:"QUOTA_EXCEEDED_ERR",11:"TYPE_MISMATCH_ERR",12:"PATH_EXISTS_ERR"},i={resourceId:"",resourceFile:"",resourceName:"",resourceDownloadUrl:"",resourceIndex:0,resourceTargetPath:"",belongsCourseId:"",status:"no_start",speed:"0",progress:"0%",loaded:"0",fileSize:"0"}},function(e,o,a){"use strict";a.d(o,"a",function(){return t});var t="history";"http://mmapi.open.com.cn/api/",t=""},function(e,o,a){"use strict";Object.defineProperty(o,"__esModule",{value:!0});var t=a(119),r=(a.n(t),a(118)),i=a.n(r),n=a(121),s=(a.n(n),a(120)),d=a.n(s),u=a(117),l=(a.n(u),a(116)),c=a.n(l),p=a(21),f=a(123),m=a.n(f),b=a(114),h=a(113),v=a(111),w=(a.n(v),a(46),a(122)),y=a.n(w),g=(a(112),a(115)),k=a.n(g),T=a(124),P=a.n(T),L=a(46);if(p.default.use(P.a),p.default.use(c.a),p.default.use(d.a),p.default.use(i.a),"addEventListener"in document&&document.addEventListener("DOMContentLoaded",function(){k.a.attach(document.body)},!1),p.default.use(y.a,{optionTestKey:"optionTestValue"}),"file:"===window.location.protocol||"3000"===window.location.port){var S=document.createElement("script");S.setAttribute("type","text/javascript"),S.setAttribute("src","cordova.js"),document.body.appendChild(S)}document.addEventListener("deviceready",function(){L.a.init(),window.screen.orientation.lock("portrait")}),p.default.config.productionTip=!1,new p.default({el:"#app",router:h.a,store:b.a,template:"<App/>",components:{App:m.a}})},function(e,o,a){"use strict";var t=a(151),r=a.n(t),i=a(147),n=a.n(i),s=a(71);o.a={showLoading:function(e,o){var a=this,t=e.commit;e.state;return n()(r.a.mark(function e(){return r.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t(s.a,o);case 1:case"end":return e.stop()}},e,a)}))()}}},function(e,o,a){"use strict";o.a={}},function(e,o,a){"use strict";o.a={}},function(e,o,a){"use strict";o.a={bannerListCount:function(e){var o=0;return e.bannerList.Data&&(o=e.bannerList.Data.length),o}}},function(e,o,a){"use strict";var t=a(133),r=a(136),i=a(134),n=a(137);o.a={state:n.a,getters:i.a,actions:t.a,mutations:r.a}},function(e,o,a){"use strict";o.a={}},function(e,o,a){"use strict";o.a={}},function(e,o,a){"use strict";var t=a(150),r=a.n(t),i=a(71),n=a(70);o.a=r()({},i.b,function(e,o){"1"===o.status?e.isLogin=!0:(e.isLogin=!1,e.userInfo=o),a.i(n.a)("isLogin",e.isLogin)})},function(e,o,a){"use strict";o.a={isLogin:!0,isLoading:!1,updateApp:{}}},function(e,o,a){"use strict";Object.defineProperty(o,"__esModule",{value:!0});var t=a(51),r=a.n(t);window.videojs=a(108),a(91);var i=a(309);o.default={name:"video-player",props:{options:{type:Object,required:!0}},mounted:function(){this.player||this.initialize()},beforeDestroy:function(){this.player&&this.dispose()},methods:{initialize:function(){var e=this;this.player=null;var o=r()({start:0,playsinline:!1,customEventName:"statechanged",autoplay:!1,controls:!0,preload:"auto",fluid:!1,muted:!1,width:"100%",height:"360",language:"en",controlBar:{remainingTimeDisplay:!1,playToggle:{},progressControl:{},fullscreenToggle:{},volumeMenuButton:{inline:!1,vertical:!0}},techOrder:["html5","flash"],playbackRates:[],plugins:{}},this.options),a=o.language;videojs.addLanguage(a,i[a]);var t=o.playsinline;t&&(this.$el.children[0].setAttribute("playsinline",t),this.$el.children[0].setAttribute("webkit-playsinline",t));var n=function(a,t){if(a&&e.$emit(a,e.player),t){var r={};r[a]=t,e.$emit(o.customEventName,r)}};o.plugins&&delete o.plugins.__ob__,this.player=videojs(this.$el.children[0],o,function(){e.$emit("ready",e.player),this.on("loadeddata",function(){this.muted(o.muted),o.start&&this.currentTime(o.start),n("loadeddata",!0)}),this.on("canplay",function(){n("canplay",!0)}),this.on("canplaythrough",function(){n("canplaythrough",!0)}),this.on("play",function(){n("play",!0)}),this.on("pause",function(){n("pause",!0)}),this.on("waiting",function(){n("waiting",!0)}),this.on("playing",function(){n("playing",!0)}),this.on("ended",function(){n("ended",!0)}),this.on("timeupdate",function(){n("timeupdate",this.currentTime())})})},dispose:function(){if(this.player&&videojs){if(this.player.pause&&this.player.pause(),videojs(this.$el.children[0]).dispose(),!this.$el.children.length){var e=document.createElement("video");e.className="video-js vjs-custom-skin",this.$el.appendChild(e)}this.player=null}}},watch:{options:{deep:!0,handler:function(e,o){this.dispose(),e&&e.sources&&e.sources.length&&this.initialize()}}}}},function(e,o,a){"use strict";Object.defineProperty(o,"__esModule",{value:!0});var t=a(272),r=a.n(t);o.default={name:"app",data:function(){return{transitionName:"vux-pop-in",isUpdate:!0,bkData:{},routerTo:"",count:1}},mounted:function(){console.log(1234)},components:{loading:r.a},methods:{}}},function(e,o,a){"use strict";Object.defineProperty(o,"__esModule",{value:!0});var t=a(125),r=a.n(t),i=a(109);o.default={data:function(){return{positionY:0,timer:null}},mounted:function(){},computed:r()({},a.i(i.a)({isLoading:function(e){return e.isLoading}})),watch:{isLoading:function(){var e=this;this.isLoading?this.timer=setInterval(function(){e.positionY++},600):clearInterval(this.timer)}},beforeDestroy:function(){clearInterval(this.timer)}}},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(e,o){},function(e,o){},function(e,o){},function(e,o){throw new Error("Module build failed: ModuleBuildError: Module build failed: Error: Missing binding G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@node-sass\\vendor\\win32-x64-51\\binding.node\nNode Sass could not find a binding for your current environment: Windows 64-bit with Node.js 7.x\n\nFound bindings for the following environments:\n - Windows 64-bit with Node.js 8.x\n\nThis usually happens because your environment has changed since running `npm install`.\nRun `npm rebuild node-sass --force` to build the binding for your current environment.\n at module.exports (G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@node-sass\\lib\\binding.js:15:13)\n at Object.<anonymous> (G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@node-sass\\lib\\index.js:14:35)\n at Module._compile (module.js:571:32)\n at Object.Module._extensions..js (module.js:580:10)\n at Module.load (module.js:488:32)\n at tryModuleLoad (module.js:447:12)\n at Function.Module._load (module.js:439:3)\n at Module.require (module.js:498:17)\n at require (internal/module.js:20:19)\n at Object.<anonymous> (G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@sass-loader\\lib\\loader.js:3:14)\n at Module._compile (module.js:571:32)\n at Object.Module._extensions..js (module.js:580:10)\n at Module.load (module.js:488:32)\n at tryModuleLoad (module.js:447:12)\n at Function.Module._load (module.js:439:3)\n at Module.require (module.js:498:17)\n at runLoaders (G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@webpack\\lib\\NormalModule.js:192:19)\n at G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@loader-runner\\lib\\LoaderRunner.js:364:11\n at G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@loader-runner\\lib\\LoaderRunner.js:170:18\n at loadLoader (G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@loader-runner\\lib\\loadLoader.js:27:11)\n at iteratePitchingLoaders (G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@loader-runner\\lib\\LoaderRunner.js:169:2)\n at iteratePitchingLoaders (G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@loader-runner\\lib\\LoaderRunner.js:165:10)\n at G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@loader-runner\\lib\\LoaderRunner.js:173:18\n at loadLoader (G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@loader-runner\\lib\\loadLoader.js:36:3)\n at iteratePitchingLoaders (G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@loader-runner\\lib\\LoaderRunner.js:169:2)\n at iteratePitchingLoaders (G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@loader-runner\\lib\\LoaderRunner.js:165:10)\n at G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@loader-runner\\lib\\LoaderRunner.js:173:18\n at loadLoader (G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@loader-runner\\lib\\loadLoader.js:36:3)\n at iteratePitchingLoaders (G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@loader-runner\\lib\\LoaderRunner.js:169:2)\n at runLoaders (G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@loader-runner\\lib\\LoaderRunner.js:362:2)\n at NormalModule.doBuild (G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@webpack\\lib\\NormalModule.js:179:3)\n at NormalModule.build (G:\\chrome\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\oesapp-dev-466879f903a77a6ca7f8bb3b6811acf920531854\\node_modules\\[email protected]@webpack\\lib\\NormalModule.js:268:15)")},function(e,o){},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(e,o,a){function t(e){a(193)}var r=a(47)(a(142),a(274),t,"data-v-313b5053",null);e.exports=r.exports},function(e,o,a){function t(e){a(195)}var r=a(47)(a(140),a(276),t,null,null);e.exports=r.exports},function(e,o){e.exports={render:function(){var e=this,o=e.$createElement,a=e._self._c||o;return a("transition",{attrs:{name:"loading-fade",mode:"out-in"}},[a("div",{directives:[{name:"show",rawName:"v-show",value:e.isLoading,expression:"isLoading"}],staticClass:"loading_bg"},[a("div",{staticClass:"loading_container"},[a("div",{staticClass:"load_img",style:{backgroundPositionY:-e.positionY%7*2.5+"rem"}}),e._v(" "),a("svg",{staticClass:"load_ellipse",attrs:{xmlns:"http://www.w3.org/2000/svg",version:"1.1"}},[a("ellipse",{staticStyle:{fill:"#ddd",stroke:"none"},attrs:{cx:"26",cy:"10",rx:"26",ry:"10"}})])])])])},staticRenderFns:[]}},function(e,o){e.exports={render:function(){var e=this,o=e.$createElement,a=e._self._c||o;return a("div",{attrs:{id:"app"}},[a("transition",{attrs:{name:e.transitionName}},[a("router-view")],1),e._v(" "),a("loading")],1)},staticRenderFns:[]}},function(e,o){e.exports={render:function(){var e=this,o=e.$createElement;e._self._c;return e._m(0)},staticRenderFns:[function(){var e=this,o=e.$createElement,a=e._self._c||o;return a("div",{staticClass:"video-player"},[a("video",{staticClass:"video-js vjs-custom-skin"})])}]}},,,function(e,o){e.exports={Play:"تشغيل",Pause:"ايقاف","Current Time":"الوقت الحالي","Duration Time":"Dauer","Remaining Time":"الوقت المتبقي","Stream Type":"نوع التيار",LIVE:"مباشر",Loaded:"تم التحميل",Progress:"التقدم",Fullscreen:"ملء الشاشة","Non-Fullscreen":"غير ملء الشاشة",Mute:"صامت",Unmute:"غير الصامت","Playback Rate":"معدل التشغيل",Subtitles:"الترجمة","subtitles off":"ايقاف الترجمة",Captions:"التعليقات","captions off":"ايقاف التعليقات",Chapters:"فصول","You aborted the media playback":"لقد ألغيت تشغيل الفيديو","A network error caused the media download to fail part-way.":"تسبب خطأ في الشبكة بفشل تحميل الفيديو بالكامل.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"لا يمكن تحميل الفيديو بسبب فشل في الخادم أو الشبكة ، أو فشل بسبب عدم امكانية قراءة تنسيق الفيديو.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"تم ايقاف تشغيل الفيديو بسبب مشكلة فساد أو لأن الفيديو المستخدم يستخدم ميزات غير مدعومة من متصفحك.","No compatible source was found for this media.":"فشل العثور على أي مصدر متوافق مع هذا الفيديو.","Play Video":"تشغيل الفيديو",Close:"أغلق","Modal Window":"نافذة مشروطة","This is a modal window":"هذه نافذة مشروطة","This modal can be closed by pressing the Escape key or activating the close button.":"يمكن غلق هذه النافذة المشروطة عن طريق الضغط على زر الخروج أو تفعيل زر الإغلاق",", opens captions settings dialog":", تفتح نافذة خيارات التعليقات",", opens subtitles settings dialog":", تفتح نافذة خيارات الترجمة",", selected":", مختار"}},function(e,o){e.exports={Play:"Възпроизвеждане",Pause:"Пауза","Current Time":"Текущо време","Duration Time":"Продължителност","Remaining Time":"Оставащо време","Stream Type":"Тип на потока",LIVE:"НА ЖИВО",Loaded:"Заредено",Progress:"Прогрес",Fullscreen:"Цял екран","Non-Fullscreen":"Спиране на цял екран",Mute:"Без звук",Unmute:"Със звук","Playback Rate":"Скорост на възпроизвеждане",Subtitles:"Субтитри","subtitles off":"Спряни субтитри",Captions:"Аудио надписи","captions off":"Спряни аудио надписи",Chapters:"Глави","You aborted the media playback":"Спряхте възпроизвеждането на видеото","A network error caused the media download to fail part-way.":"Грешка в мрежата провали изтеглянето на видеото.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Видеото не може да бъде заредено заради проблем със сървъра или мрежата или защото този формат не е поддържан.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Възпроизвеждането на видеото беше прекъснато заради проблем с файла или защото видеото използва опции които браузърът Ви не поддържа.","No compatible source was found for this media.":"Не беше намерен съвместим източник за това видео."}},function(e,o){e.exports={Play:"Reproducció",Pause:"Pausa","Current Time":"Temps reproduït","Duration Time":"Durada total","Remaining Time":"Temps restant","Stream Type":"Tipus de seqüència",LIVE:"EN DIRECTE",Loaded:"Carregat",Progress:"Progrés",Fullscreen:"Pantalla completa","Non-Fullscreen":"Pantalla no completa",Mute:"Silencia",Unmute:"Amb so","Playback Rate":"Velocitat de reproducció",Subtitles:"Subtítols","subtitles off":"Subtítols desactivats",Captions:"Llegendes","captions off":"Llegendes desactivades",Chapters:"Capítols","You aborted the media playback":"Heu interromput la reproducció del vídeo.","A network error caused the media download to fail part-way.":"Un error de la xarxa ha interromput la baixada del vídeo.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"No s'ha pogut carregar el vídeo perquè el servidor o la xarxa han fallat, o bé perquè el seu format no és compatible.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"La reproducció de vídeo s'ha interrumput per un problema de corrupció de dades o bé perquè el vídeo demanava funcions que el vostre navegador no ofereix.","No compatible source was found for this media.":"No s'ha trobat cap font compatible amb el vídeo."}},function(e,o){e.exports={Play:"Přehrát",Pause:"Pauza","Current Time":"Aktuální čas","Duration Time":"Doba trvání","Remaining Time":"Zbývající čas","Stream Type":"Stream Type",LIVE:"ŽIVĚ",Loaded:"Načteno",Progress:"Stav",Fullscreen:"Celá obrazovka","Non-Fullscreen":"Zmenšená obrazovka",Mute:"Ztlumit zvuk",Unmute:"Přehrát zvuk","Playback Rate":"Rychlost přehrávání",Subtitles:"Titulky","subtitles off":"Titulky vypnuty",Captions:"Popisky","captions off":"Popisky vypnuty",Chapters:"Kapitoly","You aborted the media playback":"Přehrávání videa je přerušeno.","A network error caused the media download to fail part-way.":"Video nemohlo být načteno, kvůli chybě v síti.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Video nemohlo být načteno, buď kvůli chybě serveru nebo sítě nebo proto, že daný formát není podporován.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Váš prohlížeč nepodporuje formát videa.","No compatible source was found for this media.":"Špatně zadaný zdroj videa."}},function(e,o){e.exports={Play:"Afspil",Pause:"Pause","Current Time":"Aktuel tid","Duration Time":"Varighed","Remaining Time":"Resterende tid","Stream Type":"Stream-type",LIVE:"LIVE",Loaded:"Indlæst",Progress:"Status",Fullscreen:"Fuldskærm","Non-Fullscreen":"Luk fuldskærm",Mute:"Uden lyd",Unmute:"Med lyd","Playback Rate":"Afspilningsrate",Subtitles:"Undertekster","subtitles off":"Uden undertekster",Captions:"Undertekster for hørehæmmede","captions off":"Uden undertekster for hørehæmmede",Chapters:"Kapitler","You aborted the media playback":"Du afbrød videoafspilningen.","A network error caused the media download to fail part-way.":"En netværksfejl fik download af videoen til at fejle.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Videoen kunne ikke indlæses, enten fordi serveren eller netværket fejlede, eller fordi formatet ikke er understøttet.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Videoafspilningen blev afbrudt på grund af ødelagte data eller fordi videoen benyttede faciliteter som din browser ikke understøtter.","No compatible source was found for this media.":"Fandt ikke en kompatibel kilde for denne media."}},function(e,o){e.exports={Play:"Wiedergabe",Pause:"Pause","Current Time":"Aktueller Zeitpunkt","Duration Time":"Dauer","Remaining Time":"Verbleibende Zeit","Stream Type":"Streamtyp",LIVE:"LIVE",Loaded:"Geladen",Progress:"Status",Fullscreen:"Vollbild","Non-Fullscreen":"Kein Vollbild",Mute:"Ton aus",Unmute:"Ton ein","Playback Rate":"Wiedergabegeschwindigkeit",Subtitles:"Untertitel","subtitles off":"Untertitel aus",Captions:"Untertitel","captions off":"Untertitel aus",Chapters:"Kapitel","You aborted the media playback":"Sie haben die Videowiedergabe abgebrochen.","A network error caused the media download to fail part-way.":"Der Videodownload ist aufgrund eines Netzwerkfehlers fehlgeschlagen.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Das Video konnte nicht geladen werden, da entweder ein Server- oder Netzwerkfehler auftrat oder das Format nicht unterstützt wird.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Die Videowiedergabe wurde entweder wegen eines Problems mit einem beschädigten Video oder wegen verwendeten Funktionen, die vom Browser nicht unterstützt werden, abgebrochen.","No compatible source was found for this media.":"Für dieses Video wurde keine kompatible Quelle gefunden.","Play Video":"Video abspielen",Close:"Schließen","Modal Window":"Modales Fenster","This is a modal window":"Dies ist ein modales Fenster","This modal can be closed by pressing the Escape key or activating the close button.":'Durch Drücken der Esc-Taste bzw. Betätigung der Schaltfläche "Schließen" wird dieses modale Fenster geschlossen.',", opens captions settings dialog":", öffnet Einstellungen für Untertitel",", opens subtitles settings dialog":", öffnet Einstellungen für Untertitel",", selected":", ausgewählt","Close Modal Dialog":"Modales Fenster schließen",Descriptions:"Beschreibungen","descriptions off":"Beschreibungen aus","The media is encrypted and we do not have the keys to decrypt it.":"Die Entschlüsselungsschlüssel für den verschlüsselten Medieninhalt sind nicht verfügbar.",", opens descriptions settings dialog":", öffnet Einstellungen für Beschreibungen","Audio Track":"Tonspur"}},function(e,o){e.exports={Play:"Aναπαραγωγή",Pause:"Παύση","Current Time":"Τρέχων χρόνος","Duration Time":"Συνολικός χρόνος","Remaining Time":"Υπολοιπόμενος χρόνος","Stream Type":"Τύπος ροής",LIVE:"ΖΩΝΤΑΝΑ",Loaded:"Φόρτωση επιτυχής",Progress:"Πρόοδος",Fullscreen:"Πλήρης οθόνη","Non-Fullscreen":"Έξοδος από πλήρη οθόνη",Mute:"Σίγαση",Unmute:"Kατάργηση σίγασης","Playback Rate":"Ρυθμός αναπαραγωγής",Subtitles:"Υπότιτλοι","subtitles off":"απόκρυψη υπότιτλων",Captions:"Λεζάντες","captions off":"απόκρυψη λεζάντων",Chapters:"Κεφάλαια","Close Modal Dialog":"Κλείσιμο παραθύρου",Descriptions:"Περιγραφές","descriptions off":"απόκρυψη περιγραφών","Audio Track":"Ροή ήχου","You aborted the media playback":"Ακυρώσατε την αναπαραγωγή","A network error caused the media download to fail part-way.":"Ένα σφάλμα δικτύου προκάλεσε την αποτυχία μεταφόρτωσης του αρχείου προς αναπαραγωγή.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Το αρχείο προς αναπαραγωγή δεν ήταν δυνατό να φορτωθεί είτε γιατί υπήρξε σφάλμα στον διακομιστή ή το δίκτυο, είτε γιατί ο τύπος του αρχείου δεν υποστηρίζεται.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Η αναπαραγωγή ακυρώθηκε είτε λόγω κατεστραμμένου αρχείου, είτε γιατί το αρχείο απαιτεί λειτουργίες που δεν υποστηρίζονται από το πρόγραμμα περιήγησης που χρησιμοποιείτε.","No compatible source was found for this media.":"Δεν βρέθηκε συμβατή πηγή αναπαραγωγής για το συγκεκριμένο αρχείο.","The media is encrypted and we do not have the keys to decrypt it.":"Το αρχείο προς αναπαραγωγή είναι κρυπτογραφημένo και δεν υπάρχουν τα απαραίτητα κλειδιά αποκρυπτογράφησης.","Play Video":"Αναπαραγωγή βίντεο",Close:"Κλείσιμο","Modal Window":"Aναδυόμενο παράθυρο","This is a modal window":"Το παρών είναι ένα αναδυόμενο παράθυρο","This modal can be closed by pressing the Escape key or activating the close button.":"Αυτό το παράθυρο μπορεί να εξαφανιστεί πατώντας το πλήκτρο Escape ή πατώντας το κουμπί κλεισίματος.",", opens captions settings dialog":", εμφανίζει τις ρυθμίσεις για τις λεζάντες",", opens subtitles settings dialog":", εμφανίζει τις ρυθμίσεις για τους υπότιτλους",", opens descriptions settings dialog":", εμφανίζει τις ρυθμίσεις για τις περιγραφές",", selected":", επιλεγμένο"}},function(e,o){e.exports={Play:"Play",Pause:"Pause","Current Time":"Current Time","Duration Time":"Duration Time","Remaining Time":"Remaining Time","Stream Type":"Stream Type",LIVE:"LIVE",Loaded:"Loaded",Progress:"Progress",Fullscreen:"Fullscreen","Non-Fullscreen":"Non-Fullscreen",Mute:"Mute",Unmute:"Unmute","Playback Rate":"Playback Rate",Subtitles:"Subtitles","subtitles off":"subtitles off",Captions:"Captions","captions off":"captions off",Chapters:"Chapters","Close Modal Dialog":"Close Modal Dialog",Descriptions:"Descriptions","descriptions off":"descriptions off","Audio Track":"Audio Track","You aborted the media playback":"You aborted the media playback","A network error caused the media download to fail part-way.":"A network error caused the media download to fail part-way.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"The media could not be loaded, either because the server or network failed or because the format is not supported.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"The media playback was aborted due to a corruption problem or because the media used features your browser did not support.","No compatible source was found for this media.":"No compatible source was found for this media.","The media is encrypted and we do not have the keys to decrypt it.":"The media is encrypted and we do not have the keys to decrypt it.","Play Video":"Play Video",Close:"Close","Modal Window":"Modal Window","This is a modal window":"This is a modal window","This modal can be closed by pressing the Escape key or activating the close button.":"This modal can be closed by pressing the Escape key or activating the close button.",", opens captions settings dialog":", opens captions settings dialog",", opens subtitles settings dialog":", opens subtitles settings dialog",", opens descriptions settings dialog":", opens descriptions settings dialog",", selected":", selected"}},function(e,o){e.exports={Play:"Reproducción",Pause:"Pausa","Current Time":"Tiempo reproducido","Duration Time":"Duración total","Remaining Time":"Tiempo restante","Stream Type":"Tipo de secuencia",LIVE:"DIRECTO",Loaded:"Cargado",Progress:"Progreso",Fullscreen:"Pantalla completa","Non-Fullscreen":"Pantalla no completa",Mute:"Silenciar",Unmute:"No silenciado","Playback Rate":"Velocidad de reproducción",Subtitles:"Subtítulos","subtitles off":"Subtítulos desactivados",Captions:"Subtítulos especiales","captions off":"Subtítulos especiales desactivados",Chapters:"Capítulos","You aborted the media playback":"Ha interrumpido la reproducción del vídeo.","A network error caused the media download to fail part-way.":"Un error de red ha interrumpido la descarga del vídeo.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"No se ha podido cargar el vídeo debido a un fallo de red o del servidor o porque el formato es incompatible.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"La reproducción de vídeo se ha interrumpido por un problema de corrupción de datos o porque el vídeo precisa funciones que su navegador no ofrece.","No compatible source was found for this media.":"No se ha encontrado ninguna fuente compatible con este vídeo."}},function(e,o){e.exports={Play:"پخش",Pause:"وقفه","Current Time":"زمان کنونی","Duration Time":"مدت زمان","Remaining Time":"زمان باقیمانده","Stream Type":"نوع استریم",LIVE:"زنده",Loaded:"فراخوانی شده",Progress:"پیشرفت",Fullscreen:"تمام صفحه","Non-Fullscreen":"نمایش عادی",Mute:"بی صدا",Unmute:"بهمراه صدا","Playback Rate":"سرعت پخش",Subtitles:"زیرنویس","subtitles off":"بدون زیرنویس",Captions:"عنوان","captions off":"بدون عنوان",Chapters:"فصل","You aborted the media playback":"شما پخش را متوقف کردید.","A network error caused the media download to fail part-way.":"مشکل در دریافت ویدئو ...","The media could not be loaded, either because the server or network failed or because the format is not supported.":"فرمت پشتیبانی نمیشود یا خطایی روی داده است.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"مشکل در دریافت ویدئو ...","No compatible source was found for this media.":"هیچ ورودی ای برای این رسانه شناسایی نشد."}},function(e,o){e.exports={Play:"Toisto",Pause:"Tauko","Current Time":"Tämänhetkinen aika","Duration Time":"Kokonaisaika","Remaining Time":"Jäljellä oleva aika","Stream Type":"Lähetystyyppi",LIVE:"LIVE",Loaded:"Ladattu",Progress:"Edistyminen",Fullscreen:"Koko näyttö","Non-Fullscreen":"Koko näyttö pois",Mute:"Ääni pois",Unmute:"Ääni päällä","Playback Rate":"Toistonopeus",Subtitles:"Tekstitys","subtitles off":"Tekstitys pois",Captions:"Tekstitys","captions off":"Tekstitys pois",Chapters:"Kappaleet","You aborted the media playback":"Olet keskeyttänyt videotoiston.","A network error caused the media download to fail part-way.":"Verkkovirhe keskeytti videon latauksen.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Videon lataus ei onnistunut joko palvelin- tai verkkovirheestä tai väärästä formaatista johtuen.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Videon toisto keskeytyi, koska media on vaurioitunut tai käyttää käyttää toimintoja, joita selaimesi ei tue.","No compatible source was found for this media.":"Tälle videolle ei löytynyt yhteensopivaa lähdettä."}},function(e,o){e.exports={Play:"Lecture",Pause:"Pause","Current Time":"Temps actuel","Duration Time":"Durée","Remaining Time":"Temps restant","Stream Type":"Type de flux",LIVE:"EN DIRECT",Loaded:"Chargé",Progress:"Progression",Fullscreen:"Plein écran","Non-Fullscreen":"Fenêtré",Mute:"Sourdine",Unmute:"Son activé","Playback Rate":"Vitesse de lecture",Subtitles:"Sous-titres","subtitles off":"Sous-titres désactivés",Captions:"Sous-titres transcrits","captions off":"Sous-titres transcrits désactivés",Chapters:"Chapitres","Close Modal Dialog":"Fermer la boîte de dialogue modale",Descriptions:"Descriptions","descriptions off":"descriptions désactivées","Audio Track":"Piste audio","You aborted the media playback":"Vous avez interrompu la lecture de la vidéo.","A network error caused the media download to fail part-way.":"Une erreur de réseau a interrompu le téléchargement de la vidéo.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Cette vidéo n'a pas pu être chargée, soit parce que le serveur ou le réseau a échoué ou parce que le format n'est pas reconnu.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"La lecture de la vidéo a été interrompue à cause d'un problème de corruption ou parce que la vidéo utilise des fonctionnalités non prises en charge par votre navigateur.","No compatible source was found for this media.":"Aucune source compatible n'a été trouvée pour cette vidéo.","The media is encrypted and we do not have the keys to decrypt it.":"Le média est chiffré et nous n'avons pas les clés pour le déchiffrer.","Play Video":"Lire la vidéo",Close:"Fermer","Modal Window":"Fenêtre modale","This is a modal window":"Ceci est une fenêtre modale","This modal can be closed by pressing the Escape key or activating the close button.":"Ce modal peut être fermé en appuyant sur la touche Échap ou activer le bouton de fermeture.",", opens captions settings dialog":", ouvrir les paramètres des sous-titres transcrits",", opens subtitles settings dialog":", ouvrir les paramètres des sous-titres",", opens descriptions settings dialog":", ouvrir les paramètres des descriptions",", selected":", sélectionné"}},function(e,o){e.exports={Play:"Pusti",Pause:"Pauza","Current Time":"Trenutno vrijeme","Duration Time":"Vrijeme trajanja","Remaining Time":"Preostalo vrijeme","Stream Type":"Način strimovanja",LIVE:"UŽIVO",Loaded:"Učitan",Progress:"Progres",Fullscreen:"Puni ekran","Non-Fullscreen":"Mali ekran",Mute:"Prigušen",Unmute:"Ne-prigušen","Playback Rate":"Stopa reprodukcije",Subtitles:"Podnaslov","subtitles off":"Podnaslov deaktiviran",Captions:"Titlovi","captions off":"Titlovi deaktivirani",Chapters:"Poglavlja","You aborted the media playback":"Isključili ste reprodukciju videa.","A network error caused the media download to fail part-way.":"Video se prestao preuzimati zbog greške na mreži.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Video se ne može reproducirati zbog servera, greške u mreži ili je format ne podržan.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Reprodukcija videa je zaustavljenja zbog greške u formatu ili zbog verzije vašeg pretraživača.","No compatible source was found for this media.":"Nije nađen nijedan kompatibilan izvor ovog videa."}},function(e,o){e.exports={Play:"Lejátszás",Pause:"Szünet","Current Time":"Aktuális időpont","Duration Time":"Hossz","Remaining Time":"Hátralévő idő","Stream Type":"Adatfolyam típusa",LIVE:"ÉLŐ",Loaded:"Betöltve",Progress:"Állapot",Fullscreen:"Teljes képernyő","Non-Fullscreen":"Normál méret",Mute:"Némítás",Unmute:"Némítás kikapcsolva","Playback Rate":"Lejátszási sebesség",Subtitles:"Feliratok","subtitles off":"Feliratok kikapcsolva",Captions:"Magyarázó szöveg","captions off":"Magyarázó szöveg kikapcsolva",Chapters:"Fejezetek","You aborted the media playback":"Leállította a lejátszást","A network error caused the media download to fail part-way.":"Hálózati hiba miatt a videó részlegesen töltődött le.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"A videó nem tölthető be hálózati vagy kiszolgálói hiba miatt, vagy a formátuma nem támogatott.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"A lejátszás adatsérülés miatt leállt, vagy a videó egyes tulajdonságait a böngészője nem támogatja.","No compatible source was found for this media.":"Nincs kompatibilis forrás ehhez a videóhoz."}},function(e,o){e.exports={Play:"Play",Pause:"Pausa","Current Time":"Orario attuale","Duration Time":"Durata","Remaining Time":"Tempo rimanente","Stream Type":"Tipo del Streaming",LIVE:"LIVE",Loaded:"Caricato",Progress:"Stato",Fullscreen:"Schermo intero","Non-Fullscreen":"Chiudi schermo intero",Mute:"Muto",Unmute:"Audio","Playback Rate":"Tasso di riproduzione",Subtitles:"Sottotitoli","subtitles off":"Senza sottotitoli",Captions:"Sottotitoli non udenti","captions off":"Senza sottotitoli non udenti",Chapters:"Capitolo","You aborted the media playback":"La riproduzione del filmato è stata interrotta.","A network error caused the media download to fail part-way.":"Il download del filmato è stato interrotto a causa di un problema rete.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Il filmato non può essere caricato a causa di un errore nel server o nella rete o perché il formato non viene supportato.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"La riproduzione del filmato è stata interrotta a causa di un file danneggiato o per l’utilizzo di impostazioni non supportate dal browser.","No compatible source was found for this media.":"Non ci sono fonti compatibili per questo filmato."}},function(e,o){e.exports={Play:"再生",Pause:"一時停止","Current Time":"現在の時間","Duration Time":"長さ","Remaining Time":"残りの時間","Stream Type":"ストリームの種類",LIVE:"ライブ",Loaded:"ロード済み",Progress:"進行状況",Fullscreen:"フルスクリーン","Non-Fullscreen":"フルスクリーン以外",Mute:"ミュート",Unmute:"ミュート解除","Playback Rate":"再生レート",Subtitles:"サブタイトル","subtitles off":"サブタイトル オフ",Captions:"キャプション","captions off":"キャプション オフ",Chapters:"チャプター","You aborted the media playback":"動画再生を中止しました","A network error caused the media download to fail part-way.":"ネットワーク エラーにより動画のダウンロードが途中で失敗しました","The media could not be loaded, either because the server or network failed or because the format is not supported.":"サーバーまたはネットワークのエラー、またはフォーマットがサポートされていないため、動画をロードできませんでした","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"破損の問題、またはお使いのブラウザがサポートしていない機能が動画に使用されていたため、動画の再生が中止されました","No compatible source was found for this media.":"この動画に対して互換性のあるソースが見つかりませんでした"}},function(e,o){e.exports={Play:"재생",Pause:"일시중지","Current Time":"현재 시간","Duration Time":"지정 기간","Remaining Time":"남은 시간","Stream Type":"스트리밍 유형",LIVE:"라이브",Loaded:"로드됨",Progress:"진행",Fullscreen:"전체 화면","Non-Fullscreen":"전체 화면 해제",Mute:"음소거",Unmute:"음소거 해제","Playback Rate":"재생 비율",Subtitles:"서브타이틀","subtitles off":"서브타이틀 끄기",Captions:"자막","captions off":"자막 끄기",Chapters:"챕터","You aborted the media playback":"비디오 재생을 취소했습니다.","A network error caused the media download to fail part-way.":"네트워크 오류로 인하여 비디오 일부를 다운로드하지 못 했습니다.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"비디오를 로드할 수 없습니다. 서버 혹은 네트워크 오류 때문이거나 지원되지 않는 형식 때문일 수 있습니다.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"비디오 재생이 취소됐습니다. 비디오가 손상되었거나 비디오가 사용하는 기능을 브라우저에서 지원하지 않는 것 같습니다.","No compatible source was found for this media.":"비디오에 호환되지 않는 소스가 있습니다."}},function(e,o){e.exports={Play:"Spill",Pause:"Pause","Current Time":"Aktuell tid","Duration Time":"Varighet","Remaining Time":"Gjenstående tid","Stream Type":"Type strøm",LIVE:"DIREKTE",Loaded:"Lastet inn",Progress:"Status",Fullscreen:"Fullskjerm","Non-Fullscreen":"Lukk fullskjerm",Mute:"Lyd av",Unmute:"Lyd på","Playback Rate":"Avspillingsrate",Subtitles:"Undertekst på","subtitles off":"Undertekst av",Captions:"Undertekst for hørselshemmede på","captions off":"Undertekst for hørselshemmede av",Chapters:"Kapitler","You aborted the media playback":"Du avbrøt avspillingen.","A network error caused the media download to fail part-way.":"En nettverksfeil avbrøt nedlasting av videoen.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Videoen kunne ikke lastes ned, på grunn av nettverksfeil eller serverfeil, eller fordi formatet ikke er støttet.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Videoavspillingen ble avbrudt på grunn av ødelagte data eller fordi videoen ville gjøre noe som nettleseren din ikke har støtte for.","No compatible source was found for this media.":"Fant ikke en kompatibel kilde for dette mediainnholdet."}},function(e,o){e.exports={Play:"Afspelen",Pause:"Pauze","Current Time":"Huidige tijd","Duration Time":"Looptijd","Remaining Time":"Resterende tijd","Stream Type":"Streamtype",LIVE:"LIVE",Loaded:"Geladen",Progress:"Status",Fullscreen:"Volledig scherm","Non-Fullscreen":"Geen volledig scherm",Mute:"Geluid uit",Unmute:"Geluid aan","Playback Rate":"Weergavesnelheid",Subtitles:"Ondertiteling","subtitles off":"ondertiteling uit",Captions:"Bijschriften","captions off":"bijschriften uit",Chapters:"Hoofdstukken",Descriptions:"Beschrijvingen","descriptions off":"beschrijvingen off","You aborted the media playback":"U hebt de mediaweergave afgebroken.","A network error caused the media download to fail part-way.":"De mediadownload is mislukt door een netwerkfout.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"De media kon niet worden geladen, vanwege een server- of netwerkfout of doordat het formaat niet wordt ondersteund.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"De mediaweergave is afgebroken vanwege beschadigde data of het mediabestand gebruikt functies die niet door uw browser worden ondersteund.","No compatible source was found for this media.":"Voor deze media is geen ondersteunde bron gevonden.","Play Video":"Video Afspelen",Close:"Sluiten","Modal Window":"Modal Venster","This is a modal window":"Dit is een modaal venster","This modal can be closed by pressing the Escape key or activating the close button.":"Dit modaal venster kan gesloten worden door op Escape te drukken of de 'sluiten' knop te activeren.",", opens captions settings dialog":", opent bijschriften instellingen venster",", opens subtitles settings dialog":", opent ondertiteling instellingen venster",", opens descriptions settings dialog":", opent beschrijvingen instellingen venster",", selected":", selected"}},function(e,o){e.exports={Play:"Spel",Pause:"Pause","Current Time":"Aktuell tid","Duration Time":"Varigheit","Remaining Time":"Tid attende","Stream Type":"Type straum",LIVE:"DIREKTE",Loaded:"Lasta inn",Progress:"Status",Fullscreen:"Fullskjerm","Non-Fullscreen":"Stenga fullskjerm",Mute:"Ljod av",Unmute:"Ljod på","Playback Rate":"Avspelingsrate",Subtitles:"Teksting på","subtitles off":"Teksting av",Captions:"Teksting for høyrselshemma på","captions off":"Teksting for høyrselshemma av",Chapters:"Kapitel","You aborted the media playback":"Du avbraut avspelinga.","A network error caused the media download to fail part-way.":"Ein nettverksfeil avbraut nedlasting av videoen.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Videoen kunne ikkje lastas ned, på grunn av ein nettverksfeil eller serverfeil, eller av di formatet ikkje er stoda.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Videoavspelinga blei broten på grunn av øydelagde data eller av di videoen ville gjera noe som nettlesaren din ikkje stodar.","No compatible source was found for this media.":"Fant ikke en kompatibel kilde for dette mediainnholdet."}},function(e,o){e.exports={Play:"Odtwarzaj",Pause:"Pauza","Current Time":"Aktualny czas","Duration Time":"Czas trwania","Remaining Time":"Pozostały czas","Stream Type":"Typ strumienia",LIVE:"NA ŻYWO",Loaded:"Załadowany",Progress:"Status",Fullscreen:"Pełny ekran","Non-Fullscreen":"Pełny ekran niedostępny",Mute:"Wyłącz dźwięk",Unmute:"Włącz dźwięk","Playback Rate":"Szybkość odtwarzania",Subtitles:"Napisy","subtitles off":"Napisy wyłączone",Captions:"Transkrypcja","captions off":"Transkrypcja wyłączona",Chapters:"Rozdziały","You aborted the media playback":"Odtwarzanie zostało przerwane","A network error caused the media download to fail part-way.":"Problemy z siecią spowodowały błąd przy pobieraniu materiału wideo.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Materiał wideo nie może być załadowany, ponieważ wystąpił problem z siecią lub format nie jest obsługiwany","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Odtwarzanie materiału wideo zostało przerwane z powodu uszkodzonego pliku wideo lub z powodu błędu funkcji, które nie są wspierane przez przeglądarkę.","No compatible source was found for this media.":"Dla tego materiału wideo nie znaleziono kompatybilnego źródła.","Play video":"Odtwarzaj wideo",Close:"Zamknij","Modal Window":"Okno Modala","This is a modal window":"To jest okno modala","This modal can be closed by pressing the Escape key or activating the close button.":"Ten modal możesz zamknąć naciskając przycisk Escape albo wybierając przycisk Zamknij.",", opens captions settings dialog":", otwiera okno dialogowe ustawień transkrypcji",", opens subtitles settings dialog":", otwiera okno dialogowe napisów",", selected":", zaznaczone"}},function(e,o){e.exports={Play:"Tocar",Pause:"Pausar","Current Time":"Tempo","Duration Time":"Duração","Remaining Time":"Tempo Restante","Stream Type":"Tipo de Stream",LIVE:"AO VIVO",Loaded:"Carregado",Progress:"Progresso",Fullscreen:"Tela Cheia","Non-Fullscreen":"Tela Normal",Mute:"Mudo",Unmute:"Habilitar Som","Playback Rate":"Velocidade",Subtitles:"Legendas","subtitles off":"Sem Legendas",Captions:"Anotações","captions off":"Sem Anotações",Chapters:"Capítulos","You aborted the media playback":"Você parou a execução do vídeo.","A network error caused the media download to fail part-way.":"Um erro na rede fez o vídeo parar parcialmente.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"O vídeo não pode ser carregado, ou porque houve um problema com sua rede ou pelo formato do vídeo não ser suportado.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"A execução foi interrompida por um problema com o vídeo ou por seu navegador não dar suporte ao seu formato.","No compatible source was found for this media.":"Não foi encontrada fonte de vídeo compatível."}},function(e,o){e.exports={Play:"Воспроизвести",Pause:"Приостановить","Current Time":"Текущее время","Duration Time":"Продолжительность","Remaining Time":"Оставшееся время","Stream Type":"Тип потока",LIVE:"ОНЛАЙН",Loaded:"Загрузка",Progress:"Прогресс",Fullscreen:"Полноэкранный режим","Non-Fullscreen":"Неполноэкранный режим",Mute:"Без звука",Unmute:"Со звуком","Playback Rate":"Скорость воспроизведения",Subtitles:"Субтитры","subtitles off":"Субтитры выкл.",Captions:"Подписи","captions off":"Подписи выкл.",Chapters:"Главы","You aborted the media playback":"Вы прервали воспроизведение видео","A network error caused the media download to fail part-way.":"Ошибка сети вызвала сбой во время загрузки видео.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Невозможно загрузить видео из-за сетевого или серверного сбоя либо формат не поддерживается.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Воспроизведение видео было приостановлено из-за повреждения либо в связи с тем, что видео использует функции, неподдерживаемые вашим браузером.","No compatible source was found for this media.":"Совместимые источники для этого видео отсутствуют."}},function(e,o){e.exports={Play:"Pusti",Pause:"Pauza","Current Time":"Trenutno vrijeme","Duration Time":"Vrijeme trajanja","Remaining Time":"Preostalo vrijeme","Stream Type":"Način strimovanja",LIVE:"UŽIVO",Loaded:"Učitan",Progress:"Progres",Fullscreen:"Puni ekran","Non-Fullscreen":"Mali ekran",Mute:"Prigušen",Unmute:"Ne-prigušen","Playback Rate":"Stopa reprodukcije",Subtitles:"Podnaslov","subtitles off":"Podnaslov deaktiviran",Captions:"Titlovi","captions off":"Titlovi deaktivirani",Chapters:"Poglavlja","You aborted the media playback":"Isključili ste reprodukciju videa.","A network error caused the media download to fail part-way.":"Video se prestao preuzimati zbog greške na mreži.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Video se ne može reproducirati zbog servera, greške u mreži ili je format ne podržan.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Reprodukcija videa je zaustavljenja zbog greške u formatu ili zbog verzije vašeg pretraživača.","No compatible source was found for this media.":"Nije nađen nijedan kompatibilan izvor ovog videa."}},function(e,o){e.exports={Play:"Spela",Pause:"Pausa","Current Time":"Aktuell tid","Duration Time":"Total tid","Remaining Time":"Återstående tid","Stream Type":"Strömningstyp",LIVE:"LIVE",Loaded:"Laddad",Progress:"Förlopp",Fullscreen:"Fullskärm","Non-Fullscreen":"Ej fullskärm",Mute:"Ljud av",Unmute:"Ljud på","Playback Rate":"Uppspelningshastighet",Subtitles:"Text på","subtitles off":"Text av",Captions:"Text på","captions off":"Text av",Chapters:"Kapitel","You aborted the media playback":"Du har avbrutit videouppspelningen.","A network error caused the media download to fail part-way.":"Ett nätverksfel gjorde att nedladdningen av videon avbröts.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Det gick inte att ladda videon, antingen på grund av ett server- eller nätverksfel, eller för att formatet inte stöds.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Uppspelningen avbröts på grund av att videon är skadad, eller också för att videon använder funktioner som din webbläsare inte stöder.","No compatible source was found for this media.":"Det gick inte att hitta någon kompatibel källa för den här videon."}},function(e,o){e.exports={Play:"Oynat",Pause:"Duraklat","Current Time":"Süre","Duration Time":"Toplam Süre","Remaining Time":"Kalan Süre","Stream Type":"Yayın Tipi",LIVE:"CANLI",Loaded:"Yüklendi",Progress:"Yükleniyor",Fullscreen:"Tam Ekran","Non-Fullscreen":"Küçük Ekran",Mute:"Ses Kapa",Unmute:"Ses Aç","Playback Rate":"Oynatma Hızı",Subtitles:"Altyazı","subtitles off":"Altyazı Kapalı",Captions:"Ek Açıklamalar","captions off":"Ek Açıklamalar Kapalı",Chapters:"Bölümler","You aborted the media playback":"Video oynatmayı iptal ettiniz","A network error caused the media download to fail part-way.":"Video indirilirken bağlantı sorunu oluştu.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Video oynatılamadı, ağ ya da sunucu hatası veya belirtilen format desteklenmiyor.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Tarayıcınız desteklemediği için videoda hata oluştu.","No compatible source was found for this media.":"Video için kaynak bulunamadı.","Play Video":"Videoyu Oynat",Close:"Kapat","Modal Window":"Modal Penceresi","This is a modal window":"Bu bir modal penceresidir","This modal can be closed by pressing the Escape key or activating the close button.":"Bu modal ESC tuşuna basarak ya da kapata tıklanarak kapatılabilir.",", opens captions settings dialog":", ek açıklama ayarları menüsünü açar",", opens subtitles settings dialog":", altyazı ayarları menüsünü açar",", selected":", seçildi"}},function(e,o){e.exports={Play:"Відтворити",Pause:"Призупинити","Current Time":"Поточний час","Duration Time":"Тривалість","Remaining Time":"Час, що залишився","Stream Type":"Тип потоку",LIVE:"НАЖИВО",Loaded:"Завантаження",Progress:"Прогрес",Fullscreen:"Повноекранний режим","Non-Fullscreen":"Неповноекранний режим",Mute:"Без звуку",Unmute:"Зі звуком","Playback Rate":"Швидкість відтворення",Subtitles:"Субтитри","subtitles off":"Без субтитрів",Captions:"Підписи","captions off":"Без підписів",Chapters:"Розділи","You aborted the media playback":"Ви припинили відтворення відео","A network error caused the media download to fail part-way.":"Помилка мережі викликала збій під час завантаження відео.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Неможливо завантажити відео через мережевий чи серверний збій або формат не підтримується.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Відтворення відео було припинено через пошкодження або у зв'язку з тим, що відео використовує функції, які не підтримуються вашим браузером.","No compatible source was found for this media.":"Сумісні джерела для цього відео відсутні."}},function(e,o){e.exports={Play:"Phát",Pause:"Tạm dừng","Current Time":"Thời gian hiện tại","Duration Time":"Độ dài","Remaining Time":"Thời gian còn lại","Stream Type":"Kiểu Stream",LIVE:"TRỰC TIẾP",Loaded:"Đã tải",Progress:"Tiến trình",Fullscreen:"Toàn màn hình","Non-Fullscreen":"Thoát toàn màn hình",Mute:"Tắt tiếng",Unmute:"Bật âm thanh","Playback Rate":"Tốc độ phát",Subtitles:"Phụ đề","subtitles off":"Tắt phụ đề",Captions:"Chú thích","captions off":"Tắt chú thích",Chapters:"Chương","You aborted the media playback":"Bạn đã hủy việc phát media.","A network error caused the media download to fail part-way.":"Một lỗi mạng dẫn đến việc tải media bị lỗi.","The media could not be loaded, either because the server or network failed or because the format is not supported.":"Video không tải được, mạng hay server có lỗi hoặc định dạng không được hỗ trợ.","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"Phát media đã bị hủy do một sai lỗi hoặc media sử dụng những tính năng trình duyệt không hỗ trợ.","No compatible source was found for this media.":"Không có nguồn tương thích cho media này."}},function(e,o){e.exports={Play:"播放",Pause:"暂停","Current Time":"当前时间","Duration Time":"时长","Remaining Time":"剩余时间","Stream Type":"媒体流类型",LIVE:"直播",Loaded:"加载完毕",Progress:"进度",Fullscreen:"全屏","Non-Fullscreen":"退出全屏",Mute:"静音",Unmute:"取消静音","Playback Rate":"播放码率",Subtitles:"字幕","subtitles off":"字幕关闭",Captions:"内嵌字幕","captions off":"内嵌字幕关闭",Chapters:"节目段落","You aborted the media playback":"视频播放被终止","A network error caused the media download to fail part-way.":"网络错误导致视频下载中途失败。","The media could not be loaded, either because the server or network failed or because the format is not supported.":"视频因格式不支持或者服务器或网络的问题无法加载。","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"由于视频文件损坏或是该视频使用了你的浏览器不支持的功能,播放终止。","No compatible source was found for this media.":"无法找到此视频兼容的源。","The media is encrypted and we do not have the keys to decrypt it.":"视频已加密,无法解密。"}},function(e,o){e.exports={Play:"播放",Pause:"暫停","Current Time":"目前時間","Duration Time":"總共時間","Remaining Time":"剩餘時間","Stream Type":"串流類型",LIVE:"直播",Loaded:"載入完畢",Progress:"進度",Fullscreen:"全螢幕","Non-Fullscreen":"退出全螢幕",Mute:"靜音",Unmute:"取消靜音","Playback Rate":" 播放速率",Subtitles:"字幕","subtitles off":"關閉字幕",Captions:"內嵌字幕","captions off":"關閉內嵌字幕",Chapters:"章節","You aborted the media playback":"影片播放已終止","A network error caused the media download to fail part-way.":"網路錯誤導致影片下載失敗。","The media could not be loaded, either because the server or network failed or because the format is not supported.":"影片因格式不支援或者伺服器或網路的問題無法載入。","The media playback was aborted due to a corruption problem or because the media used features your browser did not support.":"由於影片檔案損毀或是該影片使用了您的瀏覽器不支援的功能,播放終止。","No compatible source was found for this media.":"無法找到相容此影片的來源。","The media is encrypted and we do not have the keys to decrypt it.":"影片已加密,無法解密。"}},,,function(e,o){}]),[130]);
//# sourceMappingURL=app.e50be079437edf6ed3fd.js.map |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
profile_photo = models.ImageField(upload_to = 'profile/', null=True)
editor = models.ForeignKey(User,on_delete=models.CASCADE, null=True)
bio = models.TextField(null=True)
def save_profile(self):
self.save()
@classmethod
def save_profile(cls):
posts=cls.objects.filter()
return posts
def update_profile(self):
self.update()
def delete_profile():
self.delete()
class Comment(models.Model):
comment = models.TextField()
editor = models.ForeignKey(User,on_delete=models.CASCADE, null=True)
def save_comment(self):
self.save()
@classmethod
def save_comment(cls):
comment=cls.objects.filter()
return comment
class Image(models.Model):
image = models.ImageField(upload_to = 'image/', null=True)
name = models.CharField(max_length = 60)
caption = models.TextField(null=True)
likes = models.IntegerField(null=True)
editor = models.ForeignKey(User,on_delete=models.CASCADE, null=True)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
comment = models.ForeignKey(Comment, on_delete=models.CASCADE, null=True)
pub_date = models.DateTimeField(auto_now_add=True, null=True)
def save_image(self):
self.save()
@classmethod
def save_image(cls):
photos=cls.objects.filter()
return photos
@classmethod
def search_by_name(cls,search_term):
photos = cls.objects.filter(name__icontains=search_term)
return photos
def update_image(self):
self.update()
def delete_image():
self.delete()
|
/**
* @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'codesnippet', 'zh-cn', {
button: '插入代码段',
codeContents: '代码内容',
emptySnippetError: '插入的代码不能为空。',
language: '代码语言',
title: '代码段',
pathName: '代码段'
} );
|
/* eslint-env node */
/* eslint-disable func-style */
'use strict';
const gulp = require('gulp');
const $ = require('gulp-load-plugins')();
const del = require('del');
const rollup = require('rollup').rollup;
const composer = require('gulp-uglify/composer');
const uglify = composer(require('terser'), console);
const escapeStringRegexp = require('escape-string-regexp');
const operators = require('glsl-tokenizer/lib/operators');
const SPACES_AROUND_OPERATORS_REGEX = new RegExp(
`\\s*(${operators.map(escapeStringRegexp).join('|')})\\s*`,
'g',
);
gulp.task('clean', () => del(['build', 'dist']));
// https://github.com/mrdoob/three.js/blob/dev/rollup.config.js
function glsl() {
function minify(code) {
return (
code
// Remove //
.replace(/\s*\/\/.*\n/g, '')
// Remove /* */
.replace(/\s*\/\*[\s\S]*?\*\//g, '')
// # \n+ to \n
.replace(/\n{2,}/g, '\n')
// Remove tabs and consecutive spaces with a single space
.replace(/\s{2,}|\t/g, ' ')
.split('\n')
.map((line, index, array) => {
line = line.trim();
// Remove spaces around operators if not an #extension directive.
// For example, #extension GL_OES_standard_derivatives : enable.
if (!line.startsWith('#extension')) {
line = line.replace(SPACES_AROUND_OPERATORS_REGEX, '$1');
}
// Append newlines after preprocessor directives.
if (line[0] === '#') {
line += '\n';
// Append newlines before the start of preprocessor directive blocks.
if (index > 0) {
if (array[index - 1][0] !== '#') {
line = '\n' + line;
}
}
}
return line;
})
.join('')
);
}
return {
transform(code, id) {
if (!id.endsWith('.glsl.js')) {
return;
}
const startIndex = code.indexOf('`');
const prefix = code.slice(0, startIndex);
const endIndex = code.lastIndexOf('`');
const glslString = code.slice(startIndex + 1, endIndex - 1).trim();
return {
code: `${prefix}\`${minify(glslString)}\``,
map: { mappings: '' },
};
},
};
}
gulp.task('rollup', () => {
return (
rollup({
input: 'src/index.js',
plugins: [glsl()],
})
.then(bundle =>
bundle.write({
file: 'build/bundle.js',
format: 'iife',
}),
)
// eslint-disable-next-line no-console
.catch(error => console.error(error))
);
});
gulp.task('uglify', () => {
return gulp
.src('build/bundle.js')
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
gulp.task('js', gulp.series('rollup', 'uglify'));
gulp.task('html', () => {
return gulp
.src('./index.html')
.pipe(
$.htmlmin({
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true,
minifyCSS: true,
}),
)
.pipe($.replace('./src/index.js', './bundle.js'))
.pipe(gulp.dest('dist'));
});
gulp.task('build', gulp.series('clean', gulp.parallel('html', 'js')));
gulp.task('compress', () => {
return gulp
.src('dist/**/*')
.pipe($.zip('build.zip'))
.pipe($.size())
.pipe($.size({ pretty: false }))
.pipe(gulp.dest('build'));
});
gulp.task('dist', gulp.series('build', 'compress'));
|
function my_function316(){
//38071484443691339429956102913721cmiqQvciVfEHICSAxxTifeeyxXoUvdmy
}
function my_function030(){
//22318346551079441304681658449989kWfZTsoiucrTtfElGTuZxMwyGXkwndSs
}
function my_function853(){
//87026069060937759004129989496364ufKPhWjTkfjVlBjaImyybVSEyiWaOQyM
}
function my_function359(){
//11500010997255227292253168125803AsDZTQLscjhOrsgDbdudLQhzqbuPNuyH
}
function my_function179(){
//53569145413017552643856999993350NYFeftJURdmTqKqDuuBFydodmkIzSsys
}
function my_function747(){
//70381989617572903075860832827001ExyQPbpAPNBQtFvrfFVSddpMUtXUOuiC
}
function my_function151(){
//59241080306217558966012924554770ICnnzzCYoWOUOIpYTQWWFrRrGLNvmNOt
}
function my_function510(){
//42520570549756373701159966689900CJJAqvTSjFNMlwnmAznfdxuVDRXlLeZG
}
function my_function829(){
//13457831646841750920841903584827lYpBoQwBTcIBtZbERILJPqqFFmKpjvlG
}
function my_function647(){
//87126781935023403297442488491689TXFmkGGYEFWCxqlFihcRpbndSLOFYvyq
}
function my_function699(){
//54886725466164338105046696628080YixXNJiScuQYJWowrjuRCMnMUfRHgaJU
}
function my_function134(){
//63601007279768261664986978762538BsvCTDDyhADUipNLGuagqJxDKwWiHDyT
}
function my_function734(){
//93765102486989682312632157156068UkzxIWefVgkYqqdoFZjHfpXvUqnqnCQX
}
function my_function365(){
//42990482945705441930873235277902smeezOhVHnwhCsjvgbKnDvmITBfroDXE
}
function my_function566(){
//06035027479867531489081786069211uRffjdNLzTnRtaiVPfJrjueqUiPIxodY
}
function my_function986(){
//24719566799596722512491001919335WguKhxGfXyTFhKfIxzQEEoSCInZsMXLv
}
function my_function126(){
//44569951682476816064308371230772UMvVfpVsEchwzogpuBYJTNkhrKLHTPjz
}
function my_function450(){
//35152189646281745304806643430608jlwkLkdhgzjoBlLrZnORkoMZPxYSibUc
}
function my_function625(){
//89376762304506159880505989212664zfNeEwKYZLvlZMRkHSAZdDJHlufoWfeG
}
function my_function877(){
//14838085022495033088934079253140NDhyFKmlSoCdkLCMNmcaDAStibzZPDKY
}
function my_function468(){
//43658513301582221817176787106943StoqIRRzmGGKQpnUciiLbPZYWwUMnpsI
}
function my_function396(){
//93924592893693076107691576790858eLNeIclgBWcdnuNksyPRYrcNkbciEgvj
}
function my_function572(){
//99673351499616202185135758376810WVLcnwVNTAkTwcrNCxPDbnTzyJuQPUlr
}
function my_function900(){
//05957913967087722646385083586627YEOxDGMOFnxYcJYcYzkiparAvUZIphOm
}
function my_function831(){
//20432541754565065333243004777272VWpCMaEhlYcjtWHpZFisLBiEaiyYbjao
}
function my_function808(){
//56047183090207823759493860176958wuQTkWSnkNpGNPxHOaqPxyQYzxYZUKmC
}
function my_function360(){
//21438716783479645381192432186560oBUnxuUNLhvTIlpcvTanjUFxLoVxEyvc
}
|
import csv
import os
import cv2
import numpy as np
from keras.models import Sequential
from keras.layers import Flatten, Dense, Lambda, Conv2D, Cropping2D
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from math import ceil
import random
import sklearn
DATA_LOCATION = '../udacity_data/'
def get_samples():
"""
Get training and validation data
driving_log.csv contains the udacity provided data
driving_log_shiv.csv' contains data I generated by running the simulator
on track 1.
Params:
----------
n/a
Returns
----------
train_samples : list of strings
filenames of training samples
validation_samples : list of strings
filenames of validation samples
"""
samples = []
for datafile in ['driving_log.csv', 'driving_log_shiv.csv']:
with open(os.path.join(DATA_LOCATION, datafile)) as csvfile:
reader = csv.reader(csvfile)
next(reader, None)
for line in reader:
samples.append(line)
train_samples, validation_samples = train_test_split(samples, test_size=0.2)
return train_samples, validation_samples
def generator(samples, batch_size=32):
"""
Coroutine to generate samples for keras' model fit function
Note: Yields 6*batch_size samples at a time. For each "sample" in the batch
images are loaded from the right, left, and center cameras. For each of
these images their flipped counterparts are appended as well. Thus 6x the
data is generated from a single image.
Params:
----------
samples: list of strings
filenames of all images from which to draw batches
batch_size: int
desired batch size, default 32
Returns (yields)
----------
XX: np.array of shape (batch_size*6, 160, 320, 3)
collection of images
yy: np.array of shape (batch_size*6)
labels corresponding to images held in XX
"""
num_samples = len(samples)
while 1: # Loop forever so the generator never terminates
random.shuffle(samples)
for offset in range(0, num_samples, batch_size):
batch_samples = samples[offset:offset+batch_size]
images = []
measurements = []
for batch_sample in batch_samples:
for source_path in batch_sample[0:3]:
source_path = batch_sample[0]
filename = source_path.split('/')[-1]
check_dirs = [os.path.join(DATA_LOCATION, 'IMG' ,filename),
os.path.join(DATA_LOCATION, 'IMG_shiv' ,filename)]
current_path = None
for check_dir in check_dirs:
if os.path.exists(check_dir):
current_path = check_dir
image = cv2.imread(current_path)
measurement = float(batch_sample[3]) # steering angle measurement
# Use the left and right cameras to generate additional data
# Add a correction factor so the car steers away from the edges of the road
if 'left' in filename:
measurement += 0.2
elif 'right' in filename:
measurement -= 0.2
images.append(image)
measurements.append(measurement)
# add a flipped version of the image for further data augmentation
# flip the steering angle as well
image_flipped = np.fliplr(image)
images.append(image_flipped)
measurements.append(-measurement)
XX = np.array(images)
yy = np.array(measurements)
yield sklearn.utils.shuffle(XX, yy)
def get_model():
"""
Implement model similar to the one used by NVIDIA in their paper
"End to End Learning for Self-Driving Cars".
Params:
----------
n/a
Returns
----------
train_samples : keras.Model()
final model architecture
"""
model = Sequential()
model.add(Lambda(lambda x: x / 255.0 - 0.5, input_shape=(160,320,3)))
model.add(Cropping2D(cropping=((70,25),(0,0))))
model.add(Conv2D(24,5,strides=(2,2),activation="relu"))
model.add(Conv2D(36,5,strides=(2,2),activation="relu"))
model.add(Conv2D(48,5,strides=(2,2),activation="relu"))
model.add(Conv2D(64,3,activation="relu"))
model.add(Conv2D(64,3,activation="relu"))
model.add(Flatten())
model.add(Dense(100))
model.add(Dense(50))
model.add(Dense(10))
model.add(Dense(1))
model.compile(loss='mse', optimizer='adam')
model.summary()
return model
def train_and_save_model(model, train_samples, validation_samples):
"""
Train and save model. Save picture of loss curves.
Params:
----------
model: keras.Model()
model to train!
train_samples : list of strings
filenames of training samples
validation_samples : list of strings
filenames of validation samples
Returns
----------
n/a
"""
batch_size = 32
train_generator = generator(train_samples, batch_size=batch_size)
validation_generator = generator(validation_samples, batch_size=batch_size)
history_object = model.fit_generator(train_generator, steps_per_epoch=ceil(len(train_samples)/batch_size),
validation_data=validation_generator,
validation_steps=ceil(len(validation_samples)/batch_size),
epochs=5, verbose=1)
model.save('model_data_augmentation.h5')
plt.plot(history_object.history['loss'])
plt.plot(history_object.history['val_loss'])
plt.title('model mean squared error loss')
plt.ylabel('mean squared error loss')
plt.xlabel('epoch')
plt.legend(['training set', 'validation set'], loc='upper right')
plt.savefig('loss.png')
if __name__ == '__main__':
train_samples, validation_samples = get_samples()
model = get_model()
random.seed(1234)
train_and_save_model(model, train_samples, validation_samples)
|
import {Area} from '../../path.ux/scripts/screen/ScreenArea.js';
import {STRUCT} from '../../core/struct.js';
import {Container} from '../../path.ux/scripts/core/ui.js';
import {Editor} from '../editor_base.js';
import {PackFlags, UIBase, saveUIData, loadUIData} from '../../path.ux/scripts/core/ui_base.js';
import {ShiftLayerOrderOp} from '../viewport/spline_editops.js';
import {AddLayerOp, DeleteLayerOp, ChangeLayerOp, ChangeElementLayerOp} from '../viewport/spline_layerops.js';
import '../../path.ux/scripts/widgets/ui_table.js';
import '../../path.ux/scripts/widgets/ui_menu.js';
import '../../path.ux/scripts/widgets/ui_listbox.js';
import {LastToolPanel} from '../../path.ux/scripts/widgets/ui_lasttool.js';
import {TPropFlags} from '../../core/toolprops.js';
export class MyLastToolPanel extends LastToolPanel {
getToolStackHead(ctx) {
return ctx.toolstack.head;
}
buildTool(ctx, tool, container) {
for (let k in tool.inputs) {
let prop = tool.inputs[k];
if (prop.flag & TPropFlags.PRIVATE) {
continue;
}
let apiname = prop.apiname || k;
let path = "last_tool." + apiname;
container.prop(path);
}
}
static define() {return {
tagname : 'last-tool-panel-fairmotion-x'
}}
}
UIBase.register(MyLastToolPanel);
function list(iter) {
let ret = [];
for (let item of iter) {
ret.push(item);
}
return ret;
}
class LayerPanel extends Container {
last_active_id : number
do_rebuild : number
delayed_recalc : number;
constructor(ctx) {
super(ctx);
//this.last_spline_path = "";
this.last_total_layers = this.last_active_id = 0;
this.do_rebuild = 1;
this.delayed_recalc = 0;
}
init() {
super.init();
}
update() {
if (this.do_rebuild) {
this.rebuild();
return;
}
super.update();
if (this.ctx == undefined) return;
var spline = this.ctx.frameset.spline;
var do_rebuild = spline.layerset.length != this.last_total_layers;
//do_rebuild = do_rebuild || this.last_spline_path != this.ctx.splinepath;
do_rebuild = do_rebuild || spline.layerset.active.id != this.last_active_id;
this.do_rebuild |= do_rebuild;
if (this.delayed_recalc > 0) {
this.delayed_recalc--;
this.update();
}
}
rebuild() {
if (this.ctx == undefined) return;
this.do_rebuild = false;
console.log("layers ui rebuild!");
var spline = this.ctx.frameset.spline;
//this.last_spline_path = this.ctx.splinepath;
this.last_total_layers = spline.layerset.length;
this.last_active_id = spline.layerset.active.id;
for (let child of this.childNodes) {
child.remove();
}
for (let child of this.shadow.childNodes) {
child.remove();
}
for (let child of this.children) {
child.remove();
}
this.label("Layers");
let listbox = this.listbox();
for (var i=spline.layerset.length-1; i>= 0; i--) {
var layer = spline.layerset[i];
let row = listbox.addItem(layer.name, layer.id);
console.log("Adding item", layer.name);
//list.add_item(layer.name, layer.id);
}
if (spline.layerset.active !== undefined) {
listbox.setActive(spline.layerset.active.id);
}
listbox.onchange = (id, item) => {
var layer = spline.layerset.idmap[id];
if (layer == undefined) {
console.log("Error!", arguments);
return;
}
console.log("Changing layers!", id);ChangeLayerOp
g_app_state.toolstack.exec_tool(new ChangeLayerOp(id));
}
let row = this.row();
row.iconbutton(Icons.SMALL_PLUS, "Add Layer", () => {
g_app_state.toolstack.exec_tool(new AddLayerOp());
this.rebuild();
}, undefined);
row.iconbutton(Icons.SCROLL_UP, "Move Up", () => {
console.log("Shift layers up");
var ctx = new Context(), spline = ctx.frameset.spline;
var layer = spline.layerset.active;
var tool = new ShiftLayerOrderOp(layer.id, 1);
g_app_state.toolstack.exec_tool(tool);
this.rebuild();
}, undefined);
row.iconbutton(Icons.SCROLL_DOWN, "Move Down", () => {
console.log("Shift layers down");
var ctx = new Context(), spline = ctx.frameset.spline;
var layer = spline.layerset.active;
var tool = new ShiftLayerOrderOp(layer.id, -1);
g_app_state.toolstack.exec_tool(tool);
this.rebuild();
}, undefined);
row.iconbutton(Icons.SMALL_MINUS, "Remove Layer", () => {
var tool = new DeleteLayerOp();
var layer = this.ctx.spline.layerset.active;
if (layer == undefined)
return;
tool.inputs.layer_id.set_data(layer.id);
g_app_state.toolstack.exec_tool(tool);
this.rebuild();
}, undefined);
row = this.row();
row.button("Move Up", () => {
var lset = this.ctx.frameset.spline.layerset;
var oldl = lset.active;
console.log("oldl", oldl);
if (oldl.order === lset.length-1) return;
var newl = lset[oldl.order+1];
var tool = new ChangeElementLayerOp(oldl.id, newl.id);
this.ctx.toolstack.execTool(tool);
});
row.button("Move Down", () => {
var lset = this.ctx.frameset.spline.layerset;
var oldl = lset.active;
console.log("oldl", oldl);
if (oldl.order == 0) return;
var newl = lset[oldl.order-1];
var tool = new ChangeElementLayerOp(oldl.id, newl.id);
this.ctx.toolstack.execTool(tool);
});
row.prop('frameset.drawspline.active_layer.flag[HIDE]');
row.prop('frameset.drawspline.active_layer.flag[CAN_SELECT]');
this.flushUpdate();
}
_old() {
return;
var controls = this.col();
var add = new UIButtonIcon(this.ctx, "Add");
var del = new UIButtonIcon(this.ctx, "Delete");
add.icon = Icons.SMALL_PLUS;
del.icon = Icons.SMALL_MINUS;
var this2 = this;
add.callback = function() {
g_app_state.toolstack.exec_tool(new AddLayerOp());
}
del.callback = function() {
var tool = new DeleteLayerOp();
var layer = this.ctx.spline.layerset.active;
if (layer == undefined)
return;
tool.inputs.layer_id.set_data(layer.id);
g_app_state.toolstack.exec_tool(tool);
}
var up = new UIButtonIcon(this.ctx, "Up", 30);
var down = new UIButtonIcon(this.ctx, "Down", 29);
up.icon = Icons.SCROLL_UP;
down.icon = Icons.SCROLL_DOWN;
var this2 = this;
down.callback = function() {
console.log("Shift layers down");
var ctx = new Context(), spline = ctx.frameset.spline;
var layer = spline.layerset.active;
var tool = new ShiftLayerOrderOp(layer.id, -1);
g_app_state.toolstack.exec_tool(tool);
this2.rebuild();
}
up.callback = function() {
console.log("Shift layers up");
var ctx = new Context(), spline = ctx.frameset.spline;
var layer = spline.layerset.active;
var tool = new ShiftLayerOrderOp(layer.id, 1);
g_app_state.toolstack.exec_tool(tool);
this2.rebuild();
}
this.controls = {
add : add,
del : del,
up : up,
down : down
};
for (var k in this.controls) {
controls.add(this.controls[k]);
}
var list = this.list = new UIListBox();
list.size = [200, 250];
this.add(list);
for (var i=spline.layerset.length-1; i>= 0; i--) {
var layer = spline.layerset[i];
list.add_item(layer.name, layer.id);
}
list.set_active(spline.layerset.active.id);
list.callback = function(list, text, id) {
var layer = spline.layerset.idmap[id];
if (layer == undefined) {
console.log("Error!", arguments);
return;
}
console.log("Changing layers!");
g_app_state.toolstack.exec_tool(new ChangeLayerOp(id));
}
var controls2 = this.col();
let selup = new UIButton(this.ctx, "Sel Up");
let seldown = new UIButton(this.ctx, "Sel Down");
controls2.add(selup);
controls2.add(seldown);
var this2 = this;
selup.callback = function() {
var lset = this2.ctx.frameset.spline.layerset;
var oldl = lset.active;
console.log("oldl", oldl);
if (oldl.order == lset.length-1) return;
var newl = lset[oldl.order+1];
var tool = new ChangeElementLayerOp(oldl.id, newl.id);
g_app_state.toolstack.exec_tool(tool);
}
seldown.callback = function() {
var lset = this2.ctx.frameset.spline.layerset;
var oldl = lset.active;
console.log("oldl", oldl);
if (oldl.order == 0) return;
var newl = lset[oldl.order-1];
var tool = new ChangeElementLayerOp(oldl.id, newl.id);
g_app_state.toolstack.exec_tool(tool);
}
var controls3 = this.col();
controls3.prop('frameset.drawspline.active_layer.flag');
this.delayed_recalc = 4;
}
static define() {return {
tagname : "layerpanel-x"
}}
};
UIBase.register(LayerPanel);
export class MaterialEditor extends Editor {
constructor() {
super();
this._last_toolmode = undefined;
this.define_keymap();
}
init() {
if (this.ctx === undefined) {
//this.ctx = g_app_state.screen.ctx;
//XXX eek!
this.ctx = new Context();
}
super.init();
this.useDataPathUndo = true;
this.inner = this.container.col();
this.makeToolbars();
this.setCSS();
}
setCSS() {
super.setCSS();
this.style["background-color"] = this.getDefault("DefaultPanelBG");
}
update() {
super.update();
if (!this.ctx || !this.ctx.toolmode) {
return;
}
let name = this.ctx.toolmode.constructor.name;
if (name !== this._last_toolmode) {
this._last_toolmode = name;
console.warn("Rebuilding properties editor");
this.rebuild();
}
}
rebuild() {
let data = saveUIData(this.container, "properties");
this.makeToolbars();
loadUIData(this, data);
this.flushUpdate();
this.flushUpdate();
}
makeToolbars() {
let row = this.inner;
row.clear();
let tabs = row.tabs("right");
//tabs.style["width"] = "300px";
//tabs.style["height"] = "400px";
tabs.float(1, 35*UIBase.getDPI(), 7);
let tab = tabs.tab("Workspace");
let toolmode = this.ctx.toolmode;
if (toolmode) {
toolmode.constructor.buildProperties(tab);
}
this.strokePanel(tabs);
this.fillPanel(tabs);
this.layersPanel(tabs);
this.vertexPanel(tabs);
this.lastToolPanel(tabs);
this.update();
}
lastToolPanel(tabs : TabContainer) {
let tab = tabs.tab("Most Recent Command");
let panel = document.createElement("last-tool-panel-fairmotion-x");
tab.add(panel);
}
fillPanel(tabs : TabContainer) {
var ctx = this.ctx;
let panel = tabs.tab("Fill");
let panel2 = panel.panel("Fill Color");
//panel.packflag |= PackFlags.INHERIT_WIDTH;
//panel.packflag |= PackFlags.NO_AUTO_SPACING;
//panel.packflag |= PackFlags.IGNORE_LIMIT;
//"spline.faces{($.flag & 1) && !$.hidden}.fillcolor"
panel2.prop("spline.active_face.mat.fillcolor", undefined,
"spline.editable_faces{(ctx.spline.layerset.active.id in $.layers) && ($.flag & 1) && !$.hidden}.mat.fillcolor");
panel.prop("spline.active_face.mat.blur", undefined,
"spline.editable_faces{(ctx.spline.layerset.active.id in $.layers) && ($.flag & 1) && !$.hidden}.mat.blur");
return panel
}
strokePanel(tabs : TabContainer) {
let panel = tabs.tab("Stroke");
var ctx = this.ctx;
//panel.packflag |= PackFlags.INHERIT_WIDTH;
//panel.packflag |= PackFlags.NO_AUTO_SPACING;
//panel.packflag |= PackFlags.IGNORE_LIMIT;
//let ctxcode = "(ctx.edit_all_layers || ctx.spline.layerset.active.id in $.layers)"
//var set_prefix = `spline.segments[{${ctxcode} && ($.flag & 1) && !$.hidden}]`;
let set_prefix = `spline.segments[{$.editable}]`;
//panel.label("Stroke Color");
let panel2 = panel.panel("Stroke Color");
panel2.prop("spline.active_segment.mat.strokecolor", undefined,
set_prefix + ".mat.strokecolor");
panel.prop("spline.active_segment.mat.linewidth", undefined,
set_prefix + ".mat.linewidth");
panel.prop("spline.active_segment.mat.blur", undefined,
set_prefix + ".mat.blur");
panel.prop("spline.active_segment.renderable", undefined,
set_prefix + ".mat.renderable");
panel.prop("spline.active_segment.mat.flag[MASK_TO_FACE]", undefined,
set_prefix + ".mat.flag[MASK_TO_FACE]");
panel2 = panel2.panel("Double Stroking");
panel2.prop("spline.active_segment.mat.strokecolor2", undefined,
set_prefix + ".mat.strokecolor2");
panel2.prop("spline.active_segment.mat.linewidth2", undefined,
set_prefix + ".mat.linewidth2");
panel2 = panel.panel("Vertex Width");
panel2.prop("spline.active_vertex.width", undefined, set_prefix+".width");
panel2.prop("spline.active_vertex.shift", undefined, set_prefix+".shift");
panel2 = panel.panel("Segment Width");
panel2.prop("spline.active_segment.w1", undefined, set_prefix + ".w1");
panel2.prop("spline.active_segment.w2", undefined, set_prefix + ".w2");
panel2.prop("spline.active_segment.shift1", undefined, set_prefix + ".shift1");
panel2.prop("spline.active_segment.shift2", undefined, set_prefix + ".shift2");
return panel
}
layersPanel(tabs : TabContainer) {
var ctx = this.ctx;
var panel = tabs.tab("Layers");
panel.add(document.createElement("layerpanel-x"));
//return new LayerPanel(new Context());
}
vertexPanel(tabs : TabContainer) {
let ctx = this.ctx;
let tab = tabs.tab("Control Point");
let set_prefix = "spline.verts[{(ctx.spline.layerset.active.id in $.layers) && ($.flag & 1) && !$.hidden}]";
let panel = tab.panel("Vertex");
panel.prop("spline.active_vertex.flag[BREAK_TANGENTS]", undefined, set_prefix + ".flag[BREAK_TANGENTS]");
panel.prop("spline.active_vertex.flag[BREAK_CURVATURES]", undefined, set_prefix + ".flag[BREAK_CURVATURES]");
panel.prop("spline.active_vertex.flag[USE_HANDLES]", undefined, set_prefix + ".flag[USE_HANDLES]");
panel.prop("spline.active_vertex.flag[GHOST]", undefined, set_prefix + ".flag[GHOST]");
panel.prop("spline.active_vertex.width", undefined, set_prefix+".width");
panel.prop("spline.active_vertex.shift", undefined, set_prefix+".shift");
panel = tab.panel("Animation Settings")
set_prefix = "frameset.keypaths{$.animflag & 8}";
panel.prop("frameset.active_keypath.animflag[STEP_FUNC]", undefined, set_prefix + ".animflag[STEP_FUNC]");
return panel;
}
define_keymap() {
let k = this.keymap;
}
copy() {
return document.createElement("material-editor-x");
}
static define() { return {
tagname : "material-editor-x",
areaname : "material_editor",
uiname : "Properties",
icon : Icons.MATERIAL_EDITOR
}}
}
MaterialEditor.STRUCT = STRUCT.inherit(MaterialEditor, Area) + `
}
`;
Editor.register(MaterialEditor);
|
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Retrieval of HTTP character set information.
"""
import unittest
from zope.publisher.http import HTTPCharsets
class HTTPCharsetTest(unittest.TestCase):
def testGetPreferredCharset(self):
request = {'HTTP_ACCEPT_CHARSET':
'ISO-8859-1, UTF-8;q=0.66, UTF-16;q=0.33'}
browser_charsets = HTTPCharsets(request)
self.assertEqual(list(browser_charsets.getPreferredCharsets()),
['utf-8', 'iso-8859-1', 'utf-16'])
def testGetPreferredCharsetOrdering(self):
# test that the charsets are returned sorted according to
# their "quality value"
request = {'HTTP_ACCEPT_CHARSET':
'ISO-8859-1, UTF-16;Q=0.33, UTF-8;q=0.66'}
browser_charsets = HTTPCharsets(request)
self.assertEqual(list(browser_charsets.getPreferredCharsets()),
['utf-8', 'iso-8859-1', 'utf-16'])
def testGetPreferredCharsetBogusQuality(self):
# test that handling of bogus "quality values" and non-quality
# parameters is reasonable
request = {'HTTP_ACCEPT_CHARSET':
'ISO-8859-1;x, UTF-16;Q=0.33, UTF-8;q=foo'}
browser_charsets = HTTPCharsets(request)
self.assertEqual(list(browser_charsets.getPreferredCharsets()),
['iso-8859-1', 'utf-16'])
def testNoStar(self):
request = {'HTTP_ACCEPT_CHARSET': 'utf-16;q=0.66'}
browser_charsets = HTTPCharsets(request)
self.assertEqual(list(browser_charsets.getPreferredCharsets()),
['iso-8859-1', 'utf-16'])
def testStarNoUtf8(self):
# If '*' is in HTTP_ACCEPT_CHARSET, but 'utf-8' isn't, we insert
# utf-8 in the list, since we prefer that over any other #
# charset.
request = {'HTTP_ACCEPT_CHARSET': 'ISO-8859-1, *'}
browser_charsets = HTTPCharsets(request)
self.assertEqual(list(browser_charsets.getPreferredCharsets()),
['utf-8', 'iso-8859-1', '*'])
def testStarAndUtf8(self):
# If '*' and 'utf-8' are in HTTP_ACCEPT_CHARSET, we won't insert
# an extra 'utf-8'.
request = {'HTTP_ACCEPT_CHARSET': 'ISO-8859-1, utf-8, *'}
browser_charsets = HTTPCharsets(request)
self.assertEqual(list(browser_charsets.getPreferredCharsets()),
['utf-8', 'iso-8859-1', '*'])
def testNoHTTP_ACCEPT_CHARSET(self):
# If the client doesn't provide a HTTP_ACCEPT_CHARSET, it can
# accept any charset.
request = {}
browser_charsets = HTTPCharsets(request)
self.assertEqual(list(browser_charsets.getPreferredCharsets()),
['utf-8'])
def testTrivialHTTP_ACCEPT_CHARSET(self):
# If the client provides a trivial HTTP_ACCEPT_CHARSET, it can
# accept any charset
request = {'HTTP_ACCEPT_CHARSET': ''}
browser_charsets = HTTPCharsets(request)
self.assertEqual(list(browser_charsets.getPreferredCharsets()),
['utf-8'])
def testMalformedHTTP_ACCEPT_CHARSET(self):
"""Test for Launchpad #253362."""
request = {
'HTTP_ACCEPT_CHARSET': 'utf-8;q=0.7,iso-8859-1;q=0.2*;q=0.1'}
browser_charsets = HTTPCharsets(request)
self.assertEqual(list(browser_charsets.getPreferredCharsets()),
['utf-8', 'iso-8859-1'])
def test_suite():
loader = unittest.TestLoader()
return loader.loadTestsFromTestCase(HTTPCharsetTest)
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.locationSchema = exports.jobcategorySchema = void 0;
const mongoose = require("mongoose");
var autoIncrement = require('mongoose-auto-increment');
exports.jobcategorySchema = new mongoose.Schema({
jobcateoryId: String,
jobcateory: String,
});
exports.locationSchema = new mongoose.Schema({
locationId: String,
country: String,
state: String,
});
//# sourceMappingURL=job-categories.schema.js.map |
class ListViewItemMouseHoverEventArgs(EventArgs):
"""
Provides data for the System.Windows.Forms.ListView.ItemMouseHover event.
ListViewItemMouseHoverEventArgs(item: ListViewItem)
"""
def __getitem__(self, *args):
""" x.__getitem__(y) <==> x[y] """
pass
@staticmethod
def __new__(self, item):
""" __new__(cls: type,item: ListViewItem) """
pass
Item = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Gets the item the mouse pointer is currently hovering over.
Get: Item(self: ListViewItemMouseHoverEventArgs) -> ListViewItem
"""
|
$(document).ready(function(){adminInit("Nuova tratta","Modifica tratta","xhr_tratte","xhr_elimina_tratte","Tratte eliminate");$("#a_partenza,#a_arrivo").select2({dropdownParent:$("#exampleModal"),ajax:{url:__site_url+"/"+__xhr_controller+"/xhr_search_aeroporto",dataType:"json",delay:250,data:function(a){return{q:a.term}},processResults:function(c,b){var a=[];$.each(c,function(e,d){var f={};f.id=d.sigla;f.name=d.nome;f.value=d.sigla;f.citta=d.nome_citta;f.paese=d.nome_paese;f.code2=d.code2;a.push(f)});return{results:a}},cache:true},placeholder:"Seleziona un aeroporto",escapeMarkup:function(a){return a},minimumInputLength:2,templateResult:formatAeroporto,templateSelection:function(a){return a.name||a.text}});$("#compagnia").select2({dropdownParent:$("#exampleModal"),ajax:{url:__site_url+"/"+__xhr_controller+"/xhr_search_compagnia",dataType:"json",delay:250,data:function(a){return{q:a.term}},processResults:function(c,b){var a=[];$.each(c,function(e,d){var f={};f.id=d.id;f.name=d.nome;f.value=d.id;f.paese=d.paese;f.code2=d.code2;a.push(f)});return{results:a}},cache:true},placeholder:"Seleziona una compagnia",escapeMarkup:function(a){return a},minimumInputLength:2,templateResult:formatCompagnia,templateSelection:function(a){return a.name||a.text}});$("#aeroplano").select2({dropdownParent:$("#exampleModal"),ajax:{url:__site_url+"/"+__xhr_controller+"/xhr_search_aeroplano",dataType:"json",delay:250,data:function(a){return{q:a.term}},processResults:function(c,b){var a=[];$.each(c,function(e,d){var f={};f.id=d.id;f.name=d.nome;f.p_economy=d.posti_economy;f.p_business=d.posti_business;a.push(f)});return{results:a}},cache:true},placeholder:"Seleziona un aeroplano",escapeMarkup:function(a){return a},minimumInputLength:2,templateResult:formatAeroplano,templateSelection:function(a){return a.name||a.text}});$("#btn_save").click(function(){if(requiredFieldsCheck()){bootbox.confirm("Procedere?",function(a){if(a){$.ajax({type:"POST",cache:false,url:__site_url+"/"+__xhr_controller+"/xhr_nuova_tratta",data:{codice:$("#codice").val(),compagnia:$("#compagnia").val(),a_partenza:$("#a_partenza").val(),a_arrivo:$("#a_arrivo").val(),durata:$("#durata").val(),p_economy:$("#p_economy").val(),p_business:$("#p_business").val(),aeroplano:$("#aeroplano").val()}}).done(function(b){if(b.result===1){_modal.modal("hide");$.notify("Tratta inserita","success");table.ajax.reload(null,false)}else{$.notify(b.error,"error")}})}})}});$("#btn_update").click(function(){if(requiredFieldsCheck()){bootbox.confirm("Procedere?",function(a){if(a){$.ajax({type:"POST",cache:false,url:__site_url+"/"+__xhr_controller+"/xhr_modifica_tratta",data:{old_codice:editing_old_id,codice:$("#codice").val(),compagnia:$("#compagnia").val(),a_partenza:$("#a_partenza").val(),a_arrivo:$("#a_arrivo").val(),durata:$("#durata").val(),p_economy:$("#p_economy").val(),p_business:$("#p_business").val(),aeroplano:$("#aeroplano").val()}}).done(function(b){if(b.result===1){_modal.modal("hide");$.notify("Tratta modificata","success");table.ajax.reload(null,false)}else{$.notify(b.error,"error")}})}})}});$("#btn_edit").click(function(){editing_old_id=$(".selected:first").data("id");$.ajax({type:"POST",cache:false,url:__site_url+"/"+__xhr_controller+"/xhr_tratta",data:{codice:editing_old_id}}).done(function(a){if(a.result===1){_modal.find("#codice").val(a.tratta.codice);_modal.find("#compagnia").append('<option value="'+a.tratta.cod_compagnia+'" selected="selected">'+a.tratta.nome_compagnia+"</option>");_modal.find("#compagnia").trigger("change");_modal.find("#a_partenza").append('<option value="'+a.tratta.aeroporto_partenza+'" selected="selected">'+a.tratta.aeroporto_partenza+"</option>");_modal.find("#a_partenza").trigger("change");_modal.find("#a_arrivo").append('<option value="'+a.tratta.aeroporto_arrivo+'" selected="selected">'+a.tratta.aeroporto_arrivo+"</option>");_modal.find("#a_arrivo").trigger("change");_modal.find("#durata").val(a.tratta.durata_volo);_modal.find("#p_economy").val(a.tratta.prezzo_economy);_modal.find("#p_business").val(a.tratta.prezzo_business);$("#aeroplano").append('<option value="'+a.tratta.tipo_aeroplano+'" selected="selected">'+a.tratta.nome_aeroplano+"</option>");$("#aeroplano").trigger("change");_modal.modal("show")}else{$.notify(a.error,"error")}})})}); |
import os
import pathlib
from pprint import pprint
import numpy as np
from scipy import stats
from scipy.spatial import distance
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import trajectorytools as tt
import trajectorytools.plot as ttplot
import trajectorytools.socialcontext as ttsocial
from trajectorytools.constants import dir_of_data
import csv
import pickle
import argparse
import pandas as pd
#argparse
def boolean_string(s):
# this function helps with getting Boolean input
if s not in ['False', 'True']:
raise ValueError('Not a valid boolean string')
return s == 'True' # note use of ==
# create the parser object
parser = argparse.ArgumentParser()
# NOTE: argparse will throw an error if:
# - a flag is given with no value
# - the value does not match the type
# and if a flag is not given it will be filled with the default.
parser.add_argument('-a', '--a_string', default='hi', type=str)
parser.add_argument('-b1', '--integer_b1', default=29, type=int)
parser.add_argument('-b2', '--integer_b2', default=16, type=int)
parser.add_argument('-b3', '--integer_b3', default=3, type=int)
parser.add_argument('-f1', '--integer_f1', default=0, type=int)
parser.add_argument('-f2', '--integer_f2', default=10000, type=int)
parser.add_argument('-c', '--float_c', default=1.5, type=float)
parser.add_argument('-v', '--verbose', default=True, type=boolean_string)
# Note that you assign a short name and a long name to each argument.
# You can use either when you call the program, but you have to use the
# long name when getting the values back from "args".
# get the arguments
args = parser.parse_args()
parent_dir = '../../output/temp_collective/roi'
input_dir = parent_dir + '/' + str(args.integer_b1) + '/' + str(args.integer_b2) + '/'
input_file = input_dir + str(args.integer_b3) + '_nosmooth.p'
#sigma_values = 1.5 #smoothing parameter
if args.integer_b2 == 1:
trajectories_file_path = '../../data/temp_collective/roi/'+str(args.integer_b1)+'/' +str(args.integer_b2)+'/GS_'+str(args.integer_b2)+'_T_'+str(args.integer_b1)+'_roi_'+str(args.integer_b3)+'/trajectories.npy'
else:
trajectories_file_path = '../../data/temp_collective/roi/'+str(args.integer_b1)+'/' +str(args.integer_b2)+'/GS_'+str(args.integer_b2)+'_T_'+str(args.integer_b1)+'_roi_'+str(args.integer_b3)+'/trajectories_wo_gaps.npy'
try:
tr = tt.Trajectories.from_idtrackerai(trajectories_file_path)
#tr.new_time_unit(tr.params['frame_rate'], 'seconds')
except FileNotFoundError:
print(args.integer_b1,args.integer_b2,args.integer_b3)
print('File not found')
pass
def speed_histogram(x):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
#speed_pdf, speed = np.histogram(x,bins=10,density=True)
#plt.plot(speed,np.log(speed_pdf))
ax.hist(x, density=True, bins=100, log = False)
#ax.set_xscale('log')
#ax.set_xlim(left = 5)
#ax.set_ylim([0,0.0002])
ax.set_xlabel('Speed')
ax.set_ylabel('Probability')
#plt.show()
#plt.xticks(ticks = [10,20,100,300], labels = [10,20,100,300])
out_dir = parent_dir = '../../output/temp_collective/trial_hist4.png'
fig.savefig(out_dir, dpi = 300)
return(ax)
df = pd.read_csv('../../data/temp_collective/colin_trial.csv',names=["Frame", "Individual", "x1", "y1","x2","y2"])
x = np.minimum(df.x1,df.x2)+ abs(df.x1 - df.x2)/2
y = np.minimum(df.y1,df.y2)+ abs(df.y1 - df.y2)/2
xx = pd.Series(x, name = 'x')
yy = pd.Series(y, name = 'y')
#xxx = pd.DataFrame(data = [xx.values], columns = xx.index)
#yyy = pd.DataFrame(data = [yy.values], columns = yy.index)
#x = np.reshape(tr.speed,tr.speed.shape[0]*tr.speed.shape[1])
data = pd.concat([df,xx, yy], axis=1)
grouped = data.groupby('Individual')
for group in grouped:
print(group)
speed_histogram(x)
speed = []
for i in range(len(data)):
for j in range(len(data)):
if data['Frame'][j] == data['Frame'][i] + 1:
if data['Individual'][j] == data['Individual'][i]:
speed.append(np.sqrt((data['x'][j] - data['x'][i])**2 + (data['y'][j] - data['y'][i])**2))
|
//
// WellCollectionView.h
// yuyan
//
// Created by tangfeimu on 2019/4/10.
// Copyright © 2019 tangfeimu. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol WellDelegate <NSObject>
- (void)send:(NSString *)ID;
@end
@interface WellCollectionView : UICollectionView
@property (nonatomic,strong)NSArray *arr;
@property (nonatomic,weak)id<WellDelegate>wellDelegate;
//@property (nonatomic,weak)id<WellDelegate>delegate;
@end
|
import React from "react";
import "antd/dist/antd.css";
import "./styles.css";
import { Modal, Descriptions, Divider, Spin } from "antd";
import LoadingBee from "../LoadingBee";
class ModalDetalhesMap extends React.Component {
state = {
modalVisible: false
};
setModalVisible(modalVisible) {
this.setState({ modalVisible });
}
render() {
const apiario = this.props.apiario;
console.log('====================================');
console.log('API', this.props);
console.log('====================================');
return (
<div>
<Modal
title="Detalhes"
centered
width={700}
visible={this.state.modalVisible}
onOk={() => this.setModalVisible(false)}
onCancel={() => this.setModalVisible(false)}
>
{this.props.loadingApiario ? (
<Spin size="large" loading={true} />
) : (
<Divider orientation="left" style={{ color: "black" }}>
Informações básicas do apiário
</Divider>
)}
</Modal>
</div>
);
}
}
export default ModalDetalhesMap;
|
#!/usr/bin/env python3
# Copyright 2014 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
"""Tool to manage building of system libraries and ports.
In general emcc will build them automatically on demand, so you do not
strictly need to use this tool, but it gives you more control over the
process (in particular, if emcc does this automatically, and you are
running multiple build commands in parallel, confusion can occur).
"""
from __future__ import print_function
import argparse
import logging
import sys
from tools import shared
from tools import system_libs
import emscripten
SYSTEM_LIBRARIES = system_libs.Library.get_all_variations()
SYSTEM_TASKS = list(SYSTEM_LIBRARIES.keys())
# This is needed to build the generated_struct_info.json file.
# It is not a system library, but it needs to be built before running with FROZEN_CACHE.
SYSTEM_TASKS += ['struct_info']
# Minimal subset of SYSTEM_TASKS used by CI systems to build enough to useful
MINIMAL_TASKS = [
'libcompiler_rt',
'libc',
'libc++abi',
'libc++abi-except',
'libc++abi-noexcept',
'libc++',
'libc++-except',
'libc++-noexcept',
'libal',
'libdlmalloc',
'libdlmalloc-debug',
'libemmalloc',
'libemmalloc-64bit',
'libpthread_stub',
'libsockets',
'libc_rt_wasm',
'struct_info',
'libstandalonewasm',
'crt1',
'libunwind-except'
]
USER_TASKS = [
'boost_headers',
'bullet',
'bzip2',
'cocos2d',
'freetype',
'harfbuzz',
'icu',
'libjpeg',
'libpng',
'ogg',
'regal',
'regal-mt',
'sdl2',
'sdl2-mt',
'sdl2-gfx',
'sdl2-image',
'sdl2-image-png',
'sdl2-image-jpg',
'sdl2-mixer',
'sdl2-mixer-ogg',
'sdl2-mixer-mp3',
'sdl2-net',
'sdl2-ttf',
'vorbis',
'zlib',
]
temp_files = shared.configuration.get_temp_files()
logger = logging.getLogger('embuilder')
force = False
def get_help():
all_tasks = SYSTEM_TASKS + USER_TASKS
all_tasks.sort()
return '''
Available targets:
build %s
Issuing 'embuilder.py build ALL' causes each task to be built.
''' % '\n '.join(all_tasks)
def build_port(port_name, lib_name):
if force:
shared.Cache.erase_file(lib_name)
system_libs.build_port(port_name, shared.Settings)
def main():
global force
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=get_help())
parser.add_argument('--lto', action='store_true', help='build bitcode object for LTO')
parser.add_argument('--pic', action='store_true',
help='build relocatable objects for suitable for dynamic linking')
parser.add_argument('--force', action='store_true',
help='force rebuild of target (by removing it first)')
parser.add_argument('operation', help='currently only "build" is supported')
parser.add_argument('targets', nargs='+', help='see below')
args = parser.parse_args()
if args.operation != 'build':
shared.exit_with_error('unfamiliar operation: ' + args.operation)
# process flags
# Check sanity so that if settings file has changed, the cache is cleared here.
# Otherwise, the cache will clear in an emcc process, which is invoked while building
# a system library into the cache, causing trouble.
shared.check_sanity()
if args.lto:
shared.Settings.LTO = "full"
# Reconfigure the cache dir to reflect the change
shared.reconfigure_cache()
if args.pic:
shared.Settings.RELOCATABLE = 1
# Reconfigure the cache dir to reflect the change
shared.reconfigure_cache()
if args.force:
force = True
# process tasks
libname = system_libs.Ports.get_lib_name
auto_tasks = False
tasks = args.targets
if 'SYSTEM' in tasks:
tasks = SYSTEM_TASKS
auto_tasks = True
elif 'USER' in tasks:
tasks = USER_TASKS
auto_tasks = True
elif 'MINIMAL' in tasks:
tasks = MINIMAL_TASKS
auto_tasks = True
elif 'ALL' in tasks:
tasks = SYSTEM_TASKS + USER_TASKS
auto_tasks = True
if auto_tasks:
skip_tasks = []
if shared.Settings.RELOCATABLE:
# we don't support PIC + pthreads yet
for task in SYSTEM_TASKS + USER_TASKS:
if '-mt' in task:
skip_tasks.append(task)
if 'pthread' in task and 'stub' not in task:
skip_tasks.append(task)
print('Skipping building of %s, because we don\'t support threads and PIC code.' % ', '.join(skip_tasks))
# cocos2d: must be ported, errors on
# "Cannot recognize the target platform; are you targeting an unsupported platform?"
skip_tasks += ['cocos2d']
tasks = [x for x in tasks if x not in skip_tasks]
print('Building targets: %s' % ' '.join(tasks))
for what in tasks:
logger.info('building and verifying ' + what)
if what in SYSTEM_LIBRARIES:
library = SYSTEM_LIBRARIES[what]
if force:
library.erase()
library.get_path()
elif what == 'struct_info':
if force:
shared.Cache.erase_file('generated_struct_info.json')
emscripten.generate_struct_info()
elif what == 'icu':
build_port('icu', libname('libicuuc'))
elif what == 'zlib':
shared.Settings.USE_ZLIB = 1
build_port('zlib', 'libz.a')
shared.Settings.USE_ZLIB = 0
elif what == 'bzip2':
build_port('bzip2', 'libbz2.a')
elif what == 'bullet':
build_port('bullet', libname('libbullet'))
elif what == 'vorbis':
build_port('vorbis', libname('libvorbis'))
elif what == 'ogg':
build_port('ogg', libname('libogg'))
elif what == 'libjpeg':
build_port('libjpeg', libname('libjpeg'))
elif what == 'libpng':
build_port('libpng', libname('libpng'))
elif what == 'sdl2':
build_port('sdl2', libname('libSDL2'))
elif what == 'sdl2-mt':
shared.Settings.USE_PTHREADS = 1
build_port('sdl2', libname('libSDL2-mt'))
shared.Settings.USE_PTHREADS = 0
elif what == 'sdl2-gfx':
build_port('sdl2_gfx', libname('libSDL2_gfx'))
elif what == 'sdl2-image':
build_port('sdl2_image', libname('libSDL2_image'))
elif what == 'sdl2-image-png':
shared.Settings.SDL2_IMAGE_FORMATS = ["png"]
build_port('sdl2_image', libname('libSDL2_image_png'))
shared.Settings.SDL2_IMAGE_FORMATS = []
elif what == 'sdl2-image-jpg':
shared.Settings.SDL2_IMAGE_FORMATS = ["jpg"]
build_port('sdl2_image', libname('libSDL2_image_jpg'))
shared.Settings.SDL2_IMAGE_FORMATS = []
elif what == 'sdl2-net':
build_port('sdl2_net', libname('libSDL2_net'))
elif what == 'sdl2-mixer':
old_formats = shared.Settings.SDL2_MIXER_FORMATS
shared.Settings.SDL2_MIXER_FORMATS = []
build_port('sdl2_mixer', libname('libSDL2_mixer'))
shared.Settings.SDL2_MIXER_FORMATS = old_formats
elif what == 'sdl2-mixer-ogg':
old_formats = shared.Settings.SDL2_MIXER_FORMATS
shared.Settings.SDL2_MIXER_FORMATS = ["ogg"]
build_port('sdl2_mixer', libname('libSDL2_mixer_ogg'))
shared.Settings.SDL2_MIXER_FORMATS = old_formats
elif what == 'sdl2-mixer-mp3':
old_formats = shared.Settings.SDL2_MIXER_FORMATS
shared.Settings.SDL2_MIXER_FORMATS = ["mp3"]
build_port('sdl2_mixer', libname('libSDL2_mixer_mp3'))
shared.Settings.SDL2_MIXER_FORMATS = old_formats
elif what == 'freetype':
build_port('freetype', 'libfreetype.a')
elif what == 'harfbuzz':
build_port('harfbuzz', 'libharfbuzz.a')
elif what == 'harfbuzz-mt':
shared.Settings.USE_PTHREADS = 1
build_port('harfbuzz', 'libharfbuzz-mt.a')
shared.Settings.USE_PTHREADS = 0
elif what == 'sdl2-ttf':
build_port('sdl2_ttf', libname('libSDL2_ttf'))
elif what == 'cocos2d':
build_port('cocos2d', libname('libcocos2d'))
elif what == 'regal':
build_port('regal', libname('libregal'))
elif what == 'regal-mt':
shared.Settings.USE_PTHREADS = 1
build_port('regal', libname('libregal-mt'))
shared.Settings.USE_PTHREADS = 0
elif what == 'boost_headers':
build_port('boost_headers', libname('libboost_headers'))
else:
logger.error('unfamiliar build target: ' + what)
return 1
logger.info('...success')
return 0
if __name__ == '__main__':
try:
sys.exit(main())
except KeyboardInterrupt:
logger.warning("KeyboardInterrupt")
sys.exit(1)
|
# -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Quantum circuit object."""
from copy import deepcopy
import itertools
import sys
import multiprocessing as mp
import sympy
from qiskit.qasm.qasm import Qasm
from qiskit.exceptions import QiskitError
from .quantumregister import QuantumRegister
from .classicalregister import ClassicalRegister
from .variabletable import VariableTable
class QuantumCircuit:
"""Quantum circuit."""
instances = 0
prefix = 'circuit'
# Class variable OPENQASM header
header = "OPENQASM 2.0;"
extension_lib = "include \"qelib1.inc\";"
def __init__(self, *regs, name=None):
"""Create a new circuit.
A circuit is a list of instructions bound to some registers.
Args:
*regs (list(Register) or list(Int)): To be included in the circuit.
- If [Register], the QuantumRegister and/or ClassicalRegister
to include in the circuit.
E.g.: QuantumCircuit(QuantumRegister(4))
QuantumCircuit(QuantumRegister(4), ClassicalRegister(3))
QuantumCircuit(QuantumRegister(4, 'qr0'), QuantumRegister(2, 'qr1'))
- If [Int], the amount of qubits and/or classical bits to include
in the circuit. It can be (Int, ) or (Int, Int).
E.g.: QuantumCircuit(4) # A QuantumCircuit with 4 qubits
QuantumCircuit(4, 3) # A QuantumCircuit with 4 qubits and 3 classical bits
name (str or None): the name of the quantum circuit. If
None, an automatically generated string will be assigned.
Raises:
QiskitError: if the circuit name, if given, is not valid.
"""
if name is None:
name = self.cls_prefix() + str(self.cls_instances())
# pylint: disable=not-callable
# (known pylint bug: https://github.com/PyCQA/pylint/issues/1699)
if sys.platform != "win32" and \
isinstance(mp.current_process(), mp.context.ForkProcess):
name += '-{}'.format(mp.current_process().pid)
self._increment_instances()
if not isinstance(name, str):
raise QiskitError("The circuit name should be a string "
"(or None to auto-generate a name).")
self.name = name
# Data contains a list of instructions and their contexts,
# in the order they were applied.
self.data = []
# This is a map of registers bound to this circuit, by name.
self.qregs = []
self.cregs = []
self.add_register(*regs)
# Variable table tracks instructions with variable parameters.
self._variable_table = VariableTable()
def __str__(self):
return str(self.draw(output='text'))
def __eq__(self, other):
# TODO: remove the DAG from this function
from qiskit.converters import circuit_to_dag
return circuit_to_dag(self) == circuit_to_dag(other)
@classmethod
def _increment_instances(cls):
cls.instances += 1
@classmethod
def cls_instances(cls):
"""Return the current number of instances of this class,
useful for auto naming."""
return cls.instances
@classmethod
def cls_prefix(cls):
"""Return the prefix to use for auto naming."""
return cls.prefix
def has_register(self, register):
"""
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
"""
has_reg = False
if (isinstance(register, QuantumRegister) and
register in self.qregs):
has_reg = True
elif (isinstance(register, ClassicalRegister) and
register in self.cregs):
has_reg = True
return has_reg
def mirror(self):
"""Mirror the circuit by reversing the instructions.
This is done by recursively mirroring all instructions.
It does not invert any gate.
Returns:
QuantumCircuit: the mirrored circuit
"""
reverse_circ = self.copy(name=self.name+'_mirror')
reverse_circ.data = []
for inst, qargs, cargs in reversed(self.data):
reverse_circ.data.append((inst.mirror(), qargs, cargs))
return reverse_circ
def inverse(self):
"""Invert this circuit.
This is done by recursively inverting all gates.
Returns:
QuantumCircuit: the inverted circuit
Raises:
QiskitError: if the circuit cannot be inverted.
"""
inverse_circ = self.copy(name=self.name+'_dg')
inverse_circ.data = []
for inst, qargs, cargs in reversed(self.data):
inverse_circ.data.append((inst.inverse(), qargs, cargs))
return inverse_circ
def combine(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Make new circuit with combined registers
combined_qregs = deepcopy(self.qregs)
combined_cregs = deepcopy(self.cregs)
for element in rhs.qregs:
if element not in self.qregs:
combined_qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
combined_cregs.append(element)
circuit = QuantumCircuit(*combined_qregs, *combined_cregs)
for instruction_context in itertools.chain(self.data, rhs.data):
circuit.append(*instruction_context)
return circuit
def extend(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Add new registers
for element in rhs.qregs:
if element not in self.qregs:
self.qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
self.cregs.append(element)
# Add new gates
for instruction_context in rhs.data:
self.append(*instruction_context)
return self
def qubits(self):
"""
Returns a list of quantum bits in the order that the registers had been added.
"""
return [qbit for qreg in self.qregs for qbit in qreg]
def clbits(self):
"""
Returns a list of classical bits in the order that the registers had been added.
"""
return [cbit for creg in self.cregs for cbit in creg]
def __add__(self, rhs):
"""Overload + to implement self.combine."""
return self.combine(rhs)
def __iadd__(self, rhs):
"""Overload += to implement self.extend."""
return self.extend(rhs)
def __len__(self):
"""Return number of operations in circuit."""
return len(self.data)
def __getitem__(self, item):
"""Return indexed operation."""
return self.data[item]
def append(self, instruction, qargs=None, cargs=None):
"""Append an instruction to the end of the circuit, modifying
the circuit in place.
Args:
instruction (Instruction): Instruction instance to append
qargs (list(tuple)): qubits to attach instruction to
cargs (list(tuple)): clbits to attach instruction to
Returns:
Instruction: a handle to the instruction that was just added
Raises:
QiskitError: if the gate is of a different shape than the wires
it is being attached to.
"""
qargs = qargs or []
cargs = cargs or []
# do some compatibility checks
self._check_dups(qargs)
self._check_qargs(qargs)
self._check_cargs(cargs)
if instruction.num_qubits != len(qargs) or \
instruction.num_clbits != len(cargs):
raise QiskitError("instruction %s with %d qubits and %d clbits "
"cannot be appended onto %d qubits and %d clbits." %
(instruction.name,
instruction.num_qubits, instruction.num_clbits,
len(qargs), len(cargs)))
# add the instruction onto the given wires
instruction_context = instruction, qargs, cargs
self.data.append(instruction_context)
# track variable parameters in instruction
for param_index, param in enumerate(instruction.params):
if isinstance(param, sympy.Expr):
current_symbols = set(self._variable_table.keys())
these_symbols = set(param.free_symbols)
new_symbols = these_symbols - current_symbols
common_symbols = these_symbols & current_symbols
for symbol in new_symbols:
self._variable_table[symbol] = [(instruction, param_index)]
for symbol in common_symbols:
self._variable_table[symbol].append((instruction, param_index))
return instruction
def _attach(self, instruction, qargs, cargs):
"""DEPRECATED after 0.8"""
self.append(instruction, qargs, cargs)
def add_register(self, *regs):
"""Add registers."""
if not regs:
return
if any([isinstance(reg, int) for reg in regs]):
# QuantumCircuit defined without registers
if len(regs) == 1 and isinstance(regs[0], int):
# QuantumCircuit with anonymous quantum wires e.g. QuantumCircuit(2)
regs = (QuantumRegister(regs[0], 'q'),)
elif len(regs) == 2 and all([isinstance(reg, int) for reg in regs]):
# QuantumCircuit with anonymous wires e.g. QuantumCircuit(2, 3)
regs = (QuantumRegister(regs[0], 'q'), ClassicalRegister(regs[1], 'c'))
else:
raise QiskitError("QuantumCircuit parameters can be Registers or Integers."
" If Integers, up to 2 arguments. QuantumCircuit was called"
" with %s." % (regs,))
for register in regs:
if register in self.qregs or register in self.cregs:
raise QiskitError("register name \"%s\" already exists"
% register.name)
if isinstance(register, QuantumRegister):
self.qregs.append(register)
elif isinstance(register, ClassicalRegister):
self.cregs.append(register)
else:
raise QiskitError("expected a register")
def _check_dups(self, qubits):
"""Raise exception if list of qubits contains duplicates."""
squbits = set(qubits)
if len(squbits) != len(qubits):
raise QiskitError("duplicate qubit arguments")
def _check_qargs(self, qargs):
"""Raise exception if a qarg is not in this circuit or bad format."""
if not all(isinstance(i, tuple) and
isinstance(i[0], QuantumRegister) and
isinstance(i[1], int) for i in qargs):
raise QiskitError("qarg not (QuantumRegister, int) tuple")
if not all(self.has_register(i[0]) for i in qargs):
raise QiskitError("register not in this circuit")
for qubit in qargs:
qubit[0].check_range(qubit[1])
def _check_cargs(self, cargs):
"""Raise exception if clbit is not in this circuit or bad format."""
if not all(isinstance(i, tuple) and
isinstance(i[0], ClassicalRegister) and
isinstance(i[1], int) for i in cargs):
raise QiskitError("carg not (ClassicalRegister, int) tuple")
if not all(self.has_register(i[0]) for i in cargs):
raise QiskitError("register not in this circuit")
for clbit in cargs:
clbit[0].check_range(clbit[1])
def to_instruction(self):
"""Create an Instruction out of this circuit.
Returns:
Instruction: a composite instruction encapsulating this circuit
(can be decomposed back)
"""
from qiskit.converters.circuit_to_instruction import circuit_to_instruction
return circuit_to_instruction(self)
def decompose(self):
"""Call a decomposition pass on this circuit,
to decompose one level (shallow decompose).
Returns:
QuantumCircuit: a circuit one level decomposed
"""
from qiskit.transpiler.passes.decompose import Decompose
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.converters.dag_to_circuit import dag_to_circuit
pass_ = Decompose()
decomposed_dag = pass_.run(circuit_to_dag(self))
return dag_to_circuit(decomposed_dag)
def _check_compatible_regs(self, rhs):
"""Raise exception if the circuits are defined on incompatible registers"""
list1 = self.qregs + self.cregs
list2 = rhs.qregs + rhs.cregs
for element1 in list1:
for element2 in list2:
if element2.name == element1.name:
if element1 != element2:
raise QiskitError("circuits are not compatible")
def qasm(self):
"""Return OpenQASM string."""
string_temp = self.header + "\n"
string_temp += self.extension_lib + "\n"
for register in self.qregs:
string_temp += register.qasm() + "\n"
for register in self.cregs:
string_temp += register.qasm() + "\n"
for instruction, qargs, cargs in self.data:
if instruction.name == 'measure':
qubit = qargs[0]
clbit = cargs[0]
string_temp += "%s %s[%d] -> %s[%d];\n" % (instruction.qasm(),
qubit[0].name, qubit[1],
clbit[0].name, clbit[1])
else:
string_temp += "%s %s;\n" % (instruction.qasm(),
",".join(["%s[%d]" % (j[0].name, j[1])
for j in qargs + cargs]))
return string_temp
def draw(self, scale=0.7, filename=None, style=None, output='text',
interactive=False, line_length=None, plot_barriers=True,
reverse_bits=False, justify=None):
"""Draw the quantum circuit
Using the output parameter you can specify the format. The choices are:
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style
file. You can refer to the
:ref:`Style Dict Doc <style-dict-doc>` for more information
on the contents.
output (str): Select the output method to use for drawing the
circuit. Valid choices are `text`, `latex`, `latex_source`,
`mpl`.
interactive (bool): when set true show the circuit in a new window
(for `mpl` this depends on the matplotlib backend being used
supporting this). Note when used with either the `text` or the
`latex_source` output type this has no effect and will be
silently ignored.
line_length (int): sets the length of the lines generated by `text`
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (string): Options are `left`, `right` or `none`, if anything
else is supplied it defaults to left justified. It refers to where
gates should be placed in the output circuit if there is an option.
`none` results in each gate being placed in its own column. Currently
only supported by text drawer.
Returns:
PIL.Image or matplotlib.figure or str or TextDrawing:
* PIL.Image: (output `latex`) an in-memory representation of the
image of the circuit diagram.
* matplotlib.figure: (output `mpl`) a matplotlib figure object
for the circuit diagram.
* str: (output `latex_source`). The LaTeX source code.
* TextDrawing: (output `text`). A drawing that can be printed as
ascii art
Raises:
VisualizationError: when an invalid output method is selected
"""
from qiskit.tools import visualization
return visualization.circuit_drawer(self, scale=scale,
filename=filename, style=style,
output=output,
interactive=interactive,
line_length=line_length,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits,
justify=justify)
def size(self):
"""Returns total number of gate operations in circuit.
Returns:
int: Total number of gate operations.
"""
gate_ops = 0
for instr, _, _ in self.data:
if instr.name not in ['barrier', 'snapshot']:
gate_ops += 1
return gate_ops
def depth(self):
"""Return circuit depth (i.e. length of critical path).
This does not include compiler or simulator directives
such as 'barrier' or 'snapshot'.
Returns:
int: Depth of circuit.
Notes:
The circuit depth and the DAG depth need not bt the
same.
"""
# Labels the registers by ints
# and then the qubit position in
# a register is given by reg_int+qubit_num
reg_offset = 0
reg_map = {}
for reg in self.qregs+self.cregs:
reg_map[reg.name] = reg_offset
reg_offset += reg.size
# A list that holds the height of each qubit
# and classical bit.
op_stack = [0]*reg_offset
# Here we are playing a modified version of
# Tetris where we stack gates, but multi-qubit
# gates, or measurements have a block for each
# qubit or cbit that are connected by a virtual
# line so that they all stacked at the same depth.
# Conditional gates act on all cbits in the register
# they are conditioned on.
# We do not consider barriers or snapshots as
# They are transpiler and simulator directives.
# The max stack height is the circuit depth.
for instr, qargs, cargs in self.data:
if instr.name not in ['barrier', 'snapshot']:
levels = []
reg_ints = []
for ind, reg in enumerate(qargs+cargs):
# Add to the stacks of the qubits and
# cbits used in the gate.
reg_ints.append(reg_map[reg[0].name]+reg[1])
levels.append(op_stack[reg_ints[ind]] + 1)
if instr.control:
# Controls operate over all bits in the
# classical register they use.
cint = reg_map[instr.control[0].name]
for off in range(instr.control[0].size):
if cint+off not in reg_ints:
reg_ints.append(cint+off)
levels.append(op_stack[cint+off]+1)
max_level = max(levels)
for ind in reg_ints:
op_stack[ind] = max_level
return max(op_stack)
def width(self):
"""Return number of qubits plus clbits in circuit.
Returns:
int: Width of circuit.
"""
return sum(reg.size for reg in self.qregs+self.cregs)
def count_ops(self):
"""Count each operation kind in the circuit.
Returns:
dict: a breakdown of how many operations of each kind.
"""
count_ops = {}
for instr, _, _ in self.data:
if instr.name in count_ops.keys():
count_ops[instr.name] += 1
else:
count_ops[instr.name] = 1
return count_ops
def num_connected_components(self, unitary_only=False):
"""How many non-entangled subcircuits can the circuit be factored to.
Args:
unitary_only (bool): Compute only unitary part of graph.
Returns:
int: Number of connected components in circuit.
"""
# Convert registers to ints (as done in depth).
reg_offset = 0
reg_map = {}
if unitary_only:
regs = self.qregs
else:
regs = self.qregs+self.cregs
for reg in regs:
reg_map[reg.name] = reg_offset
reg_offset += reg.size
# Start with each qubit or cbit being its own subgraph.
sub_graphs = [[bit] for bit in range(reg_offset)]
num_sub_graphs = len(sub_graphs)
# Here we are traversing the gates and looking to see
# which of the sub_graphs the gate joins together.
for instr, qargs, cargs in self.data:
if unitary_only:
args = qargs
num_qargs = len(args)
else:
args = qargs+cargs
num_qargs = len(args) + (1 if instr.control else 0)
if num_qargs >= 2 and instr.name not in ['barrier', 'snapshot']:
graphs_touched = []
num_touched = 0
# Controls necessarily join all the cbits in the
# register that they use.
if instr.control and not unitary_only:
creg = instr.control[0]
creg_int = reg_map[creg.name]
for coff in range(creg.size):
temp_int = creg_int+coff
for k in range(num_sub_graphs):
if temp_int in sub_graphs[k]:
graphs_touched.append(k)
num_touched += 1
break
for item in args:
reg_int = reg_map[item[0].name]+item[1]
for k in range(num_sub_graphs):
if reg_int in sub_graphs[k]:
if k not in graphs_touched:
graphs_touched.append(k)
num_touched += 1
break
# If the gate touches more than one subgraph
# join those graphs together and return
# reduced number of subgraphs
if num_touched > 1:
connections = []
for idx in graphs_touched:
connections.extend(sub_graphs[idx])
_sub_graphs = []
for idx in range(num_sub_graphs):
if idx not in graphs_touched:
_sub_graphs.append(sub_graphs[idx])
_sub_graphs.append(connections)
sub_graphs = _sub_graphs
num_sub_graphs -= (num_touched-1)
# Cannot go lower than one so break
if num_sub_graphs == 1:
break
return num_sub_graphs
def num_unitary_factors(self):
"""Computes the number of tensor factors in the unitary
(quantum) part of the circuit only.
"""
return self.num_connected_components(unitary_only=True)
def num_tensor_factors(self):
"""Computes the number of tensor factors in the unitary
(quantum) part of the circuit only.
Notes:
This is here for backwards compatibility, and will be
removed in a future release of qiskit. You should call
`num_unitary_factors` instead.
"""
return self.num_unitary_factors()
def copy(self, name=None):
"""
Args:
name (str): name to be given to the copied circuit, if None then the name stays the same
Returns:
QuantumCircuit: a deepcopy of the current circuit, with the name updated if
it was provided
"""
cpy = deepcopy(self)
if name:
cpy.name = name
return cpy
@staticmethod
def from_qasm_file(path):
"""Take in a QASM file and generate a QuantumCircuit object.
Args:
path (str): Path to the file for a QASM program
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = Qasm(filename=path)
return _circuit_from_qasm(qasm)
@staticmethod
def from_qasm_str(qasm_str):
"""Take in a QASM string and generate a QuantumCircuit object.
Args:
qasm_str (str): A QASM program string
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = Qasm(data=qasm_str)
return _circuit_from_qasm(qasm)
@property
def variable_table(self):
"""get the circuit variable table"""
return self._variable_table
@property
def variables(self):
"""convenience function to get the variables defined in the variable table"""
return set(self._variable_table.keys())
def assign_variables(self, value_dict):
"""Assign variables to values yielding a new circuit.
Args:
value_dict (dict): {variable: value, ...}
Returns:
QuantumCircuit: copy of self with assignment substitution.
"""
new_circuit = self.copy()
for variable in value_dict:
new_circuit.variable_table[variable] = value_dict
# clear evaluated expressions
for variable in value_dict:
del new_circuit.variable_table[variable]
return new_circuit
@property
def unassigned_variables(self):
"""Returns a set containing any variables which have not yet been assigned."""
return {variable
for variable, parameterized_instructions in self.variable_table.items()
if any(instruction.params[parameter_index].free_symbols
for instruction, parameter_index in parameterized_instructions)}
def _circuit_from_qasm(qasm):
# pylint: disable=cyclic-import
from qiskit.converters import ast_to_dag
from qiskit.converters import dag_to_circuit
ast = qasm.parse()
dag = ast_to_dag(ast)
return dag_to_circuit(dag)
|
from transiter.db import models
import pytest
import datetime
from transiter.services import views
SYSTEM_ID = "1"
ROUTE_ONE_PK = 2
ROUTE_ONE_ID = "3"
ROUTE_TWO_PK = 4
ROUTE_TWO_ID = "5"
ALERT_ID = "6"
ALERT_HEADER = "Header"
ALERT_DESCRIPTION = "Description"
TRIP_ONE_ID = "3"
TRIP_ONE_PK = 4
TRIP_TWO_ID = "5"
TRIP_TWO_PK = 6
SERVICE_MAP_ONE_GROUP_ID = "1000"
SERVICE_MAP_TWO_GROUP_ID = "1001"
STOP_ONE_ID = "7"
STOP_ONE_NAME = "7-Name"
STOP_TWO_ID = "8"
STOP_TWO_NAME = "8-Name"
TIME_1 = datetime.datetime.utcfromtimestamp(1000)
TIME_2 = datetime.datetime.utcfromtimestamp(2000)
FEED_ONE_ID = "2"
FEED_ONE_PK = 3
FEED_ONE_AUTO_UPDATE_PERIOD = 500
FEED_TWO_AUTO_UPDATE_PERIOD = -1
FEED_TWO_ID = "4"
@pytest.fixture
def alert_1_model():
return models.Alert(
id=ALERT_ID,
cause=models.Alert.Cause.UNKNOWN_CAUSE,
effect=models.Alert.Effect.UNKNOWN_EFFECT,
active_periods=[models.AlertActivePeriod(starts_at=TIME_1, ends_at=TIME_2)],
messages=[
models.AlertMessage(header=ALERT_HEADER, description=ALERT_DESCRIPTION)
],
)
@pytest.fixture
def alert_1_small_view():
return views.AlertSmall(
id=ALERT_ID,
cause=models.Alert.Cause.UNKNOWN_CAUSE,
effect=models.Alert.Effect.UNKNOWN_EFFECT,
)
@pytest.fixture
def alert_1_large_view():
return views.AlertLarge(
id=ALERT_ID,
cause=models.Alert.Cause.UNKNOWN_CAUSE,
effect=models.Alert.Effect.UNKNOWN_EFFECT,
active_period=views.AlertActivePeriod(starts_at=TIME_1, ends_at=TIME_2),
messages=[
views.AlertMessage(header=ALERT_HEADER, description=ALERT_DESCRIPTION)
],
)
@pytest.fixture
def system_1_model():
return models.System(id=SYSTEM_ID, name="System Name")
@pytest.fixture
def system_1_view():
return views.System(id=SYSTEM_ID, name="System Name", status=None)
@pytest.fixture
def route_1_model(system_1_model):
return models.Route(
system=system_1_model,
id=ROUTE_ONE_ID,
color="route_1_color",
short_name="route_1_short_name",
long_name="route_1_long_name",
description="route_1_description",
url="route_1_url",
type=models.Route.Type.FUNICULAR,
pk=ROUTE_ONE_PK,
)
@pytest.fixture
def route_1_small_view():
return views.Route(id=ROUTE_ONE_ID, color="route_1_color", _system_id=SYSTEM_ID)
@pytest.fixture
def route_1_large_view():
return views.RouteLarge(
id=ROUTE_ONE_ID,
periodicity=0,
color="route_1_color",
short_name="route_1_short_name",
long_name="route_1_long_name",
description="route_1_description",
url="route_1_url",
type=models.Route.Type.FUNICULAR,
_system_id=SYSTEM_ID,
)
@pytest.fixture
def route_2_model(system_1_model):
return models.Route(
system=system_1_model, id=ROUTE_TWO_ID, color="route_2_color", pk=ROUTE_TWO_PK
)
@pytest.fixture
def route_2_small_view():
return views.Route(id=ROUTE_TWO_ID, color="route_2_color", _system_id=SYSTEM_ID)
@pytest.fixture
def trip_1_model(route_1_model):
return models.Trip(
pk=TRIP_ONE_PK, id=TRIP_ONE_ID, route=route_1_model, current_stop_sequence=1
)
@pytest.fixture
def trip_1_view():
return views.Trip(
id=TRIP_ONE_ID,
direction_id=None,
started_at=None,
updated_at=None,
_route_id=ROUTE_ONE_ID,
_system_id=SYSTEM_ID,
)
@pytest.fixture
def trip_2_model(route_1_model):
return models.Trip(
pk=TRIP_TWO_PK, id=TRIP_TWO_ID, route=route_1_model, current_stop_sequence=1
)
@pytest.fixture
def trip_2_view():
return views.Trip(
id=TRIP_TWO_ID,
direction_id=None,
started_at=None,
updated_at=None,
_route_id=ROUTE_ONE_ID,
_system_id=SYSTEM_ID,
)
@pytest.fixture
def stop_1_model(system_1_model):
return models.Stop(id=STOP_ONE_ID, name=STOP_ONE_NAME, system=system_1_model)
@pytest.fixture
def stop_1_small_view():
return views.Stop(id=STOP_ONE_ID, name=STOP_ONE_NAME, _system_id=SYSTEM_ID)
@pytest.fixture
def stop_2_model(system_1_model):
return models.Stop(id=STOP_TWO_ID, name=STOP_TWO_NAME, system=system_1_model)
@pytest.fixture
def stop_2_small_view():
return views.Stop(id=STOP_TWO_ID, name=STOP_TWO_NAME, _system_id=SYSTEM_ID)
@pytest.fixture
def feed_1_model(system_1_model):
return models.Feed(
id=FEED_ONE_ID,
auto_update_period=FEED_ONE_AUTO_UPDATE_PERIOD,
system=system_1_model,
)
@pytest.fixture
def feed_1_small_view():
return views.Feed(
id=FEED_ONE_ID,
auto_update_period=FEED_ONE_AUTO_UPDATE_PERIOD,
_system_id=SYSTEM_ID,
)
@pytest.fixture
def feed_1_large_view():
return views.FeedLarge(
id=FEED_ONE_ID,
auto_update_period=FEED_ONE_AUTO_UPDATE_PERIOD,
_system_id=SYSTEM_ID,
updates=views.UpdatesInFeedLink(_feed_id=FEED_ONE_ID, _system_id=SYSTEM_ID),
)
@pytest.fixture
def feed_2_model(system_1_model):
return models.Feed(
id=FEED_TWO_ID,
auto_update_period=FEED_TWO_AUTO_UPDATE_PERIOD,
system=system_1_model,
)
@pytest.fixture
def feed_2_small_view():
return views.Feed(
id=FEED_TWO_ID,
auto_update_period=FEED_TWO_AUTO_UPDATE_PERIOD,
_system_id=SYSTEM_ID,
)
|
# coding=utf-8
# Copyright 2020 The Google Research 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.
"""Evaluates the model based on a performance metric."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
from absl import flags
import model
import model_utils
import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import
import tensorflow_datasets as tfds
flags.DEFINE_string('ckpt_path', '', 'Path to evaluation checkpoint')
flags.DEFINE_string('cls_dense_name', '', 'Final dense layer name')
flags.DEFINE_integer('train_batch_size', 600,
'The batch size for the target dataset.')
FLAGS = flags.FLAGS
NUM_EVAL_IMAGES = {
'mnist': 10000,
'svhn_cropped_small': 6000,
}
def get_model_fn():
"""Returns the model definition."""
def model_fn(features, labels, mode, params):
"""Returns the model function."""
feature = features['feature']
labels = labels['label']
one_hot_labels = model_utils.get_label(
labels,
params,
FLAGS.src_num_classes,
batch_size=FLAGS.train_batch_size)
def get_logits():
"""Return the logits."""
network_output = model.conv_model(
feature,
mode,
target_dataset=FLAGS.target_dataset,
src_hw=FLAGS.src_hw,
target_hw=FLAGS.target_hw)
name = FLAGS.cls_dense_name
with tf.variable_scope('target_CLS'):
logits = tf.layers.dense(
inputs=network_output, units=FLAGS.src_num_classes, name=name)
return logits
logits = get_logits()
logits = tf.cast(logits, tf.float32)
dst_loss = tf.losses.softmax_cross_entropy(
logits=logits,
onehot_labels=one_hot_labels,
)
loss = dst_loss
eval_metrics = model_utils.metric_fn(labels, logits)
return tf.estimator.EstimatorSpec(
mode=mode,
loss=loss,
train_op=None,
eval_metric_ops=eval_metrics,
)
return model_fn
def main(unused_argv):
config = tf.estimator.RunConfig()
classifier = tf.estimator.Estimator(get_model_fn(), config=config)
def _merge_datasets(test_batch):
feature, label = test_batch['image'], test_batch['label'],
features = {
'feature': feature,
}
labels = {
'label': label,
}
return (features, labels)
def get_dataset(dataset_split):
"""Returns dataset creation function."""
def make_input_dataset():
"""Returns input dataset."""
test_data = tfds.load(name=FLAGS.target_dataset, split=dataset_split)
test_data = test_data.batch(FLAGS.train_batch_size)
dataset = tf.data.Dataset.zip((test_data,))
dataset = dataset.map(_merge_datasets)
dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
return dataset
return make_input_dataset
num_eval_images = NUM_EVAL_IMAGES[FLAGS.target_dataset]
eval_steps = num_eval_images // FLAGS.train_batch_size
classifier.evaluate(
input_fn=get_dataset('test'),
steps=eval_steps,
checkpoint_path=FLAGS.ckpt_path,
)
if __name__ == '__main__':
tf.logging.set_verbosity(tf.logging.INFO)
app.run(main)
|
# include <stdio.h>
#define NUMEROLIVROS 100
#define MAXTITULO 40
#define MAXNOME 20
typedef struct {
int dia;
int mes;
int ano;
} Data;
typedef struct {
char titulo[MAXTITULO+1];
char autor[MAXNOME+1];
long int isbn;
int anoPublicacao;
int numeroDaCopia;
Data dataEmprestimo;
Data dataRetorno;
} Livro;
void mostraMenu(void);
void mostraMenu(void){
printf("****BIBLIOTECA DO IST****\n");
printf("1 - Inserir novo livro\n");
printf("2 - Listar livros\n");
printf("3 - Procurar livro por isbn\n");
printf("4 - Procurar livro por título\n");
printf("5 - Alterar título do livro\n");
printf("6 - Apagar livro pelo isbn\n");
printf("7 - Registar data de empréstimo de um livro pelo isbn");
printf("8 - Registar data de retorno de um livro pelo isbn");
printf("0 - Sair\n");
printf("*************************\n");
}
int main(){
mostraMenu();
return 0;
}
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M20 6.83V20H6.83L20 6.83M22 2L2 22h20V2z" />
, 'SignalCellularNull');
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def main():
print('helloka')
|
var express = require('express');
var usersController = require('../controllers/users');
var categoriesController = require('../controllers/categories');
var challengesController = require('../controllers/challenges');
var awardsController = require('../controllers/awards');
module.exports = function () {
var router = express.Router();
router.get('/users', usersController.getUsers);
router.post('/users', usersController.createUser);
router.get('/users/:id', usersController.getUser);
router.delete('/users/:id', usersController.deleteUser);
router.get('/categories', categoriesController.getCategories);
router.post('/categories', categoriesController.createCategory);
router.get('/categories/:id', categoriesController.getCategory);
router.delete('/categories/:id', categoriesController.deleteCategory);
router.get('/challenges', challengesController.getChallenges);
router.post('/challenges', challengesController.createChallenge);
router.get('/challenges/:id', challengesController.getChallenge);
router.delete('/challenges/:id', challengesController.deleteChallenge);
router.post('/challenges/:id/action/:action', challengesController.applyActionToChallenge);
router.get('/awards', awardsController.getAwards);
router.post('/awards', awardsController.createAward);
return router;
};
|
// @file endcall.js
class EndCall {
constructor() {
this.container = document.querySelector("#webrtcendcall");
this.xhrLog = new XHRLog(this.container);
this.status = new Status(this.container.querySelector(".status"));
}
set proceedTo(fn) {
this.proceed = fn;
}
set skipTo(fn) {
this.skip = fn;
}
onSuccess(data) {
this.makeCallResponse = data;
this.status.success();
this.xhrLog.initialize(JSON.stringify(data, null, 4));
this.proceed(data);
}
onFailure() {
this.status.failure();
this.skip();
}
onError() {
this.status.error();
}
destroy() {
this.status.failure();
this.xhrLog.destroy();
}
request(url, accessToken, cargo) {
var self = this;
var xhr = new XMLHttpRequest();
xhr.open("DELETE", url, true);
xhr.onload = function() {
if (this.status >= 200 && this.status < 400)
self.onSuccess("NA");
else
self.onFailure();
};
xhr.onerror = self.onError;
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
xhr.send();
}
initialize(cpaasUrl, idToken, accessToken, resourceUrl) {
console.log('EndCall, initialize');
let username = Extract.username(idToken);
let url = cpaasUrl + resourceUrl;
this.request(url, accessToken, null);
}
} |
import sublime, sublime_plugin
import re
def match(rex, str):
m = rex.match(str)
if m:
return m.group(0)
else:
return None
def make_completion(tag):
# make it look like
# ("table\tTag", "table>$1</table>"),
return (tag + '\tTag', tag + '>$0</' + tag + '>')
def get_tag_to_attributes():
"""
Returns a dictionary with attributes accociated to tags
This assumes that all tags can have global attributes as per MDN:
https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes
"""
# Map tags to specific attributes applicable for that tag
tag_dict = {
'fest:template': ['xmlns:fest', 'xmlns:i18n', 'context_name'],
'fest:var': ['name', 'select'],
'fest:value': ['output'],
'fest:text': [],
'fest:space': [],
'fest:set': ['name', 'test'],
'fest:get': ['name', 'select'],
'fest:element': ['name', 'select'],
'fest:attributes': [],
'fest:attribute': ['name', 'value'],
'fest:each': ['iterate', 'index', 'value'],
'fest:for': ['iterate', 'index', 'value', 'from', 'to'],
'fest:if': ['test'],
'fest:choose': [],
'fest:otherwise': [],
'fest:when': ['test'],
'fest:cdata': [],
'fest:comment': [],
'fest:doctype': [],
'fest:script': ['src'],
'fest:include': ['src', 'context'],
'fest:insert': ['src'],
'fest:message': ['context'],
'fest:msg': ['context'],
'fest:plural': ['select'],
'fest:params': [],
'fest:param': ['name'],
'i18n:msg': ['context', 'data-name'],
'a' : ['charset', 'coords', 'download', 'href', 'hreflang', 'media', 'name', 'ping', 'rel', 'rev', 'shape', 'target', 'type'],
'abbr' : ['title'],
'address' : [],
'applet' : ['align', 'alt', 'archive', 'code', 'codebase', 'height', 'hspace', 'name', 'object', 'vspace', 'width'],
'area' : ['alt', 'coords', 'download', 'href', 'hreflang', 'media', 'nohref', 'rel', 'shape', 'target'],
'article' : [],
'aside' : [],
'audio' : ['autoplay', 'buffered', 'controls', 'loop', 'muted', 'played', 'preload', 'src', 'volume'],
'b' : [],
'base' : ['href', 'target'],
'basefont' : ['color', 'face', 'size'],
'bdi' : [],
'bdo' : [],
'blockquote' : ['cite'],
'body' : ['alink', 'background', 'bgcolor', 'link', 'onafterprint', 'onbeforeprint', 'onbeforeunload', 'onhashchange', 'onmessage', 'onoffline', 'ononline', 'onpopstate', 'onredo', 'onstorage', 'onundo', 'onunload', 'text', 'vlink'],
'br' : ['clear'],
'button' : ['autofocus', 'disabled', 'form', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'name', 'type', 'value'],
'canvas' : ['height', 'width'],
'caption' : ['align'],
'cite' : [],
'code' : [],
'col' : ['align', 'char', 'charoff', 'span', 'valign', 'width'],
'colgroup' : ['align', 'char', 'charoff', 'span', 'valign', 'width'],
'content' : ['select'],
'data' : ['value'],
'datalist' : [],
'dd' : [],
'del' : ['cite', 'datetime'],
'details' : ['open'],
'dfn' : [],
'dir' : ['compact'],
'div' : ['align'],
'dl' : ['compact'],
'dt' : [],
'element' : [],
'em' : [],
'embed' : ['height', 'src', 'type', 'width'],
'fieldset' : ['disabled', 'form', 'name'],
'figcaption' : [],
'figure' : [],
'font' : ['color', 'face', 'size'],
'footer' : [],
'form' : ['accept-charset', 'accept', 'action', 'autocomplete', 'enctype', 'method', 'name', 'novalidate', 'target'],
'frame' : ['frameborder', 'longdesc', 'marginheight', 'marginwidth', 'name', 'noresize', 'scrolling', 'src'],
'frameset' : ['cols', 'onunload', 'rows'],
'h1' : ['align'],
'h2' : ['align'],
'h3' : ['align'],
'h4' : ['align'],
'h5' : ['align'],
'h6' : ['align'],
'head' : ['profile'],
'header' : [],
'hr' : ['align', 'noshade', 'size', 'width'],
'html' : ['manifest', 'version', 'xmlns'],
'i' : [],
'iframe' : ['align', 'frameborder', 'height', 'longdesc', 'marginheight', 'marginwidth', 'name', 'sandbox', 'scrolling', 'seamless', 'src', 'srcdoc', 'width'],
'img' : ['align', 'alt', 'border', 'crossorigin', 'height', 'hspace', 'ismap', 'longdesc', 'name', 'sizes', 'src', 'srcset', 'usemap', 'vspace', 'width'],
'input' : ['accept', 'align', 'alt', 'autocomplete', 'autofocus', 'autosave', 'checked', 'disabled', 'form', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'height', 'inputmode', 'ismap', 'list', 'max', 'maxlength', 'min', 'minlength', 'multiple', 'name', 'pattern', 'placeholder', 'readonly', 'required', 'selectionDirection', 'size', 'spellcheck', 'src', 'step', 'tabindex', 'type', 'usemap', 'value', 'width'],
'ins' : ['cite', 'datetime'],
'isindex' : ['prompt'],
'kbd' : [],
'keygen' : ['autofocus', 'challenge', 'disabled', 'form', 'keytype', 'name'],
'label' : ['for', 'form'],
'legend' : [],
'li' : ['type', 'value'],
'link' : ['charset', 'crossorigin', 'href', 'hreflang', 'media', 'rel', 'rev', 'sizes', 'target', 'type'],
'main' : [],
'map' : ['name'],
'mark' : [],
'menu' : ['compact'],
'meta' : ['charset', 'content', 'http-equiv', 'name', 'scheme'],
'meter' : ['value', 'min', 'max', 'low', 'high', 'optimum', 'form'],
'nav' : [],
'noframes' : [],
'noscript' : [],
'object' : ['align', 'archive', 'border', 'classid', 'codebase', 'codetype', 'data', 'declare', 'form', 'height', 'hspace', 'name', 'standby', 'type', 'typemustmatch', 'usemap', 'vspace', 'width'],
'ol' : ['compact', 'reversed', 'start', 'type'],
'optgroup' : ['disabled', 'label'],
'option' : ['disabled', 'label', 'selected', 'value'],
'output' : ['for', 'form', 'name'],
'p' : ['align'],
'param' : ['name', 'type', 'value', 'valuetype'],
'picture' : [],
'pre' : ['width'],
'progress' : ['max', 'value'],
'q' : ['cite'],
'rp' : [],
'rt' : [],
'rtc' : [],
's' : [],
'samp' : [],
'script' : ['async', 'charset', 'defer', 'language', 'src', 'type'],
'section' : [],
'select' : ['autofocus', 'disabled', 'form', 'multiple', 'name', 'required', 'size'],
'shadow' : [],
'small' : [],
'source' : ['src', 'type'],
'span' : [],
'strong' : [],
'style' : ['disabled', 'media', 'scoped', 'title', 'type'],
'sub' : [],
'summary': [],
'sup' : [],
'table' : ['align', 'bgcolor', 'border', 'cellpadding', 'cellspacing', 'frame', 'rules', 'summary', 'width'],
'tbody' : ['align', 'char', 'charoff', 'valign'],
'td' : ['abbr', 'align', 'axis', 'bgcolor', 'char', 'charoff', 'colspan', 'headers', 'height', 'nowrap', 'rowspan', 'scope', 'valign', 'width'],
'template' : ['content'],
'textarea' : ['autocomplete', 'autofocus', 'cols', 'disabled', 'form', 'maxlength', 'minlength', 'name', 'placeholder', 'readonly', 'required', 'rows', 'selectionDirection', 'selectionEnd', 'selectionStart', 'spellcheck', 'wrap'],
'tfoot' : ['align', 'char', 'charoff', 'valign'],
'th' : ['abbr', 'align', 'axis', 'bgcolor', 'char', 'charoff', 'colspan', 'headers', 'height', 'nowrap', 'rowspan', 'scope', 'valign', 'width'],
'thead' : ['align', 'char', 'charoff', 'valign'],
'time' : ['datetime'],
'title' : [],
'tr' : ['align', 'bgcolor', 'char', 'charoff', 'valign'],
'track' : ['default', 'kind', 'label', 'src', 'srclang'],
'u' : [],
'ul' : ['compact', 'type'],
'var' : [],
'video' : ['autoplay', 'autobuffer', 'buffered', 'controls', 'crossorigin', 'height', 'loop', 'muted', 'played', 'preload', 'poster', 'src', 'width'],
'wbr' : []
}
# Assume that global attributes are common to all HTML elements
global_attributes = [
'accesskey', 'class', 'contenteditable', 'contextmenu', 'dir',
'hidden', 'id', 'lang', 'style', 'tabindex', 'title', 'translate'
]
# Extend `global_attributes` by the event handler attributes
global_attributes.extend([
'onabort', 'onautocomplete', 'onautocompleteerror', 'onblur',
'oncancel', 'oncanplay', 'oncanplaythrough', 'onchange', 'onclick',
'onclose', 'oncontextmenu', 'oncuechange', 'ondblclick', 'ondrag',
'ondragend', 'ondragenter', 'ondragexit', 'ondragleave', 'ondragover',
'ondragstart', 'ondrop', 'ondurationchange', 'onemptied', 'onended',
'onerror', 'onfocus', 'oninput', 'oninvalid', 'onkeydown',
'onkeypress', 'onkeyup', 'onload', 'onloadeddata', 'onloadedmetadata',
'onloadstart', 'onmousedown', 'onmouseenter', 'onmouseleave',
'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup',
'onmousewheel', 'onpause', 'onplay', 'onplaying', 'onprogress',
'onratechange', 'onreset', 'onresize', 'onscroll', 'onseeked',
'onseeking', 'onselect', 'onshow', 'onsort', 'onstalled', 'onsubmit',
'onsuspend', 'ontimeupdate', 'ontoggle', 'onvolumechange', 'onwaiting'
])
for attributes in tag_dict.values():
attributes.extend(global_attributes)
# Remove `dir` attribute from `bdi` key, because it is *not* inherited
# from the global attributes
if 'bdi' in tag_dict:
tag_dict['bdi'] = [attr for attr in tag_dict['bdi'] if attr != 'dir']
return tag_dict
class HtmlTagCompletions(sublime_plugin.EventListener):
"""
Provide tag completions for HTML
It matches just after typing the first letter of a tag name
"""
def __init__(self):
completion_list = self.default_completion_list()
self.prefix_completion_dict = {}
# construct a dictionary where the key is first character of
# the completion list to the completion
for s in completion_list:
prefix = s[0][0]
self.prefix_completion_dict.setdefault(prefix, []).append(s)
# construct a dictionary from (tag, attribute[0]) -> [attribute]
self.tag_to_attributes = get_tag_to_attributes()
def on_query_completions(self, view, prefix, locations):
# Only trigger within HTML
if not view.match_selector(locations[0], "text.html - source"):
return []
# check if we are inside a tag
is_inside_tag = view.match_selector(locations[0],
"text.html meta.tag - text.html punctuation.definition.tag.begin")
return self.get_completions(view, prefix, locations, is_inside_tag)
def get_completions(self, view, prefix, locations, is_inside_tag):
# see if it is in tag.attr or tag#attr format
if not is_inside_tag:
tag_attr_expr = self.expand_tag_attributes(view, locations)
if tag_attr_expr != []:
return (tag_attr_expr, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
pt = locations[0] - len(prefix) - 1
ch = view.substr(sublime.Region(pt, pt + 1))
# print('prefix:', prefix)
# print('location0:', locations[0])
# print('substr:', view.substr(sublime.Region(locations[0], locations[0] + 3)), '!end!')
# print('is_inside_tag', is_inside_tag)
# print('ch:', ch)
completion_list = []
if is_inside_tag and ch != '<':
if ch in [' ', '\t', '\n']:
# maybe trying to type an attribute
completion_list = self.get_attribute_completions(view, locations[0], prefix)
# only ever trigger completion inside a tag if the previous character is a <
# this is needed to stop completion from happening when typing attributes
return (completion_list, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
if prefix == '':
# need completion list to match
return ([], sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
# match completion list using prefix
completion_list = self.prefix_completion_dict.get(prefix[0], [])
# if the opening < is not here insert that
if ch != '<':
completion_list = [(pair[0], '<' + pair[1]) for pair in completion_list]
flags = 0
if is_inside_tag:
sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS
return (completion_list, flags)
def default_completion_list(self):
"""
Generate a default completion list for HTML
"""
default_list = []
normal_tags = ([
'abbr', 'acronym', 'address', 'applet', 'article', 'aside',
'audio', 'b', 'basefont', 'bdi', 'bdo', 'big', 'blockquote',
'body', 'button', 'center', 'canvas', 'caption', 'cdata',
'cite', 'colgroup', 'code', 'content', 'data', 'datalist',
'dir', 'div', 'dd', 'del', 'details', 'dfn', 'dl', 'dt', 'element',
'em', 'embed', 'fieldset', 'figure', 'figcaption', 'font', 'footer',
'form', 'frame', 'frameset', 'head', 'header', 'h1', 'h2', 'h3',
'h4', 'h5', 'h6', 'i', 'ins', 'isindex', 'kbd', 'keygen',
'li', 'label', 'legend', 'main', 'map', 'mark', 'meter',
'nav', 'noframes', 'noscript', 'object', 'ol', 'optgroup',
'option', 'output', 'p', 'picture', 'pre', 'q', 'rp',
'rt', 'rtc', 'ruby', 's', 'samp', 'section', 'select', 'shadow',
'small', 'span', 'strong', 'sub', 'summary', 'sup',
'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th',
'thead', 'time', 'title', 'tr', 'tt', 'u', 'ul', 'var',
'video',
'fest:template', 'fest:var', 'fest:value', 'fest:text', 'fest:space', 'fest:set', 'fest:get', 'fest:element', 'fest:attributes', 'fest:attribute', 'fest:each', 'fest:for', 'fest:if', 'fest:choose', 'fest:otherwise', 'fest:when', 'fest:cdata', 'fest:comment', 'fest:doctype', 'fest:script', 'fest:include', 'fest:insert', 'fest:message', 'fest:msg', 'fest:plural', 'fest:params', 'fest:param'
'i18n:msg'
])
for tag in normal_tags:
default_list.append(make_completion(tag))
default_list.append(make_completion(tag.upper()))
default_list += ([
('ftemplate\tTag', 'fest:template xmlns:fest=\"http://fest.mail.ru\">\n\t$0\n</fest:template>'),
('fvar\tTag', 'fest:var name=\"$1\">$0</fest:var>'),
('fvalue\tTag', 'fest:value>$0</fest:value>'),
('ftext\tTag', 'fest:text>$0</fest:text>'),
('fspace\tTag', 'fest:space/>'),
('fset\tTag', 'fest:set name=\"$1\">\n\t$0\n</fest:set>'),
('fget\tTag', 'fest:get name=\"$1\">\n\t{\n\t\t$0\n\t}\n</fest:get>'),
('felement\tTag', 'fest:element name=\"$1\">\n\t$0\n</fest:element>'),
('fattributes\tTag', 'fest:attributes>\n\t$0\n</fest:attributes>'),
('fattribute\tTag', 'fest:attribute name=\"$1\">$0</fest:attribute>'),
('feach\tTag', 'fest:each iterate=\"$1\" index=\"$2\" value=\"$3\">\n\t$0\n</fest:each>'),
('ffor\tTag', 'fest:for from=\"$1\" to=\"$2\" index=\"$3\">\n\t$0\n</fest:for>'),
('fif\tTag', 'fest:if test=\"$1\">\n\t$0\n</fest:if>'),
('fchoose\tTag', 'fest:choose>\n\t$0\n</fest:choose>'),
('fotherwise\tTag', 'fest:otherwise>\n\t$0\n</fest:otherwise>'),
('fwhen\tTag', 'fest:when test=\"$1\">\n\t$0\n</fest:when>'),
('fcdata\tTag', 'fest:cdata>\n\t$0\n</fest:cdata>'),
('fcomment\tTag', 'fest:comment>$0</fest:comment>'),
('fdoctype\tTag', 'fest:doctype>$0</fest:doctype>'),
('fscript\tTag', 'fest:script>\n\t<![CDATA[\n\t\t$0\n\t]]>\n</fest:script>'),
('finclude\tTag', 'fest:include context=\"$1\" src=\"$0\"/>'),
('finsert\tTag', 'fest:insert src=\"$0\"/>'),
('fmessage\tTag', 'fest:message context=\"$1\">$0</fest:message>'),
('fmsg\tTag', 'fest:msg context=\"$1\">$0</fest:msg>'),
('fplural\tTag', 'fest:plural select=\"$1\">%s $2|%s $3|%s $0</fest:plural>'),
('i18n\tTag', 'i18n:msg context=\"$1\" data-name=\"$2\">$0</i18n:msg>'),
('fparams\tTag', 'fest:params>\n\t{\n\t\t$0\n\t}\n</fest:params>'),
('fparam\tTag', 'fest:param name=\"$1\">\n\t$0\n</fest:param>'),
('a\tTag', 'a href=\"$1\">$0</a>'),
('area\tTag', 'area shape=\"$1\" coords=\"$2\" href=\"$3\">'),
('audio\tTag', 'audio src=\"$1\">$0</audio>'),
('base\tTag', 'base href=\"$1\">'),
('br\tTag', 'br/>'),
('col\tTag', 'col>'),
('hr\tTag', 'hr/>'),
('iframe\tTag', 'iframe src=\"$1\">$0</iframe>'),
('input\tTag', 'input type=\"$1\" name=\"$2\"/>'),
('img\tTag', 'img src=\"$1\"/>'),
('link\tTag', 'link rel=\"stylesheet\" type=\"text/css\" href=\"$1\"/>'),
('meta\tTag', 'meta ${1:charset=\"utf-8\"}/>'),
('param\tTag', 'param name=\"$1\" value=\"$2\"/>'),
('progress\tTag', 'progress value=\"$1\" max=\"$2\"/>'),
('script\tTag', 'script>\n\t<![CDATA[\n\t\t$0\n\t]]>\n</script>'),
('source\tTag', 'source src=\"$1\" type=\"$2\"/>'),
('style\tTag', 'style>$0</style>'),
('track\tTag', 'track kind=\"$1\" src=\"$2\"/>'),
('wbr\tTag', 'wbr/>'),
('video\tTag', 'video src=\"$1\">$0</video>')
])
return default_list
# This responds to on_query_completions, but conceptually it's expanding
# expressions, rather than completing words.
#
# It expands these simple expressions:
# tag.class
# tag#id
def expand_tag_attributes(self, view, locations):
# Get the contents of each line, from the beginning of the line to
# each point
lines = [view.substr(sublime.Region(view.line(l).a, l))
for l in locations]
# Reverse the contents of each line, to simulate having the regex
# match backwards
lines = [l[::-1] for l in lines]
# Check the first location looks like an expression
rex = re.compile("([\w-]+)([.#])(\w+)")
expr = match(rex, lines[0])
if not expr:
return []
# Ensure that all other lines have identical expressions
for i in range(1, len(lines)):
ex = match(rex, lines[i])
if ex != expr:
return []
# Return the completions
arg, op, tag = rex.match(expr).groups()
arg = arg[::-1]
tag = tag[::-1]
expr = expr[::-1]
if op == '.':
snippet = '<{0} class=\"{1}\">$1</{0}>$0'.format(tag, arg)
else:
snippet = '<{0} id=\"{1}\">$1</{0}>$0'.format(tag, arg)
return [(expr, snippet)]
def get_attribute_completions(self, view, pt, prefix):
SEARCH_LIMIT = 500
search_start = max(0, pt - SEARCH_LIMIT - len(prefix))
line = view.substr(sublime.Region(search_start, pt + SEARCH_LIMIT))
line_head = line[0:pt - search_start]
line_tail = line[pt - search_start:]
# find the tag from end of line_head
i = len(line_head) - 1
tag = None
space_index = len(line_head)
while i >= 0:
c = line_head[i]
if c == '<':
# found the open tag
tag = line_head[i + 1:space_index]
break
elif c == ' ':
space_index = i
i -= 1
# check that this tag looks valid
if not tag or not tag.isalnum():
return []
# determines whether we need to close the tag
# default to closing the tag
suffix = '>'
for c in line_tail:
if c == '>':
# found end tag
suffix = ''
break
elif c == '<':
# found another open tag, need to close this one
break
if suffix == '' and not line_tail.startswith(' ') and not line_tail.startswith('>'):
# add a space if not there
suffix = ' '
# got the tag, now find all attributes that match
attributes = self.tag_to_attributes.get(tag, [])
# ("class\tAttr", "class="$1">"),
attri_completions = [(a + '\tAttr', a + '="$1"' + suffix) for a in attributes]
return attri_completions
# unit testing
# to run it in sublime text:
# import HTML.html_completions
# HTML.html_completions.Unittest.run()
import unittest
class Unittest(unittest.TestCase):
class Sublime:
INHIBIT_WORD_COMPLETIONS = 1
INHIBIT_EXPLICIT_COMPLETIONS = 2
# this view contains a hard coded one line super simple HTML fragment
class View:
def __init__(self):
self.buf = '<tr><td class="a">td.class</td></tr>'
def line(self, pt):
# only ever 1 line
return sublime.Region(0, len(self.buf))
def substr(self, region):
return self.buf[region.a : region.b]
def run():
# redefine the modules to use the mock version
global sublime
sublime_module = sublime
# use the normal region
Unittest.Sublime.Region = sublime.Region
sublime = Unittest.Sublime
test = Unittest()
test.test_simple_completion()
test.test_inside_tag_completion()
test.test_inside_tag_no_completion()
test.test_expand_tag_attributes()
# set it back after testing
sublime = sublime_module
# def get_completions(self, view, prefix, locations, is_inside_tag):
def test_simple_completion(self):
# <tr><td class="a">td.class</td></tr>
view = Unittest.View()
completor = HtmlTagCompletions()
# simulate typing 'tab' at the start of the line, it is outside a tag
completion_list, flags = completor.get_completions(view, 'tab', [0], False)
# should give a bunch of tags that starts with t
self.assertEqual(completion_list[0], ('table\tTag', '<table>$0</table>'))
self.assertEqual(completion_list[1], ('tbody\tTag', '<tbody>$0</tbody>'))
# suppress word based completion
self.assertEqual(flags, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
def test_inside_tag_completion(self):
# <tr><td class="a">td.class</td></tr>
view = Unittest.View()
completor = HtmlTagCompletions()
# simulate typing 'h' after <tr><, i.e. <tr><h
completion_list, flags = completor.get_completions(view, 'h', [6], True)
# should give a bunch of tags that starts with h, and without <
self.assertEqual(completion_list[0], ('head\tTag', 'head>$0</head>'))
self.assertEqual(completion_list[1], ('h1\tTag', 'h1>$0</h1>'))
# suppress word based completion
self.assertEqual(flags, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
def test_inside_tag_no_completion(self):
# <tr><td class="a">td.class</td></tr>
view = Unittest.View()
completor = HtmlTagCompletions()
# simulate typing 'h' after <tr><td , i.e. <tr><td h
completion_list, flags = completor.get_completions(view, 'h', [8], True)
# should give nothing, but disable word based completions, since it is inside a tag
self.assertEqual(completion_list, [])
self.assertEqual(flags, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
def test_expand_tag_attributes(self):
# <tr><td class="a">td.class</td></tr>
view = Unittest.View()
completor = HtmlTagCompletions()
# simulate typing tab after td.class
completion_list, flags = completor.get_completions(view, '', [26], False)
# should give just one completion, and suppress word based completion
self.assertEqual(completion_list, [('td.class', '<td class="class">$1</td>$0')])
self.assertEqual(flags, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
|
/*
* This program 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 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/** \file
* \ingroup edtransform
*
* \name 3D Transform Gizmo
*
* Used for 3D View
*/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include "DNA_armature_types.h"
#include "DNA_curve_types.h"
#include "DNA_gpencil_types.h"
#include "DNA_lattice_types.h"
#include "DNA_meta_types.h"
#include "DNA_screen_types.h"
#include "DNA_scene_types.h"
#include "DNA_view3d_types.h"
#include "BLI_array_utils.h"
#include "BLI_listbase.h"
#include "BLI_math.h"
#include "BLI_utildefines.h"
#include "BLI_string.h"
#include "BKE_action.h"
#include "BKE_context.h"
#include "BKE_curve.h"
#include "BKE_global.h"
#include "BKE_layer.h"
#include "BKE_particle.h"
#include "BKE_pointcache.h"
#include "BKE_editmesh.h"
#include "BKE_lattice.h"
#include "BKE_gpencil.h"
#include "BKE_scene.h"
#include "BKE_workspace.h"
#include "BKE_object.h"
#include "BKE_paint.h"
#include "DEG_depsgraph.h"
#include "WM_api.h"
#include "WM_types.h"
#include "WM_message.h"
#include "WM_toolsystem.h"
#include "wm.h"
#include "ED_armature.h"
#include "ED_curve.h"
#include "ED_object.h"
#include "ED_particle.h"
#include "ED_view3d.h"
#include "ED_gpencil.h"
#include "ED_screen.h"
#include "ED_gizmo_library.h"
#include "ED_gizmo_utils.h"
#include "UI_interface.h"
#include "UI_resources.h"
#include "RNA_access.h"
#include "RNA_define.h"
/* local module include */
#include "transform.h"
#include "transform_convert.h"
#include "MEM_guardedalloc.h"
#include "GPU_state.h"
#include "DEG_depsgraph_query.h"
/* return codes for select, and drawing flags */
#define MAN_TRANS_X (1 << 0)
#define MAN_TRANS_Y (1 << 1)
#define MAN_TRANS_Z (1 << 2)
#define MAN_TRANS_C (MAN_TRANS_X | MAN_TRANS_Y | MAN_TRANS_Z)
#define MAN_ROT_X (1 << 3)
#define MAN_ROT_Y (1 << 4)
#define MAN_ROT_Z (1 << 5)
#define MAN_ROT_C (MAN_ROT_X | MAN_ROT_Y | MAN_ROT_Z)
#define MAN_SCALE_X (1 << 8)
#define MAN_SCALE_Y (1 << 9)
#define MAN_SCALE_Z (1 << 10)
#define MAN_SCALE_C (MAN_SCALE_X | MAN_SCALE_Y | MAN_SCALE_Z)
/* threshold for testing view aligned gizmo axis */
static struct {
float min, max;
} g_tw_axis_range[2] = {
/* Regular range */
{0.02f, 0.1f},
/* Use a different range because we flip the dot product,
* also the view aligned planes are harder to see so hiding early is preferred. */
{0.175f, 0.25f},
};
/* axes as index */
enum {
MAN_AXIS_TRANS_X = 0,
MAN_AXIS_TRANS_Y,
MAN_AXIS_TRANS_Z,
MAN_AXIS_TRANS_C,
MAN_AXIS_TRANS_XY,
MAN_AXIS_TRANS_YZ,
MAN_AXIS_TRANS_ZX,
#define MAN_AXIS_RANGE_TRANS_START MAN_AXIS_TRANS_X
#define MAN_AXIS_RANGE_TRANS_END (MAN_AXIS_TRANS_ZX + 1)
MAN_AXIS_ROT_X,
MAN_AXIS_ROT_Y,
MAN_AXIS_ROT_Z,
MAN_AXIS_ROT_C,
MAN_AXIS_ROT_T, /* trackball rotation */
#define MAN_AXIS_RANGE_ROT_START MAN_AXIS_ROT_X
#define MAN_AXIS_RANGE_ROT_END (MAN_AXIS_ROT_T + 1)
MAN_AXIS_SCALE_X,
MAN_AXIS_SCALE_Y,
MAN_AXIS_SCALE_Z,
MAN_AXIS_SCALE_C,
MAN_AXIS_SCALE_XY,
MAN_AXIS_SCALE_YZ,
MAN_AXIS_SCALE_ZX,
#define MAN_AXIS_RANGE_SCALE_START MAN_AXIS_SCALE_X
#define MAN_AXIS_RANGE_SCALE_END (MAN_AXIS_SCALE_ZX + 1)
MAN_AXIS_LAST = MAN_AXIS_SCALE_ZX + 1,
};
/* axis types */
enum {
MAN_AXES_ALL = 0,
MAN_AXES_TRANSLATE,
MAN_AXES_ROTATE,
MAN_AXES_SCALE,
};
typedef struct GizmoGroup {
bool all_hidden;
int twtype;
/* Users may change the twtype, detect changes to re-setup gizmo options. */
int twtype_init;
int twtype_prev;
int use_twtype_refresh;
/* Only for view orientation. */
struct {
float viewinv_m3[3][3];
} prev;
struct wmGizmo *gizmos[MAN_AXIS_LAST];
} GizmoGroup;
/* -------------------------------------------------------------------- */
/** \name Utilities
* \{ */
/* loop over axes */
#define MAN_ITER_AXES_BEGIN(axis, axis_idx) \
{ \
wmGizmo *axis; \
int axis_idx; \
for (axis_idx = 0; axis_idx < MAN_AXIS_LAST; axis_idx++) { \
axis = gizmo_get_axis_from_index(ggd, axis_idx);
#define MAN_ITER_AXES_END \
} \
} \
((void)0)
static wmGizmo *gizmo_get_axis_from_index(const GizmoGroup *ggd, const short axis_idx)
{
BLI_assert(IN_RANGE_INCL(axis_idx, (float)MAN_AXIS_TRANS_X, (float)MAN_AXIS_LAST));
return ggd->gizmos[axis_idx];
}
static short gizmo_get_axis_type(const int axis_idx)
{
if (axis_idx >= MAN_AXIS_RANGE_TRANS_START && axis_idx < MAN_AXIS_RANGE_TRANS_END) {
return MAN_AXES_TRANSLATE;
}
if (axis_idx >= MAN_AXIS_RANGE_ROT_START && axis_idx < MAN_AXIS_RANGE_ROT_END) {
return MAN_AXES_ROTATE;
}
if (axis_idx >= MAN_AXIS_RANGE_SCALE_START && axis_idx < MAN_AXIS_RANGE_SCALE_END) {
return MAN_AXES_SCALE;
}
BLI_assert(0);
return -1;
}
static uint gizmo_orientation_axis(const int axis_idx, bool *r_is_plane)
{
switch (axis_idx) {
case MAN_AXIS_TRANS_YZ:
case MAN_AXIS_SCALE_YZ:
if (r_is_plane) {
*r_is_plane = true;
}
ATTR_FALLTHROUGH;
case MAN_AXIS_TRANS_X:
case MAN_AXIS_ROT_X:
case MAN_AXIS_SCALE_X:
return 0;
case MAN_AXIS_TRANS_ZX:
case MAN_AXIS_SCALE_ZX:
if (r_is_plane) {
*r_is_plane = true;
}
ATTR_FALLTHROUGH;
case MAN_AXIS_TRANS_Y:
case MAN_AXIS_ROT_Y:
case MAN_AXIS_SCALE_Y:
return 1;
case MAN_AXIS_TRANS_XY:
case MAN_AXIS_SCALE_XY:
if (r_is_plane) {
*r_is_plane = true;
}
ATTR_FALLTHROUGH;
case MAN_AXIS_TRANS_Z:
case MAN_AXIS_ROT_Z:
case MAN_AXIS_SCALE_Z:
return 2;
}
return 3;
}
static bool gizmo_is_axis_visible(const RegionView3D *rv3d,
const int twtype,
const float idot[3],
const int axis_type,
const int axis_idx)
{
if ((axis_idx >= MAN_AXIS_RANGE_ROT_START && axis_idx < MAN_AXIS_RANGE_ROT_END) == 0) {
bool is_plane = false;
const uint aidx_norm = gizmo_orientation_axis(axis_idx, &is_plane);
/* don't draw axis perpendicular to the view */
if (aidx_norm < 3) {
float idot_axis = idot[aidx_norm];
if (is_plane) {
idot_axis = 1.0f - idot_axis;
}
if (idot_axis < g_tw_axis_range[is_plane].min) {
return false;
}
}
}
if ((axis_type == MAN_AXES_TRANSLATE && !(twtype & V3D_GIZMO_SHOW_OBJECT_TRANSLATE)) ||
(axis_type == MAN_AXES_ROTATE && !(twtype & V3D_GIZMO_SHOW_OBJECT_ROTATE)) ||
(axis_type == MAN_AXES_SCALE && !(twtype & V3D_GIZMO_SHOW_OBJECT_SCALE))) {
return false;
}
switch (axis_idx) {
case MAN_AXIS_TRANS_X:
return (rv3d->twdrawflag & MAN_TRANS_X);
case MAN_AXIS_TRANS_Y:
return (rv3d->twdrawflag & MAN_TRANS_Y);
case MAN_AXIS_TRANS_Z:
return (rv3d->twdrawflag & MAN_TRANS_Z);
case MAN_AXIS_TRANS_C:
return (rv3d->twdrawflag & MAN_TRANS_C);
case MAN_AXIS_ROT_X:
return (rv3d->twdrawflag & MAN_ROT_X);
case MAN_AXIS_ROT_Y:
return (rv3d->twdrawflag & MAN_ROT_Y);
case MAN_AXIS_ROT_Z:
return (rv3d->twdrawflag & MAN_ROT_Z);
case MAN_AXIS_ROT_C:
case MAN_AXIS_ROT_T:
return (rv3d->twdrawflag & MAN_ROT_C);
case MAN_AXIS_SCALE_X:
return (rv3d->twdrawflag & MAN_SCALE_X);
case MAN_AXIS_SCALE_Y:
return (rv3d->twdrawflag & MAN_SCALE_Y);
case MAN_AXIS_SCALE_Z:
return (rv3d->twdrawflag & MAN_SCALE_Z);
case MAN_AXIS_SCALE_C:
return (rv3d->twdrawflag & MAN_SCALE_C && (twtype & V3D_GIZMO_SHOW_OBJECT_TRANSLATE) == 0);
case MAN_AXIS_TRANS_XY:
return (rv3d->twdrawflag & MAN_TRANS_X && rv3d->twdrawflag & MAN_TRANS_Y &&
(twtype & V3D_GIZMO_SHOW_OBJECT_ROTATE) == 0);
case MAN_AXIS_TRANS_YZ:
return (rv3d->twdrawflag & MAN_TRANS_Y && rv3d->twdrawflag & MAN_TRANS_Z &&
(twtype & V3D_GIZMO_SHOW_OBJECT_ROTATE) == 0);
case MAN_AXIS_TRANS_ZX:
return (rv3d->twdrawflag & MAN_TRANS_Z && rv3d->twdrawflag & MAN_TRANS_X &&
(twtype & V3D_GIZMO_SHOW_OBJECT_ROTATE) == 0);
case MAN_AXIS_SCALE_XY:
return (rv3d->twdrawflag & MAN_SCALE_X && rv3d->twdrawflag & MAN_SCALE_Y &&
(twtype & V3D_GIZMO_SHOW_OBJECT_TRANSLATE) == 0 &&
(twtype & V3D_GIZMO_SHOW_OBJECT_ROTATE) == 0);
case MAN_AXIS_SCALE_YZ:
return (rv3d->twdrawflag & MAN_SCALE_Y && rv3d->twdrawflag & MAN_SCALE_Z &&
(twtype & V3D_GIZMO_SHOW_OBJECT_TRANSLATE) == 0 &&
(twtype & V3D_GIZMO_SHOW_OBJECT_ROTATE) == 0);
case MAN_AXIS_SCALE_ZX:
return (rv3d->twdrawflag & MAN_SCALE_Z && rv3d->twdrawflag & MAN_SCALE_X &&
(twtype & V3D_GIZMO_SHOW_OBJECT_TRANSLATE) == 0 &&
(twtype & V3D_GIZMO_SHOW_OBJECT_ROTATE) == 0);
}
return false;
}
static void gizmo_get_axis_color(const int axis_idx,
const float idot[3],
float r_col[4],
float r_col_hi[4])
{
/* alpha values for normal/highlighted states */
const float alpha = 0.6f;
const float alpha_hi = 1.0f;
float alpha_fac;
if (axis_idx >= MAN_AXIS_RANGE_ROT_START && axis_idx < MAN_AXIS_RANGE_ROT_END) {
/* Never fade rotation rings. */
/* trackball rotation axis is a special case, we only draw a slight overlay */
alpha_fac = (axis_idx == MAN_AXIS_ROT_T) ? 0.1f : 1.0f;
}
else {
bool is_plane = false;
const int axis_idx_norm = gizmo_orientation_axis(axis_idx, &is_plane);
/* Get alpha fac based on axis angle,
* to fade axis out when hiding it because it points towards view. */
if (axis_idx_norm < 3) {
const float idot_min = g_tw_axis_range[is_plane].min;
const float idot_max = g_tw_axis_range[is_plane].max;
float idot_axis = idot[axis_idx_norm];
if (is_plane) {
idot_axis = 1.0f - idot_axis;
}
alpha_fac = ((idot_axis > idot_max) ?
1.0f :
(idot_axis < idot_min) ? 0.0f :
((idot_axis - idot_min) / (idot_max - idot_min)));
}
else {
alpha_fac = 1.0f;
}
}
switch (axis_idx) {
case MAN_AXIS_TRANS_X:
case MAN_AXIS_ROT_X:
case MAN_AXIS_SCALE_X:
case MAN_AXIS_TRANS_YZ:
case MAN_AXIS_SCALE_YZ:
UI_GetThemeColor4fv(TH_AXIS_X, r_col);
break;
case MAN_AXIS_TRANS_Y:
case MAN_AXIS_ROT_Y:
case MAN_AXIS_SCALE_Y:
case MAN_AXIS_TRANS_ZX:
case MAN_AXIS_SCALE_ZX:
UI_GetThemeColor4fv(TH_AXIS_Y, r_col);
break;
case MAN_AXIS_TRANS_Z:
case MAN_AXIS_ROT_Z:
case MAN_AXIS_SCALE_Z:
case MAN_AXIS_TRANS_XY:
case MAN_AXIS_SCALE_XY:
UI_GetThemeColor4fv(TH_AXIS_Z, r_col);
break;
case MAN_AXIS_TRANS_C:
case MAN_AXIS_ROT_C:
case MAN_AXIS_SCALE_C:
case MAN_AXIS_ROT_T:
copy_v4_fl(r_col, 1.0f);
break;
}
copy_v4_v4(r_col_hi, r_col);
r_col[3] = alpha * alpha_fac;
r_col_hi[3] = alpha_hi * alpha_fac;
}
static void gizmo_get_axis_constraint(const int axis_idx, bool r_axis[3])
{
ARRAY_SET_ITEMS(r_axis, 0, 0, 0);
switch (axis_idx) {
case MAN_AXIS_TRANS_X:
case MAN_AXIS_ROT_X:
case MAN_AXIS_SCALE_X:
r_axis[0] = 1;
break;
case MAN_AXIS_TRANS_Y:
case MAN_AXIS_ROT_Y:
case MAN_AXIS_SCALE_Y:
r_axis[1] = 1;
break;
case MAN_AXIS_TRANS_Z:
case MAN_AXIS_ROT_Z:
case MAN_AXIS_SCALE_Z:
r_axis[2] = 1;
break;
case MAN_AXIS_TRANS_XY:
case MAN_AXIS_SCALE_XY:
r_axis[0] = r_axis[1] = 1;
break;
case MAN_AXIS_TRANS_YZ:
case MAN_AXIS_SCALE_YZ:
r_axis[1] = r_axis[2] = 1;
break;
case MAN_AXIS_TRANS_ZX:
case MAN_AXIS_SCALE_ZX:
r_axis[2] = r_axis[0] = 1;
break;
default:
break;
}
}
/* **************** Preparation Stuff **************** */
static void reset_tw_center(struct TransformBounds *tbounds)
{
INIT_MINMAX(tbounds->min, tbounds->max);
zero_v3(tbounds->center);
for (int i = 0; i < 3; i++) {
tbounds->axis_min[i] = +FLT_MAX;
tbounds->axis_max[i] = -FLT_MAX;
}
}
/* transform widget center calc helper for below */
static void calc_tw_center(struct TransformBounds *tbounds, const float co[3])
{
minmax_v3v3_v3(tbounds->min, tbounds->max, co);
add_v3_v3(tbounds->center, co);
for (int i = 0; i < 3; i++) {
const float d = dot_v3v3(tbounds->axis[i], co);
tbounds->axis_min[i] = min_ff(d, tbounds->axis_min[i]);
tbounds->axis_max[i] = max_ff(d, tbounds->axis_max[i]);
}
}
static void calc_tw_center_with_matrix(struct TransformBounds *tbounds,
const float co[3],
const bool use_matrix,
const float matrix[4][4])
{
float co_world[3];
if (use_matrix) {
mul_v3_m4v3(co_world, matrix, co);
co = co_world;
}
calc_tw_center(tbounds, co);
}
static void protectflag_to_drawflags(short protectflag, short *drawflags)
{
if (protectflag & OB_LOCK_LOCX) {
*drawflags &= ~MAN_TRANS_X;
}
if (protectflag & OB_LOCK_LOCY) {
*drawflags &= ~MAN_TRANS_Y;
}
if (protectflag & OB_LOCK_LOCZ) {
*drawflags &= ~MAN_TRANS_Z;
}
if (protectflag & OB_LOCK_ROTX) {
*drawflags &= ~MAN_ROT_X;
}
if (protectflag & OB_LOCK_ROTY) {
*drawflags &= ~MAN_ROT_Y;
}
if (protectflag & OB_LOCK_ROTZ) {
*drawflags &= ~MAN_ROT_Z;
}
if (protectflag & OB_LOCK_SCALEX) {
*drawflags &= ~MAN_SCALE_X;
}
if (protectflag & OB_LOCK_SCALEY) {
*drawflags &= ~MAN_SCALE_Y;
}
if (protectflag & OB_LOCK_SCALEZ) {
*drawflags &= ~MAN_SCALE_Z;
}
}
/* for pose mode */
static void protectflag_to_drawflags_pchan(RegionView3D *rv3d, const bPoseChannel *pchan)
{
protectflag_to_drawflags(pchan->protectflag, &rv3d->twdrawflag);
}
/* for editmode*/
static void protectflag_to_drawflags_ebone(RegionView3D *rv3d, const EditBone *ebo)
{
if (ebo->flag & BONE_EDITMODE_LOCKED) {
protectflag_to_drawflags(OB_LOCK_LOC | OB_LOCK_ROT | OB_LOCK_SCALE, &rv3d->twdrawflag);
}
}
/* could move into BLI_math however this is only useful for display/editing purposes */
static void axis_angle_to_gimbal_axis(float gmat[3][3], const float axis[3], const float angle)
{
/* X/Y are arbitrary axies, most importantly Z is the axis of rotation */
float cross_vec[3];
float quat[4];
/* this is an un-scientific method to get a vector to cross with
* XYZ intentionally YZX */
cross_vec[0] = axis[1];
cross_vec[1] = axis[2];
cross_vec[2] = axis[0];
/* X-axis */
cross_v3_v3v3(gmat[0], cross_vec, axis);
normalize_v3(gmat[0]);
axis_angle_to_quat(quat, axis, angle);
mul_qt_v3(quat, gmat[0]);
/* Y-axis */
axis_angle_to_quat(quat, axis, M_PI_2);
copy_v3_v3(gmat[1], gmat[0]);
mul_qt_v3(quat, gmat[1]);
/* Z-axis */
copy_v3_v3(gmat[2], axis);
normalize_m3(gmat);
}
static bool test_rotmode_euler(short rotmode)
{
return (ELEM(rotmode, ROT_MODE_AXISANGLE, ROT_MODE_QUAT)) ? 0 : 1;
}
bool gimbal_axis(Object *ob, float gmat[3][3])
{
if (ob->mode & OB_MODE_POSE) {
bPoseChannel *pchan = BKE_pose_channel_active(ob);
if (pchan) {
float mat[3][3], tmat[3][3], obmat[3][3];
if (test_rotmode_euler(pchan->rotmode)) {
eulO_to_gimbal_axis(mat, pchan->eul, pchan->rotmode);
}
else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
axis_angle_to_gimbal_axis(mat, pchan->rotAxis, pchan->rotAngle);
}
else { /* quat */
return 0;
}
/* apply bone transformation */
mul_m3_m3m3(tmat, pchan->bone->bone_mat, mat);
if (pchan->parent) {
float parent_mat[3][3];
copy_m3_m4(parent_mat, pchan->parent->pose_mat);
mul_m3_m3m3(mat, parent_mat, tmat);
/* needed if object transformation isn't identity */
copy_m3_m4(obmat, ob->obmat);
mul_m3_m3m3(gmat, obmat, mat);
}
else {
/* needed if object transformation isn't identity */
copy_m3_m4(obmat, ob->obmat);
mul_m3_m3m3(gmat, obmat, tmat);
}
normalize_m3(gmat);
return 1;
}
}
else {
if (test_rotmode_euler(ob->rotmode)) {
eulO_to_gimbal_axis(gmat, ob->rot, ob->rotmode);
}
else if (ob->rotmode == ROT_MODE_AXISANGLE) {
axis_angle_to_gimbal_axis(gmat, ob->rotAxis, ob->rotAngle);
}
else { /* quat */
return 0;
}
if (ob->parent) {
float parent_mat[3][3];
copy_m3_m4(parent_mat, ob->parent->obmat);
normalize_m3(parent_mat);
mul_m3_m3m3(gmat, parent_mat, gmat);
}
return 1;
}
return 0;
}
void ED_transform_calc_orientation_from_type(const bContext *C, float r_mat[3][3])
{
ARegion *ar = CTX_wm_region(C);
Scene *scene = CTX_data_scene(C);
ViewLayer *view_layer = CTX_data_view_layer(C);
Object *obedit = CTX_data_edit_object(C);
RegionView3D *rv3d = ar->regiondata;
Object *ob = OBACT(view_layer);
const short orientation_type = scene->orientation_slots[SCE_ORIENT_DEFAULT].type;
const short orientation_index_custom = scene->orientation_slots[SCE_ORIENT_DEFAULT].index_custom;
const int pivot_point = scene->toolsettings->transform_pivot_point;
ED_transform_calc_orientation_from_type_ex(
C, r_mat, scene, rv3d, ob, obedit, orientation_type, orientation_index_custom, pivot_point);
}
void ED_transform_calc_orientation_from_type_ex(const bContext *C,
float r_mat[3][3],
/* extra args (can be accessed from context) */
Scene *scene,
RegionView3D *rv3d,
Object *ob,
Object *obedit,
const short orientation_type,
int orientation_index_custom,
const int pivot_point)
{
bool ok = false;
switch (orientation_type) {
case V3D_ORIENT_GLOBAL: {
break; /* nothing to do */
}
case V3D_ORIENT_GIMBAL: {
if (gimbal_axis(ob, r_mat)) {
ok = true;
break;
}
/* if not gimbal, fall through to normal */
ATTR_FALLTHROUGH;
}
case V3D_ORIENT_NORMAL: {
if (obedit || ob->mode & OB_MODE_POSE) {
ED_getTransformOrientationMatrix(C, r_mat, pivot_point);
ok = true;
break;
}
/* no break we define 'normal' as 'local' in Object mode */
ATTR_FALLTHROUGH;
}
case V3D_ORIENT_LOCAL: {
if (ob->mode & OB_MODE_POSE) {
/* each bone moves on its own local axis, but to avoid confusion,
* use the active pones axis for display [#33575], this works as expected on a single bone
* and users who select many bones will understand what's going on and what local means
* when they start transforming */
ED_getTransformOrientationMatrix(C, r_mat, pivot_point);
ok = true;
break;
}
copy_m3_m4(r_mat, ob->obmat);
normalize_m3(r_mat);
ok = true;
break;
}
case V3D_ORIENT_VIEW: {
if (rv3d != NULL) {
copy_m3_m4(r_mat, rv3d->viewinv);
normalize_m3(r_mat);
ok = true;
}
break;
}
case V3D_ORIENT_CURSOR: {
BKE_scene_cursor_rot_to_mat3(&scene->cursor, r_mat);
ok = true;
break;
}
case V3D_ORIENT_CUSTOM: {
TransformOrientation *custom_orientation = BKE_scene_transform_orientation_find(
scene, orientation_index_custom);
if (applyTransformOrientation(custom_orientation, r_mat, NULL)) {
ok = true;
}
break;
}
}
if (!ok) {
unit_m3(r_mat);
}
}
/* centroid, boundbox, of selection */
/* returns total items selected */
int ED_transform_calc_gizmo_stats(const bContext *C,
const struct TransformCalcParams *params,
struct TransformBounds *tbounds)
{
ScrArea *sa = CTX_wm_area(C);
ARegion *ar = CTX_wm_region(C);
Scene *scene = CTX_data_scene(C);
/* TODO(sergey): This function is used from operator's modal() and from gizmo's refresh().
* Is it fine to possibly evaluate dependency graph here? */
Depsgraph *depsgraph = CTX_data_expect_evaluated_depsgraph(C);
ViewLayer *view_layer = CTX_data_view_layer(C);
View3D *v3d = sa->spacedata.first;
Object *obedit = CTX_data_edit_object(C);
RegionView3D *rv3d = ar->regiondata;
Base *base;
Object *ob = OBACT(view_layer);
bGPdata *gpd = CTX_data_gpencil_data(C);
const bool is_gp_edit = GPENCIL_ANY_MODE(gpd);
int a, totsel = 0;
const int pivot_point = scene->toolsettings->transform_pivot_point;
/* transform widget matrix */
unit_m4(rv3d->twmat);
unit_m3(rv3d->tw_axis_matrix);
zero_v3(rv3d->tw_axis_min);
zero_v3(rv3d->tw_axis_max);
rv3d->twdrawflag = 0xFFFF;
/* global, local or normal orientation?
* if we could check 'totsel' now, this should be skipped with no selection. */
if (ob) {
const short orientation_type = params->orientation_type ?
(params->orientation_type - 1) :
scene->orientation_slots[SCE_ORIENT_DEFAULT].type;
const short orientation_index_custom =
params->orientation_type ? params->orientation_index_custom :
scene->orientation_slots[SCE_ORIENT_DEFAULT].index_custom;
float mat[3][3];
ED_transform_calc_orientation_from_type_ex(
C, mat, scene, rv3d, ob, obedit, orientation_type, orientation_index_custom, pivot_point);
copy_m4_m3(rv3d->twmat, mat);
}
/* transform widget centroid/center */
reset_tw_center(tbounds);
copy_m3_m4(tbounds->axis, rv3d->twmat);
if (params->use_local_axis && (ob && ob->mode & OB_MODE_EDIT)) {
float diff_mat[3][3];
copy_m3_m4(diff_mat, ob->obmat);
normalize_m3(diff_mat);
invert_m3(diff_mat);
mul_m3_m3m3(tbounds->axis, tbounds->axis, diff_mat);
normalize_m3(tbounds->axis);
}
if (is_gp_edit) {
float diff_mat[4][4];
const bool use_mat_local = true;
for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
/* only editable and visible layers are considered */
if (gpencil_layer_is_editable(gpl) && (gpl->actframe != NULL)) {
/* calculate difference matrix */
ED_gpencil_parent_location(depsgraph, ob, gpd, gpl, diff_mat);
for (bGPDstroke *gps = gpl->actframe->strokes.first; gps; gps = gps->next) {
/* skip strokes that are invalid for current view */
if (ED_gpencil_stroke_can_use(C, gps) == false) {
continue;
}
/* we're only interested in selected points here... */
if (gps->flag & GP_STROKE_SELECT) {
bGPDspoint *pt;
int i;
/* Change selection status of all points, then make the stroke match */
for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) {
if (pt->flag & GP_SPOINT_SELECT) {
calc_tw_center_with_matrix(tbounds, &pt->x, use_mat_local, diff_mat);
totsel++;
}
}
}
}
}
}
/* selection center */
if (totsel) {
mul_v3_fl(tbounds->center, 1.0f / (float)totsel); /* centroid! */
}
}
else if (obedit) {
#define FOREACH_EDIT_OBJECT_BEGIN(ob_iter, use_mat_local) \
{ \
invert_m4_m4(obedit->imat, obedit->obmat); \
uint objects_len = 0; \
Object **objects = BKE_view_layer_array_from_objects_in_edit_mode( \
view_layer, CTX_wm_view3d(C), &objects_len); \
for (uint ob_index = 0; ob_index < objects_len; ob_index++) { \
Object *ob_iter = objects[ob_index]; \
const bool use_mat_local = (ob_iter != obedit);
#define FOREACH_EDIT_OBJECT_END() \
} \
MEM_freeN(objects); \
} \
((void)0)
ob = obedit;
if (obedit->type == OB_MESH) {
FOREACH_EDIT_OBJECT_BEGIN (ob_iter, use_mat_local) {
BMEditMesh *em_iter = BKE_editmesh_from_object(ob_iter);
BMesh *bm = em_iter->bm;
if (bm->totvertsel == 0) {
continue;
}
BMVert *eve;
BMIter iter;
float mat_local[4][4];
if (use_mat_local) {
mul_m4_m4m4(mat_local, obedit->imat, ob_iter->obmat);
}
BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
calc_tw_center_with_matrix(tbounds, eve->co, use_mat_local, mat_local);
totsel++;
}
}
}
}
FOREACH_EDIT_OBJECT_END();
} /* end editmesh */
else if (obedit->type == OB_ARMATURE) {
FOREACH_EDIT_OBJECT_BEGIN (ob_iter, use_mat_local) {
bArmature *arm = ob_iter->data;
float mat_local[4][4];
if (use_mat_local) {
mul_m4_m4m4(mat_local, obedit->imat, ob_iter->obmat);
}
for (EditBone *ebo = arm->edbo->first; ebo; ebo = ebo->next) {
if (EBONE_VISIBLE(arm, ebo)) {
if (ebo->flag & BONE_TIPSEL) {
calc_tw_center_with_matrix(tbounds, ebo->tail, use_mat_local, mat_local);
totsel++;
}
if ((ebo->flag & BONE_ROOTSEL) &&
/* don't include same point multiple times */
((ebo->flag & BONE_CONNECTED) && (ebo->parent != NULL) &&
(ebo->parent->flag & BONE_TIPSEL) && EBONE_VISIBLE(arm, ebo->parent)) == 0) {
calc_tw_center_with_matrix(tbounds, ebo->head, use_mat_local, mat_local);
totsel++;
}
if (ebo->flag & BONE_SELECTED) {
protectflag_to_drawflags_ebone(rv3d, ebo);
}
}
}
}
FOREACH_EDIT_OBJECT_END();
}
else if (ELEM(obedit->type, OB_CURVE, OB_SURF)) {
FOREACH_EDIT_OBJECT_BEGIN (ob_iter, use_mat_local) {
Curve *cu = ob_iter->data;
Nurb *nu;
BezTriple *bezt;
BPoint *bp;
ListBase *nurbs = BKE_curve_editNurbs_get(cu);
float mat_local[4][4];
if (use_mat_local) {
mul_m4_m4m4(mat_local, obedit->imat, ob_iter->obmat);
}
nu = nurbs->first;
while (nu) {
if (nu->type == CU_BEZIER) {
bezt = nu->bezt;
a = nu->pntsu;
while (a--) {
/* exceptions
* if handles are hidden then only check the center points.
* If the center knot is selected then only use this as the center point.
*/
if ((v3d->overlay.edit_flag & V3D_OVERLAY_EDIT_CU_HANDLES) == 0) {
if (bezt->f2 & SELECT) {
calc_tw_center_with_matrix(tbounds, bezt->vec[1], use_mat_local, mat_local);
totsel++;
}
}
else if (bezt->f2 & SELECT) {
calc_tw_center_with_matrix(tbounds, bezt->vec[1], use_mat_local, mat_local);
totsel++;
}
else {
if (bezt->f1 & SELECT) {
const float *co = bezt->vec[(pivot_point == V3D_AROUND_LOCAL_ORIGINS) ? 1 : 0];
calc_tw_center_with_matrix(tbounds, co, use_mat_local, mat_local);
totsel++;
}
if (bezt->f3 & SELECT) {
const float *co = bezt->vec[(pivot_point == V3D_AROUND_LOCAL_ORIGINS) ? 1 : 2];
calc_tw_center_with_matrix(tbounds, co, use_mat_local, mat_local);
totsel++;
}
}
bezt++;
}
}
else {
bp = nu->bp;
a = nu->pntsu * nu->pntsv;
while (a--) {
if (bp->f1 & SELECT) {
calc_tw_center_with_matrix(tbounds, bp->vec, use_mat_local, mat_local);
totsel++;
}
bp++;
}
}
nu = nu->next;
}
}
FOREACH_EDIT_OBJECT_END();
}
else if (obedit->type == OB_MBALL) {
FOREACH_EDIT_OBJECT_BEGIN (ob_iter, use_mat_local) {
MetaBall *mb = (MetaBall *)ob_iter->data;
float mat_local[4][4];
if (use_mat_local) {
mul_m4_m4m4(mat_local, obedit->imat, ob_iter->obmat);
}
for (MetaElem *ml = mb->editelems->first; ml; ml = ml->next) {
if (ml->flag & SELECT) {
calc_tw_center_with_matrix(tbounds, &ml->x, use_mat_local, mat_local);
totsel++;
}
}
}
FOREACH_EDIT_OBJECT_END();
}
else if (obedit->type == OB_LATTICE) {
FOREACH_EDIT_OBJECT_BEGIN (ob_iter, use_mat_local) {
Lattice *lt = ((Lattice *)ob_iter->data)->editlatt->latt;
BPoint *bp = lt->def;
a = lt->pntsu * lt->pntsv * lt->pntsw;
float mat_local[4][4];
if (use_mat_local) {
mul_m4_m4m4(mat_local, obedit->imat, ob_iter->obmat);
}
while (a--) {
if (bp->f1 & SELECT) {
calc_tw_center_with_matrix(tbounds, bp->vec, use_mat_local, mat_local);
totsel++;
}
bp++;
}
}
FOREACH_EDIT_OBJECT_END();
}
#undef FOREACH_EDIT_OBJECT_BEGIN
#undef FOREACH_EDIT_OBJECT_END
/* selection center */
if (totsel) {
mul_v3_fl(tbounds->center, 1.0f / (float)totsel); // centroid!
mul_m4_v3(obedit->obmat, tbounds->center);
mul_m4_v3(obedit->obmat, tbounds->min);
mul_m4_v3(obedit->obmat, tbounds->max);
}
}
else if (ob && (ob->mode & OB_MODE_POSE)) {
invert_m4_m4(ob->imat, ob->obmat);
uint objects_len = 0;
Object **objects = BKE_view_layer_array_from_objects_in_mode(
view_layer, v3d, &objects_len, {.object_mode = OB_MODE_POSE});
for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
Object *ob_iter = objects[ob_index];
const bool use_mat_local = (ob_iter != ob);
bPoseChannel *pchan;
/* mislead counting bones... bah. We don't know the gizmo mode, could be mixed */
const int mode = TFM_ROTATION;
const int totsel_iter = count_set_pose_transflags(
ob_iter, mode, V3D_AROUND_CENTER_BOUNDS, NULL);
if (totsel_iter) {
float mat_local[4][4];
if (use_mat_local) {
mul_m4_m4m4(mat_local, ob->imat, ob_iter->obmat);
}
/* use channels to get stats */
for (pchan = ob_iter->pose->chanbase.first; pchan; pchan = pchan->next) {
Bone *bone = pchan->bone;
if (bone && (bone->flag & BONE_TRANSFORM)) {
calc_tw_center_with_matrix(tbounds, pchan->pose_head, use_mat_local, mat_local);
protectflag_to_drawflags_pchan(rv3d, pchan);
}
}
totsel += totsel_iter;
}
}
MEM_freeN(objects);
if (totsel) {
mul_v3_fl(tbounds->center, 1.0f / (float)totsel); // centroid!
mul_m4_v3(ob->obmat, tbounds->center);
mul_m4_v3(ob->obmat, tbounds->min);
mul_m4_v3(ob->obmat, tbounds->max);
}
}
else if (ob && (ob->mode & OB_MODE_ALL_PAINT)) {
if (ob->mode & OB_MODE_SCULPT) {
totsel = 1;
calc_tw_center_with_matrix(tbounds, ob->sculpt->pivot_pos, false, ob->obmat);
mul_m4_v3(ob->obmat, tbounds->center);
mul_m4_v3(ob->obmat, tbounds->min);
mul_m4_v3(ob->obmat, tbounds->max);
}
}
else if (ob && ob->mode & OB_MODE_PARTICLE_EDIT) {
PTCacheEdit *edit = PE_get_current(depsgraph, scene, ob);
PTCacheEditPoint *point;
PTCacheEditKey *ek;
int k;
if (edit) {
point = edit->points;
for (a = 0; a < edit->totpoint; a++, point++) {
if (point->flag & PEP_HIDE) {
continue;
}
for (k = 0, ek = point->keys; k < point->totkey; k++, ek++) {
if (ek->flag & PEK_SELECT) {
calc_tw_center(tbounds, (ek->flag & PEK_USE_WCO) ? ek->world_co : ek->co);
totsel++;
}
}
}
/* selection center */
if (totsel) {
mul_v3_fl(tbounds->center, 1.0f / (float)totsel); // centroid!
}
}
}
else {
/* we need the one selected object, if its not active */
base = BASACT(view_layer);
ob = OBACT(view_layer);
if (base && ((base->flag & BASE_SELECTED) == 0)) {
ob = NULL;
}
for (base = view_layer->object_bases.first; base; base = base->next) {
if (!BASE_SELECTED_EDITABLE(v3d, base)) {
continue;
}
if (ob == NULL) {
ob = base->object;
}
/* Get the boundbox out of the evaluated object. */
const BoundBox *bb = NULL;
if (params->use_only_center == false) {
bb = BKE_object_boundbox_get(base->object);
}
if (params->use_only_center || (bb == NULL)) {
calc_tw_center(tbounds, base->object->obmat[3]);
}
else {
for (uint j = 0; j < 8; j++) {
float co[3];
mul_v3_m4v3(co, base->object->obmat, bb->vec[j]);
calc_tw_center(tbounds, co);
}
}
protectflag_to_drawflags(base->object->protectflag, &rv3d->twdrawflag);
totsel++;
}
/* selection center */
if (totsel) {
mul_v3_fl(tbounds->center, 1.0f / (float)totsel); // centroid!
}
}
if (totsel == 0) {
unit_m4(rv3d->twmat);
}
else {
copy_v3_v3(rv3d->tw_axis_min, tbounds->axis_min);
copy_v3_v3(rv3d->tw_axis_max, tbounds->axis_max);
copy_m3_m3(rv3d->tw_axis_matrix, tbounds->axis);
}
return totsel;
}
static void gizmo_get_idot(RegionView3D *rv3d, float r_idot[3])
{
float view_vec[3], axis_vec[3];
ED_view3d_global_to_vector(rv3d, rv3d->twmat[3], view_vec);
for (int i = 0; i < 3; i++) {
normalize_v3_v3(axis_vec, rv3d->twmat[i]);
r_idot[i] = 1.0f - fabsf(dot_v3v3(view_vec, axis_vec));
}
}
static void gizmo_prepare_mat(const bContext *C,
RegionView3D *rv3d,
const struct TransformBounds *tbounds)
{
Scene *scene = CTX_data_scene(C);
ViewLayer *view_layer = CTX_data_view_layer(C);
switch (scene->toolsettings->transform_pivot_point) {
case V3D_AROUND_CENTER_BOUNDS:
case V3D_AROUND_ACTIVE: {
mid_v3_v3v3(rv3d->twmat[3], tbounds->min, tbounds->max);
if (scene->toolsettings->transform_pivot_point == V3D_AROUND_ACTIVE) {
bGPdata *gpd = CTX_data_gpencil_data(C);
if (gpd && (gpd->flag & GP_DATA_STROKE_EDITMODE)) {
/* pass */
}
else {
Object *ob = OBACT(view_layer);
if (ob != NULL) {
if ((ob->mode & OB_MODE_ALL_SCULPT) && ob->sculpt) {
SculptSession *ss = ob->sculpt;
copy_v3_v3(rv3d->twmat[3], ss->pivot_pos);
}
else {
ED_object_calc_active_center(ob, false, rv3d->twmat[3]);
}
}
}
}
break;
}
case V3D_AROUND_LOCAL_ORIGINS:
case V3D_AROUND_CENTER_MEDIAN:
copy_v3_v3(rv3d->twmat[3], tbounds->center);
break;
case V3D_AROUND_CURSOR:
copy_v3_v3(rv3d->twmat[3], scene->cursor.location);
break;
}
}
/**
* Sets up \a r_start and \a r_len to define arrow line range.
* Needed to adjust line drawing for combined gizmo axis types.
*/
static void gizmo_line_range(const int twtype, const short axis_type, float *r_start, float *r_len)
{
const float ofs = 0.2f;
*r_start = 0.2f;
*r_len = 1.0f;
switch (axis_type) {
case MAN_AXES_TRANSLATE:
if (twtype & V3D_GIZMO_SHOW_OBJECT_SCALE) {
*r_start = *r_len - ofs + 0.075f;
}
if (twtype & V3D_GIZMO_SHOW_OBJECT_ROTATE) {
*r_len += ofs;
}
break;
case MAN_AXES_SCALE:
if (twtype & (V3D_GIZMO_SHOW_OBJECT_TRANSLATE | V3D_GIZMO_SHOW_OBJECT_ROTATE)) {
*r_len -= ofs + 0.025f;
}
break;
}
*r_len -= *r_start;
}
static void gizmo_xform_message_subscribe(wmGizmoGroup *gzgroup,
struct wmMsgBus *mbus,
Scene *scene,
bScreen *screen,
ScrArea *sa,
ARegion *ar,
const void *type_fn)
{
/* Subscribe to view properties */
wmMsgSubscribeValue msg_sub_value_gz_tag_refresh = {
.owner = ar,
.user_data = gzgroup->parent_gzmap,
.notify = WM_gizmo_do_msg_notify_tag_refresh,
};
int orient_flag = 0;
if (type_fn == VIEW3D_GGT_xform_gizmo) {
GizmoGroup *ggd = gzgroup->customdata;
orient_flag = ggd->twtype_init;
}
else if (type_fn == VIEW3D_GGT_xform_cage) {
orient_flag = V3D_GIZMO_SHOW_OBJECT_SCALE;
/* pass */
}
else if (type_fn == VIEW3D_GGT_xform_shear) {
orient_flag = V3D_GIZMO_SHOW_OBJECT_ROTATE;
}
TransformOrientationSlot *orient_slot = BKE_scene_orientation_slot_get_from_flag(scene,
orient_flag);
PointerRNA orient_ref_ptr;
RNA_pointer_create(&scene->id, &RNA_TransformOrientationSlot, orient_slot, &orient_ref_ptr);
const ToolSettings *ts = scene->toolsettings;
PointerRNA scene_ptr;
RNA_id_pointer_create(&scene->id, &scene_ptr);
{
extern PropertyRNA rna_Scene_transform_orientation_slots;
const PropertyRNA *props[] = {
&rna_Scene_transform_orientation_slots,
};
for (int i = 0; i < ARRAY_SIZE(props); i++) {
WM_msg_subscribe_rna(mbus, &scene_ptr, props[i], &msg_sub_value_gz_tag_refresh, __func__);
}
}
if ((ts->transform_pivot_point == V3D_AROUND_CURSOR) ||
(orient_slot->type == V3D_ORIENT_CURSOR)) {
/* We could be more specific here, for now subscribe to any cursor change. */
PointerRNA cursor_ptr;
RNA_pointer_create(&scene->id, &RNA_View3DCursor, &scene->cursor, &cursor_ptr);
WM_msg_subscribe_rna(mbus, &cursor_ptr, NULL, &msg_sub_value_gz_tag_refresh, __func__);
}
{
extern PropertyRNA rna_TransformOrientationSlot_type;
extern PropertyRNA rna_TransformOrientationSlot_use;
const PropertyRNA *props[] = {
&rna_TransformOrientationSlot_type,
&rna_TransformOrientationSlot_use,
};
for (int i = 0; i < ARRAY_SIZE(props); i++) {
if (props[i]) {
WM_msg_subscribe_rna(
mbus, &orient_ref_ptr, props[i], &msg_sub_value_gz_tag_refresh, __func__);
}
}
}
PointerRNA toolsettings_ptr;
RNA_pointer_create(&scene->id, &RNA_ToolSettings, scene->toolsettings, &toolsettings_ptr);
if (ELEM(type_fn, VIEW3D_GGT_xform_gizmo, VIEW3D_GGT_xform_shear)) {
extern PropertyRNA rna_ToolSettings_transform_pivot_point;
const PropertyRNA *props[] = {
&rna_ToolSettings_transform_pivot_point,
};
for (int i = 0; i < ARRAY_SIZE(props); i++) {
WM_msg_subscribe_rna(
mbus, &toolsettings_ptr, props[i], &msg_sub_value_gz_tag_refresh, __func__);
}
}
PointerRNA view3d_ptr;
RNA_pointer_create(&screen->id, &RNA_SpaceView3D, sa->spacedata.first, &view3d_ptr);
if (type_fn == VIEW3D_GGT_xform_gizmo) {
GizmoGroup *ggd = gzgroup->customdata;
if (ggd->use_twtype_refresh) {
extern PropertyRNA rna_SpaceView3D_show_gizmo_object_translate;
extern PropertyRNA rna_SpaceView3D_show_gizmo_object_rotate;
extern PropertyRNA rna_SpaceView3D_show_gizmo_object_scale;
const PropertyRNA *props[] = {
&rna_SpaceView3D_show_gizmo_object_translate,
&rna_SpaceView3D_show_gizmo_object_rotate,
&rna_SpaceView3D_show_gizmo_object_scale,
};
for (int i = 0; i < ARRAY_SIZE(props); i++) {
WM_msg_subscribe_rna(mbus, &view3d_ptr, props[i], &msg_sub_value_gz_tag_refresh, __func__);
}
}
}
else if (type_fn == VIEW3D_GGT_xform_cage) {
/* pass */
}
else if (type_fn == VIEW3D_GGT_xform_shear) {
/* pass */
}
else {
BLI_assert(0);
}
WM_msg_subscribe_rna_anon_prop(mbus, Window, view_layer, &msg_sub_value_gz_tag_refresh);
}
void drawDial3d(const TransInfo *t)
{
if (t->mode == TFM_ROTATION && t->spacetype == SPACE_VIEW3D) {
wmGizmo *gz = wm_gizmomap_modal_get(t->ar->gizmo_map);
if (gz == NULL) {
/* We only draw Dial3d if the operator has been called by a gizmo. */
return;
}
float mat_basis[4][4];
float mat_final[4][4];
float color[4];
float increment;
float line_with = GIZMO_AXIS_LINE_WIDTH + 1.0f;
float scale = UI_DPI_FAC * U.gizmo_size;
int axis_idx;
const TransCon *tc = &(t->con);
if (tc->mode & CON_APPLY) {
if (tc->mode & CON_AXIS0) {
axis_idx = MAN_AXIS_ROT_X;
negate_v3_v3(mat_basis[2], tc->mtx[0]);
}
else if (tc->mode & CON_AXIS1) {
axis_idx = MAN_AXIS_ROT_Y;
negate_v3_v3(mat_basis[2], tc->mtx[1]);
}
else {
BLI_assert((tc->mode & CON_AXIS2) != 0);
axis_idx = MAN_AXIS_ROT_Z;
negate_v3_v3(mat_basis[2], tc->mtx[2]);
}
}
else {
axis_idx = MAN_AXIS_ROT_C;
negate_v3_v3(mat_basis[2], t->orient_matrix[t->orient_axis]);
scale *= 1.2f;
line_with -= 1.0f;
}
copy_v3_v3(mat_basis[3], t->center_global);
mat_basis[2][3] = -dot_v3v3(mat_basis[2], mat_basis[3]);
if (ED_view3d_win_to_3d_on_plane(
t->ar, mat_basis[2], (float[2]){UNPACK2(t->mouse.imval)}, false, mat_basis[1])) {
sub_v3_v3(mat_basis[1], mat_basis[3]);
normalize_v3(mat_basis[1]);
cross_v3_v3v3(mat_basis[0], mat_basis[1], mat_basis[2]);
}
else {
/* The plane and the mouse direction are parallel.
* Calculate a matrix orthogonal to the axis. */
ortho_basis_v3v3_v3(mat_basis[0], mat_basis[1], mat_basis[2]);
}
mat_basis[0][3] = 0.0f;
mat_basis[1][3] = 0.0f;
mat_basis[2][3] = 0.0f;
mat_basis[3][3] = 1.0f;
copy_m4_m4(mat_final, mat_basis);
scale *= ED_view3d_pixel_size_no_ui_scale(t->ar->regiondata, mat_final[3]);
mul_mat3_m4_fl(mat_final, scale);
if (activeSnap(t) && (!transformModeUseSnap(t) ||
(t->tsnap.mode & (SCE_SNAP_MODE_INCREMENT | SCE_SNAP_MODE_GRID)))) {
increment = (t->modifiers & MOD_PRECISION) ? t->snap[2] : t->snap[1];
}
else {
increment = t->snap[0];
}
BLI_assert(axis_idx >= MAN_AXIS_RANGE_ROT_START && axis_idx < MAN_AXIS_RANGE_ROT_END);
gizmo_get_axis_color(axis_idx, NULL, color, color);
GPU_depth_test(false);
GPU_blend(true);
GPU_line_smooth(true);
ED_gizmotypes_dial_3d_draw_util(mat_basis,
mat_final,
line_with,
color,
false,
&(struct Dial3dParams){
.draw_options = ED_GIZMO_DIAL_DRAW_FLAG_ANGLE_VALUE,
.angle_delta = t->values[0],
.angle_increment = increment,
});
GPU_line_smooth(false);
GPU_depth_test(true);
GPU_blend(false);
}
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Transform Gizmo
* \{ */
static GizmoGroup *gizmogroup_init(wmGizmoGroup *gzgroup)
{
GizmoGroup *ggd;
ggd = MEM_callocN(sizeof(GizmoGroup), "gizmo_data");
const wmGizmoType *gzt_arrow = WM_gizmotype_find("GIZMO_GT_arrow_3d", true);
const wmGizmoType *gzt_dial = WM_gizmotype_find("GIZMO_GT_dial_3d", true);
const wmGizmoType *gzt_prim = WM_gizmotype_find("GIZMO_GT_primitive_3d", true);
#define GIZMO_NEW_ARROW(v, draw_style) \
{ \
ggd->gizmos[v] = WM_gizmo_new_ptr(gzt_arrow, gzgroup, NULL); \
RNA_enum_set(ggd->gizmos[v]->ptr, "draw_style", draw_style); \
} \
((void)0)
#define GIZMO_NEW_DIAL(v, draw_options) \
{ \
ggd->gizmos[v] = WM_gizmo_new_ptr(gzt_dial, gzgroup, NULL); \
RNA_enum_set(ggd->gizmos[v]->ptr, "draw_options", draw_options); \
} \
((void)0)
#define GIZMO_NEW_PRIM(v, draw_style) \
{ \
ggd->gizmos[v] = WM_gizmo_new_ptr(gzt_prim, gzgroup, NULL); \
RNA_enum_set(ggd->gizmos[v]->ptr, "draw_style", draw_style); \
} \
((void)0)
/* add/init widgets - order matters! */
GIZMO_NEW_DIAL(MAN_AXIS_ROT_T, ED_GIZMO_DIAL_DRAW_FLAG_FILL);
GIZMO_NEW_DIAL(MAN_AXIS_SCALE_C, ED_GIZMO_DIAL_DRAW_FLAG_FILL_SELECT);
GIZMO_NEW_ARROW(MAN_AXIS_SCALE_X, ED_GIZMO_ARROW_STYLE_BOX);
GIZMO_NEW_ARROW(MAN_AXIS_SCALE_Y, ED_GIZMO_ARROW_STYLE_BOX);
GIZMO_NEW_ARROW(MAN_AXIS_SCALE_Z, ED_GIZMO_ARROW_STYLE_BOX);
GIZMO_NEW_PRIM(MAN_AXIS_SCALE_XY, ED_GIZMO_PRIMITIVE_STYLE_PLANE);
GIZMO_NEW_PRIM(MAN_AXIS_SCALE_YZ, ED_GIZMO_PRIMITIVE_STYLE_PLANE);
GIZMO_NEW_PRIM(MAN_AXIS_SCALE_ZX, ED_GIZMO_PRIMITIVE_STYLE_PLANE);
GIZMO_NEW_DIAL(MAN_AXIS_ROT_X, ED_GIZMO_DIAL_DRAW_FLAG_CLIP);
GIZMO_NEW_DIAL(MAN_AXIS_ROT_Y, ED_GIZMO_DIAL_DRAW_FLAG_CLIP);
GIZMO_NEW_DIAL(MAN_AXIS_ROT_Z, ED_GIZMO_DIAL_DRAW_FLAG_CLIP);
/* init screen aligned widget last here, looks better, behaves better */
GIZMO_NEW_DIAL(MAN_AXIS_ROT_C, ED_GIZMO_DIAL_DRAW_FLAG_NOP);
GIZMO_NEW_DIAL(MAN_AXIS_TRANS_C, ED_GIZMO_DIAL_DRAW_FLAG_FILL_SELECT);
GIZMO_NEW_ARROW(MAN_AXIS_TRANS_X, ED_GIZMO_ARROW_STYLE_NORMAL);
GIZMO_NEW_ARROW(MAN_AXIS_TRANS_Y, ED_GIZMO_ARROW_STYLE_NORMAL);
GIZMO_NEW_ARROW(MAN_AXIS_TRANS_Z, ED_GIZMO_ARROW_STYLE_NORMAL);
GIZMO_NEW_PRIM(MAN_AXIS_TRANS_XY, ED_GIZMO_PRIMITIVE_STYLE_PLANE);
GIZMO_NEW_PRIM(MAN_AXIS_TRANS_YZ, ED_GIZMO_PRIMITIVE_STYLE_PLANE);
GIZMO_NEW_PRIM(MAN_AXIS_TRANS_ZX, ED_GIZMO_PRIMITIVE_STYLE_PLANE);
ggd->gizmos[MAN_AXIS_ROT_T]->flag |= WM_GIZMO_SELECT_BACKGROUND;
/* Prevent axis gizmos overlapping the center point, see: T63744. */
ggd->gizmos[MAN_AXIS_TRANS_C]->select_bias = 2.0f;
ggd->gizmos[MAN_AXIS_SCALE_C]->select_bias = -2.0f;
/* Use 1/6 since this is '0.2' if the main scale is 1.2. */
RNA_float_set(ggd->gizmos[MAN_AXIS_SCALE_C]->ptr, "arc_inner_factor", 1.0 / 6.0);
return ggd;
}
/**
* Custom handler for gizmo widgets
*/
static int gizmo_modal(bContext *C,
wmGizmo *widget,
const wmEvent *event,
eWM_GizmoFlagTweak UNUSED(tweak_flag))
{
/* Avoid unnecessary updates, partially address: T55458. */
if (ELEM(event->type, TIMER, INBETWEEN_MOUSEMOVE)) {
return OPERATOR_RUNNING_MODAL;
}
ARegion *ar = CTX_wm_region(C);
RegionView3D *rv3d = ar->regiondata;
struct TransformBounds tbounds;
if (ED_transform_calc_gizmo_stats(C,
&(struct TransformCalcParams){
.use_only_center = true,
},
&tbounds)) {
gizmo_prepare_mat(C, rv3d, &tbounds);
WM_gizmo_set_matrix_location(widget, rv3d->twmat[3]);
}
ED_region_tag_redraw(ar);
return OPERATOR_RUNNING_MODAL;
}
static void gizmogroup_init_properties_from_twtype(wmGizmoGroup *gzgroup)
{
struct {
wmOperatorType *translate, *rotate, *trackball, *resize;
} ot_store = {NULL};
GizmoGroup *ggd = gzgroup->customdata;
MAN_ITER_AXES_BEGIN (axis, axis_idx) {
const short axis_type = gizmo_get_axis_type(axis_idx);
bool constraint_axis[3] = {1, 0, 0};
PointerRNA *ptr = NULL;
gizmo_get_axis_constraint(axis_idx, constraint_axis);
/* custom handler! */
WM_gizmo_set_fn_custom_modal(axis, gizmo_modal);
switch (axis_idx) {
case MAN_AXIS_TRANS_X:
case MAN_AXIS_TRANS_Y:
case MAN_AXIS_TRANS_Z:
case MAN_AXIS_SCALE_X:
case MAN_AXIS_SCALE_Y:
case MAN_AXIS_SCALE_Z:
if (axis_idx >= MAN_AXIS_RANGE_TRANS_START && axis_idx < MAN_AXIS_RANGE_TRANS_END) {
int draw_options = 0;
if ((ggd->twtype & (V3D_GIZMO_SHOW_OBJECT_ROTATE | V3D_GIZMO_SHOW_OBJECT_SCALE)) == 0) {
draw_options |= ED_GIZMO_ARROW_DRAW_FLAG_STEM;
}
RNA_enum_set(axis->ptr, "draw_options", draw_options);
}
WM_gizmo_set_line_width(axis, GIZMO_AXIS_LINE_WIDTH);
break;
case MAN_AXIS_ROT_X:
case MAN_AXIS_ROT_Y:
case MAN_AXIS_ROT_Z:
/* increased line width for better display */
WM_gizmo_set_line_width(axis, GIZMO_AXIS_LINE_WIDTH + 1.0f);
WM_gizmo_set_flag(axis, WM_GIZMO_DRAW_VALUE, true);
break;
case MAN_AXIS_TRANS_XY:
case MAN_AXIS_TRANS_YZ:
case MAN_AXIS_TRANS_ZX:
case MAN_AXIS_SCALE_XY:
case MAN_AXIS_SCALE_YZ:
case MAN_AXIS_SCALE_ZX: {
const float ofs_ax = 7.0f;
const float ofs[3] = {ofs_ax, ofs_ax, 0.0f};
WM_gizmo_set_scale(axis, 0.07f);
WM_gizmo_set_matrix_offset_location(axis, ofs);
WM_gizmo_set_flag(axis, WM_GIZMO_DRAW_OFFSET_SCALE, true);
break;
}
case MAN_AXIS_TRANS_C:
case MAN_AXIS_ROT_C:
case MAN_AXIS_SCALE_C:
case MAN_AXIS_ROT_T:
WM_gizmo_set_line_width(axis, GIZMO_AXIS_LINE_WIDTH);
if (axis_idx == MAN_AXIS_ROT_T) {
WM_gizmo_set_flag(axis, WM_GIZMO_DRAW_HOVER, true);
}
else if (axis_idx == MAN_AXIS_ROT_C) {
WM_gizmo_set_flag(axis, WM_GIZMO_DRAW_VALUE, true);
WM_gizmo_set_scale(axis, 1.2f);
}
else if (axis_idx == MAN_AXIS_SCALE_C) {
WM_gizmo_set_scale(axis, 1.2f);
}
else {
WM_gizmo_set_scale(axis, 0.2f);
}
break;
}
switch (axis_type) {
case MAN_AXES_TRANSLATE:
if (ot_store.translate == NULL) {
ot_store.translate = WM_operatortype_find("TRANSFORM_OT_translate", true);
}
ptr = WM_gizmo_operator_set(axis, 0, ot_store.translate, NULL);
break;
case MAN_AXES_ROTATE: {
wmOperatorType *ot_rotate;
if (axis_idx == MAN_AXIS_ROT_T) {
if (ot_store.trackball == NULL) {
ot_store.trackball = WM_operatortype_find("TRANSFORM_OT_trackball", true);
}
ot_rotate = ot_store.trackball;
}
else {
if (ot_store.rotate == NULL) {
ot_store.rotate = WM_operatortype_find("TRANSFORM_OT_rotate", true);
}
ot_rotate = ot_store.rotate;
}
ptr = WM_gizmo_operator_set(axis, 0, ot_rotate, NULL);
break;
}
case MAN_AXES_SCALE: {
if (ot_store.resize == NULL) {
ot_store.resize = WM_operatortype_find("TRANSFORM_OT_resize", true);
}
ptr = WM_gizmo_operator_set(axis, 0, ot_store.resize, NULL);
break;
}
}
if (ptr) {
PropertyRNA *prop;
if (ELEM(true, UNPACK3(constraint_axis))) {
if ((prop = RNA_struct_find_property(ptr, "constraint_axis"))) {
RNA_property_boolean_set_array(ptr, prop, constraint_axis);
}
}
RNA_boolean_set(ptr, "release_confirm", 1);
}
}
MAN_ITER_AXES_END;
}
static void WIDGETGROUP_gizmo_setup(const bContext *C, wmGizmoGroup *gzgroup)
{
GizmoGroup *ggd = gizmogroup_init(gzgroup);
gzgroup->customdata = ggd;
{
ScrArea *sa = CTX_wm_area(C);
const bToolRef *tref = sa->runtime.tool;
ggd->twtype = 0;
if (tref && STREQ(tref->idname, "builtin.move")) {
ggd->twtype |= V3D_GIZMO_SHOW_OBJECT_TRANSLATE;
}
else if (tref && STREQ(tref->idname, "builtin.rotate")) {
ggd->twtype |= V3D_GIZMO_SHOW_OBJECT_ROTATE;
}
else if (tref && STREQ(tref->idname, "builtin.scale")) {
ggd->twtype |= V3D_GIZMO_SHOW_OBJECT_SCALE;
}
else if (tref && STREQ(tref->idname, "builtin.transform")) {
ggd->twtype = V3D_GIZMO_SHOW_OBJECT_TRANSLATE | V3D_GIZMO_SHOW_OBJECT_ROTATE |
V3D_GIZMO_SHOW_OBJECT_SCALE;
}
else {
/* This is also correct logic for 'builtin.transform', no special check needed. */
/* Setup all gizmos, they can be toggled via 'ToolSettings.gizmo_flag' */
ggd->twtype = V3D_GIZMO_SHOW_OBJECT_TRANSLATE | V3D_GIZMO_SHOW_OBJECT_ROTATE |
V3D_GIZMO_SHOW_OBJECT_SCALE;
ggd->use_twtype_refresh = true;
}
BLI_assert(ggd->twtype != 0);
ggd->twtype_init = ggd->twtype;
}
/* *** set properties for axes *** */
gizmogroup_init_properties_from_twtype(gzgroup);
}
static void WIDGETGROUP_gizmo_refresh(const bContext *C, wmGizmoGroup *gzgroup)
{
GizmoGroup *ggd = gzgroup->customdata;
Scene *scene = CTX_data_scene(C);
ScrArea *sa = CTX_wm_area(C);
View3D *v3d = sa->spacedata.first;
ARegion *ar = CTX_wm_region(C);
RegionView3D *rv3d = ar->regiondata;
struct TransformBounds tbounds;
if (ggd->use_twtype_refresh) {
ggd->twtype = v3d->gizmo_show_object & ggd->twtype_init;
if (ggd->twtype != ggd->twtype_prev) {
ggd->twtype_prev = ggd->twtype;
gizmogroup_init_properties_from_twtype(gzgroup);
}
}
const TransformOrientationSlot *orient_slot = BKE_scene_orientation_slot_get_from_flag(
scene, ggd->twtype_init);
/* skip, we don't draw anything anyway */
if ((ggd->all_hidden = (ED_transform_calc_gizmo_stats(
C,
&(struct TransformCalcParams){
.use_only_center = true,
.orientation_type = orient_slot->type + 1,
.orientation_index_custom = orient_slot->index_custom,
},
&tbounds) == 0))) {
return;
}
gizmo_prepare_mat(C, rv3d, &tbounds);
/* *** set properties for axes *** */
MAN_ITER_AXES_BEGIN (axis, axis_idx) {
const short axis_type = gizmo_get_axis_type(axis_idx);
const int aidx_norm = gizmo_orientation_axis(axis_idx, NULL);
WM_gizmo_set_matrix_location(axis, rv3d->twmat[3]);
switch (axis_idx) {
case MAN_AXIS_TRANS_X:
case MAN_AXIS_TRANS_Y:
case MAN_AXIS_TRANS_Z:
case MAN_AXIS_SCALE_X:
case MAN_AXIS_SCALE_Y:
case MAN_AXIS_SCALE_Z: {
float start_co[3] = {0.0f, 0.0f, 0.0f};
float len;
gizmo_line_range(ggd->twtype, axis_type, &start_co[2], &len);
WM_gizmo_set_matrix_rotation_from_z_axis(axis, rv3d->twmat[aidx_norm]);
RNA_float_set(axis->ptr, "length", len);
if (axis_idx >= MAN_AXIS_RANGE_TRANS_START && axis_idx < MAN_AXIS_RANGE_TRANS_END) {
if (ggd->twtype & V3D_GIZMO_SHOW_OBJECT_ROTATE) {
/* Avoid rotate and translate arrows overlap. */
start_co[2] += 0.215f;
}
}
WM_gizmo_set_matrix_offset_location(axis, start_co);
WM_gizmo_set_flag(axis, WM_GIZMO_DRAW_OFFSET_SCALE, true);
break;
}
case MAN_AXIS_ROT_X:
case MAN_AXIS_ROT_Y:
case MAN_AXIS_ROT_Z:
WM_gizmo_set_matrix_rotation_from_z_axis(axis, rv3d->twmat[aidx_norm]);
break;
case MAN_AXIS_TRANS_XY:
case MAN_AXIS_TRANS_YZ:
case MAN_AXIS_TRANS_ZX:
case MAN_AXIS_SCALE_XY:
case MAN_AXIS_SCALE_YZ:
case MAN_AXIS_SCALE_ZX: {
const float *y_axis = rv3d->twmat[aidx_norm - 1 < 0 ? 2 : aidx_norm - 1];
const float *z_axis = rv3d->twmat[aidx_norm];
WM_gizmo_set_matrix_rotation_from_yz_axis(axis, y_axis, z_axis);
break;
}
}
}
MAN_ITER_AXES_END;
/* Ensure rotate disks don't overlap scale arrows, especially in ortho view. */
float rotate_select_bias = 0.0f;
if ((ggd->twtype & V3D_GIZMO_SHOW_OBJECT_SCALE) && ggd->twtype & V3D_GIZMO_SHOW_OBJECT_ROTATE) {
rotate_select_bias = -2.0f;
}
for (int i = MAN_AXIS_RANGE_ROT_START; i < MAN_AXIS_RANGE_ROT_END; i++) {
ggd->gizmos[i]->select_bias = rotate_select_bias;
}
}
static void WIDGETGROUP_gizmo_message_subscribe(const bContext *C,
wmGizmoGroup *gzgroup,
struct wmMsgBus *mbus)
{
Scene *scene = CTX_data_scene(C);
bScreen *screen = CTX_wm_screen(C);
ScrArea *sa = CTX_wm_area(C);
ARegion *ar = CTX_wm_region(C);
gizmo_xform_message_subscribe(gzgroup, mbus, scene, screen, sa, ar, VIEW3D_GGT_xform_gizmo);
}
static void WIDGETGROUP_gizmo_draw_prepare(const bContext *C, wmGizmoGroup *gzgroup)
{
GizmoGroup *ggd = gzgroup->customdata;
// ScrArea *sa = CTX_wm_area(C);
ARegion *ar = CTX_wm_region(C);
// View3D *v3d = sa->spacedata.first;
RegionView3D *rv3d = ar->regiondata;
float viewinv_m3[3][3];
copy_m3_m4(viewinv_m3, rv3d->viewinv);
float idot[3];
/* when looking through a selected camera, the gizmo can be at the
* exact same position as the view, skip so we don't break selection */
if (ggd->all_hidden || fabsf(ED_view3d_pixel_size(rv3d, rv3d->twmat[3])) < 1e-6f) {
MAN_ITER_AXES_BEGIN (axis, axis_idx) {
WM_gizmo_set_flag(axis, WM_GIZMO_HIDDEN, true);
}
MAN_ITER_AXES_END;
return;
}
gizmo_get_idot(rv3d, idot);
/* *** set properties for axes *** */
MAN_ITER_AXES_BEGIN (axis, axis_idx) {
const short axis_type = gizmo_get_axis_type(axis_idx);
/* XXX maybe unset _HIDDEN flag on redraw? */
if (gizmo_is_axis_visible(rv3d, ggd->twtype, idot, axis_type, axis_idx)) {
WM_gizmo_set_flag(axis, WM_GIZMO_HIDDEN, false);
}
else {
WM_gizmo_set_flag(axis, WM_GIZMO_HIDDEN, true);
continue;
}
float color[4], color_hi[4];
gizmo_get_axis_color(axis_idx, idot, color, color_hi);
WM_gizmo_set_color(axis, color);
WM_gizmo_set_color_highlight(axis, color_hi);
switch (axis_idx) {
case MAN_AXIS_TRANS_C:
case MAN_AXIS_ROT_C:
case MAN_AXIS_SCALE_C:
case MAN_AXIS_ROT_T:
WM_gizmo_set_matrix_rotation_from_z_axis(axis, rv3d->viewinv[2]);
break;
}
}
MAN_ITER_AXES_END;
/* Refresh handled above when using view orientation. */
if (!equals_m3m3(viewinv_m3, ggd->prev.viewinv_m3)) {
{
Scene *scene = CTX_data_scene(C);
const TransformOrientationSlot *orient_slot = BKE_scene_orientation_slot_get_from_flag(
scene, ggd->twtype_init);
switch (orient_slot->type) {
case V3D_ORIENT_VIEW: {
WIDGETGROUP_gizmo_refresh(C, gzgroup);
break;
}
}
}
copy_m3_m4(ggd->prev.viewinv_m3, rv3d->viewinv);
}
}
static void WIDGETGROUP_gizmo_invoke_prepare(const bContext *C,
wmGizmoGroup *gzgroup,
wmGizmo *gz,
const wmEvent *UNUSED(event))
{
GizmoGroup *ggd = gzgroup->customdata;
/* Support gizmo specific orientation. */
if (gz != ggd->gizmos[MAN_AXIS_ROT_T]) {
Scene *scene = CTX_data_scene(C);
wmGizmoOpElem *gzop = WM_gizmo_operator_get(gz, 0);
PointerRNA *ptr = &gzop->ptr;
PropertyRNA *prop_orient_type = RNA_struct_find_property(ptr, "orient_type");
const TransformOrientationSlot *orient_slot = BKE_scene_orientation_slot_get_from_flag(
scene, ggd->twtype_init);
if (orient_slot == &scene->orientation_slots[SCE_ORIENT_DEFAULT]) {
RNA_property_unset(ptr, prop_orient_type);
}
else {
/* TODO: APIfunction */
int index = BKE_scene_orientation_slot_get_index(orient_slot);
RNA_property_enum_set(ptr, prop_orient_type, index);
}
}
/* Support shift click to constrain axis. */
const int axis_idx = BLI_array_findindex(ggd->gizmos, ARRAY_SIZE(ggd->gizmos), &gz);
int axis = -1;
switch (axis_idx) {
case MAN_AXIS_TRANS_X:
case MAN_AXIS_TRANS_Y:
case MAN_AXIS_TRANS_Z:
axis = axis_idx - MAN_AXIS_TRANS_X;
break;
case MAN_AXIS_SCALE_X:
case MAN_AXIS_SCALE_Y:
case MAN_AXIS_SCALE_Z:
axis = axis_idx - MAN_AXIS_SCALE_X;
break;
}
if (axis != -1) {
wmWindow *win = CTX_wm_window(C);
/* Swap single axis for two-axis constraint. */
bool flip = win->eventstate->shift;
BLI_assert(axis_idx != -1);
const short axis_type = gizmo_get_axis_type(axis_idx);
if (axis_type != MAN_AXES_ROTATE) {
wmGizmoOpElem *gzop = WM_gizmo_operator_get(gz, 0);
PointerRNA *ptr = &gzop->ptr;
PropertyRNA *prop_constraint_axis = RNA_struct_find_property(ptr, "constraint_axis");
if (prop_constraint_axis) {
bool constraint[3] = {false};
constraint[axis] = true;
if (flip) {
for (int i = 0; i < ARRAY_SIZE(constraint); i++) {
constraint[i] = !constraint[i];
}
}
RNA_property_boolean_set_array(ptr, prop_constraint_axis, constraint);
}
}
}
}
static bool WIDGETGROUP_gizmo_poll_generic(View3D *v3d)
{
if (v3d->gizmo_flag & V3D_GIZMO_HIDE) {
return false;
}
if (G.moving & (G_TRANSFORM_OBJ | G_TRANSFORM_EDIT)) {
return false;
}
return true;
}
static bool WIDGETGROUP_gizmo_poll_context(const struct bContext *C,
struct wmGizmoGroupType *UNUSED(gzgt))
{
ScrArea *sa = CTX_wm_area(C);
View3D *v3d = sa->spacedata.first;
if (!WIDGETGROUP_gizmo_poll_generic(v3d)) {
return false;
}
const bToolRef *tref = sa->runtime.tool;
if (v3d->gizmo_flag & V3D_GIZMO_HIDE_CONTEXT) {
return false;
}
if ((v3d->gizmo_show_object & (V3D_GIZMO_SHOW_OBJECT_TRANSLATE | V3D_GIZMO_SHOW_OBJECT_ROTATE |
V3D_GIZMO_SHOW_OBJECT_SCALE)) == 0) {
return false;
}
/* Don't show if the tool has a gizmo. */
if (tref && tref->runtime && tref->runtime->gizmo_group[0]) {
return false;
}
return true;
}
static bool WIDGETGROUP_gizmo_poll_tool(const struct bContext *C, struct wmGizmoGroupType *gzgt)
{
if (!ED_gizmo_poll_or_unlink_delayed_from_tool(C, gzgt)) {
return false;
}
ScrArea *sa = CTX_wm_area(C);
View3D *v3d = sa->spacedata.first;
if (!WIDGETGROUP_gizmo_poll_generic(v3d)) {
return false;
}
if (v3d->gizmo_flag & V3D_GIZMO_HIDE_TOOL) {
return false;
}
return true;
}
/* Expose as multiple gizmos so tools use one, persistent context another.
* Needed because they use different options which isn't so simple to dynamically update. */
void VIEW3D_GGT_xform_gizmo(wmGizmoGroupType *gzgt)
{
gzgt->name = "3D View: Transform Gizmo";
gzgt->idname = "VIEW3D_GGT_xform_gizmo";
gzgt->flag = WM_GIZMOGROUPTYPE_3D;
gzgt->gzmap_params.spaceid = SPACE_VIEW3D;
gzgt->gzmap_params.regionid = RGN_TYPE_WINDOW;
gzgt->poll = WIDGETGROUP_gizmo_poll_tool;
gzgt->setup = WIDGETGROUP_gizmo_setup;
gzgt->setup_keymap = WM_gizmogroup_setup_keymap_generic_maybe_drag;
gzgt->refresh = WIDGETGROUP_gizmo_refresh;
gzgt->message_subscribe = WIDGETGROUP_gizmo_message_subscribe;
gzgt->draw_prepare = WIDGETGROUP_gizmo_draw_prepare;
gzgt->invoke_prepare = WIDGETGROUP_gizmo_invoke_prepare;
static const EnumPropertyItem rna_enum_gizmo_items[] = {
{V3D_GIZMO_SHOW_OBJECT_TRANSLATE, "TRANSLATE", 0, "Move", ""},
{V3D_GIZMO_SHOW_OBJECT_ROTATE, "ROTATE", 0, "Rotate", ""},
{V3D_GIZMO_SHOW_OBJECT_SCALE, "SCALE", 0, "Scale", ""},
{0, "NONE", 0, "None", ""},
{0, NULL, 0, NULL, NULL},
};
RNA_def_enum(gzgt->srna,
"drag_action",
rna_enum_gizmo_items,
V3D_GIZMO_SHOW_OBJECT_TRANSLATE,
"Drag Action",
"");
}
/** Only poll, flag & gzmap_params differ. */
void VIEW3D_GGT_xform_gizmo_context(wmGizmoGroupType *gzgt)
{
gzgt->name = "3D View: Transform Gizmo Context";
gzgt->idname = "VIEW3D_GGT_xform_gizmo_context";
gzgt->flag = WM_GIZMOGROUPTYPE_3D | WM_GIZMOGROUPTYPE_PERSISTENT;
gzgt->poll = WIDGETGROUP_gizmo_poll_context;
gzgt->setup = WIDGETGROUP_gizmo_setup;
gzgt->setup_keymap = WM_gizmogroup_setup_keymap_generic_maybe_drag;
gzgt->refresh = WIDGETGROUP_gizmo_refresh;
gzgt->message_subscribe = WIDGETGROUP_gizmo_message_subscribe;
gzgt->draw_prepare = WIDGETGROUP_gizmo_draw_prepare;
gzgt->invoke_prepare = WIDGETGROUP_gizmo_invoke_prepare;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Scale Cage Gizmo
* \{ */
struct XFormCageWidgetGroup {
wmGizmo *gizmo;
/* Only for view orientation. */
struct {
float viewinv_m3[3][3];
} prev;
};
static bool WIDGETGROUP_xform_cage_poll(const bContext *C, wmGizmoGroupType *gzgt)
{
if (!ED_gizmo_poll_or_unlink_delayed_from_tool(C, gzgt)) {
return false;
}
View3D *v3d = CTX_wm_view3d(C);
if (v3d->gizmo_flag & (V3D_GIZMO_HIDE | V3D_GIZMO_HIDE_TOOL)) {
return false;
}
if (G.moving & (G_TRANSFORM_OBJ | G_TRANSFORM_EDIT)) {
return false;
}
return true;
}
static void WIDGETGROUP_xform_cage_setup(const bContext *UNUSED(C), wmGizmoGroup *gzgroup)
{
struct XFormCageWidgetGroup *xgzgroup = MEM_mallocN(sizeof(struct XFormCageWidgetGroup),
__func__);
const wmGizmoType *gzt_cage = WM_gizmotype_find("GIZMO_GT_cage_3d", true);
xgzgroup->gizmo = WM_gizmo_new_ptr(gzt_cage, gzgroup, NULL);
wmGizmo *gz = xgzgroup->gizmo;
RNA_enum_set(gz->ptr,
"transform",
ED_GIZMO_CAGE2D_XFORM_FLAG_SCALE | ED_GIZMO_CAGE2D_XFORM_FLAG_TRANSLATE);
gz->color[0] = 1;
gz->color_hi[0] = 1;
gzgroup->customdata = xgzgroup;
{
wmOperatorType *ot_resize = WM_operatortype_find("TRANSFORM_OT_resize", true);
PointerRNA *ptr;
/* assign operator */
PropertyRNA *prop_release_confirm = NULL;
PropertyRNA *prop_constraint_axis = NULL;
int i = ED_GIZMO_CAGE3D_PART_SCALE_MIN_X_MIN_Y_MIN_Z;
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
for (int z = 0; z < 3; z++) {
bool constraint[3] = {x != 1, y != 1, z != 1};
ptr = WM_gizmo_operator_set(gz, i, ot_resize, NULL);
if (prop_release_confirm == NULL) {
prop_release_confirm = RNA_struct_find_property(ptr, "release_confirm");
prop_constraint_axis = RNA_struct_find_property(ptr, "constraint_axis");
}
RNA_property_boolean_set(ptr, prop_release_confirm, true);
RNA_property_boolean_set_array(ptr, prop_constraint_axis, constraint);
i++;
}
}
}
}
}
static void WIDGETGROUP_xform_cage_refresh(const bContext *C, wmGizmoGroup *gzgroup)
{
ARegion *ar = CTX_wm_region(C);
RegionView3D *rv3d = ar->regiondata;
Scene *scene = CTX_data_scene(C);
struct XFormCageWidgetGroup *xgzgroup = gzgroup->customdata;
wmGizmo *gz = xgzgroup->gizmo;
struct TransformBounds tbounds;
const TransformOrientationSlot *orient_slot = BKE_scene_orientation_slot_get(scene,
SCE_ORIENT_SCALE);
if ((ED_transform_calc_gizmo_stats(C,
&(struct TransformCalcParams){
.use_local_axis = true,
.orientation_type = orient_slot->type + 1,
.orientation_index_custom = orient_slot->index_custom,
},
&tbounds) == 0) ||
equals_v3v3(rv3d->tw_axis_min, rv3d->tw_axis_max)) {
WM_gizmo_set_flag(gz, WM_GIZMO_HIDDEN, true);
}
else {
gizmo_prepare_mat(C, rv3d, &tbounds);
WM_gizmo_set_flag(gz, WM_GIZMO_HIDDEN, false);
WM_gizmo_set_flag(gz, WM_GIZMO_MOVE_CURSOR, true);
float dims[3];
sub_v3_v3v3(dims, rv3d->tw_axis_max, rv3d->tw_axis_min);
RNA_float_set_array(gz->ptr, "dimensions", dims);
mul_v3_fl(dims, 0.5f);
copy_m4_m3(gz->matrix_offset, rv3d->tw_axis_matrix);
mid_v3_v3v3(gz->matrix_offset[3], rv3d->tw_axis_max, rv3d->tw_axis_min);
mul_m3_v3(rv3d->tw_axis_matrix, gz->matrix_offset[3]);
float matrix_offset_global[4][4];
mul_m4_m4m4(matrix_offset_global, gz->matrix_space, gz->matrix_offset);
PropertyRNA *prop_center_override = NULL;
float center[3];
float center_global[3];
int i = ED_GIZMO_CAGE3D_PART_SCALE_MIN_X_MIN_Y_MIN_Z;
for (int x = 0; x < 3; x++) {
center[0] = (float)(1 - x) * dims[0];
for (int y = 0; y < 3; y++) {
center[1] = (float)(1 - y) * dims[1];
for (int z = 0; z < 3; z++) {
center[2] = (float)(1 - z) * dims[2];
struct wmGizmoOpElem *gzop = WM_gizmo_operator_get(gz, i);
if (prop_center_override == NULL) {
prop_center_override = RNA_struct_find_property(&gzop->ptr, "center_override");
}
mul_v3_m4v3(center_global, matrix_offset_global, center);
RNA_property_float_set_array(&gzop->ptr, prop_center_override, center_global);
i++;
}
}
}
}
/* Needed to test view orientation changes. */
copy_m3_m4(xgzgroup->prev.viewinv_m3, rv3d->viewinv);
}
static void WIDGETGROUP_xform_cage_message_subscribe(const bContext *C,
wmGizmoGroup *gzgroup,
struct wmMsgBus *mbus)
{
Scene *scene = CTX_data_scene(C);
bScreen *screen = CTX_wm_screen(C);
ScrArea *sa = CTX_wm_area(C);
ARegion *ar = CTX_wm_region(C);
gizmo_xform_message_subscribe(gzgroup, mbus, scene, screen, sa, ar, VIEW3D_GGT_xform_cage);
}
static void WIDGETGROUP_xform_cage_draw_prepare(const bContext *C, wmGizmoGroup *gzgroup)
{
struct XFormCageWidgetGroup *xgzgroup = gzgroup->customdata;
wmGizmo *gz = xgzgroup->gizmo;
ViewLayer *view_layer = CTX_data_view_layer(C);
Object *ob = OBACT(view_layer);
if (ob && ob->mode & OB_MODE_EDIT) {
copy_m4_m4(gz->matrix_space, ob->obmat);
}
else {
unit_m4(gz->matrix_space);
}
RegionView3D *rv3d = CTX_wm_region_view3d(C);
{
Scene *scene = CTX_data_scene(C);
const TransformOrientationSlot *orient_slot = BKE_scene_orientation_slot_get(scene,
SCE_ORIENT_SCALE);
switch (orient_slot->type) {
case V3D_ORIENT_VIEW: {
float viewinv_m3[3][3];
copy_m3_m4(viewinv_m3, rv3d->viewinv);
if (!equals_m3m3(viewinv_m3, xgzgroup->prev.viewinv_m3)) {
/* Take care calling refresh from draw_prepare,
* this should be OK because it's only adjusting the cage orientation. */
WIDGETGROUP_xform_cage_refresh(C, gzgroup);
}
break;
}
}
}
}
void VIEW3D_GGT_xform_cage(wmGizmoGroupType *gzgt)
{
gzgt->name = "Transform Cage";
gzgt->idname = "VIEW3D_GGT_xform_cage";
gzgt->flag |= WM_GIZMOGROUPTYPE_3D;
gzgt->gzmap_params.spaceid = SPACE_VIEW3D;
gzgt->gzmap_params.regionid = RGN_TYPE_WINDOW;
gzgt->poll = WIDGETGROUP_xform_cage_poll;
gzgt->setup = WIDGETGROUP_xform_cage_setup;
gzgt->setup_keymap = WM_gizmogroup_setup_keymap_generic_maybe_drag;
gzgt->refresh = WIDGETGROUP_xform_cage_refresh;
gzgt->message_subscribe = WIDGETGROUP_xform_cage_message_subscribe;
gzgt->draw_prepare = WIDGETGROUP_xform_cage_draw_prepare;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Transform Shear Gizmo
* \{ */
struct XFormShearWidgetGroup {
wmGizmo *gizmo[3][2];
/* Only for view orientation. */
struct {
float viewinv_m3[3][3];
} prev;
};
static bool WIDGETGROUP_xform_shear_poll(const bContext *C, wmGizmoGroupType *gzgt)
{
if (!ED_gizmo_poll_or_unlink_delayed_from_tool(C, gzgt)) {
return false;
}
View3D *v3d = CTX_wm_view3d(C);
if (v3d->gizmo_flag & (V3D_GIZMO_HIDE | V3D_GIZMO_HIDE_TOOL)) {
return false;
}
return true;
}
static void WIDGETGROUP_xform_shear_setup(const bContext *UNUSED(C), wmGizmoGroup *gzgroup)
{
struct XFormShearWidgetGroup *xgzgroup = MEM_mallocN(sizeof(struct XFormShearWidgetGroup),
__func__);
const wmGizmoType *gzt_arrow = WM_gizmotype_find("GIZMO_GT_arrow_3d", true);
wmOperatorType *ot_shear = WM_operatortype_find("TRANSFORM_OT_shear", true);
float axis_color[3][3];
for (int i = 0; i < 3; i++) {
UI_GetThemeColor3fv(TH_AXIS_X + i, axis_color[i]);
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
wmGizmo *gz = WM_gizmo_new_ptr(gzt_arrow, gzgroup, NULL);
RNA_enum_set(gz->ptr, "draw_style", ED_GIZMO_ARROW_STYLE_BOX);
const int i_ortho_a = (i + j + 1) % 3;
const int i_ortho_b = (i + (1 - j) + 1) % 3;
interp_v3_v3v3(gz->color, axis_color[i_ortho_a], axis_color[i_ortho_b], 0.75f);
gz->color[3] = 0.5f;
PointerRNA *ptr = WM_gizmo_operator_set(gz, 0, ot_shear, NULL);
RNA_boolean_set(ptr, "release_confirm", 1);
xgzgroup->gizmo[i][j] = gz;
}
}
gzgroup->customdata = xgzgroup;
}
static void WIDGETGROUP_xform_shear_refresh(const bContext *C, wmGizmoGroup *gzgroup)
{
Scene *scene = CTX_data_scene(C);
ARegion *ar = CTX_wm_region(C);
RegionView3D *rv3d = ar->regiondata;
struct XFormShearWidgetGroup *xgzgroup = gzgroup->customdata;
struct TransformBounds tbounds;
const TransformOrientationSlot *orient_slot = BKE_scene_orientation_slot_get(scene,
SCE_ORIENT_ROTATE);
if (ED_transform_calc_gizmo_stats(C,
&(struct TransformCalcParams){
.use_local_axis = false,
.orientation_type = orient_slot->type + 1,
.orientation_index_custom = orient_slot->index_custom,
},
&tbounds) == 0) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
wmGizmo *gz = xgzgroup->gizmo[i][j];
WM_gizmo_set_flag(gz, WM_GIZMO_HIDDEN, true);
}
}
}
else {
gizmo_prepare_mat(C, rv3d, &tbounds);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
wmGizmo *gz = xgzgroup->gizmo[i][j];
WM_gizmo_set_flag(gz, WM_GIZMO_HIDDEN, false);
WM_gizmo_set_flag(gz, WM_GIZMO_MOVE_CURSOR, true);
wmGizmoOpElem *gzop = WM_gizmo_operator_get(gz, 0);
const int i_ortho_a = (i + j + 1) % 3;
const int i_ortho_b = (i + (1 - j) + 1) % 3;
WM_gizmo_set_matrix_rotation_from_yz_axis(gz, rv3d->twmat[i_ortho_a], rv3d->twmat[i]);
WM_gizmo_set_matrix_location(gz, rv3d->twmat[3]);
RNA_float_set_array(&gzop->ptr, "orient_matrix", &tbounds.axis[0][0]);
RNA_enum_set(&gzop->ptr, "orient_type", orient_slot->type);
RNA_enum_set(&gzop->ptr, "orient_axis", i_ortho_b);
RNA_enum_set(&gzop->ptr, "orient_axis_ortho", i_ortho_a);
mul_v3_fl(gz->matrix_basis[0], 0.5f);
mul_v3_fl(gz->matrix_basis[1], 6.0f);
}
}
}
/* Needed to test view orientation changes. */
copy_m3_m4(xgzgroup->prev.viewinv_m3, rv3d->viewinv);
}
static void WIDGETGROUP_xform_shear_message_subscribe(const bContext *C,
wmGizmoGroup *gzgroup,
struct wmMsgBus *mbus)
{
Scene *scene = CTX_data_scene(C);
bScreen *screen = CTX_wm_screen(C);
ScrArea *sa = CTX_wm_area(C);
ARegion *ar = CTX_wm_region(C);
gizmo_xform_message_subscribe(gzgroup, mbus, scene, screen, sa, ar, VIEW3D_GGT_xform_shear);
}
static void WIDGETGROUP_xform_shear_draw_prepare(const bContext *C, wmGizmoGroup *gzgroup)
{
struct XFormShearWidgetGroup *xgzgroup = gzgroup->customdata;
RegionView3D *rv3d = CTX_wm_region_view3d(C);
{
Scene *scene = CTX_data_scene(C);
/* Shear is like rotate, use the rotate setting. */
const TransformOrientationSlot *orient_slot = BKE_scene_orientation_slot_get(
scene, SCE_ORIENT_ROTATE);
switch (orient_slot->type) {
case V3D_ORIENT_VIEW: {
float viewinv_m3[3][3];
copy_m3_m4(viewinv_m3, rv3d->viewinv);
if (!equals_m3m3(viewinv_m3, xgzgroup->prev.viewinv_m3)) {
/* Take care calling refresh from draw_prepare,
* this should be OK because it's only adjusting the cage orientation. */
WIDGETGROUP_xform_shear_refresh(C, gzgroup);
}
break;
}
}
}
/* Basic ordering for drawing only. */
{
LISTBASE_FOREACH (wmGizmo *, gz, &gzgroup->gizmos) {
/* Since we have two pairs of each axis,
* bias the values so gizmos that are orthogonal to the view get priority.
* This means we never default to shearing along
* the view axis in the case of an overlap. */
float axis_order[3], axis_bias[3];
copy_v3_v3(axis_order, gz->matrix_basis[2]);
copy_v3_v3(axis_bias, gz->matrix_basis[1]);
if (dot_v3v3(axis_bias, rv3d->viewinv[2]) < 0.0f) {
negate_v3(axis_bias);
}
madd_v3_v3fl(axis_order, axis_bias, 0.01f);
gz->temp.f = dot_v3v3(rv3d->viewinv[2], axis_order);
}
BLI_listbase_sort(&gzgroup->gizmos, WM_gizmo_cmp_temp_fl_reverse);
}
}
void VIEW3D_GGT_xform_shear(wmGizmoGroupType *gzgt)
{
gzgt->name = "Transform Shear";
gzgt->idname = "VIEW3D_GGT_xform_shear";
gzgt->flag |= WM_GIZMOGROUPTYPE_3D;
gzgt->gzmap_params.spaceid = SPACE_VIEW3D;
gzgt->gzmap_params.regionid = RGN_TYPE_WINDOW;
gzgt->poll = WIDGETGROUP_xform_shear_poll;
gzgt->setup = WIDGETGROUP_xform_shear_setup;
gzgt->setup_keymap = WM_gizmogroup_setup_keymap_generic_maybe_drag;
gzgt->refresh = WIDGETGROUP_xform_shear_refresh;
gzgt->message_subscribe = WIDGETGROUP_xform_shear_message_subscribe;
gzgt->draw_prepare = WIDGETGROUP_xform_shear_draw_prepare;
}
/** \} */
|
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import { createSelector } from 'reselect';
import groupBy from 'lodash/groupBy';
import { miradorSlice } from './utils';
import { getWindow, getWindows } from './getters';
/** */
export function getCompanionWindows(state) {
return miradorSlice(state).companionWindows || {};
}
export var getCompanionWindow = createSelector([getCompanionWindows, function (state, _ref) {
var companionWindowId = _ref.companionWindowId;
return companionWindowId;
}], function (companionWindows, companionWindowId) {
return companionWindowId && companionWindows[companionWindowId];
});
/** Return position of thumbnail navigation in a certain window.
* @param {object} state
* @param {String} windowId
* @param {String}
*/
export var getThumbnailNavigationPosition = createSelector([getWindow, getCompanionWindows], function (window, companionWindows) {
return window && companionWindows[window.thumbnailNavigationId] && companionWindows[window.thumbnailNavigationId].position;
});
/**
* Return compantion window ids from a window
* @param {String} windowId
* @return {Array}
*/
var getCompanionWindowIndexByWindowAndPosition = createSelector([getWindows, getCompanionWindows], function (windows, companionWindows) {
return (Object.keys(windows) || []).reduce(function (obj, id) {
return _objectSpread(_objectSpread({}, obj), {}, _defineProperty({}, id, groupBy(windows[id].companionWindowIds, function (cwid) {
return companionWindows[cwid] && companionWindows[cwid].position;
})));
}, {});
});
/**
* Return compantion window ids from a window
* @param {String} windowId
* @return {Array}
*/
var getCompanionWindowsByWindowAndPosition = createSelector([getWindows, getCompanionWindows], function (windows, companionWindows) {
return (Object.keys(windows) || []).reduce(function (obj, id) {
return _objectSpread(_objectSpread({}, obj), {}, _defineProperty({}, id, groupBy(windows[id].companionWindowIds.map(function (cwid) {
return companionWindows[cwid];
}), function (cw) {
return cw.position;
})));
}, {});
});
/**
* Return companion windows of a window
* @param {String} windowId
* @return {Array}
*/
var getCompanionWindowsOfWindow = createSelector([function (state, _ref2) {
var windowId = _ref2.windowId;
return windowId;
}, getCompanionWindowsByWindowAndPosition], function (windowId, companionWindows) {
return companionWindows[windowId] || {};
});
/**
* Return companion windows of a window
* @param {String} windowId
* @return {Array}
*/
var getCompanionWindowIdsOfWindow = createSelector([function (state, _ref3) {
var windowId = _ref3.windowId;
return windowId;
}, getCompanionWindowIndexByWindowAndPosition], function (windowId, companionWindowIds) {
return companionWindowIds[windowId] || {};
});
/**
* Return the companion window string from state in a given windowId and position
* @param {object} state
* @param {String} windowId
* @param {String} position
* @return {String}
*/
export var getCompanionWindowsForPosition = createSelector([getCompanionWindowsOfWindow, function (state, _ref4) {
var position = _ref4.position;
return {
position: position
};
}], function (companionWindows, _ref5) {
var position = _ref5.position;
return companionWindows[position] || EMPTY_ARRAY;
});
/**
* Return the companion window string from state in a given windowId and content type
* @param {object} state
* @param {String} windowId
* @param {String} position
* @return {String}
*/
export var getCompanionWindowsForContent = createSelector([getCompanionWindowsOfWindow, function (state, _ref6) {
var content = _ref6.content;
return {
content: content
};
}], function (companionWindows, _ref7) {
var _ref8;
var content = _ref7.content;
return (_ref8 = []).concat.apply(_ref8, _toConsumableArray(Object.values(companionWindows))).filter(function (w) {
return w.content === content;
});
});
var EMPTY_ARRAY = [];
/** */
export var getCompanionWindowIdsForPosition = createSelector([getCompanionWindowIdsOfWindow, function (state, _ref9) {
var position = _ref9.position;
return {
position: position
};
}], function (companionWindowIds, _ref10) {
var position = _ref10.position;
return companionWindowIds[position] || EMPTY_ARRAY;
});
/**
* Returns the visibility of the companion area
* @param {object} state
* @param {object} props
* @return {Boolean}
*/
export var getCompanionAreaVisibility = createSelector([function (state, _ref11) {
var position = _ref11.position;
return position;
}, getWindow], function (position, window) {
if (!window) return false;
var companionAreaOpen = window.companionAreaOpen,
sideBarOpen = window.sideBarOpen;
if (position !== 'left') return true;
return !!(companionAreaOpen && sideBarOpen);
});
export var selectCompanionWindowDimensions = createSelector([getCompanionWindowsOfWindow], function (companionWindows) {
var _ref12;
var width = 0;
var height = 0;
(_ref12 = []).concat.apply(_ref12, _toConsumableArray(Object.values(companionWindows))).forEach(function (cw) {
if (cw.position.match(/right/)) {
width += 235;
}
if (cw.position.match(/bottom/)) {
height += 201;
}
});
return {
height: height,
width: width
};
}); |
# -*- coding: utf-8 -*-
'''
Copyright (c) 2018 by Tobias Houska
This file is part of Statistical Parameter Optimization Tool for Python(SPOTPY).
:author: Tobias Houska and Motjaba Sadegh
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from . import _algorithm
import numpy as np
import random
import time
class dream(_algorithm):
"""
Implements the DiffeRential Evolution Adaptive Metropolis (DREAM) algorithhm
based on:
Vrugt, J. A. (2016) Markov chain Monte Carlo simulation using the DREAM software package.
"""
def __init__(self, *args, **kwargs):
"""
Input
----------
spot_setup: class
model: function
Should be callable with a parameter combination of the parameter-function
and return an list of simulation results (as long as evaluation list)
parameter: function
When called, it should return a random parameter combination. Which can
be e.g. uniform or Gaussian
objectivefunction: function
Should return the objectivefunction for a given list of a model simulation and
observation.
evaluation: function
Should return the true values as return by the model.
dbname: str
* Name of the database where parameter, objectivefunction value and simulation results will be saved.
dbformat: str
* ram: fast suited for short sampling time. no file will be created and results are saved in an array.
* csv: A csv file will be created, which you can import afterwards.
parallel: str
* seq: Sequentiel sampling (default): Normal iterations on one core of your cpu.
* mpi: Message Passing Interface: Parallel computing on cluster pcs (recommended for unix os).
save_sim: boolean
* True: Simulation results will be saved
* False: Simulation results will not be saved
"""
kwargs['optimization_direction'] = 'maximize'
kwargs['algorithm_name'] = 'DiffeRential Evolution Adaptive Metropolis (DREAM) algorithm'
super(dream, self).__init__(*args, **kwargs)
def check_par_validity_bound(self, par):
if len(par) == len(self.min_bound) and len(par) == len(self.max_bound):
for i in range(len(par)):
if par[i] < self.min_bound[i]:
par[i] = self.min_bound[i]
if par[i] > self.max_bound[i]:
par[i] = self.max_bound[i]
else:
print('ERROR: Bounds have not the same lenghts as Parameterarray')
return par
def get_regular_startingpoint(self, nChains):
randompar = self.parameter()['random']
for i in range(1000):
randompar = np.column_stack(
(randompar, self.parameter()['random']))
startpoints = []
for j in range(nChains):
startpoints.append(
np.percentile(
randompar,
(j +
1) /
float(
nChains +
1) *
100,
axis=1)) # ,np.amax(randompar,axis=1)
startpoints = np.array(startpoints)
for k in range(len(randompar)):
random.shuffle(startpoints[:, k])
return startpoints
def check_par_validity_reflect(self, par):
if len(par) == len(self.min_bound) and len(par) == len(self.max_bound):
for i in range(len(par)):
if par[i] < self.min_bound[i]:
par[i] = self.min_bound[i] + (self.min_bound[i] - par[i])
elif par[i] > self.max_bound[i]:
par[i] = self.max_bound[i] - (par[i] - self.max_bound[i])
# Postprocessing if reflecting jumped out of bounds
for i in range(len(par)):
if par[i] < self.min_bound[i]:
par[i] = self.min_bound[i]
if par[i] > self.max_bound[i]:
par[i] = self.max_bound[i]
else:
print('ERROR: Bounds have not the same lenghts as Parameterarray')
return par
def _get_gamma(self, N):
# N = Number of parameters
p = np.random.uniform(low=0, high=1)
if p >= 0.2:
gamma = 2.38 / np.sqrt(2 * int(N)) # /self.gammalevel
else:
gamma = 1
return gamma
def get_other_random_chains(self, cur_chain):
valid = False
while valid == False:
random_chain1 = np.random.randint(0, self.nChains)
random_chain2 = np.random.randint(0, self.nChains)
if random_chain1 != cur_chain and random_chain2 != cur_chain and random_chain1 != random_chain2:
valid = True
return random_chain1, random_chain2
def get_new_proposal_vector(self, cur_chain, newN, nrN):
gamma = self._get_gamma(nrN)
random_chain1, random_chain2 = self.get_other_random_chains(cur_chain)
new_parameterset = []
# position =
# self.chain_samples-1#self.nChains*self.chain_samples+self.chain_samples+cur_chain-1
cur_par_set = list(
self.bestpar[cur_chain][self.nChainruns[cur_chain] - 1])
random_par_set1 = list(
self.bestpar[random_chain1][self.nChainruns[random_chain1] - 1])
random_par_set2 = list(
self.bestpar[random_chain2][self.nChainruns[random_chain2] - 1])
for i in range(self.N): # Go through parameters
if newN[i] == True:
new_parameterset.append(
cur_par_set[i] +
gamma *
np.array(
random_par_set1[i] -
random_par_set2[i]) +
np.random.normal(
0,
self.eps))
else:
new_parameterset.append(cur_par_set[i])
new_parameter = self.check_par_validity_reflect(new_parameterset)
# new_parameter=self.check_par_validity_bound(new_parameterset)
return new_parameter
# new_par = np.random.normal(loc=old_par, scale=self.stepsizes)
# new_par = self.check_par_validity_reflect(new_par)
# return new_par
def update_mcmc_status(self, par, like, sim, cur_chain):
self.bestpar[cur_chain][self.nChainruns[cur_chain]] = list(par)
self.bestlike[cur_chain] = like
self.bestsim[cur_chain] = list(sim)
def get_r_hat(self, parameter_array):
"""
Based on some fancy mathlab code, it return an array [R_stat, MR_stat]
:param parameter_array: 3 dim array of parameter estimation sets
:type parameter_array: list
:return: [R_stat, MR_stat]
:rtype: list
"""
n, d, N = parameter_array.shape
# Use only the last 50% of each chain (vrugt 2009), that means only the half of "d". Cause "d" ist the count
# of the repetition and we use the d/2 to d of those values which are
# already not NAN
whereIsNoNAN = np.logical_not(np.isnan(parameter_array))
alreadyToNum = np.sum(whereIsNoNAN[0, :, 0])
if alreadyToNum > 3:
parameter_array = parameter_array[:, int(
np.floor(alreadyToNum / 2)): alreadyToNum, :]
else:
# the later functions need some data to work right, so we use in
# this case 100% of NON NAN values
parameter_array = parameter_array[:, 0: alreadyToNum, :]
# I made a big confusion with d, n and N, I figured it out by tests
if n > 3:
mean_chains = np.zeros((n, N))
for i in range(n):
for j in range(N):
mean_chains[i, j] = np.nanmean(parameter_array[i, :, j])
B_uni = np.zeros(N)
for i in range(N):
B_uni[i] = d * np.nanvar(mean_chains[:, i],
ddof=1) # make numpy Mathalab like: https://stackoverflow.com/a/27600240/5885054
var_chains = np.zeros((n, N))
for i in range(n):
for j in range(N):
var_chains[i, j] = np.nanvar(
parameter_array[i, :, j], ddof=1)
W_uni = np.zeros(N)
for i in range(N):
W_uni[i] = np.mean(var_chains[:, i])
sigma2 = ((d - 1) / d) * W_uni + (1 / d) * B_uni
whichW_UNIIsNull = W_uni == 0.0
W_uni[whichW_UNIIsNull] = np.random.uniform(0.1, 1, 1)
R_stat = np.sqrt(
(n + 1) / n * (np.divide(sigma2, W_uni)) - (d - 1) / (n * d))
# W_mult = 0
# for ii in range(n):
# W_mult = W_mult + np.cov(np.nan_to_num(np.transpose(parameter_array[ii, :, :])), ddof=1)
#
# W_mult = W_mult / n + 2e-52 * np.eye(N)
#
# # Note that numpy.cov() considers its input data matrix to have observations in each column,
# # and variables in each row, so to get numpy.cov() to return what other packages do,
# # you have to pass the transpose of the data matrix to numpy.cov().
# # https://stats.stackexchange.com/a/263508/168054
#
# B_mult = np.cov(np.nan_to_num(np.transpose(mean_chains))) + 2e-52 * np.eye(N) # 2e-52 avoids problems with eig if var = 0
# M = np.linalg.lstsq(W_mult, B_mult)
# R = np.max(np.abs(np.linalg.eigvals(M[0])))
# MR_stat = np.sqrt((n + 1) / n * R + (d - 1) / d)
return R_stat # [R_stat, MR_stat]
def sample(self, repetitions, nChains=5, nCr=3, eps=10e-6,
convergence_limit=1.2, runs_after_convergence=100, acceptance_test_option=6):
self.set_repetiton(repetitions)
print(
'Starting the DREAM algotrithm with ' +
str(repetitions) +
' repetitions...')
if nChains < 3:
print('Please use at least n=3 chains!')
return None
# Prepare storing MCMC chain as array of arrays.
# define stepsize of MCMC.
self.repetitions = int(repetitions)
self.nChains = int(nChains)
# Ensure initialisation of chains and database
self.burnIn = self.nChains
self.stepsizes = self.parameter()['step'] # array of stepsizes
self.nr_of_pars = len(self.stepsizes)
self.gammalevel = 1
starttime = time.time()
intervaltime = starttime
# Metropolis-Hastings iterations.
self.bestpar = np.array(
[[[np.nan] * self.nr_of_pars] * self.repetitions] * self.nChains)
# [0]->chain #[0][0]->parameter #[0][0][0]->repetitons
self.bestlike = [[-np.inf]] * self.nChains
self.bestsim = [[np.nan]] * self.nChains
self.accepted = np.zeros(self.nChains)
self.nChainruns = [0] * self.nChains
self.min_bound, self.max_bound = self.parameter(
)['minbound'], self.parameter()['maxbound']
#firstcall = True
print('Initialize ', self.nChains, ' chain(s)...')
self.iter = 0
# for i in range(10):
startpoints = self.get_regular_startingpoint(nChains)
# param_generator = ((curChain,list(self.parameter()['random'])) for
# curChain in range(int(self.nChains))) #TODO: Start with regular
# interval raster
param_generator = ((curChain, list(startpoints[curChain])) for curChain in range(
int(self.nChains))) # TODO: Start with regular interval raster
for curChain, par, sim in self.repeat(param_generator):
like = self.postprocessing(self.iter, par, sim, chains=curChain)
self.update_mcmc_status(par, like, sim, curChain)
self.iter += 1
self.nChainruns[curChain] += 1
print('Beginn of Random Walk')
convergence = False
# Walf through chains
self.r_hats = []
self.eps = eps
self.CR = []
for i in range(nCr):
self.CR.append((i + 1) / nCr)
self.N = len(self.parameter()['random'])
nrN = 1
newN = [True] * self.N
while self.iter < self.repetitions:
param_generator = ((curChain, self.get_new_proposal_vector(
curChain, newN, nrN)) for curChain in range(int(self.nChains)))
for cChain, par, sim in self.repeat(param_generator):
pCr = np.random.randint(0, nCr)
ids = []
for i in range(self.N):
ids.append(np.random.uniform(low=0, high=1))
newN = []
nrN = 0
for i in range(len(ids)):
if ids[i] < self.CR[pCr]:
newN.append(True)
nrN += 1
else:
newN.append(False)
if nrN == 0:
ids = [np.random.randint(0, self.N)]
nrN = 1
like = self.postprocessing(self.iter, par, sim, chains=cChain)
# set a option which type of comparision should be choose:
metro_opt = acceptance_test_option
if metro_opt == 1:
logMetropHastRatio = like / self.bestlike[cChain]
elif metro_opt == 2 or metro_opt == 4:
logMetropHastRatio = np.exp(like - self.bestlike[cChain])
elif metro_opt == 3:
# SSR probability evaluation
# nrN is defined in this loop so it will increase every
# step
logMetropHastRatio = (
like / self.bestlike[cChain]) ** (-nrN * (1 + self._get_gamma(nrN)) / 2)
elif metro_opt == 5:
# SSR probability evaluation, but now weighted with mesurement error
# Note that measurement error is single number --> homoscedastic; variance can be taken out of sum sign
# SIGMA will be calculated from the orginal data
Sigma = np.mean(np.array(self.evaluation) * 0.1)
# signs are different because we write -SSR
logMetropHastRatio = np.exp(-0.5 * (-like +
self.bestlike[cChain]) / (Sigma ** 2))
elif metro_opt == 6: # SSR probability evaluation, but now weighted with mesurement error
# Note that measurement error is a vector -->
# heteroscedastic; variance within sum sign -- see
# CompDensity.m
# signs are different because we write -SSR
logMetropHastRatio = np.exp(-0.5 *
(-like + self.bestlike[cChain]))
u = np.random.uniform(low=0.0, high=1)
if logMetropHastRatio > u:
self.update_mcmc_status(par, like, sim, cChain)
self.accepted[cChain] += 1 # monitor acceptance
else:
self.update_mcmc_status(
self.bestpar[cChain][self.nChainruns[cChain] - 1], self.bestlike[cChain], self.bestsim[cChain], cChain)
if self.status.stop:
self.iter = self.repetitions
print('Stopping samplig')
break
self.iter += 1
self.nChainruns[cChain] += 1
r_hat = self.get_r_hat(self.bestpar)
self.r_hats.append(r_hat)
# Refresh progressbar every two seconds
acttime = time.time()
if acttime - \
intervaltime >= 2 and self.iter >= 2 and self.nChainruns[-1] >= 3:
text = "Acceptance rates [%] =" + str(np.around((self.accepted) / float(
((self.iter - self.burnIn) / self.nChains)), decimals=4) * 100).strip('array([])')
print(text)
text = "Convergence rates =" + \
str(np.around((r_hat), decimals=4)).strip('array([])')
print(text)
intervaltime = time.time()
if (np.array(r_hat) < convergence_limit).all(
) and not convergence and self.nChainruns[-1] >= 5:
# Stop sampling
print('#############')
print('Convergence has been achieved after ' +
str(self.iter) +
' of ' +
str(self.repetitions) +
' runs! Finally, ' +
str(runs_after_convergence) +
' runs will be additionally sampled to form the posterior distribution')
print('#############')
self.repetitions = self.iter + runs_after_convergence
self.set_repetiton(self.repetitions)
#self.iter =self.repetitions - runs_after_convergence
convergence = True
self.final_call()
# try:
# self.datawriter.finalize()
# except AttributeError: # Happens if no database was assigned
# pass
#print('End of sampling')
# text = '%i of %i (best like=%g)' % (
# self.status.rep, repetitions, self.status.objectivefunction)
# print(text)
#print('Best parameter set')
# print(self.status.params)
#text = 'Duration:' + str(round((acttime - starttime), 2)) + ' s'
# print(text)
return self.r_hats
|
import logging
from stream.data import generate_id
from stream.service import StreamingService
class YouTubeStreamingService(StreamingService):
def start_stream(self) -> str:
stream_reference = generate_id()
logging.info(f"Starting YouTube stream with reference {stream_reference}.")
return stream_reference
def fill_buffer(self, stream_reference: str) -> None:
buffer_data = self.retrieve_buffer_data()
logging.info(
f"Received buffer data: {buffer_data}. Sending to YouTube stream: {stream_reference}."
)
def stop_stream(self, stream_reference: str) -> None:
logging.info(f"Closing YouTube stream with reference {stream_reference}.")
|
# Copyright 2021 The TensorFlow 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.
# ==============================================================================
"""Abstract target."""
import abc
from typing import Any, Callable, Optional
QueryHandle = Any
class Target(abc.ABC):
"""Base abstraction for targets."""
@abc.abstractmethod
def prepare(self, sample: Any) -> Any:
"""Preprocesses a sample into a query."""
pass
@abc.abstractmethod
def send(
self,
query: Any,
completion_callback: Optional[Callable[[QueryHandle], Any]] = None,
query_handle: QueryHandle = None):
"""Sends the query to the target.
Args:
query: The processed query.
completion_callback: An optional executable function that runs after
sending the query (e.g. once a response is received). This callback
should receive a `QueryHandle` instance as a parameter.
query_handle: An optional identifier for the query.
"""
pass
def flush(self):
return
|
from .paginator import Paginator
__version__ = "0.0.1"
|
/*
* This header is generated by classdump-dyld 1.0
* on Saturday, June 1, 2019 at 6:44:38 PM Mountain Standard Time
* Operating System: Version 12.1.1 (Build 16C5050a)
* Image Source: /System/Library/PrivateFrameworks/CloudPhotoLibrary.framework/CloudPhotoLibrary
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <CloudPhotoLibrary/CPLRecordChange.h>
@class NSString, CPLSuggestionAssetList, NSDate, NSData;
@interface CPLSuggestionChange : CPLRecordChange {
unsigned short _type;
unsigned short _subtype;
unsigned short _notificationState;
unsigned short _state;
NSString* _title;
NSString* _subtitle;
CPLSuggestionAssetList* _assetList;
NSDate* _creationDate;
long long _version;
NSDate* _activationDate;
NSDate* _relevantUntilDate;
NSDate* _expungeDate;
NSData* _actionData;
NSData* _featuresData;
}
@property (nonatomic,copy) NSString * title; //@synthesize title=_title - In the implementation block
@property (nonatomic,copy) NSString * subtitle; //@synthesize subtitle=_subtitle - In the implementation block
@property (assign,nonatomic) unsigned short type; //@synthesize type=_type - In the implementation block
@property (assign,nonatomic) unsigned short subtype; //@synthesize subtype=_subtype - In the implementation block
@property (nonatomic,copy) CPLSuggestionAssetList * assetList; //@synthesize assetList=_assetList - In the implementation block
@property (nonatomic,copy) NSDate * creationDate; //@synthesize creationDate=_creationDate - In the implementation block
@property (assign,nonatomic) unsigned short notificationState; //@synthesize notificationState=_notificationState - In the implementation block
@property (assign,nonatomic) unsigned short state; //@synthesize state=_state - In the implementation block
@property (assign,nonatomic) long long version; //@synthesize version=_version - In the implementation block
@property (nonatomic,copy) NSDate * activationDate; //@synthesize activationDate=_activationDate - In the implementation block
@property (nonatomic,copy) NSDate * relevantUntilDate; //@synthesize relevantUntilDate=_relevantUntilDate - In the implementation block
@property (nonatomic,copy) NSDate * expungeDate; //@synthesize expungeDate=_expungeDate - In the implementation block
@property (nonatomic,copy) NSData * actionData; //@synthesize actionData=_actionData - In the implementation block
@property (nonatomic,copy) NSData * featuresData; //@synthesize featuresData=_featuresData - In the implementation block
+(id)_createTestSuggestionWithKeyAssets:(id)arg1 representativeAssets:(id)arg2 ;
+(BOOL)serverSupportsSuggestion;
-(/*^block*/id)checkDefaultValueBlockForPropertyWithSelector:(SEL)arg1 ;
-(BOOL)supportsDirectDeletion;
-(id)propertiesDescription;
-(id)scopedIdentifiersForMapping;
-(id)translateToCloudChangeUsingIDMapping:(id)arg1 error:(id*)arg2 ;
-(id)translateToClientChangeUsingIDMapping:(id)arg1 error:(id*)arg2 ;
-(NSDate *)activationDate;
-(void)setActivationDate:(NSDate *)arg1 ;
-(NSDate *)relevantUntilDate;
-(void)setRelevantUntilDate:(NSDate *)arg1 ;
-(NSDate *)expungeDate;
-(void)setExpungeDate:(NSDate *)arg1 ;
-(NSData *)actionData;
-(void)setActionData:(NSData *)arg1 ;
-(NSData *)featuresData;
-(void)setFeaturesData:(NSData *)arg1 ;
-(CPLSuggestionAssetList *)assetList;
-(void)setAssetList:(CPLSuggestionAssetList *)arg1 ;
-(void)setNotificationState:(unsigned short)arg1 ;
-(unsigned short)notificationState;
-(NSDate *)creationDate;
-(void)setCreationDate:(NSDate *)arg1 ;
-(BOOL)supportsDeletion;
-(unsigned short)state;
-(void)setTitle:(NSString *)arg1 ;
-(NSString *)title;
-(void)setSubtitle:(NSString *)arg1 ;
-(NSString *)subtitle;
-(unsigned short)type;
-(void)setType:(unsigned short)arg1 ;
-(void)setState:(unsigned short)arg1 ;
-(void)setVersion:(long long)arg1 ;
-(long long)version;
-(unsigned short)subtype;
-(void)setSubtype:(unsigned short)arg1 ;
@end
|
// Custom scripts for the Spyder docs site
;(function () {
'use strict'
/* Top-level variables */
// Name of the dropdown class to check for
const dropdownClassName = 'dropdown'
// Interactive tour driver options
var quickstartDriverOptions = {
animate: false,
opacity: 0.1,
padding: 0,
allowClose: false,
nextBtnText: 'Next',
prevBtnText: 'Previous'
}
// Step definitions for the quickstart tour
var quickstartTourSteps = [
{
element: '#introduction-rect',
popover: {
title: 'Spyder',
description: 'Spyder is a powerful scientific IDE for Python. Here, we will guide you through some of its most important features.',
position: 'bottom'
}
},
{
element: '#toolbar-rect',
popover: {
title: 'Toolbar',
description: 'The toolbar allows you to quickly access some of the most common commands in Spyder, such as run, save and debug files.',
position: 'bottom'
}
},
{
element: '#statusbar-rect',
popover: {
title: 'Status Bar',
description: 'The status bar shows your current Python environment, git branch, memory usage and various attributes of the currently active file.',
position: 'top'
}
},
{
element: '#options-menu-rect',
popover: {
title: 'Options Menu',
description: 'You can display each pane\'s options menu by clicking the "hamburger" icon at the top right. It contains useful settings and actions relevant to the pane.',
position: 'right'
}
},
{
element: '#context-menu-rect',
popover: {
title: 'Context Menu',
description: 'To display the context menu for a pane, right-click anywhere over it. The menu shows actions relevant to the element under your cursor.',
position: 'right'
}
},
{
element: '#editor-rect',
popover: {
title: 'Editor',
description: 'The <a href="editor.html">Editor</a> is the pane where you can create, open and edit files. It contains useful features like autocompletion, real-time analysis and syntax highlighting.',
position: 'right'
}
},
{
element: '#console-rect',
popover: {
title: 'IPython Console',
description: 'The <a href="ipythonconsole.html">Console</a> allows you to run your code from the Editor or interactively. You can also use it to control Spyder’s debugger.',
position: 'left'
}
},
{
element: '#help-rect',
popover: {
title: 'Help',
description: 'The <a href="help.html">Help</a> pane displays documentation for the objects you are using in the Editor or the IPython Console. To trigger Help, press Ctrl-I (Cmd-I on macOS) with your cursor over an object, or type its name in the Object field.',
position: 'left'
}
},
{
element: '#variable-explorer-rect',
popover: {
title: 'Variable Explorer',
description: 'The <a href="variableexplorer.html">Variable Explorer</a> allows you to browse and interact with the objects generated when running your code. Double-clicking a variable will open a specialized viewer, allowing you to inspect its contents.',
position: 'left'
}
},
{
element: '#plots-rect',
popover: {
title: 'Plots',
description: 'The <a href="plots.html">Plots</a> pane shows the figures and images created during your code execution. It allows you to browse, zoom, copy, and save the generated plots.',
position: 'left'
}
},
{
element: '#files-rect',
popover: {
title: 'Files',
description: 'The <a href="fileexplorer.html">Files</a> pane lets you browse the directories on your computer, open files in the Editor, and perform a variety of other operations.',
position: 'left'
}
},
{
element: '#find-rect',
popover: {
title: 'Find',
description: 'The <a href="findinfiles.html">Find</a> pane allows you to search for text in a given directory and navigate through all the found occurrences.',
position: 'left'
}
},
{
element: '#profiler-rect',
popover: {
title: 'Profiler',
description: 'The <a href="profiler.html">Profiler</a> helps you optimize your code by determining the run time and number of calls for every function and method used in a file. It also allows you to save and compare your results between runs.',
position: 'left'
}
},
{
element: '#code-analysis-rect',
popover: {
title: 'Code Analysis',
description: 'The <a href="pylint.html">Code Analysis</a> helps you improve the quality of your programs by detecting style issues, bad practices and potential bugs.',
position: 'left'
}
}
]
/* Helper functions */
// Set the active image for the tour based on the element's class
function setActiveTourImage (activeElement) {
var activeClass = 'tour-screenshot-active'
var classNames = activeElement.node.className.baseVal.split(' ')
for (var i = 0; i < classNames.length; i++) {
var imageToActivate = document.getElementById(classNames[i])
if (imageToActivate) break
};
var imageToDeactivate = document.getElementsByClassName(activeClass)[0]
imageToDeactivate.classList.remove(activeClass)
imageToActivate.classList.add(activeClass)
};
// Add a span for the progress indicator to each tour step title
function addProgressSpan (tourSteps) {
for (var i = 0; i < tourSteps.length; i++) {
var spanToAdd = '<span class="tour-progress-indicator">' + (i + 1).toString() + '/' + tourSteps.length.toString() + '</span>'
tourSteps[i].popover.title += spanToAdd
};
};
// Get the currently selected anchor element if its a dropdown
function getDropdownElement () {
var dropdownID = window.location.hash
if (!dropdownID) {
return false
};
var dropdownElement = document.getElementById(dropdownID.substring(1))
if ((!dropdownElement) || (!dropdownElement.classList.contains(dropdownClassName))) {
return false
};
return dropdownElement
};
// Scroll to the specified element, with an offset for the navbar
function scrollToElement (theElement) {
if (theElement) {
theElement.scrollIntoView(true)
window.scrollBy(0, -100)
};
};
/* Main functions */
var driver = null
// Event handler to start tour
function startTour () {
driver.start()
};
// Interactive tour of Spyder for Quickstart using Driver
function setupTourDriver (driverOptions, tourSteps) {
driverOptions.onHighlightStarted = setActiveTourImage
driver = new Driver(driverOptions) // eslint-disable-line no-undef
addProgressSpan(tourSteps)
driver.defineSteps(tourSteps)
document.getElementById('quickstart-tour-start').onclick = startTour
return driver
};
// Handle version selector
function setupVersionSelector () {
document.querySelectorAll('#select-versions').forEach(function (ele) {
ele.onchange = function () {
if (this.value) {
window.location.href = this.value
};
}
})
};
// Set up ids and direct links to dropdowns in FAQ
function setupDropdownLinks () {
var dropdowns = document.getElementsByClassName(dropdownClassName)
for (var i = 0; i < dropdowns.length; i++) {
for (var j = 0; j < dropdowns[i].classList.length; j++) {
if (dropdowns[i].classList[j].startsWith('dropdown-id-')) {
dropdowns[i].id = dropdowns[i].classList[j].replace('dropdown-id-', '')
};
};
if (!dropdowns[i].id) {
dropdowns[i].id = 'dropdown-' + (i + 1)
};
var aTag = document.createElement('a')
aTag.setAttribute('href', '#' + dropdowns[i].id)
aTag.classList.add('fas')
aTag.classList.add('fa-link')
aTag.classList.add('dropdown-link')
var summaryElement = dropdowns[i].getElementsByClassName('summary-title')[0]
summaryElement.insertBefore(aTag, summaryElement.getElementsByClassName('docutils')[0])
};
};
// Open the specified dropdown, wait for images to load then scroll to it
function scrollToDropdown () {
var dropdownElement = getDropdownElement()
if (dropdownElement) {
if (dropdownElement.open) {
scrollToElement(dropdownElement)
} else {
dropdownElement.open = true
setTimeout(scrollToElement, 500, dropdownElement)
};
};
};
// Open all dropdowns that have highlighted words
function openHighlightedDropdowns () {
var dropdowns = document.getElementsByClassName(dropdownClassName)
for (var idx = 0; idx < dropdowns.length; idx++) {
if (dropdowns[idx].getElementsByClassName('highlighted').length) {
dropdowns[idx].open = true
};
};
};
/* Fire events */
// Initial DOM ready
document.addEventListener('DOMContentLoaded', function () {
// Set up the tour
if (document.getElementsByClassName('interactive-tour-container').length) {
driver = setupTourDriver(quickstartDriverOptions, quickstartTourSteps)
};
// Set up the version dropdown
if (document.getElementById('select-versions')) {
setupVersionSelector()
};
// Set up the dropdown direct links
if (document.getElementsByClassName(dropdownClassName).length) {
setupDropdownLinks()
window.onhashchange = scrollToDropdown
};
})
// Asset load complete
window.onload = function () {
// Start the tour
if (document.getElementsByClassName('interactive-tour-container').length) {
startTour()
};
// Open any dropdowns with highlighted words
if (document.getElementsByClassName(dropdownClassName).length) {
openHighlightedDropdowns()
};
// Scroll to and open the dropdown direct links
if (getDropdownElement()) {
scrollToDropdown()
};
}
}())
|
'use strict';
var VError = require('verror')
, xtend = require('xtend')
, log = require('./log');
module.exports = function genUpdateFn (opts) {
return function mySqlUpdate (connection, params, callback) {
var sql = opts.stmt.update(params);
log.debug('perform update with sql, "%s"', sql);
connection.execute(
// e.g "UPDATE table_name SET name=:name where id=:id;"
sql,
// Create composite object with id and other fields to build the
// statement with less effort
xtend({id: params.id}, params.data),
function onMySqlUpdate (err, rows) {
// TODO: Get updated row in db?
if (err) {
callback(new VError(err, 'error executing "update" query'), null);
} else if (rows[0]) {
callback(null, rows[0]);
} else {
callback(null, null);
}
}
);
};
};
|
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["polyfills"],{
/***/ "0TWp":
/*!*******************************************!*\
!*** ./node_modules/zone.js/dist/zone.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
* @license Angular v9.1.0-next.4+61.sha-e552591.with-local-changes
* (c) 2010-2020 Google LLC. https://angular.io/
* License: MIT
*/
(function (factory) {
true ? !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : undefined;
})(function () {
'use strict';
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var Zone$1 = function (global) {
var performance = global['performance'];
function mark(name) {
performance && performance['mark'] && performance['mark'](name);
}
function performanceMeasure(name, label) {
performance && performance['measure'] && performance['measure'](name, label);
}
mark('Zone'); // Initialize before it's accessed below.
// __Zone_symbol_prefix global can be used to override the default zone
// symbol prefix with a custom one if needed.
var symbolPrefix = global['__Zone_symbol_prefix'] || '__zone_symbol__';
function __symbol__(name) {
return symbolPrefix + name;
}
var checkDuplicate = global[__symbol__('forceDuplicateZoneCheck')] === true;
if (global['Zone']) {
// if global['Zone'] already exists (maybe zone.js was already loaded or
// some other lib also registered a global object named Zone), we may need
// to throw an error, but sometimes user may not want this error.
// For example,
// we have two web pages, page1 includes zone.js, page2 doesn't.
// and the 1st time user load page1 and page2, everything work fine,
// but when user load page2 again, error occurs because global['Zone'] already exists.
// so we add a flag to let user choose whether to throw this error or not.
// By default, if existing Zone is from zone.js, we will not throw the error.
if (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function') {
throw new Error('Zone already loaded.');
} else {
return global['Zone'];
}
}
var Zone =
/** @class */
function () {
function Zone(parent, zoneSpec) {
this._parent = parent;
this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
this._properties = zoneSpec && zoneSpec.properties || {};
this._zoneDelegate = new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
}
Zone.assertZonePatched = function () {
if (global['Promise'] !== patches['ZoneAwarePromise']) {
throw new Error('Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' + 'has been overwritten.\n' + 'Most likely cause is that a Promise polyfill has been loaded ' + 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' + 'If you must load one, do so before loading zone.js.)');
}
};
Object.defineProperty(Zone, "root", {
get: function get() {
var zone = Zone.current;
while (zone.parent) {
zone = zone.parent;
}
return zone;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Zone, "current", {
get: function get() {
return _currentZoneFrame.zone;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Zone, "currentTask", {
get: function get() {
return _currentTask;
},
enumerable: true,
configurable: true
}); // tslint:disable-next-line:require-internal-with-underscore
Zone.__load_patch = function (name, fn) {
if (patches.hasOwnProperty(name)) {
if (checkDuplicate) {
throw Error('Already loaded patch: ' + name);
}
} else if (!global['__Zone_disable_' + name]) {
var perfName = 'Zone:' + name;
mark(perfName);
patches[name] = fn(global, Zone, _api);
performanceMeasure(perfName, perfName);
}
};
Object.defineProperty(Zone.prototype, "parent", {
get: function get() {
return this._parent;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Zone.prototype, "name", {
get: function get() {
return this._name;
},
enumerable: true,
configurable: true
});
Zone.prototype.get = function (key) {
var zone = this.getZoneWith(key);
if (zone) return zone._properties[key];
};
Zone.prototype.getZoneWith = function (key) {
var current = this;
while (current) {
if (current._properties.hasOwnProperty(key)) {
return current;
}
current = current._parent;
}
return null;
};
Zone.prototype.fork = function (zoneSpec) {
if (!zoneSpec) throw new Error('ZoneSpec required!');
return this._zoneDelegate.fork(this, zoneSpec);
};
Zone.prototype.wrap = function (callback, source) {
if (typeof callback !== 'function') {
throw new Error('Expecting function got: ' + callback);
}
var _callback = this._zoneDelegate.intercept(this, callback, source);
var zone = this;
return function () {
return zone.runGuarded(_callback, this, arguments, source);
};
};
Zone.prototype.run = function (callback, applyThis, applyArgs, source) {
_currentZoneFrame = {
parent: _currentZoneFrame,
zone: this
};
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
} finally {
_currentZoneFrame = _currentZoneFrame.parent;
}
};
Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {
if (applyThis === void 0) {
applyThis = null;
}
_currentZoneFrame = {
parent: _currentZoneFrame,
zone: this
};
try {
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
} catch (error) {
if (this._zoneDelegate.handleError(this, error)) {
throw error;
}
}
} finally {
_currentZoneFrame = _currentZoneFrame.parent;
}
};
Zone.prototype.runTask = function (task, applyThis, applyArgs) {
if (task.zone != this) {
throw new Error('A task can only be run in the zone of creation! (Creation: ' + (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
} // https://github.com/angular/zone.js/issues/778, sometimes eventTask
// will run in notScheduled(canceled) state, we should not try to
// run such kind of task but just return
if (task.state === notScheduled && (task.type === eventTask || task.type === macroTask)) {
return;
}
var reEntryGuard = task.state != running;
reEntryGuard && task._transitionTo(running, scheduled);
task.runCount++;
var previousTask = _currentTask;
_currentTask = task;
_currentZoneFrame = {
parent: _currentZoneFrame,
zone: this
};
try {
if (task.type == macroTask && task.data && !task.data.isPeriodic) {
task.cancelFn = undefined;
}
try {
return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
} catch (error) {
if (this._zoneDelegate.handleError(this, error)) {
throw error;
}
}
} finally {
// if the task's state is notScheduled or unknown, then it has already been cancelled
// we should not reset the state to scheduled
if (task.state !== notScheduled && task.state !== unknown) {
if (task.type == eventTask || task.data && task.data.isPeriodic) {
reEntryGuard && task._transitionTo(scheduled, running);
} else {
task.runCount = 0;
this._updateTaskCount(task, -1);
reEntryGuard && task._transitionTo(notScheduled, running, notScheduled);
}
}
_currentZoneFrame = _currentZoneFrame.parent;
_currentTask = previousTask;
}
};
Zone.prototype.scheduleTask = function (task) {
if (task.zone && task.zone !== this) {
// check if the task was rescheduled, the newZone
// should not be the children of the original zone
var newZone = this;
while (newZone) {
if (newZone === task.zone) {
throw Error("can not reschedule task to " + this.name + " which is descendants of the original zone " + task.zone.name);
}
newZone = newZone.parent;
}
}
task._transitionTo(scheduling, notScheduled);
var zoneDelegates = [];
task._zoneDelegates = zoneDelegates;
task._zone = this;
try {
task = this._zoneDelegate.scheduleTask(this, task);
} catch (err) {
// should set task's state to unknown when scheduleTask throw error
// because the err may from reschedule, so the fromState maybe notScheduled
task._transitionTo(unknown, scheduling, notScheduled); // TODO: @JiaLiPassion, should we check the result from handleError?
this._zoneDelegate.handleError(this, err);
throw err;
}
if (task._zoneDelegates === zoneDelegates) {
// we have to check because internally the delegate can reschedule the task.
this._updateTaskCount(task, 1);
}
if (task.state == scheduling) {
task._transitionTo(scheduled, scheduling);
}
return task;
};
Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {
return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
};
Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {
return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
};
Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) {
return this.scheduleTask(new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel));
};
Zone.prototype.cancelTask = function (task) {
if (task.zone != this) throw new Error('A task can only be cancelled in the zone of creation! (Creation: ' + (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
task._transitionTo(canceling, scheduled, running);
try {
this._zoneDelegate.cancelTask(this, task);
} catch (err) {
// if error occurs when cancelTask, transit the state to unknown
task._transitionTo(unknown, canceling);
this._zoneDelegate.handleError(this, err);
throw err;
}
this._updateTaskCount(task, -1);
task._transitionTo(notScheduled, canceling);
task.runCount = 0;
return task;
};
Zone.prototype._updateTaskCount = function (task, count) {
var zoneDelegates = task._zoneDelegates;
if (count == -1) {
task._zoneDelegates = null;
}
for (var i = 0; i < zoneDelegates.length; i++) {
zoneDelegates[i]._updateTaskCount(task.type, count);
}
};
return Zone;
}(); // tslint:disable-next-line:require-internal-with-underscore
Zone.__symbol__ = __symbol__;
var DELEGATE_ZS = {
name: '',
onHasTask: function onHasTask(delegate, _, target, hasTaskState) {
return delegate.hasTask(target, hasTaskState);
},
onScheduleTask: function onScheduleTask(delegate, _, target, task) {
return delegate.scheduleTask(target, task);
},
onInvokeTask: function onInvokeTask(delegate, _, target, task, applyThis, applyArgs) {
return delegate.invokeTask(target, task, applyThis, applyArgs);
},
onCancelTask: function onCancelTask(delegate, _, target, task) {
return delegate.cancelTask(target, task);
}
};
var ZoneDelegate =
/** @class */
function () {
function ZoneDelegate(zone, parentDelegate, zoneSpec) {
this._taskCounts = {
'microTask': 0,
'macroTask': 0,
'eventTask': 0
};
this.zone = zone;
this._parentDelegate = parentDelegate;
this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);
this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);
this._forkCurrZone = zoneSpec && (zoneSpec.onFork ? this.zone : parentDelegate._forkCurrZone);
this._interceptZS = zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);
this._interceptDlgt = zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);
this._interceptCurrZone = zoneSpec && (zoneSpec.onIntercept ? this.zone : parentDelegate._interceptCurrZone);
this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);
this._invokeDlgt = zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);
this._invokeCurrZone = zoneSpec && (zoneSpec.onInvoke ? this.zone : parentDelegate._invokeCurrZone);
this._handleErrorZS = zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);
this._handleErrorDlgt = zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);
this._handleErrorCurrZone = zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate._handleErrorCurrZone);
this._scheduleTaskZS = zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
this._scheduleTaskDlgt = zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
this._scheduleTaskCurrZone = zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate._scheduleTaskCurrZone);
this._invokeTaskZS = zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);
this._invokeTaskDlgt = zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);
this._invokeTaskCurrZone = zoneSpec && (zoneSpec.onInvokeTask ? this.zone : parentDelegate._invokeTaskCurrZone);
this._cancelTaskZS = zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);
this._cancelTaskDlgt = zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);
this._cancelTaskCurrZone = zoneSpec && (zoneSpec.onCancelTask ? this.zone : parentDelegate._cancelTaskCurrZone);
this._hasTaskZS = null;
this._hasTaskDlgt = null;
this._hasTaskDlgtOwner = null;
this._hasTaskCurrZone = null;
var zoneSpecHasTask = zoneSpec && zoneSpec.onHasTask;
var parentHasTask = parentDelegate && parentDelegate._hasTaskZS;
if (zoneSpecHasTask || parentHasTask) {
// If we need to report hasTask, than this ZS needs to do ref counting on tasks. In such
// a case all task related interceptors must go through this ZD. We can't short circuit it.
this._hasTaskZS = zoneSpecHasTask ? zoneSpec : DELEGATE_ZS;
this._hasTaskDlgt = parentDelegate;
this._hasTaskDlgtOwner = this;
this._hasTaskCurrZone = zone;
if (!zoneSpec.onScheduleTask) {
this._scheduleTaskZS = DELEGATE_ZS;
this._scheduleTaskDlgt = parentDelegate;
this._scheduleTaskCurrZone = this.zone;
}
if (!zoneSpec.onInvokeTask) {
this._invokeTaskZS = DELEGATE_ZS;
this._invokeTaskDlgt = parentDelegate;
this._invokeTaskCurrZone = this.zone;
}
if (!zoneSpec.onCancelTask) {
this._cancelTaskZS = DELEGATE_ZS;
this._cancelTaskDlgt = parentDelegate;
this._cancelTaskCurrZone = this.zone;
}
}
}
ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) {
return this._forkZS ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) : new Zone(targetZone, zoneSpec);
};
ZoneDelegate.prototype.intercept = function (targetZone, callback, source) {
return this._interceptZS ? this._interceptZS.onIntercept(this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source) : callback;
};
ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {
return this._invokeZS ? this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) : callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.handleError = function (targetZone, error) {
return this._handleErrorZS ? this._handleErrorZS.onHandleError(this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error) : true;
};
ZoneDelegate.prototype.scheduleTask = function (targetZone, task) {
var returnTask = task;
if (this._scheduleTaskZS) {
if (this._hasTaskZS) {
returnTask._zoneDelegates.push(this._hasTaskDlgtOwner);
} // clang-format off
returnTask = this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task); // clang-format on
if (!returnTask) returnTask = task;
} else {
if (task.scheduleFn) {
task.scheduleFn(task);
} else if (task.type == microTask) {
scheduleMicroTask(task);
} else {
throw new Error('Task is missing scheduleFn.');
}
}
return returnTask;
};
ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {
return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) : task.callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.cancelTask = function (targetZone, task) {
var value;
if (this._cancelTaskZS) {
value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task);
} else {
if (!task.cancelFn) {
throw Error('Task is not cancelable');
}
value = task.cancelFn(task);
}
return value;
};
ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) {
// hasTask should not throw error so other ZoneDelegate
// can still trigger hasTask callback
try {
this._hasTaskZS && this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
} catch (err) {
this.handleError(targetZone, err);
}
}; // tslint:disable-next-line:require-internal-with-underscore
ZoneDelegate.prototype._updateTaskCount = function (type, count) {
var counts = this._taskCounts;
var prev = counts[type];
var next = counts[type] = prev + count;
if (next < 0) {
throw new Error('More tasks executed then were scheduled.');
}
if (prev == 0 || next == 0) {
var isEmpty = {
microTask: counts['microTask'] > 0,
macroTask: counts['macroTask'] > 0,
eventTask: counts['eventTask'] > 0,
change: type
};
this.hasTask(this.zone, isEmpty);
}
};
return ZoneDelegate;
}();
var ZoneTask =
/** @class */
function () {
function ZoneTask(type, source, callback, options, scheduleFn, cancelFn) {
// tslint:disable-next-line:require-internal-with-underscore
this._zone = null;
this.runCount = 0; // tslint:disable-next-line:require-internal-with-underscore
this._zoneDelegates = null; // tslint:disable-next-line:require-internal-with-underscore
this._state = 'notScheduled';
this.type = type;
this.source = source;
this.data = options;
this.scheduleFn = scheduleFn;
this.cancelFn = cancelFn;
if (!callback) {
throw new Error('callback is not defined');
}
this.callback = callback;
var self = this; // TODO: @JiaLiPassion options should have interface
if (type === eventTask && options && options.useG) {
this.invoke = ZoneTask.invokeTask;
} else {
this.invoke = function () {
return ZoneTask.invokeTask.call(global, self, this, arguments);
};
}
}
ZoneTask.invokeTask = function (task, target, args) {
if (!task) {
task = this;
}
_numberOfNestedTaskFrames++;
try {
task.runCount++;
return task.zone.runTask(task, target, args);
} finally {
if (_numberOfNestedTaskFrames == 1) {
drainMicroTaskQueue();
}
_numberOfNestedTaskFrames--;
}
};
Object.defineProperty(ZoneTask.prototype, "zone", {
get: function get() {
return this._zone;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ZoneTask.prototype, "state", {
get: function get() {
return this._state;
},
enumerable: true,
configurable: true
});
ZoneTask.prototype.cancelScheduleRequest = function () {
this._transitionTo(notScheduled, scheduling);
}; // tslint:disable-next-line:require-internal-with-underscore
ZoneTask.prototype._transitionTo = function (toState, fromState1, fromState2) {
if (this._state === fromState1 || this._state === fromState2) {
this._state = toState;
if (toState == notScheduled) {
this._zoneDelegates = null;
}
} else {
throw new Error(this.type + " '" + this.source + "': can not transition to '" + toState + "', expecting state '" + fromState1 + "'" + (fromState2 ? ' or \'' + fromState2 + '\'' : '') + ", was '" + this._state + "'.");
}
};
ZoneTask.prototype.toString = function () {
if (this.data && typeof this.data.handleId !== 'undefined') {
return this.data.handleId.toString();
} else {
return Object.prototype.toString.call(this);
}
}; // add toJSON method to prevent cyclic error when
// call JSON.stringify(zoneTask)
ZoneTask.prototype.toJSON = function () {
return {
type: this.type,
state: this.state,
source: this.source,
zone: this.zone.name,
runCount: this.runCount
};
};
return ZoneTask;
}(); //////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/// MICROTASK QUEUE
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
var symbolSetTimeout = __symbol__('setTimeout');
var symbolPromise = __symbol__('Promise');
var symbolThen = __symbol__('then');
var _microTaskQueue = [];
var _isDrainingMicrotaskQueue = false;
var nativeMicroTaskQueuePromise;
function scheduleMicroTask(task) {
// if we are not running in any task, and there has not been anything scheduled
// we must bootstrap the initial task creation by manually scheduling the drain
if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {
// We are not running in Task, so we need to kickstart the microtask queue.
if (!nativeMicroTaskQueuePromise) {
if (global[symbolPromise]) {
nativeMicroTaskQueuePromise = global[symbolPromise].resolve(0);
}
}
if (nativeMicroTaskQueuePromise) {
var nativeThen = nativeMicroTaskQueuePromise[symbolThen];
if (!nativeThen) {
// native Promise is not patchable, we need to use `then` directly
// issue 1078
nativeThen = nativeMicroTaskQueuePromise['then'];
}
nativeThen.call(nativeMicroTaskQueuePromise, drainMicroTaskQueue);
} else {
global[symbolSetTimeout](drainMicroTaskQueue, 0);
}
}
task && _microTaskQueue.push(task);
}
function drainMicroTaskQueue() {
if (!_isDrainingMicrotaskQueue) {
_isDrainingMicrotaskQueue = true;
while (_microTaskQueue.length) {
var queue = _microTaskQueue;
_microTaskQueue = [];
for (var i = 0; i < queue.length; i++) {
var task = queue[i];
try {
task.zone.runTask(task, null, null);
} catch (error) {
_api.onUnhandledError(error);
}
}
}
_api.microtaskDrainDone();
_isDrainingMicrotaskQueue = false;
}
} //////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/// BOOTSTRAP
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
var NO_ZONE = {
name: 'NO ZONE'
};
var notScheduled = 'notScheduled',
scheduling = 'scheduling',
scheduled = 'scheduled',
running = 'running',
canceling = 'canceling',
unknown = 'unknown';
var microTask = 'microTask',
macroTask = 'macroTask',
eventTask = 'eventTask';
var patches = {};
var _api = {
symbol: __symbol__,
currentZoneFrame: function currentZoneFrame() {
return _currentZoneFrame;
},
onUnhandledError: noop,
microtaskDrainDone: noop,
scheduleMicroTask: scheduleMicroTask,
showUncaughtError: function showUncaughtError() {
return !Zone[__symbol__('ignoreConsoleErrorUncaughtError')];
},
patchEventTarget: function patchEventTarget() {
return [];
},
patchOnProperties: noop,
patchMethod: function patchMethod() {
return noop;
},
bindArguments: function bindArguments() {
return [];
},
patchThen: function patchThen() {
return noop;
},
patchMacroTask: function patchMacroTask() {
return noop;
},
setNativePromise: function setNativePromise(NativePromise) {
// sometimes NativePromise.resolve static function
// is not ready yet, (such as core-js/es6.promise)
// so we need to check here.
if (NativePromise && typeof NativePromise.resolve === 'function') {
nativeMicroTaskQueuePromise = NativePromise.resolve(0);
}
},
patchEventPrototype: function patchEventPrototype() {
return noop;
},
isIEOrEdge: function isIEOrEdge() {
return false;
},
getGlobalObjects: function getGlobalObjects() {
return undefined;
},
ObjectDefineProperty: function ObjectDefineProperty() {
return noop;
},
ObjectGetOwnPropertyDescriptor: function ObjectGetOwnPropertyDescriptor() {
return undefined;
},
ObjectCreate: function ObjectCreate() {
return undefined;
},
ArraySlice: function ArraySlice() {
return [];
},
patchClass: function patchClass() {
return noop;
},
wrapWithCurrentZone: function wrapWithCurrentZone() {
return noop;
},
filterProperties: function filterProperties() {
return [];
},
attachOriginToPatched: function attachOriginToPatched() {
return noop;
},
_redefineProperty: function _redefineProperty() {
return noop;
},
patchCallbacks: function patchCallbacks() {
return noop;
}
};
var _currentZoneFrame = {
parent: null,
zone: new Zone(null, null)
};
var _currentTask = null;
var _numberOfNestedTaskFrames = 0;
function noop() {}
performanceMeasure('Zone', 'Zone');
return global['Zone'] = Zone;
}(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var ObjectDefineProperty = Object.defineProperty;
function readableObjectToString(obj) {
if (obj && obj.toString === Object.prototype.toString) {
var className = obj.constructor && obj.constructor.name;
return (className ? className : '') + ': ' + JSON.stringify(obj);
}
return obj ? obj.toString() : Object.prototype.toString.call(obj);
}
var __symbol__ = api.symbol;
var _uncaughtPromiseErrors = [];
var isDisableWrappingUncaughtPromiseRejection = global[__symbol__('DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION')] === true;
var symbolPromise = __symbol__('Promise');
var symbolThen = __symbol__('then');
var creationTrace = '__creationTrace__';
api.onUnhandledError = function (e) {
if (api.showUncaughtError()) {
var rejection = e && e.rejection;
if (rejection) {
console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined);
} else {
console.error(e);
}
}
};
api.microtaskDrainDone = function () {
var _loop_1 = function _loop_1() {
var uncaughtPromiseError = _uncaughtPromiseErrors.shift();
try {
uncaughtPromiseError.zone.runGuarded(function () {
throw uncaughtPromiseError;
});
} catch (error) {
handleUnhandledRejection(error);
}
};
while (_uncaughtPromiseErrors.length) {
_loop_1();
}
};
var UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
function handleUnhandledRejection(e) {
api.onUnhandledError(e);
try {
var handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
if (typeof handler === 'function') {
handler.call(this, e);
}
} catch (err) {}
}
function isThenable(value) {
return value && value.then;
}
function forwardResolution(value) {
return value;
}
function forwardRejection(rejection) {
return ZoneAwarePromise.reject(rejection);
}
var symbolState = __symbol__('state');
var symbolValue = __symbol__('value');
var symbolFinally = __symbol__('finally');
var symbolParentPromiseValue = __symbol__('parentPromiseValue');
var symbolParentPromiseState = __symbol__('parentPromiseState');
var source = 'Promise.then';
var UNRESOLVED = null;
var RESOLVED = true;
var REJECTED = false;
var REJECTED_NO_CATCH = 0;
function makeResolver(promise, state) {
return function (v) {
try {
resolvePromise(promise, state, v);
} catch (err) {
resolvePromise(promise, false, err);
} // Do not return value or you will break the Promise spec.
};
}
var once = function once() {
var wasCalled = false;
return function wrapper(wrappedFunction) {
return function () {
if (wasCalled) {
return;
}
wasCalled = true;
wrappedFunction.apply(null, arguments);
};
};
};
var TYPE_ERROR = 'Promise resolved with itself';
var CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace'); // Promise Resolution
function resolvePromise(promise, state, value) {
var onceWrapper = once();
if (promise === value) {
throw new TypeError(TYPE_ERROR);
}
if (promise[symbolState] === UNRESOLVED) {
// should only get value.then once based on promise spec.
var then = null;
try {
if (typeof value === 'object' || typeof value === 'function') {
then = value && value.then;
}
} catch (err) {
onceWrapper(function () {
resolvePromise(promise, false, err);
})();
return promise;
} // if (value instanceof ZoneAwarePromise) {
if (state !== REJECTED && value instanceof ZoneAwarePromise && value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) && value[symbolState] !== UNRESOLVED) {
clearRejectedNoCatch(value);
resolvePromise(promise, value[symbolState], value[symbolValue]);
} else if (state !== REJECTED && typeof then === 'function') {
try {
then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
} catch (err) {
onceWrapper(function () {
resolvePromise(promise, false, err);
})();
}
} else {
promise[symbolState] = state;
var queue = promise[symbolValue];
promise[symbolValue] = value;
if (promise[symbolFinally] === symbolFinally) {
// the promise is generated by Promise.prototype.finally
if (state === RESOLVED) {
// the state is resolved, should ignore the value
// and use parent promise value
promise[symbolState] = promise[symbolParentPromiseState];
promise[symbolValue] = promise[symbolParentPromiseValue];
}
} // record task information in value when error occurs, so we can
// do some additional work such as render longStackTrace
if (state === REJECTED && value instanceof Error) {
// check if longStackTraceZone is here
var trace = Zone.currentTask && Zone.currentTask.data && Zone.currentTask.data[creationTrace];
if (trace) {
// only keep the long stack trace into error when in longStackTraceZone
ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, {
configurable: true,
enumerable: false,
writable: true,
value: trace
});
}
}
for (var i = 0; i < queue.length;) {
scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
}
if (queue.length == 0 && state == REJECTED) {
promise[symbolState] = REJECTED_NO_CATCH;
var uncaughtPromiseError = value;
if (!isDisableWrappingUncaughtPromiseRejection) {
// If disable wrapping uncaught promise reject
// and the rejected value is an Error object,
// use the value instead of wrapping it.
try {
// Here we throws a new Error to print more readable error log
// and if the value is not an error, zone.js builds an `Error`
// Object here to attach the stack information.
throw new Error('Uncaught (in promise): ' + readableObjectToString(value) + (value && value.stack ? '\n' + value.stack : ''));
} catch (err) {
uncaughtPromiseError = err;
}
}
uncaughtPromiseError.rejection = value;
uncaughtPromiseError.promise = promise;
uncaughtPromiseError.zone = Zone.current;
uncaughtPromiseError.task = Zone.currentTask;
_uncaughtPromiseErrors.push(uncaughtPromiseError);
api.scheduleMicroTask(); // to make sure that it is running
}
}
} // Resolving an already resolved promise is a noop.
return promise;
}
var REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
function clearRejectedNoCatch(promise) {
if (promise[symbolState] === REJECTED_NO_CATCH) {
// if the promise is rejected no catch status
// and queue.length > 0, means there is a error handler
// here to handle the rejected promise, we should trigger
// windows.rejectionhandled eventHandler or nodejs rejectionHandled
// eventHandler
try {
var handler = Zone[REJECTION_HANDLED_HANDLER];
if (handler && typeof handler === 'function') {
handler.call(this, {
rejection: promise[symbolValue],
promise: promise
});
}
} catch (err) {}
promise[symbolState] = REJECTED;
for (var i = 0; i < _uncaughtPromiseErrors.length; i++) {
if (promise === _uncaughtPromiseErrors[i].promise) {
_uncaughtPromiseErrors.splice(i, 1);
}
}
}
}
function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
clearRejectedNoCatch(promise);
var promiseState = promise[symbolState];
var delegate = promiseState ? typeof onFulfilled === 'function' ? onFulfilled : forwardResolution : typeof onRejected === 'function' ? onRejected : forwardRejection;
zone.scheduleMicroTask(source, function () {
try {
var parentPromiseValue = promise[symbolValue];
var isFinallyPromise = !!chainPromise && symbolFinally === chainPromise[symbolFinally];
if (isFinallyPromise) {
// if the promise is generated from finally call, keep parent promise's state and value
chainPromise[symbolParentPromiseValue] = parentPromiseValue;
chainPromise[symbolParentPromiseState] = promiseState;
} // should not pass value to finally callback
var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ? [] : [parentPromiseValue]);
resolvePromise(chainPromise, true, value);
} catch (error) {
// if error occurs, should always return this error
resolvePromise(chainPromise, false, error);
}
}, chainPromise);
}
var ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
var noop = function noop() {};
var ZoneAwarePromise =
/** @class */
function () {
function ZoneAwarePromise(executor) {
var promise = this;
if (!(promise instanceof ZoneAwarePromise)) {
throw new Error('Must be an instanceof Promise.');
}
promise[symbolState] = UNRESOLVED;
promise[symbolValue] = []; // queue;
try {
executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED));
} catch (error) {
resolvePromise(promise, false, error);
}
}
ZoneAwarePromise.toString = function () {
return ZONE_AWARE_PROMISE_TO_STRING;
};
ZoneAwarePromise.resolve = function (value) {
return resolvePromise(new this(null), RESOLVED, value);
};
ZoneAwarePromise.reject = function (error) {
return resolvePromise(new this(null), REJECTED, error);
};
ZoneAwarePromise.race = function (values) {
var resolve;
var reject;
var promise = new this(function (res, rej) {
resolve = res;
reject = rej;
});
function onResolve(value) {
resolve(value);
}
function onReject(error) {
reject(error);
}
for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
var value = values_1[_i];
if (!isThenable(value)) {
value = this.resolve(value);
}
value.then(onResolve, onReject);
}
return promise;
};
ZoneAwarePromise.all = function (values) {
return ZoneAwarePromise.allWithCallback(values);
};
ZoneAwarePromise.allSettled = function (values) {
var P = this && this.prototype instanceof ZoneAwarePromise ? this : ZoneAwarePromise;
return P.allWithCallback(values, {
thenCallback: function thenCallback(value) {
return {
status: 'fulfilled',
value: value
};
},
errorCallback: function errorCallback(err) {
return {
status: 'rejected',
reason: err
};
}
});
};
ZoneAwarePromise.allWithCallback = function (values, callback) {
var resolve;
var reject;
var promise = new this(function (res, rej) {
resolve = res;
reject = rej;
}); // Start at 2 to prevent prematurely resolving if .then is called immediately.
var unresolvedCount = 2;
var valueIndex = 0;
var resolvedValues = [];
var _loop_2 = function _loop_2(value) {
if (!isThenable(value)) {
value = this_1.resolve(value);
}
var curValueIndex = valueIndex;
try {
value.then(function (value) {
resolvedValues[curValueIndex] = callback ? callback.thenCallback(value) : value;
unresolvedCount--;
if (unresolvedCount === 0) {
resolve(resolvedValues);
}
}, function (err) {
if (!callback) {
reject(err);
} else {
resolvedValues[curValueIndex] = callback.errorCallback(err);
unresolvedCount--;
if (unresolvedCount === 0) {
resolve(resolvedValues);
}
}
});
} catch (thenErr) {
reject(thenErr);
}
unresolvedCount++;
valueIndex++;
};
var this_1 = this;
for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
var value = values_2[_i];
_loop_2(value);
} // Make the unresolvedCount zero-based again.
unresolvedCount -= 2;
if (unresolvedCount === 0) {
resolve(resolvedValues);
}
return promise;
};
Object.defineProperty(ZoneAwarePromise.prototype, Symbol.toStringTag, {
get: function get() {
return 'Promise';
},
enumerable: true,
configurable: true
});
Object.defineProperty(ZoneAwarePromise.prototype, Symbol.species, {
get: function get() {
return ZoneAwarePromise;
},
enumerable: true,
configurable: true
});
ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {
var C = this.constructor[Symbol.species];
if (!C || typeof C !== 'function') {
C = this.constructor || ZoneAwarePromise;
}
var chainPromise = new C(noop);
var zone = Zone.current;
if (this[symbolState] == UNRESOLVED) {
this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
} else {
scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
}
return chainPromise;
};
ZoneAwarePromise.prototype.catch = function (onRejected) {
return this.then(null, onRejected);
};
ZoneAwarePromise.prototype.finally = function (onFinally) {
var C = this.constructor[Symbol.species];
if (!C || typeof C !== 'function') {
C = ZoneAwarePromise;
}
var chainPromise = new C(noop);
chainPromise[symbolFinally] = symbolFinally;
var zone = Zone.current;
if (this[symbolState] == UNRESOLVED) {
this[symbolValue].push(zone, chainPromise, onFinally, onFinally);
} else {
scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally);
}
return chainPromise;
};
return ZoneAwarePromise;
}(); // Protect against aggressive optimizers dropping seemingly unused properties.
// E.g. Closure Compiler in advanced mode.
ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
ZoneAwarePromise['race'] = ZoneAwarePromise.race;
ZoneAwarePromise['all'] = ZoneAwarePromise.all;
var NativePromise = global[symbolPromise] = global['Promise'];
var ZONE_AWARE_PROMISE = Zone.__symbol__('ZoneAwarePromise');
var desc = ObjectGetOwnPropertyDescriptor(global, 'Promise');
if (!desc || desc.configurable) {
desc && delete desc.writable;
desc && delete desc.value;
if (!desc) {
desc = {
configurable: true,
enumerable: true
};
}
desc.get = function () {
// if we already set ZoneAwarePromise, use patched one
// otherwise return native one.
return global[ZONE_AWARE_PROMISE] ? global[ZONE_AWARE_PROMISE] : global[symbolPromise];
};
desc.set = function (NewNativePromise) {
if (NewNativePromise === ZoneAwarePromise) {
// if the NewNativePromise is ZoneAwarePromise
// save to global
global[ZONE_AWARE_PROMISE] = NewNativePromise;
} else {
// if the NewNativePromise is not ZoneAwarePromise
// for example: after load zone.js, some library just
// set es6-promise to global, if we set it to global
// directly, assertZonePatched will fail and angular
// will not loaded, so we just set the NewNativePromise
// to global[symbolPromise], so the result is just like
// we load ES6 Promise before zone.js
global[symbolPromise] = NewNativePromise;
if (!NewNativePromise.prototype[symbolThen]) {
patchThen(NewNativePromise);
}
api.setNativePromise(NewNativePromise);
}
};
ObjectDefineProperty(global, 'Promise', desc);
}
global['Promise'] = ZoneAwarePromise;
var symbolThenPatched = __symbol__('thenPatched');
function patchThen(Ctor) {
var proto = Ctor.prototype;
var prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
if (prop && (prop.writable === false || !prop.configurable)) {
// check Ctor.prototype.then propertyDescriptor is writable or not
// in meteor env, writable is false, we should ignore such case
return;
}
var originalThen = proto.then; // Keep a reference to the original method.
proto[symbolThen] = originalThen;
Ctor.prototype.then = function (onResolve, onReject) {
var _this = this;
var wrapped = new ZoneAwarePromise(function (resolve, reject) {
originalThen.call(_this, resolve, reject);
});
return wrapped.then(onResolve, onReject);
};
Ctor[symbolThenPatched] = true;
}
api.patchThen = patchThen;
function zoneify(fn) {
return function () {
var resultPromise = fn.apply(this, arguments);
if (resultPromise instanceof ZoneAwarePromise) {
return resultPromise;
}
var ctor = resultPromise.constructor;
if (!ctor[symbolThenPatched]) {
patchThen(ctor);
}
return resultPromise;
};
}
if (NativePromise) {
patchThen(NativePromise);
var fetch_1 = global['fetch'];
if (typeof fetch_1 == 'function') {
global[api.symbol('fetch')] = fetch_1;
global['fetch'] = zoneify(fetch_1);
}
} // This is not part of public API, but it is useful for tests, so we expose it.
Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
return ZoneAwarePromise;
});
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Suppress closure compiler errors about unknown 'Zone' variable
* @fileoverview
* @suppress {undefinedVars,globalThis,missingRequire}
*/
/// <reference types="node"/>
// issue #989, to reduce bundle size, use short name
/** Object.getOwnPropertyDescriptor */
var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
/** Object.defineProperty */
var ObjectDefineProperty = Object.defineProperty;
/** Object.getPrototypeOf */
var ObjectGetPrototypeOf = Object.getPrototypeOf;
/** Object.create */
var ObjectCreate = Object.create;
/** Array.prototype.slice */
var ArraySlice = Array.prototype.slice;
/** addEventListener string const */
var ADD_EVENT_LISTENER_STR = 'addEventListener';
/** removeEventListener string const */
var REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
/** zoneSymbol addEventListener */
var ZONE_SYMBOL_ADD_EVENT_LISTENER = Zone.__symbol__(ADD_EVENT_LISTENER_STR);
/** zoneSymbol removeEventListener */
var ZONE_SYMBOL_REMOVE_EVENT_LISTENER = Zone.__symbol__(REMOVE_EVENT_LISTENER_STR);
/** true string const */
var TRUE_STR = 'true';
/** false string const */
var FALSE_STR = 'false';
/** Zone symbol prefix string const. */
var ZONE_SYMBOL_PREFIX = Zone.__symbol__('');
function wrapWithCurrentZone(callback, source) {
return Zone.current.wrap(callback, source);
}
function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) {
return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
}
var zoneSymbol = Zone.__symbol__;
var isWindowExists = typeof window !== 'undefined';
var internalWindow = isWindowExists ? window : undefined;
var _global = isWindowExists && internalWindow || typeof self === 'object' && self || global;
var REMOVE_ATTRIBUTE = 'removeAttribute';
var NULL_ON_PROP_VALUE = [null];
function bindArguments(args, source) {
for (var i = args.length - 1; i >= 0; i--) {
if (typeof args[i] === 'function') {
args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
}
}
return args;
}
function patchPrototype(prototype, fnNames) {
var source = prototype.constructor['name'];
var _loop_3 = function _loop_3(i) {
var name_1 = fnNames[i];
var delegate = prototype[name_1];
if (delegate) {
var prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, name_1);
if (!isPropertyWritable(prototypeDesc)) {
return "continue";
}
prototype[name_1] = function (delegate) {
var patched = function patched() {
return delegate.apply(this, bindArguments(arguments, source + '.' + name_1));
};
attachOriginToPatched(patched, delegate);
return patched;
}(delegate);
}
};
for (var i = 0; i < fnNames.length; i++) {
_loop_3(i);
}
}
function isPropertyWritable(propertyDesc) {
if (!propertyDesc) {
return true;
}
if (propertyDesc.writable === false) {
return false;
}
return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
}
var isWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope; // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
// this code.
var isNode = !('nw' in _global) && typeof _global.process !== 'undefined' && {}.toString.call(_global.process) === '[object process]';
var isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']); // we are in electron of nw, so we are both browser and nodejs
// Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
// this code.
var isMix = typeof _global.process !== 'undefined' && {}.toString.call(_global.process) === '[object process]' && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
var zoneSymbolEventNames = {};
var wrapFn = function wrapFn(event) {
// https://github.com/angular/zone.js/issues/911, in IE, sometimes
// event will be undefined, so we need to use window.event
event = event || _global.event;
if (!event) {
return;
}
var eventNameSymbol = zoneSymbolEventNames[event.type];
if (!eventNameSymbol) {
eventNameSymbol = zoneSymbolEventNames[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
}
var target = this || event.target || _global;
var listener = target[eventNameSymbol];
var result;
if (isBrowser && target === internalWindow && event.type === 'error') {
// window.onerror have different signiture
// https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
// and onerror callback will prevent default when callback return true
var errorEvent = event;
result = listener && listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
if (result === true) {
event.preventDefault();
}
} else {
result = listener && listener.apply(this, arguments);
if (result != undefined && !result) {
event.preventDefault();
}
}
return result;
};
function patchProperty(obj, prop, prototype) {
var desc = ObjectGetOwnPropertyDescriptor(obj, prop);
if (!desc && prototype) {
// when patch window object, use prototype to check prop exist or not
var prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
if (prototypeDesc) {
desc = {
enumerable: true,
configurable: true
};
}
} // if the descriptor not exists or is not configurable
// just return
if (!desc || !desc.configurable) {
return;
}
var onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
return;
} // A property descriptor cannot have getter/setter and be writable
// deleting the writable and value properties avoids this error:
//
// TypeError: property descriptors must not specify a value or be writable when a
// getter or setter has been specified
delete desc.writable;
delete desc.value;
var originalDescGet = desc.get;
var originalDescSet = desc.set; // substr(2) cuz 'onclick' -> 'click', etc
var eventName = prop.substr(2);
var eventNameSymbol = zoneSymbolEventNames[eventName];
if (!eventNameSymbol) {
eventNameSymbol = zoneSymbolEventNames[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
}
desc.set = function (newValue) {
// in some of windows's onproperty callback, this is undefined
// so we need to check it
var target = this;
if (!target && obj === _global) {
target = _global;
}
if (!target) {
return;
}
var previousValue = target[eventNameSymbol];
if (previousValue) {
target.removeEventListener(eventName, wrapFn);
} // issue #978, when onload handler was added before loading zone.js
// we should remove it with originalDescSet
if (originalDescSet) {
originalDescSet.apply(target, NULL_ON_PROP_VALUE);
}
if (typeof newValue === 'function') {
target[eventNameSymbol] = newValue;
target.addEventListener(eventName, wrapFn, false);
} else {
target[eventNameSymbol] = null;
}
}; // The getter would return undefined for unassigned properties but the default value of an
// unassigned property is null
desc.get = function () {
// in some of windows's onproperty callback, this is undefined
// so we need to check it
var target = this;
if (!target && obj === _global) {
target = _global;
}
if (!target) {
return null;
}
var listener = target[eventNameSymbol];
if (listener) {
return listener;
} else if (originalDescGet) {
// result will be null when use inline event attribute,
// such as <button onclick="func();">OK</button>
// because the onclick function is internal raw uncompiled handler
// the onclick will be evaluated when first time event was triggered or
// the property is accessed, https://github.com/angular/zone.js/issues/525
// so we should use original native get to retrieve the handler
var value = originalDescGet && originalDescGet.call(this);
if (value) {
desc.set.call(this, value);
if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
target.removeAttribute(prop);
}
return value;
}
}
return null;
};
ObjectDefineProperty(obj, prop, desc);
obj[onPropPatchedSymbol] = true;
}
function patchOnProperties(obj, properties, prototype) {
if (properties) {
for (var i = 0; i < properties.length; i++) {
patchProperty(obj, 'on' + properties[i], prototype);
}
} else {
var onProperties = [];
for (var prop in obj) {
if (prop.substr(0, 2) == 'on') {
onProperties.push(prop);
}
}
for (var j = 0; j < onProperties.length; j++) {
patchProperty(obj, onProperties[j], prototype);
}
}
}
var originalInstanceKey = zoneSymbol('originalInstance'); // wrap some native API on `window`
function patchClass(className) {
var OriginalClass = _global[className];
if (!OriginalClass) return; // keep original class in global
_global[zoneSymbol(className)] = OriginalClass;
_global[className] = function () {
var a = bindArguments(arguments, className);
switch (a.length) {
case 0:
this[originalInstanceKey] = new OriginalClass();
break;
case 1:
this[originalInstanceKey] = new OriginalClass(a[0]);
break;
case 2:
this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
break;
case 3:
this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
break;
case 4:
this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
break;
default:
throw new Error('Arg list too long.');
}
}; // attach original delegate to patched function
attachOriginToPatched(_global[className], OriginalClass);
var instance = new OriginalClass(function () {});
var prop;
for (prop in instance) {
// https://bugs.webkit.org/show_bug.cgi?id=44721
if (className === 'XMLHttpRequest' && prop === 'responseBlob') continue;
(function (prop) {
if (typeof instance[prop] === 'function') {
_global[className].prototype[prop] = function () {
return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
};
} else {
ObjectDefineProperty(_global[className].prototype, prop, {
set: function set(fn) {
if (typeof fn === 'function') {
this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop); // keep callback in wrapped function so we can
// use it in Function.prototype.toString to return
// the native one.
attachOriginToPatched(this[originalInstanceKey][prop], fn);
} else {
this[originalInstanceKey][prop] = fn;
}
},
get: function get() {
return this[originalInstanceKey][prop];
}
});
}
})(prop);
}
for (prop in OriginalClass) {
if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
_global[className][prop] = OriginalClass[prop];
}
}
}
function copySymbolProperties(src, dest) {
if (typeof Object.getOwnPropertySymbols !== 'function') {
return;
}
var symbols = Object.getOwnPropertySymbols(src);
symbols.forEach(function (symbol) {
var desc = Object.getOwnPropertyDescriptor(src, symbol);
Object.defineProperty(dest, symbol, {
get: function get() {
return src[symbol];
},
set: function set(value) {
if (desc && (!desc.writable || typeof desc.set !== 'function')) {
// if src[symbol] is not writable or not have a setter, just return
return;
}
src[symbol] = value;
},
enumerable: desc ? desc.enumerable : true,
configurable: desc ? desc.configurable : true
});
});
}
var shouldCopySymbolProperties = false;
function patchMethod(target, name, patchFn) {
var proto = target;
while (proto && !proto.hasOwnProperty(name)) {
proto = ObjectGetPrototypeOf(proto);
}
if (!proto && target[name]) {
// somehow we did not find it, but we can see it. This happens on IE for Window properties.
proto = target;
}
var delegateName = zoneSymbol(name);
var delegate = null;
if (proto && !(delegate = proto[delegateName])) {
delegate = proto[delegateName] = proto[name]; // check whether proto[name] is writable
// some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
var desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
if (isPropertyWritable(desc)) {
var patchDelegate_1 = patchFn(delegate, delegateName, name);
proto[name] = function () {
return patchDelegate_1(this, arguments);
};
attachOriginToPatched(proto[name], delegate);
if (shouldCopySymbolProperties) {
copySymbolProperties(delegate, proto[name]);
}
}
}
return delegate;
} // TODO: @JiaLiPassion, support cancel task later if necessary
function patchMacroTask(obj, funcName, metaCreator) {
var setNative = null;
function scheduleTask(task) {
var data = task.data;
data.args[data.cbIdx] = function () {
task.invoke.apply(this, arguments);
};
setNative.apply(data.target, data.args);
return task;
}
setNative = patchMethod(obj, funcName, function (delegate) {
return function (self, args) {
var meta = metaCreator(self, args);
if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
} else {
// cause an error by calling it directly.
return delegate.apply(self, args);
}
};
});
}
function attachOriginToPatched(patched, original) {
patched[zoneSymbol('OriginalDelegate')] = original;
}
var isDetectedIEOrEdge = false;
var ieOrEdge = false;
function isIE() {
try {
var ua = internalWindow.navigator.userAgent;
if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1) {
return true;
}
} catch (error) {}
return false;
}
function isIEOrEdge() {
if (isDetectedIEOrEdge) {
return ieOrEdge;
}
isDetectedIEOrEdge = true;
try {
var ua = internalWindow.navigator.userAgent;
if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) {
ieOrEdge = true;
}
} catch (error) {}
return ieOrEdge;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// override Function.prototype.toString to make zone.js patched function
// look like native function
Zone.__load_patch('toString', function (global) {
// patch Func.prototype.toString to let them look like native
var originalFunctionToString = Function.prototype.toString;
var ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
var PROMISE_SYMBOL = zoneSymbol('Promise');
var ERROR_SYMBOL = zoneSymbol('Error');
var newFunctionToString = function toString() {
if (typeof this === 'function') {
var originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
if (originalDelegate) {
if (typeof originalDelegate === 'function') {
return originalFunctionToString.call(originalDelegate);
} else {
return Object.prototype.toString.call(originalDelegate);
}
}
if (this === Promise) {
var nativePromise = global[PROMISE_SYMBOL];
if (nativePromise) {
return originalFunctionToString.call(nativePromise);
}
}
if (this === Error) {
var nativeError = global[ERROR_SYMBOL];
if (nativeError) {
return originalFunctionToString.call(nativeError);
}
}
}
return originalFunctionToString.call(this);
};
newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
Function.prototype.toString = newFunctionToString; // patch Object.prototype.toString to let them look like native
var originalObjectToString = Object.prototype.toString;
var PROMISE_OBJECT_TO_STRING = '[object Promise]';
Object.prototype.toString = function () {
if (this instanceof Promise) {
return PROMISE_OBJECT_TO_STRING;
}
return originalObjectToString.call(this);
};
});
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var passiveSupported = false;
if (typeof window !== 'undefined') {
try {
var options = Object.defineProperty({}, 'passive', {
get: function get() {
passiveSupported = true;
}
});
window.addEventListener('test', options, options);
window.removeEventListener('test', options, options);
} catch (err) {
passiveSupported = false;
}
} // an identifier to tell ZoneTask do not create a new invoke closure
var OPTIMIZED_ZONE_EVENT_TASK_DATA = {
useG: true
};
var zoneSymbolEventNames$1 = {};
var globalSources = {};
var EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
var IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
function prepareEventNames(eventName, eventNameToString) {
var falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
var trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
zoneSymbolEventNames$1[eventName] = {};
zoneSymbolEventNames$1[eventName][FALSE_STR] = symbol;
zoneSymbolEventNames$1[eventName][TRUE_STR] = symbolCapture;
}
function patchEventTarget(_global, apis, patchOptions) {
var ADD_EVENT_LISTENER = patchOptions && patchOptions.add || ADD_EVENT_LISTENER_STR;
var REMOVE_EVENT_LISTENER = patchOptions && patchOptions.rm || REMOVE_EVENT_LISTENER_STR;
var LISTENERS_EVENT_LISTENER = patchOptions && patchOptions.listeners || 'eventListeners';
var REMOVE_ALL_LISTENERS_EVENT_LISTENER = patchOptions && patchOptions.rmAll || 'removeAllListeners';
var zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
var ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
var PREPEND_EVENT_LISTENER = 'prependListener';
var PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
var invokeTask = function invokeTask(task, target, event) {
// for better performance, check isRemoved which is set
// by removeEventListener
if (task.isRemoved) {
return;
}
var delegate = task.callback;
if (typeof delegate === 'object' && delegate.handleEvent) {
// create the bind version of handleEvent when invoke
task.callback = function (event) {
return delegate.handleEvent(event);
};
task.originalDelegate = delegate;
} // invoke static task.invoke
task.invoke(task, target, [event]);
var options = task.options;
if (options && typeof options === 'object' && options.once) {
// if options.once is true, after invoke once remove listener here
// only browser need to do this, nodejs eventEmitter will cal removeListener
// inside EventEmitter.once
var delegate_1 = task.originalDelegate ? task.originalDelegate : task.callback;
target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate_1, options);
}
}; // global shared zoneAwareCallback to handle all event callback with capture = false
var globalZoneAwareCallback = function globalZoneAwareCallback(event) {
// https://github.com/angular/zone.js/issues/911, in IE, sometimes
// event will be undefined, so we need to use window.event
event = event || _global.event;
if (!event) {
return;
} // event.target is needed for Samsung TV and SourceBuffer
// || global is needed https://github.com/angular/zone.js/issues/190
var target = this || event.target || _global;
var tasks = target[zoneSymbolEventNames$1[event.type][FALSE_STR]];
if (tasks) {
// invoke all tasks which attached to current target with given event.type and capture = false
// for performance concern, if task.length === 1, just invoke
if (tasks.length === 1) {
invokeTask(tasks[0], target, event);
} else {
// https://github.com/angular/zone.js/issues/836
// copy the tasks array before invoke, to avoid
// the callback will remove itself or other listener
var copyTasks = tasks.slice();
for (var i = 0; i < copyTasks.length; i++) {
if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
break;
}
invokeTask(copyTasks[i], target, event);
}
}
}
}; // global shared zoneAwareCallback to handle all event callback with capture = true
var globalZoneAwareCaptureCallback = function globalZoneAwareCaptureCallback(event) {
// https://github.com/angular/zone.js/issues/911, in IE, sometimes
// event will be undefined, so we need to use window.event
event = event || _global.event;
if (!event) {
return;
} // event.target is needed for Samsung TV and SourceBuffer
// || global is needed https://github.com/angular/zone.js/issues/190
var target = this || event.target || _global;
var tasks = target[zoneSymbolEventNames$1[event.type][TRUE_STR]];
if (tasks) {
// invoke all tasks which attached to current target with given event.type and capture = false
// for performance concern, if task.length === 1, just invoke
if (tasks.length === 1) {
invokeTask(tasks[0], target, event);
} else {
// https://github.com/angular/zone.js/issues/836
// copy the tasks array before invoke, to avoid
// the callback will remove itself or other listener
var copyTasks = tasks.slice();
for (var i = 0; i < copyTasks.length; i++) {
if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
break;
}
invokeTask(copyTasks[i], target, event);
}
}
}
};
function patchEventTargetMethods(obj, patchOptions) {
if (!obj) {
return false;
}
var useGlobalCallback = true;
if (patchOptions && patchOptions.useG !== undefined) {
useGlobalCallback = patchOptions.useG;
}
var validateHandler = patchOptions && patchOptions.vh;
var checkDuplicate = true;
if (patchOptions && patchOptions.chkDup !== undefined) {
checkDuplicate = patchOptions.chkDup;
}
var returnTarget = false;
if (patchOptions && patchOptions.rt !== undefined) {
returnTarget = patchOptions.rt;
}
var proto = obj;
while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
proto = ObjectGetPrototypeOf(proto);
}
if (!proto && obj[ADD_EVENT_LISTENER]) {
// somehow we did not find it, but we can see it. This happens on IE for Window properties.
proto = obj;
}
if (!proto) {
return false;
}
if (proto[zoneSymbolAddEventListener]) {
return false;
}
var eventNameToString = patchOptions && patchOptions.eventNameToString; // a shared global taskData to pass data for scheduleEventTask
// so we do not need to create a new object just for pass some data
var taskData = {};
var nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
var nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] = proto[REMOVE_EVENT_LISTENER];
var nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] = proto[LISTENERS_EVENT_LISTENER];
var nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] = proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
var nativePrependEventListener;
if (patchOptions && patchOptions.prepend) {
nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] = proto[patchOptions.prepend];
}
/**
* This util function will build an option object with passive option
* to handle all possible input from the user.
*/
function buildEventListenerOptions(options, passive) {
if (!passiveSupported && typeof options === 'object' && options) {
// doesn't support passive but user want to pass an object as options.
// this will not work on some old browser, so we just pass a boolean
// as useCapture parameter
return !!options.capture;
}
if (!passiveSupported || !passive) {
return options;
}
if (typeof options === 'boolean') {
return {
capture: options,
passive: true
};
}
if (!options) {
return {
passive: true
};
}
if (typeof options === 'object' && options.passive !== false) {
return Object.assign(Object.assign({}, options), {
passive: true
});
}
return options;
}
var customScheduleGlobal = function customScheduleGlobal(task) {
// if there is already a task for the eventName + capture,
// just return, because we use the shared globalZoneAwareCallback here.
if (taskData.isExisting) {
return;
}
return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
};
var customCancelGlobal = function customCancelGlobal(task) {
// if task is not marked as isRemoved, this call is directly
// from Zone.prototype.cancelTask, we should remove the task
// from tasksList of target first
if (!task.isRemoved) {
var symbolEventNames = zoneSymbolEventNames$1[task.eventName];
var symbolEventName = void 0;
if (symbolEventNames) {
symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
}
var existingTasks = symbolEventName && task.target[symbolEventName];
if (existingTasks) {
for (var i = 0; i < existingTasks.length; i++) {
var existingTask = existingTasks[i];
if (existingTask === task) {
existingTasks.splice(i, 1); // set isRemoved to data for faster invokeTask check
task.isRemoved = true;
if (existingTasks.length === 0) {
// all tasks for the eventName + capture have gone,
// remove globalZoneAwareCallback and remove the task cache from target
task.allRemoved = true;
task.target[symbolEventName] = null;
}
break;
}
}
}
} // if all tasks for the eventName + capture have gone,
// we will really remove the global event callback,
// if not, return
if (!task.allRemoved) {
return;
}
return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
};
var customScheduleNonGlobal = function customScheduleNonGlobal(task) {
return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
};
var customSchedulePrepend = function customSchedulePrepend(task) {
return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
};
var customCancelNonGlobal = function customCancelNonGlobal(task) {
return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
};
var customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
var customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
var compareTaskCallbackVsDelegate = function compareTaskCallbackVsDelegate(task, delegate) {
var typeOfDelegate = typeof delegate;
return typeOfDelegate === 'function' && task.callback === delegate || typeOfDelegate === 'object' && task.originalDelegate === delegate;
};
var compare = patchOptions && patchOptions.diff ? patchOptions.diff : compareTaskCallbackVsDelegate;
var blackListedEvents = Zone[zoneSymbol('BLACK_LISTED_EVENTS')];
var passiveEvents = _global[zoneSymbol('PASSIVE_EVENTS')];
var makeAddListener = function makeAddListener(nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget, prepend) {
if (returnTarget === void 0) {
returnTarget = false;
}
if (prepend === void 0) {
prepend = false;
}
return function () {
var target = this || _global;
var eventName = arguments[0];
if (patchOptions && patchOptions.transferEventName) {
eventName = patchOptions.transferEventName(eventName);
}
var delegate = arguments[1];
if (!delegate) {
return nativeListener.apply(this, arguments);
}
if (isNode && eventName === 'uncaughtException') {
// don't patch uncaughtException of nodejs to prevent endless loop
return nativeListener.apply(this, arguments);
} // don't create the bind delegate function for handleEvent
// case here to improve addEventListener performance
// we will create the bind delegate when invoke
var isHandleEvent = false;
if (typeof delegate !== 'function') {
if (!delegate.handleEvent) {
return nativeListener.apply(this, arguments);
}
isHandleEvent = true;
}
if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
return;
}
var passive = passiveSupported && !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
var options = buildEventListenerOptions(arguments[2], passive);
if (blackListedEvents) {
// check black list
for (var i = 0; i < blackListedEvents.length; i++) {
if (eventName === blackListedEvents[i]) {
if (passive) {
return nativeListener.call(target, eventName, delegate, options);
} else {
return nativeListener.apply(this, arguments);
}
}
}
}
var capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
var once = options && typeof options === 'object' ? options.once : false;
var zone = Zone.current;
var symbolEventNames = zoneSymbolEventNames$1[eventName];
if (!symbolEventNames) {
prepareEventNames(eventName, eventNameToString);
symbolEventNames = zoneSymbolEventNames$1[eventName];
}
var symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
var existingTasks = target[symbolEventName];
var isExisting = false;
if (existingTasks) {
// already have task registered
isExisting = true;
if (checkDuplicate) {
for (var i = 0; i < existingTasks.length; i++) {
if (compare(existingTasks[i], delegate)) {
// same callback, same capture, same event name, just return
return;
}
}
}
} else {
existingTasks = target[symbolEventName] = [];
}
var source;
var constructorName = target.constructor['name'];
var targetSource = globalSources[constructorName];
if (targetSource) {
source = targetSource[eventName];
}
if (!source) {
source = constructorName + addSource + (eventNameToString ? eventNameToString(eventName) : eventName);
} // do not create a new object as task.data to pass those things
// just use the global shared one
taskData.options = options;
if (once) {
// if addEventListener with once options, we don't pass it to
// native addEventListener, instead we keep the once setting
// and handle ourselves.
taskData.options.once = false;
}
taskData.target = target;
taskData.capture = capture;
taskData.eventName = eventName;
taskData.isExisting = isExisting;
var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined; // keep taskData into data to allow onScheduleEventTask to access the task information
if (data) {
data.taskData = taskData;
}
var task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn); // should clear taskData.target to avoid memory leak
// issue, https://github.com/angular/angular/issues/20442
taskData.target = null; // need to clear up taskData because it is a global object
if (data) {
data.taskData = null;
} // have to save those information to task in case
// application may call task.zone.cancelTask() directly
if (once) {
options.once = true;
}
if (!(!passiveSupported && typeof task.options === 'boolean')) {
// if not support passive, and we pass an option object
// to addEventListener, we should save the options to task
task.options = options;
}
task.target = target;
task.capture = capture;
task.eventName = eventName;
if (isHandleEvent) {
// save original delegate for compare to check duplicate
task.originalDelegate = delegate;
}
if (!prepend) {
existingTasks.push(task);
} else {
existingTasks.unshift(task);
}
if (returnTarget) {
return target;
}
};
};
proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
if (nativePrependEventListener) {
proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
}
proto[REMOVE_EVENT_LISTENER] = function () {
var target = this || _global;
var eventName = arguments[0];
if (patchOptions && patchOptions.transferEventName) {
eventName = patchOptions.transferEventName(eventName);
}
var options = arguments[2];
var capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
var delegate = arguments[1];
if (!delegate) {
return nativeRemoveEventListener.apply(this, arguments);
}
if (validateHandler && !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
return;
}
var symbolEventNames = zoneSymbolEventNames$1[eventName];
var symbolEventName;
if (symbolEventNames) {
symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
}
var existingTasks = symbolEventName && target[symbolEventName];
if (existingTasks) {
for (var i = 0; i < existingTasks.length; i++) {
var existingTask = existingTasks[i];
if (compare(existingTask, delegate)) {
existingTasks.splice(i, 1); // set isRemoved to data for faster invokeTask check
existingTask.isRemoved = true;
if (existingTasks.length === 0) {
// all tasks for the eventName + capture have gone,
// remove globalZoneAwareCallback and remove the task cache from target
existingTask.allRemoved = true;
target[symbolEventName] = null; // in the target, we have an event listener which is added by on_property
// such as target.onclick = function() {}, so we need to clear this internal
// property too if all delegates all removed
if (typeof eventName === 'string') {
var onPropertySymbol = ZONE_SYMBOL_PREFIX + 'ON_PROPERTY' + eventName;
target[onPropertySymbol] = null;
}
}
existingTask.zone.cancelTask(existingTask);
if (returnTarget) {
return target;
}
return;
}
}
} // issue 930, didn't find the event name or callback
// from zone kept existingTasks, the callback maybe
// added outside of zone, we need to call native removeEventListener
// to try to remove it.
return nativeRemoveEventListener.apply(this, arguments);
};
proto[LISTENERS_EVENT_LISTENER] = function () {
var target = this || _global;
var eventName = arguments[0];
if (patchOptions && patchOptions.transferEventName) {
eventName = patchOptions.transferEventName(eventName);
}
var listeners = [];
var tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
listeners.push(delegate);
}
return listeners;
};
proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
var target = this || _global;
var eventName = arguments[0];
if (!eventName) {
var keys = Object.keys(target);
for (var i = 0; i < keys.length; i++) {
var prop = keys[i];
var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
var evtName = match && match[1]; // in nodejs EventEmitter, removeListener event is
// used for monitoring the removeListener call,
// so just keep removeListener eventListener until
// all other eventListeners are removed
if (evtName && evtName !== 'removeListener') {
this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
}
} // remove removeListener listener finally
this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
} else {
if (patchOptions && patchOptions.transferEventName) {
eventName = patchOptions.transferEventName(eventName);
}
var symbolEventNames = zoneSymbolEventNames$1[eventName];
if (symbolEventNames) {
var symbolEventName = symbolEventNames[FALSE_STR];
var symbolCaptureEventName = symbolEventNames[TRUE_STR];
var tasks = target[symbolEventName];
var captureTasks = target[symbolCaptureEventName];
if (tasks) {
var removeTasks = tasks.slice();
for (var i = 0; i < removeTasks.length; i++) {
var task = removeTasks[i];
var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
}
}
if (captureTasks) {
var removeTasks = captureTasks.slice();
for (var i = 0; i < removeTasks.length; i++) {
var task = removeTasks[i];
var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
}
}
}
}
if (returnTarget) {
return this;
}
}; // for native toString patch
attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
if (nativeRemoveAllListeners) {
attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
}
if (nativeListeners) {
attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
}
return true;
}
var results = [];
for (var i = 0; i < apis.length; i++) {
results[i] = patchEventTargetMethods(apis[i], patchOptions);
}
return results;
}
function findEventTasks(target, eventName) {
if (!eventName) {
var foundTasks = [];
for (var prop in target) {
var match = EVENT_NAME_SYMBOL_REGX.exec(prop);
var evtName = match && match[1];
if (evtName && (!eventName || evtName === eventName)) {
var tasks = target[prop];
if (tasks) {
for (var i = 0; i < tasks.length; i++) {
foundTasks.push(tasks[i]);
}
}
}
}
return foundTasks;
}
var symbolEventName = zoneSymbolEventNames$1[eventName];
if (!symbolEventName) {
prepareEventNames(eventName);
symbolEventName = zoneSymbolEventNames$1[eventName];
}
var captureFalseTasks = target[symbolEventName[FALSE_STR]];
var captureTrueTasks = target[symbolEventName[TRUE_STR]];
if (!captureFalseTasks) {
return captureTrueTasks ? captureTrueTasks.slice() : [];
} else {
return captureTrueTasks ? captureFalseTasks.concat(captureTrueTasks) : captureFalseTasks.slice();
}
}
function patchEventPrototype(global, api) {
var Event = global['Event'];
if (Event && Event.prototype) {
api.patchMethod(Event.prototype, 'stopImmediatePropagation', function (delegate) {
return function (self, args) {
self[IMMEDIATE_PROPAGATION_SYMBOL] = true; // we need to call the native stopImmediatePropagation
// in case in some hybrid application, some part of
// application will be controlled by zone, some are not
delegate && delegate.apply(self, args);
};
});
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function patchCallbacks(api, target, targetName, method, callbacks) {
var symbol = Zone.__symbol__(method);
if (target[symbol]) {
return;
}
var nativeDelegate = target[symbol] = target[method];
target[method] = function (name, opts, options) {
if (opts && opts.prototype) {
callbacks.forEach(function (callback) {
var source = targetName + "." + method + "::" + callback;
var prototype = opts.prototype;
if (prototype.hasOwnProperty(callback)) {
var descriptor = api.ObjectGetOwnPropertyDescriptor(prototype, callback);
if (descriptor && descriptor.value) {
descriptor.value = api.wrapWithCurrentZone(descriptor.value, source);
api._redefineProperty(opts.prototype, callback, descriptor);
} else if (prototype[callback]) {
prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
}
} else if (prototype[callback]) {
prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
}
});
}
return nativeDelegate.call(target, name, opts, options);
};
api.attachOriginToPatched(target[method], nativeDelegate);
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var globalEventHandlersEventNames = ['abort', 'animationcancel', 'animationend', 'animationiteration', 'auxclick', 'beforeinput', 'blur', 'cancel', 'canplay', 'canplaythrough', 'change', 'compositionstart', 'compositionupdate', 'compositionend', 'cuechange', 'click', 'close', 'contextmenu', 'curechange', 'dblclick', 'drag', 'dragend', 'dragenter', 'dragexit', 'dragleave', 'dragover', 'drop', 'durationchange', 'emptied', 'ended', 'error', 'focus', 'focusin', 'focusout', 'gotpointercapture', 'input', 'invalid', 'keydown', 'keypress', 'keyup', 'load', 'loadstart', 'loadeddata', 'loadedmetadata', 'lostpointercapture', 'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'mousewheel', 'orientationchange', 'pause', 'play', 'playing', 'pointercancel', 'pointerdown', 'pointerenter', 'pointerleave', 'pointerlockchange', 'mozpointerlockchange', 'webkitpointerlockerchange', 'pointerlockerror', 'mozpointerlockerror', 'webkitpointerlockerror', 'pointermove', 'pointout', 'pointerover', 'pointerup', 'progress', 'ratechange', 'reset', 'resize', 'scroll', 'seeked', 'seeking', 'select', 'selectionchange', 'selectstart', 'show', 'sort', 'stalled', 'submit', 'suspend', 'timeupdate', 'volumechange', 'touchcancel', 'touchmove', 'touchstart', 'touchend', 'transitioncancel', 'transitionend', 'waiting', 'wheel'];
var documentEventNames = ['afterscriptexecute', 'beforescriptexecute', 'DOMContentLoaded', 'freeze', 'fullscreenchange', 'mozfullscreenchange', 'webkitfullscreenchange', 'msfullscreenchange', 'fullscreenerror', 'mozfullscreenerror', 'webkitfullscreenerror', 'msfullscreenerror', 'readystatechange', 'visibilitychange', 'resume'];
var windowEventNames = ['absolutedeviceorientation', 'afterinput', 'afterprint', 'appinstalled', 'beforeinstallprompt', 'beforeprint', 'beforeunload', 'devicelight', 'devicemotion', 'deviceorientation', 'deviceorientationabsolute', 'deviceproximity', 'hashchange', 'languagechange', 'message', 'mozbeforepaint', 'offline', 'online', 'paint', 'pageshow', 'pagehide', 'popstate', 'rejectionhandled', 'storage', 'unhandledrejection', 'unload', 'userproximity', 'vrdisplayconnected', 'vrdisplaydisconnected', 'vrdisplaypresentchange'];
var htmlElementEventNames = ['beforecopy', 'beforecut', 'beforepaste', 'copy', 'cut', 'paste', 'dragstart', 'loadend', 'animationstart', 'search', 'transitionrun', 'transitionstart', 'webkitanimationend', 'webkitanimationiteration', 'webkitanimationstart', 'webkittransitionend'];
var mediaElementEventNames = ['encrypted', 'waitingforkey', 'msneedkey', 'mozinterruptbegin', 'mozinterruptend'];
var ieElementEventNames = ['activate', 'afterupdate', 'ariarequest', 'beforeactivate', 'beforedeactivate', 'beforeeditfocus', 'beforeupdate', 'cellchange', 'controlselect', 'dataavailable', 'datasetchanged', 'datasetcomplete', 'errorupdate', 'filterchange', 'layoutcomplete', 'losecapture', 'move', 'moveend', 'movestart', 'propertychange', 'resizeend', 'resizestart', 'rowenter', 'rowexit', 'rowsdelete', 'rowsinserted', 'command', 'compassneedscalibration', 'deactivate', 'help', 'mscontentzoom', 'msmanipulationstatechanged', 'msgesturechange', 'msgesturedoubletap', 'msgestureend', 'msgesturehold', 'msgesturestart', 'msgesturetap', 'msgotpointercapture', 'msinertiastart', 'mslostpointercapture', 'mspointercancel', 'mspointerdown', 'mspointerenter', 'mspointerhover', 'mspointerleave', 'mspointermove', 'mspointerout', 'mspointerover', 'mspointerup', 'pointerout', 'mssitemodejumplistitemremoved', 'msthumbnailclick', 'stop', 'storagecommit'];
var webglEventNames = ['webglcontextrestored', 'webglcontextlost', 'webglcontextcreationerror'];
var formEventNames = ['autocomplete', 'autocompleteerror'];
var detailEventNames = ['toggle'];
var frameEventNames = ['load'];
var frameSetEventNames = ['blur', 'error', 'focus', 'load', 'resize', 'scroll', 'messageerror'];
var marqueeEventNames = ['bounce', 'finish', 'start'];
var XMLHttpRequestEventNames = ['loadstart', 'progress', 'abort', 'error', 'load', 'progress', 'timeout', 'loadend', 'readystatechange'];
var IDBIndexEventNames = ['upgradeneeded', 'complete', 'abort', 'success', 'error', 'blocked', 'versionchange', 'close'];
var websocketEventNames = ['close', 'error', 'open', 'message'];
var workerEventNames = ['error', 'message'];
var eventNames = globalEventHandlersEventNames.concat(webglEventNames, formEventNames, detailEventNames, documentEventNames, windowEventNames, htmlElementEventNames, ieElementEventNames);
function filterProperties(target, onProperties, ignoreProperties) {
if (!ignoreProperties || ignoreProperties.length === 0) {
return onProperties;
}
var tip = ignoreProperties.filter(function (ip) {
return ip.target === target;
});
if (!tip || tip.length === 0) {
return onProperties;
}
var targetIgnoreProperties = tip[0].ignoreProperties;
return onProperties.filter(function (op) {
return targetIgnoreProperties.indexOf(op) === -1;
});
}
function patchFilteredProperties(target, onProperties, ignoreProperties, prototype) {
// check whether target is available, sometimes target will be undefined
// because different browser or some 3rd party plugin.
if (!target) {
return;
}
var filteredProperties = filterProperties(target, onProperties, ignoreProperties);
patchOnProperties(target, filteredProperties, prototype);
}
function propertyDescriptorPatch(api, _global) {
if (isNode && !isMix) {
return;
}
if (Zone[api.symbol('patchEvents')]) {
// events are already been patched by legacy patch.
return;
}
var supportsWebSocket = typeof WebSocket !== 'undefined';
var ignoreProperties = _global['__Zone_ignore_on_properties']; // for browsers that we can patch the descriptor: Chrome & Firefox
if (isBrowser) {
var internalWindow_1 = window;
var ignoreErrorProperties = isIE ? [{
target: internalWindow_1,
ignoreProperties: ['error']
}] : []; // in IE/Edge, onProp not exist in window object, but in WindowPrototype
// so we need to pass WindowPrototype to check onProp exist or not
patchFilteredProperties(internalWindow_1, eventNames.concat(['messageerror']), ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties, ObjectGetPrototypeOf(internalWindow_1));
patchFilteredProperties(Document.prototype, eventNames, ignoreProperties);
if (typeof internalWindow_1['SVGElement'] !== 'undefined') {
patchFilteredProperties(internalWindow_1['SVGElement'].prototype, eventNames, ignoreProperties);
}
patchFilteredProperties(Element.prototype, eventNames, ignoreProperties);
patchFilteredProperties(HTMLElement.prototype, eventNames, ignoreProperties);
patchFilteredProperties(HTMLMediaElement.prototype, mediaElementEventNames, ignoreProperties);
patchFilteredProperties(HTMLFrameSetElement.prototype, windowEventNames.concat(frameSetEventNames), ignoreProperties);
patchFilteredProperties(HTMLBodyElement.prototype, windowEventNames.concat(frameSetEventNames), ignoreProperties);
patchFilteredProperties(HTMLFrameElement.prototype, frameEventNames, ignoreProperties);
patchFilteredProperties(HTMLIFrameElement.prototype, frameEventNames, ignoreProperties);
var HTMLMarqueeElement_1 = internalWindow_1['HTMLMarqueeElement'];
if (HTMLMarqueeElement_1) {
patchFilteredProperties(HTMLMarqueeElement_1.prototype, marqueeEventNames, ignoreProperties);
}
var Worker_1 = internalWindow_1['Worker'];
if (Worker_1) {
patchFilteredProperties(Worker_1.prototype, workerEventNames, ignoreProperties);
}
}
var XMLHttpRequest = _global['XMLHttpRequest'];
if (XMLHttpRequest) {
// XMLHttpRequest is not available in ServiceWorker, so we need to check here
patchFilteredProperties(XMLHttpRequest.prototype, XMLHttpRequestEventNames, ignoreProperties);
}
var XMLHttpRequestEventTarget = _global['XMLHttpRequestEventTarget'];
if (XMLHttpRequestEventTarget) {
patchFilteredProperties(XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype, XMLHttpRequestEventNames, ignoreProperties);
}
if (typeof IDBIndex !== 'undefined') {
patchFilteredProperties(IDBIndex.prototype, IDBIndexEventNames, ignoreProperties);
patchFilteredProperties(IDBRequest.prototype, IDBIndexEventNames, ignoreProperties);
patchFilteredProperties(IDBOpenDBRequest.prototype, IDBIndexEventNames, ignoreProperties);
patchFilteredProperties(IDBDatabase.prototype, IDBIndexEventNames, ignoreProperties);
patchFilteredProperties(IDBTransaction.prototype, IDBIndexEventNames, ignoreProperties);
patchFilteredProperties(IDBCursor.prototype, IDBIndexEventNames, ignoreProperties);
}
if (supportsWebSocket) {
patchFilteredProperties(WebSocket.prototype, websocketEventNames, ignoreProperties);
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
Zone.__load_patch('util', function (global, Zone, api) {
api.patchOnProperties = patchOnProperties;
api.patchMethod = patchMethod;
api.bindArguments = bindArguments;
api.patchMacroTask = patchMacroTask; // In earlier version of zone.js (<0.9.0), we use env name `__zone_symbol__BLACK_LISTED_EVENTS` to
// define which events will not be patched by `Zone.js`.
// In newer version (>=0.9.0), we change the env name to `__zone_symbol__UNPATCHED_EVENTS` to keep
// the name consistent with angular repo.
// The `__zone_symbol__BLACK_LISTED_EVENTS` is deprecated, but it is still be supported for
// backwards compatibility.
var SYMBOL_BLACK_LISTED_EVENTS = Zone.__symbol__('BLACK_LISTED_EVENTS');
var SYMBOL_UNPATCHED_EVENTS = Zone.__symbol__('UNPATCHED_EVENTS');
if (global[SYMBOL_UNPATCHED_EVENTS]) {
global[SYMBOL_BLACK_LISTED_EVENTS] = global[SYMBOL_UNPATCHED_EVENTS];
}
if (global[SYMBOL_BLACK_LISTED_EVENTS]) {
Zone[SYMBOL_BLACK_LISTED_EVENTS] = Zone[SYMBOL_UNPATCHED_EVENTS] = global[SYMBOL_BLACK_LISTED_EVENTS];
}
api.patchEventPrototype = patchEventPrototype;
api.patchEventTarget = patchEventTarget;
api.isIEOrEdge = isIEOrEdge;
api.ObjectDefineProperty = ObjectDefineProperty;
api.ObjectGetOwnPropertyDescriptor = ObjectGetOwnPropertyDescriptor;
api.ObjectCreate = ObjectCreate;
api.ArraySlice = ArraySlice;
api.patchClass = patchClass;
api.wrapWithCurrentZone = wrapWithCurrentZone;
api.filterProperties = filterProperties;
api.attachOriginToPatched = attachOriginToPatched;
api._redefineProperty = Object.defineProperty;
api.patchCallbacks = patchCallbacks;
api.getGlobalObjects = function () {
return {
globalSources: globalSources,
zoneSymbolEventNames: zoneSymbolEventNames$1,
eventNames: eventNames,
isBrowser: isBrowser,
isMix: isMix,
isNode: isNode,
TRUE_STR: TRUE_STR,
FALSE_STR: FALSE_STR,
ZONE_SYMBOL_PREFIX: ZONE_SYMBOL_PREFIX,
ADD_EVENT_LISTENER_STR: ADD_EVENT_LISTENER_STR,
REMOVE_EVENT_LISTENER_STR: REMOVE_EVENT_LISTENER_STR
};
};
});
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/*
* This is necessary for Chrome and Chrome mobile, to enable
* things like redefining `createdCallback` on an element.
*/
var zoneSymbol$1;
var _defineProperty;
var _getOwnPropertyDescriptor;
var _create;
var unconfigurablesKey;
function propertyPatch() {
zoneSymbol$1 = Zone.__symbol__;
_defineProperty = Object[zoneSymbol$1('defineProperty')] = Object.defineProperty;
_getOwnPropertyDescriptor = Object[zoneSymbol$1('getOwnPropertyDescriptor')] = Object.getOwnPropertyDescriptor;
_create = Object.create;
unconfigurablesKey = zoneSymbol$1('unconfigurables');
Object.defineProperty = function (obj, prop, desc) {
if (isUnconfigurable(obj, prop)) {
throw new TypeError('Cannot assign to read only property \'' + prop + '\' of ' + obj);
}
var originalConfigurableFlag = desc.configurable;
if (prop !== 'prototype') {
desc = rewriteDescriptor(obj, prop, desc);
}
return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);
};
Object.defineProperties = function (obj, props) {
Object.keys(props).forEach(function (prop) {
Object.defineProperty(obj, prop, props[prop]);
});
return obj;
};
Object.create = function (obj, proto) {
if (typeof proto === 'object' && !Object.isFrozen(proto)) {
Object.keys(proto).forEach(function (prop) {
proto[prop] = rewriteDescriptor(obj, prop, proto[prop]);
});
}
return _create(obj, proto);
};
Object.getOwnPropertyDescriptor = function (obj, prop) {
var desc = _getOwnPropertyDescriptor(obj, prop);
if (desc && isUnconfigurable(obj, prop)) {
desc.configurable = false;
}
return desc;
};
}
function _redefineProperty(obj, prop, desc) {
var originalConfigurableFlag = desc.configurable;
desc = rewriteDescriptor(obj, prop, desc);
return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);
}
function isUnconfigurable(obj, prop) {
return obj && obj[unconfigurablesKey] && obj[unconfigurablesKey][prop];
}
function rewriteDescriptor(obj, prop, desc) {
// issue-927, if the desc is frozen, don't try to change the desc
if (!Object.isFrozen(desc)) {
desc.configurable = true;
}
if (!desc.configurable) {
// issue-927, if the obj is frozen, don't try to set the desc to obj
if (!obj[unconfigurablesKey] && !Object.isFrozen(obj)) {
_defineProperty(obj, unconfigurablesKey, {
writable: true,
value: {}
});
}
if (obj[unconfigurablesKey]) {
obj[unconfigurablesKey][prop] = true;
}
}
return desc;
}
function _tryDefineProperty(obj, prop, desc, originalConfigurableFlag) {
try {
return _defineProperty(obj, prop, desc);
} catch (error) {
if (desc.configurable) {
// In case of errors, when the configurable flag was likely set by rewriteDescriptor(), let's
// retry with the original flag value
if (typeof originalConfigurableFlag == 'undefined') {
delete desc.configurable;
} else {
desc.configurable = originalConfigurableFlag;
}
try {
return _defineProperty(obj, prop, desc);
} catch (error) {
var descJson = null;
try {
descJson = JSON.stringify(desc);
} catch (error) {
descJson = desc.toString();
}
console.log("Attempting to configure '" + prop + "' with descriptor '" + descJson + "' on object '" + obj + "' and got error, giving up: " + error);
}
} else {
throw error;
}
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function eventTargetLegacyPatch(_global, api) {
var _a = api.getGlobalObjects(),
eventNames = _a.eventNames,
globalSources = _a.globalSources,
zoneSymbolEventNames = _a.zoneSymbolEventNames,
TRUE_STR = _a.TRUE_STR,
FALSE_STR = _a.FALSE_STR,
ZONE_SYMBOL_PREFIX = _a.ZONE_SYMBOL_PREFIX;
var WTF_ISSUE_555 = 'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video';
var NO_EVENT_TARGET = 'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Window,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex,WebSocket'.split(',');
var EVENT_TARGET = 'EventTarget';
var apis = [];
var isWtf = _global['wtf'];
var WTF_ISSUE_555_ARRAY = WTF_ISSUE_555.split(',');
if (isWtf) {
// Workaround for: https://github.com/google/tracing-framework/issues/555
apis = WTF_ISSUE_555_ARRAY.map(function (v) {
return 'HTML' + v + 'Element';
}).concat(NO_EVENT_TARGET);
} else if (_global[EVENT_TARGET]) {
apis.push(EVENT_TARGET);
} else {
// Note: EventTarget is not available in all browsers,
// if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget
apis = NO_EVENT_TARGET;
}
var isDisableIECheck = _global['__Zone_disable_IE_check'] || false;
var isEnableCrossContextCheck = _global['__Zone_enable_cross_context_check'] || false;
var ieOrEdge = api.isIEOrEdge();
var ADD_EVENT_LISTENER_SOURCE = '.addEventListener:';
var FUNCTION_WRAPPER = '[object FunctionWrapper]';
var BROWSER_TOOLS = 'function __BROWSERTOOLS_CONSOLE_SAFEFUNC() { [native code] }';
var pointerEventsMap = {
'MSPointerCancel': 'pointercancel',
'MSPointerDown': 'pointerdown',
'MSPointerEnter': 'pointerenter',
'MSPointerHover': 'pointerhover',
'MSPointerLeave': 'pointerleave',
'MSPointerMove': 'pointermove',
'MSPointerOut': 'pointerout',
'MSPointerOver': 'pointerover',
'MSPointerUp': 'pointerup'
}; // predefine all __zone_symbol__ + eventName + true/false string
for (var i = 0; i < eventNames.length; i++) {
var eventName = eventNames[i];
var falseEventName = eventName + FALSE_STR;
var trueEventName = eventName + TRUE_STR;
var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
zoneSymbolEventNames[eventName] = {};
zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
} // predefine all task.source string
for (var i = 0; i < WTF_ISSUE_555_ARRAY.length; i++) {
var target = WTF_ISSUE_555_ARRAY[i];
var targets = globalSources[target] = {};
for (var j = 0; j < eventNames.length; j++) {
var eventName = eventNames[j];
targets[eventName] = target + ADD_EVENT_LISTENER_SOURCE + eventName;
}
}
var checkIEAndCrossContext = function checkIEAndCrossContext(nativeDelegate, delegate, target, args) {
if (!isDisableIECheck && ieOrEdge) {
if (isEnableCrossContextCheck) {
try {
var testString = delegate.toString();
if (testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS) {
nativeDelegate.apply(target, args);
return false;
}
} catch (error) {
nativeDelegate.apply(target, args);
return false;
}
} else {
var testString = delegate.toString();
if (testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS) {
nativeDelegate.apply(target, args);
return false;
}
}
} else if (isEnableCrossContextCheck) {
try {
delegate.toString();
} catch (error) {
nativeDelegate.apply(target, args);
return false;
}
}
return true;
};
var apiTypes = [];
for (var i = 0; i < apis.length; i++) {
var type = _global[apis[i]];
apiTypes.push(type && type.prototype);
} // vh is validateHandler to check event handler
// is valid or not(for security check)
api.patchEventTarget(_global, apiTypes, {
vh: checkIEAndCrossContext,
transferEventName: function transferEventName(eventName) {
var pointerEventName = pointerEventsMap[eventName];
return pointerEventName || eventName;
}
});
Zone[api.symbol('patchEventTarget')] = !!_global[EVENT_TARGET];
return true;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// we have to patch the instance since the proto is non-configurable
function apply(api, _global) {
var _a = api.getGlobalObjects(),
ADD_EVENT_LISTENER_STR = _a.ADD_EVENT_LISTENER_STR,
REMOVE_EVENT_LISTENER_STR = _a.REMOVE_EVENT_LISTENER_STR;
var WS = _global.WebSocket; // On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener
// On older Chrome, no need since EventTarget was already patched
if (!_global.EventTarget) {
api.patchEventTarget(_global, [WS.prototype]);
}
_global.WebSocket = function (x, y) {
var socket = arguments.length > 1 ? new WS(x, y) : new WS(x);
var proxySocket;
var proxySocketProto; // Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance
var onmessageDesc = api.ObjectGetOwnPropertyDescriptor(socket, 'onmessage');
if (onmessageDesc && onmessageDesc.configurable === false) {
proxySocket = api.ObjectCreate(socket); // socket have own property descriptor 'onopen', 'onmessage', 'onclose', 'onerror'
// but proxySocket not, so we will keep socket as prototype and pass it to
// patchOnProperties method
proxySocketProto = socket;
[ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR, 'send', 'close'].forEach(function (propName) {
proxySocket[propName] = function () {
var args = api.ArraySlice.call(arguments);
if (propName === ADD_EVENT_LISTENER_STR || propName === REMOVE_EVENT_LISTENER_STR) {
var eventName = args.length > 0 ? args[0] : undefined;
if (eventName) {
var propertySymbol = Zone.__symbol__('ON_PROPERTY' + eventName);
socket[propertySymbol] = proxySocket[propertySymbol];
}
}
return socket[propName].apply(socket, args);
};
});
} else {
// we can patch the real socket
proxySocket = socket;
}
api.patchOnProperties(proxySocket, ['close', 'error', 'message', 'open'], proxySocketProto);
return proxySocket;
};
var globalWebSocket = _global['WebSocket'];
for (var prop in WS) {
globalWebSocket[prop] = WS[prop];
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function propertyDescriptorLegacyPatch(api, _global) {
var _a = api.getGlobalObjects(),
isNode = _a.isNode,
isMix = _a.isMix;
if (isNode && !isMix) {
return;
}
if (!canPatchViaPropertyDescriptor(api, _global)) {
var supportsWebSocket = typeof WebSocket !== 'undefined'; // Safari, Android browsers (Jelly Bean)
patchViaCapturingAllTheEvents(api);
api.patchClass('XMLHttpRequest');
if (supportsWebSocket) {
apply(api, _global);
}
Zone[api.symbol('patchEvents')] = true;
}
}
function canPatchViaPropertyDescriptor(api, _global) {
var _a = api.getGlobalObjects(),
isBrowser = _a.isBrowser,
isMix = _a.isMix;
if ((isBrowser || isMix) && !api.ObjectGetOwnPropertyDescriptor(HTMLElement.prototype, 'onclick') && typeof Element !== 'undefined') {
// WebKit https://bugs.webkit.org/show_bug.cgi?id=134364
// IDL interface attributes are not configurable
var desc = api.ObjectGetOwnPropertyDescriptor(Element.prototype, 'onclick');
if (desc && !desc.configurable) return false; // try to use onclick to detect whether we can patch via propertyDescriptor
// because XMLHttpRequest is not available in service worker
if (desc) {
api.ObjectDefineProperty(Element.prototype, 'onclick', {
enumerable: true,
configurable: true,
get: function get() {
return true;
}
});
var div = document.createElement('div');
var result = !!div.onclick;
api.ObjectDefineProperty(Element.prototype, 'onclick', desc);
return result;
}
}
var XMLHttpRequest = _global['XMLHttpRequest'];
if (!XMLHttpRequest) {
// XMLHttpRequest is not available in service worker
return false;
}
var ON_READY_STATE_CHANGE = 'onreadystatechange';
var XMLHttpRequestPrototype = XMLHttpRequest.prototype;
var xhrDesc = api.ObjectGetOwnPropertyDescriptor(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE); // add enumerable and configurable here because in opera
// by default XMLHttpRequest.prototype.onreadystatechange is undefined
// without adding enumerable and configurable will cause onreadystatechange
// non-configurable
// and if XMLHttpRequest.prototype.onreadystatechange is undefined,
// we should set a real desc instead a fake one
if (xhrDesc) {
api.ObjectDefineProperty(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE, {
enumerable: true,
configurable: true,
get: function get() {
return true;
}
});
var req = new XMLHttpRequest();
var result = !!req.onreadystatechange; // restore original desc
api.ObjectDefineProperty(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE, xhrDesc || {});
return result;
} else {
var SYMBOL_FAKE_ONREADYSTATECHANGE_1 = api.symbol('fake');
api.ObjectDefineProperty(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE, {
enumerable: true,
configurable: true,
get: function get() {
return this[SYMBOL_FAKE_ONREADYSTATECHANGE_1];
},
set: function set(value) {
this[SYMBOL_FAKE_ONREADYSTATECHANGE_1] = value;
}
});
var req = new XMLHttpRequest();
var detectFunc = function detectFunc() {};
req.onreadystatechange = detectFunc;
var result = req[SYMBOL_FAKE_ONREADYSTATECHANGE_1] === detectFunc;
req.onreadystatechange = null;
return result;
}
} // Whenever any eventListener fires, we check the eventListener target and all parents
// for `onwhatever` properties and replace them with zone-bound functions
// - Chrome (for now)
function patchViaCapturingAllTheEvents(api) {
var eventNames = api.getGlobalObjects().eventNames;
var unboundKey = api.symbol('unbound');
var _loop_4 = function _loop_4(i) {
var property = eventNames[i];
var onproperty = 'on' + property;
self.addEventListener(property, function (event) {
var elt = event.target,
bound,
source;
if (elt) {
source = elt.constructor['name'] + '.' + onproperty;
} else {
source = 'unknown.' + onproperty;
}
while (elt) {
if (elt[onproperty] && !elt[onproperty][unboundKey]) {
bound = api.wrapWithCurrentZone(elt[onproperty], source);
bound[unboundKey] = elt[onproperty];
elt[onproperty] = bound;
}
elt = elt.parentElement;
}
}, true);
};
for (var i = 0; i < eventNames.length; i++) {
_loop_4(i);
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function registerElementPatch(_global, api) {
var _a = api.getGlobalObjects(),
isBrowser = _a.isBrowser,
isMix = _a.isMix;
if (!isBrowser && !isMix || !('registerElement' in _global.document)) {
return;
}
var callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];
api.patchCallbacks(api, document, 'Document', 'registerElement', callbacks);
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
(function (_global) {
var symbolPrefix = _global['__Zone_symbol_prefix'] || '__zone_symbol__';
function __symbol__(name) {
return symbolPrefix + name;
}
_global[__symbol__('legacyPatch')] = function () {
var Zone = _global['Zone'];
Zone.__load_patch('defineProperty', function (global, Zone, api) {
api._redefineProperty = _redefineProperty;
propertyPatch();
});
Zone.__load_patch('registerElement', function (global, Zone, api) {
registerElementPatch(global, api);
});
Zone.__load_patch('EventTargetLegacy', function (global, Zone, api) {
eventTargetLegacyPatch(global, api);
propertyDescriptorLegacyPatch(api, global);
});
};
})(typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {});
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var taskSymbol = zoneSymbol('zoneTask');
function patchTimer(window, setName, cancelName, nameSuffix) {
var setNative = null;
var clearNative = null;
setName += nameSuffix;
cancelName += nameSuffix;
var tasksByHandleId = {};
function scheduleTask(task) {
var data = task.data;
function timer() {
try {
task.invoke.apply(this, arguments);
} finally {
// issue-934, task will be cancelled
// even it is a periodic task such as
// setInterval
if (!(task.data && task.data.isPeriodic)) {
if (typeof data.handleId === 'number') {
// in non-nodejs env, we remove timerId
// from local cache
delete tasksByHandleId[data.handleId];
} else if (data.handleId) {
// Node returns complex objects as handleIds
// we remove task reference from timer object
data.handleId[taskSymbol] = null;
}
}
}
}
data.args[0] = timer;
data.handleId = setNative.apply(window, data.args);
return task;
}
function clearTask(task) {
return clearNative(task.data.handleId);
}
setNative = patchMethod(window, setName, function (delegate) {
return function (self, args) {
if (typeof args[0] === 'function') {
var options = {
isPeriodic: nameSuffix === 'Interval',
delay: nameSuffix === 'Timeout' || nameSuffix === 'Interval' ? args[1] || 0 : undefined,
args: args
};
var task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
if (!task) {
return task;
} // Node.js must additionally support the ref and unref functions.
var handle = task.data.handleId;
if (typeof handle === 'number') {
// for non nodejs env, we save handleId: task
// mapping in local cache for clearTimeout
tasksByHandleId[handle] = task;
} else if (handle) {
// for nodejs env, we save task
// reference in timerId Object for clearTimeout
handle[taskSymbol] = task;
} // check whether handle is null, because some polyfill or browser
// may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame
if (handle && handle.ref && handle.unref && typeof handle.ref === 'function' && typeof handle.unref === 'function') {
task.ref = handle.ref.bind(handle);
task.unref = handle.unref.bind(handle);
}
if (typeof handle === 'number' || handle) {
return handle;
}
return task;
} else {
// cause an error by calling it directly.
return delegate.apply(window, args);
}
};
});
clearNative = patchMethod(window, cancelName, function (delegate) {
return function (self, args) {
var id = args[0];
var task;
if (typeof id === 'number') {
// non nodejs env.
task = tasksByHandleId[id];
} else {
// nodejs env.
task = id && id[taskSymbol]; // other environments.
if (!task) {
task = id;
}
}
if (task && typeof task.type === 'string') {
if (task.state !== 'notScheduled' && (task.cancelFn && task.data.isPeriodic || task.runCount === 0)) {
if (typeof id === 'number') {
delete tasksByHandleId[id];
} else if (id) {
id[taskSymbol] = null;
} // Do not cancel already canceled functions
task.zone.cancelTask(task);
}
} else {
// cause an error by calling it directly.
delegate.apply(window, args);
}
};
});
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function patchCustomElements(_global, api) {
var _a = api.getGlobalObjects(),
isBrowser = _a.isBrowser,
isMix = _a.isMix;
if (!isBrowser && !isMix || !_global['customElements'] || !('customElements' in _global)) {
return;
}
var callbacks = ['connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback'];
api.patchCallbacks(api, _global.customElements, 'customElements', 'define', callbacks);
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function eventTargetPatch(_global, api) {
if (Zone[api.symbol('patchEventTarget')]) {
// EventTarget is already patched.
return;
}
var _a = api.getGlobalObjects(),
eventNames = _a.eventNames,
zoneSymbolEventNames = _a.zoneSymbolEventNames,
TRUE_STR = _a.TRUE_STR,
FALSE_STR = _a.FALSE_STR,
ZONE_SYMBOL_PREFIX = _a.ZONE_SYMBOL_PREFIX; // predefine all __zone_symbol__ + eventName + true/false string
for (var i = 0; i < eventNames.length; i++) {
var eventName = eventNames[i];
var falseEventName = eventName + FALSE_STR;
var trueEventName = eventName + TRUE_STR;
var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
zoneSymbolEventNames[eventName] = {};
zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
}
var EVENT_TARGET = _global['EventTarget'];
if (!EVENT_TARGET || !EVENT_TARGET.prototype) {
return;
}
api.patchEventTarget(_global, [EVENT_TARGET && EVENT_TARGET.prototype]);
return true;
}
function patchEvent(global, api) {
api.patchEventPrototype(global, api);
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
Zone.__load_patch('legacy', function (global) {
var legacyPatch = global[Zone.__symbol__('legacyPatch')];
if (legacyPatch) {
legacyPatch();
}
});
Zone.__load_patch('timers', function (global) {
var set = 'set';
var clear = 'clear';
patchTimer(global, set, clear, 'Timeout');
patchTimer(global, set, clear, 'Interval');
patchTimer(global, set, clear, 'Immediate');
});
Zone.__load_patch('requestAnimationFrame', function (global) {
patchTimer(global, 'request', 'cancel', 'AnimationFrame');
patchTimer(global, 'mozRequest', 'mozCancel', 'AnimationFrame');
patchTimer(global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
});
Zone.__load_patch('blocking', function (global, Zone) {
var blockingMethods = ['alert', 'prompt', 'confirm'];
for (var i = 0; i < blockingMethods.length; i++) {
var name_2 = blockingMethods[i];
patchMethod(global, name_2, function (delegate, symbol, name) {
return function (s, args) {
return Zone.current.run(delegate, global, args, name);
};
});
}
});
Zone.__load_patch('EventTarget', function (global, Zone, api) {
patchEvent(global, api);
eventTargetPatch(global, api); // patch XMLHttpRequestEventTarget's addEventListener/removeEventListener
var XMLHttpRequestEventTarget = global['XMLHttpRequestEventTarget'];
if (XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype) {
api.patchEventTarget(global, [XMLHttpRequestEventTarget.prototype]);
}
patchClass('MutationObserver');
patchClass('WebKitMutationObserver');
patchClass('IntersectionObserver');
patchClass('FileReader');
});
Zone.__load_patch('on_property', function (global, Zone, api) {
propertyDescriptorPatch(api, global);
});
Zone.__load_patch('customElements', function (global, Zone, api) {
patchCustomElements(global, api);
});
Zone.__load_patch('XHR', function (global, Zone) {
// Treat XMLHttpRequest as a macrotask.
patchXHR(global);
var XHR_TASK = zoneSymbol('xhrTask');
var XHR_SYNC = zoneSymbol('xhrSync');
var XHR_LISTENER = zoneSymbol('xhrListener');
var XHR_SCHEDULED = zoneSymbol('xhrScheduled');
var XHR_URL = zoneSymbol('xhrURL');
var XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
function patchXHR(window) {
var XMLHttpRequest = window['XMLHttpRequest'];
if (!XMLHttpRequest) {
// XMLHttpRequest is not available in service worker
return;
}
var XMLHttpRequestPrototype = XMLHttpRequest.prototype;
function findPendingTask(target) {
return target[XHR_TASK];
}
var oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
var oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
if (!oriAddListener) {
var XMLHttpRequestEventTarget_1 = window['XMLHttpRequestEventTarget'];
if (XMLHttpRequestEventTarget_1) {
var XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget_1.prototype;
oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
}
}
var READY_STATE_CHANGE = 'readystatechange';
var SCHEDULED = 'scheduled';
function scheduleTask(task) {
var data = task.data;
var target = data.target;
target[XHR_SCHEDULED] = false;
target[XHR_ERROR_BEFORE_SCHEDULED] = false; // remove existing event listener
var listener = target[XHR_LISTENER];
if (!oriAddListener) {
oriAddListener = target[ZONE_SYMBOL_ADD_EVENT_LISTENER];
oriRemoveListener = target[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
}
if (listener) {
oriRemoveListener.call(target, READY_STATE_CHANGE, listener);
}
var newListener = target[XHR_LISTENER] = function () {
if (target.readyState === target.DONE) {
// sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
// readyState=4 multiple times, so we need to check task state here
if (!data.aborted && target[XHR_SCHEDULED] && task.state === SCHEDULED) {
// check whether the xhr has registered onload listener
// if that is the case, the task should invoke after all
// onload listeners finish.
var loadTasks = target[Zone.__symbol__('loadfalse')];
if (loadTasks && loadTasks.length > 0) {
var oriInvoke_1 = task.invoke;
task.invoke = function () {
// need to load the tasks again, because in other
// load listener, they may remove themselves
var loadTasks = target[Zone.__symbol__('loadfalse')];
for (var i = 0; i < loadTasks.length; i++) {
if (loadTasks[i] === task) {
loadTasks.splice(i, 1);
}
}
if (!data.aborted && task.state === SCHEDULED) {
oriInvoke_1.call(task);
}
};
loadTasks.push(task);
} else {
task.invoke();
}
} else if (!data.aborted && target[XHR_SCHEDULED] === false) {
// error occurs when xhr.send()
target[XHR_ERROR_BEFORE_SCHEDULED] = true;
}
}
};
oriAddListener.call(target, READY_STATE_CHANGE, newListener);
var storedTask = target[XHR_TASK];
if (!storedTask) {
target[XHR_TASK] = task;
}
sendNative.apply(target, data.args);
target[XHR_SCHEDULED] = true;
return task;
}
function placeholderCallback() {}
function clearTask(task) {
var data = task.data; // Note - ideally, we would call data.target.removeEventListener here, but it's too late
// to prevent it from firing. So instead, we store info for the event listener.
data.aborted = true;
return abortNative.apply(data.target, data.args);
}
var openNative = patchMethod(XMLHttpRequestPrototype, 'open', function () {
return function (self, args) {
self[XHR_SYNC] = args[2] == false;
self[XHR_URL] = args[1];
return openNative.apply(self, args);
};
});
var XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
var fetchTaskAborting = zoneSymbol('fetchTaskAborting');
var fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
var sendNative = patchMethod(XMLHttpRequestPrototype, 'send', function () {
return function (self, args) {
if (Zone.current[fetchTaskScheduling] === true) {
// a fetch is scheduling, so we are using xhr to polyfill fetch
// and because we already schedule macroTask for fetch, we should
// not schedule a macroTask for xhr again
return sendNative.apply(self, args);
}
if (self[XHR_SYNC]) {
// if the XHR is sync there is no task to schedule, just execute the code.
return sendNative.apply(self, args);
} else {
var options = {
target: self,
url: self[XHR_URL],
isPeriodic: false,
args: args,
aborted: false
};
var task = scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
if (self && self[XHR_ERROR_BEFORE_SCHEDULED] === true && !options.aborted && task.state === SCHEDULED) {
// xhr request throw error when send
// we should invoke task instead of leaving a scheduled
// pending macroTask
task.invoke();
}
}
};
});
var abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', function () {
return function (self, args) {
var task = findPendingTask(self);
if (task && typeof task.type == 'string') {
// If the XHR has already completed, do nothing.
// If the XHR has already been aborted, do nothing.
// Fix #569, call abort multiple times before done will cause
// macroTask task count be negative number
if (task.cancelFn == null || task.data && task.data.aborted) {
return;
}
task.zone.cancelTask(task);
} else if (Zone.current[fetchTaskAborting] === true) {
// the abort is called from fetch polyfill, we need to call native abort of XHR.
return abortNative.apply(self, args);
} // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
// task
// to cancel. Do nothing.
};
});
}
});
Zone.__load_patch('geolocation', function (global) {
/// GEO_LOCATION
if (global['navigator'] && global['navigator'].geolocation) {
patchPrototype(global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);
}
});
Zone.__load_patch('PromiseRejectionEvent', function (global, Zone) {
// handle unhandled promise rejection
function findPromiseRejectionHandler(evtName) {
return function (e) {
var eventTasks = findEventTasks(global, evtName);
eventTasks.forEach(function (eventTask) {
// windows has added unhandledrejection event listener
// trigger the event listener
var PromiseRejectionEvent = global['PromiseRejectionEvent'];
if (PromiseRejectionEvent) {
var evt = new PromiseRejectionEvent(evtName, {
promise: e.promise,
reason: e.rejection
});
eventTask.invoke(evt);
}
});
};
}
if (global['PromiseRejectionEvent']) {
Zone[zoneSymbol('unhandledPromiseRejectionHandler')] = findPromiseRejectionHandler('unhandledrejection');
Zone[zoneSymbol('rejectionHandledHandler')] = findPromiseRejectionHandler('rejectionhandled');
}
});
});
/***/ }),
/***/ 1:
/*!********************************!*\
!*** multi ./src/polyfills.ts ***!
\********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! /Users/shiyohtohyama/PhpstormProjects/udonarium/src/polyfills.ts */"hN/g");
/***/ }),
/***/ "hN/g":
/*!**************************!*\
!*** ./src/polyfills.ts ***!
\**************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var zone_js_dist_zone__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! zone.js/dist/zone */ "0TWp");
/* harmony import */ var zone_js_dist_zone__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(zone_js_dist_zone__WEBPACK_IMPORTED_MODULE_0__);
/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
* Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
*
* Learn more in https://angular.io/guide/browser-support
*/
/***************************************************************************************************
* BROWSER POLYFILLS
*/
/** IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js'; // Run `npm install --save classlist.js`.
/**
* Web Animations `@angular/platform-browser/animations`
* Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
* Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
*/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
/**
* By default, zone.js will patch all possible macroTask and DomEvents
* user can disable parts of macroTask/DomEvents patch by setting following flags
* because those flags need to be set before `zone.js` being loaded, and webpack
* will put import in the top of bundle, so user need to create a separate file
* in this directory (for example: zone-flags.ts), and put the following flags
* into that file, and then add the following code before importing zone.js.
* import './zone-flags';
*
* The flags allowed in zone-flags.ts are listed here.
*
* The following flags will work for all browsers.
*
* (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
* (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
* (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
*
* in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
* with the following flag, it will bypass `zone.js` patch for IE/Edge
*
* (window as any).__Zone_enable_cross_context_check = true;
*
*/
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
// Included with Angular CLI.
/***************************************************************************************************
* APPLICATION IMPORTS
*/
/***/ })
},[[1,"runtime"]]]);
//# sourceMappingURL=polyfills.js.map |
const mongoose = require("mongoose");
const { Schema } = mongoose;
const authorSchema = new Schema(
{
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
},
{
timestamps: true,
versioKey: false,
}
);
const Author = mongoose.model("Author", authorSchema);
module.exports = Author;
|
var searchData=
[
['debug_517',['debug',['../classredland_1_1Logger.html#a8e48332423e589a5e11c8e6ecdd16bf1',1,'redland::Logger']]],
['deleteresultsmap_518',['deleteResultsMap',['../namespaceomexmeta.html#aac58f146c00ed4c492efebb1e239c90b',1,'omexmeta']]],
['disablebacktrace_519',['disableBacktrace',['../classredland_1_1Logger.html#a61b92676954488db03b3c3ebfbd11fe0',1,'redland::Logger']]],
['download_520',['download',['../classomexmeta_1_1CurlGet.html#a52eaa2b1179cf49ec298022011b2477c',1,'omexmeta::CurlGet::download()'],['../classomexmeta_1_1OmexMetaUtils.html#a046b603d6308242b70b55de6cb72325c',1,'omexmeta::OmexMetaUtils::download()']]],
['dumpbacktrace_521',['dumpBacktrace',['../classredland_1_1Logger.html#ac0d3043e20448acf27088756943e6487',1,'redland::Logger']]]
];
|
#ifndef MTF_XVSSD_SE2
#define MTF_XVSSD_SE2
#include "xvSSDMain.h"
class XVSSDSE2: public XVSSDMain {
typedef XVSE2Stepper< IMAGE_TYPE > STEPPER_TYPE;
typedef XVSSD< IMAGE_TYPE, STEPPER_TYPE > TRACKER_TYPE;
typedef TRACKER_TYPE::SP STATE_PAIR_TYPE;
typedef STEPPER_TYPE::STATE_TYPE STATE_TYPE;
public:
TRACKER_TYPE *ssd;
STATE_PAIR_TYPE current_state;
XVSSDSE2(const ParamType *xv_params = NULL):
XVSSDMain(xv_params){
name="se2";
}
void initTracker() {
//printf("Using SE2 SSD Tracker with:\n\t");
STATE_TYPE state;
state.trans=*init_pos;
state.angle=0.0;
state.scale=1.0;
ssd=new TRACKER_TYPE(state, init_template);
template_img = ssd->getTarget();
}
double updateTrackerState() {
current_state=ssd->step(*xv_frame);
warped_img=ssd->warpedImage();
return current_state.error;
}
void updateCorners(){
current_state=ssd->getCurrentState();
XVAffineMatrix angleMat(-current_state.state.angle);
XVAffineMatrix scaleMat( 1 / current_state.state.scale,
1 / current_state.state.scale);
XVAffineMatrix tformMat((XVMatrix)scaleMat * (XVMatrix)angleMat);
for(int i=0; i<NCORNERS; ++i)
corners[i] = (tformMat * points[i]) + current_state.state.trans;
}
void getTransformedPoints(vector<XVPositionD> &in_pts, vector<XVPositionD> &out_pts){
XVAffineMatrix angleMat(-current_state.state.angle);
XVAffineMatrix scaleMat( 1 / current_state.state.scale,
1 / current_state.state.scale);
XVAffineMatrix tformMat((XVMatrix)scaleMat * (XVMatrix)angleMat);
for(int i=0; i<NCORNERS; ++i)
out_pts[i] = (tformMat * in_pts[i]) + current_state.state.trans;
}
void resetTrackerPosition(double pos_x, double pos_y){
STATE_TYPE temp_state(current_state.state);
temp_state.trans.setX(pos_x);
temp_state.trans.setY(pos_y);
ssd->initState(temp_state);
}
void resetTrackerTemplate(IMAGE_TYPE *img, double pos_x, double pos_y,
double size_x, double size_y){
updateTemplate(img, pos_x, pos_y, size_x, size_y);
ssd->setStepper(init_template);
resetTrackerPosition(pos_x, pos_y);
}
};
#endif |
import React from "react";
import * as TaskActions from "../actions/TaskActions";
export default class TaskCompleteButton extends React.Component {
constructor(props) {
super();
}
completeTask(id) {
TaskActions.completeTask(id);
}
render() {
const id = this.props.id;
return(
<button type="button" className="button" onClick={ this.completeTask.bind(this, id) }>Complete</button>
);
}
}
|
#!/usr/bin/env python
'''
===============================================================================
Interactive Image Segmentation using GrabCut algorithm.
===============================================================================
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2 as cv
import sys
from tests_common import NewOpenCVTests
class grabcut_test(NewOpenCVTests):
def verify(self, mask, exp):
maxDiffRatio = 0.02
expArea = np.count_nonzero(exp)
nonIntersectArea = np.count_nonzero(mask != exp)
curRatio = float(nonIntersectArea) / expArea
return curRatio < maxDiffRatio
def scaleMask(self, mask):
return np.where((mask==cv.GC_FGD) + (mask==cv.GC_PR_FGD),255,0).astype('uint8')
def test_grabcut(self):
img = self.get_sample('cv/shared/airplane.png')
mask_prob = self.get_sample("cv/grabcut/mask_probpy.png", 0)
exp_mask1 = self.get_sample("cv/grabcut/exp_mask1py.png", 0)
exp_mask2 = self.get_sample("cv/grabcut/exp_mask2py.png", 0)
if img is None:
self.assertTrue(False, 'Missing test data')
rect = (24, 126, 459, 168)
mask = np.zeros(img.shape[:2], dtype = np.uint8)
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
cv.grabCut(img, mask, rect, bgdModel, fgdModel, 0, cv.GC_INIT_WITH_RECT)
cv.grabCut(img, mask, rect, bgdModel, fgdModel, 2, cv.GC_EVAL)
if mask_prob is None:
mask_prob = mask.copy()
cv.imwrite(self.extraTestDataPath + '/cv/grabcut/mask_probpy.png', mask_prob)
if exp_mask1 is None:
exp_mask1 = self.scaleMask(mask)
cv.imwrite(self.extraTestDataPath + '/cv/grabcut/exp_mask1py.png', exp_mask1)
self.assertEqual(self.verify(self.scaleMask(mask), exp_mask1), True)
mask = mask_prob
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
cv.grabCut(img, mask, rect, bgdModel, fgdModel, 0, cv.GC_INIT_WITH_MASK)
cv.grabCut(img, mask, rect, bgdModel, fgdModel, 1, cv.GC_EVAL)
if exp_mask2 is None:
exp_mask2 = self.scaleMask(mask)
cv.imwrite(self.extraTestDataPath + '/cv/grabcut/exp_mask2py.png', exp_mask2)
self.assertEqual(self.verify(self.scaleMask(mask), exp_mask2), True)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()
|
import { Link } from "gatsby"
import { useStaticQuery, graphql } from "gatsby"
import React, { useState, useEffect } from "react"
// import { parse } from 'fast-xml-parser';
const RssPage = () => {
const rssUrl = `https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fnews.ycombinator.com%2Frss`;
const [newsTitle, setNewsTitle] = useState(0)
const [newsItems, setNewsItems] = useState(1)
useEffect(() => {
fetch(rssUrl)
// .then( textResponse => parse(textResponse) )
.then(response => response.json() )
.then( resultData => {
setNewsTitle(resultData.feed.title);
setNewsItems(resultData.items)
})
.catch((error) => { console.log(error);})
}, [])
const data = useStaticQuery(graphql`
query RssQuery {
allFeedRss {
edges {
node {
title
content
link
}
}
}
}
`);
const { edges } = data.allFeedRss;
return (
<div style={{ maxWidth: `960px`, margin: `1.45rem` }}>
<h1>{newsTitle}</h1>
<ul>
{newsItems.map && newsItems.map((data, index) => {
return (
<li>
<Link to={data.link}>{data.title}</Link>
</li>
)
})}
{/* {edges.map((data, index) => {
return(
<li>
<Link to={data.node.link}>{data.node.title}</Link>
</li>
)
})} */}
</ul>
</div>
)}
export default RssPage |
# -*- coding: utf-8 -*-
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2016 Thomas Voegtlin
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
import sys
import copy
import traceback
from functools import partial
from typing import List, TYPE_CHECKING, Tuple, NamedTuple, Any, Dict, Optional
from . import bitcoin
from . import keystore
from . import mnemonic
from .bip32 import is_bip32_derivation, xpub_type, normalize_bip32_derivation
from .keystore import bip44_derivation, purpose48_derivation
from .wallet import (Imported_Wallet, Standard_Wallet, Multisig_Wallet,
wallet_types, Wallet, Abstract_Wallet)
from .storage import (WalletStorage, STO_EV_USER_PW, STO_EV_XPUB_PW,
get_derivation_used_for_hw_device_encryption)
from .i18n import _
from .util import UserCancelled, InvalidPassword, WalletFileException
from .simple_config import SimpleConfig
from .plugin import Plugins, HardwarePluginLibraryUnavailable
from .logging import Logger
from .plugins.hw_wallet.plugin import OutdatedHwFirmwareException, HW_PluginBase
if TYPE_CHECKING:
from .plugin import DeviceInfo
# hardware device setup purpose
HWD_SETUP_NEW_WALLET, HWD_SETUP_DECRYPT_WALLET = range(0, 2)
class ScriptTypeNotSupported(Exception): pass
class GoBack(Exception): pass
class WizardStackItem(NamedTuple):
action: Any
args: Any
kwargs: Dict[str, Any]
storage_data: dict
class BaseWizard(Logger):
def __init__(self, config: SimpleConfig, plugins: Plugins):
super(BaseWizard, self).__init__()
Logger.__init__(self)
self.config = config
self.plugins = plugins
self.data = {}
self.pw_args = None
self._stack = [] # type: List[WizardStackItem]
self.plugin = None
self.keystores = []
self.is_kivy = config.get('gui') == 'kivy'
self.seed_type = None
def set_icon(self, icon):
pass
def run(self, *args, **kwargs):
action = args[0]
args = args[1:]
storage_data = copy.deepcopy(self.data)
self._stack.append(WizardStackItem(action, args, kwargs, storage_data))
if not action:
return
if type(action) is tuple:
self.plugin, action = action
if self.plugin and hasattr(self.plugin, action):
f = getattr(self.plugin, action)
f(self, *args, **kwargs)
elif hasattr(self, action):
f = getattr(self, action)
f(*args, **kwargs)
else:
raise Exception("unknown action", action)
def can_go_back(self):
return len(self._stack) > 1
def go_back(self):
if not self.can_go_back():
return
# pop 'current' frame
self._stack.pop()
# pop 'previous' frame
stack_item = self._stack.pop()
# try to undo side effects since we last entered 'previous' frame
# FIXME only self.storage is properly restored
self.data = copy.deepcopy(stack_item.storage_data)
# rerun 'previous' frame
self.run(stack_item.action, *stack_item.args, **stack_item.kwargs)
def reset_stack(self):
self._stack = []
def new(self):
title = _("Create new wallet")
message = '\n'.join([
_("What kind of wallet do you want to create?")
])
wallet_kinds = [
('standard', _("Standard wallet")),
('2fa', _("Wallet with two-factor authentication")),
('multisig', _("Multi-signature wallet")),
('imported', _("Import Bitcoin addresses or private keys")),
]
choices = [pair for pair in wallet_kinds if pair[0] in wallet_types]
self.choice_dialog(title=title, message=message, choices=choices, run_next=self.on_wallet_type)
def upgrade_storage(self, storage):
exc = None
def on_finished():
if exc is None:
self.terminate(storage=storage)
else:
raise exc
def do_upgrade():
nonlocal exc
try:
storage.upgrade()
except Exception as e:
exc = e
self.waiting_dialog(do_upgrade, _('Upgrading wallet format...'), on_finished=on_finished)
def load_2fa(self):
self.data['wallet_type'] = '2fa'
self.data['use_trustedcoin'] = True
self.plugin = self.plugins.load_plugin('trustedcoin')
def on_wallet_type(self, choice):
self.data['wallet_type'] = self.wallet_type = choice
if choice == 'standard':
action = 'choose_keystore'
elif choice == 'multisig':
action = 'choose_multisig'
elif choice == '2fa':
self.load_2fa()
action = self.plugin.get_action(self.data)
elif choice == 'imported':
action = 'import_addresses_or_keys'
self.run(action)
def choose_multisig(self):
def on_multisig(m, n):
multisig_type = "%dof%d" % (m, n)
self.data['wallet_type'] = multisig_type
self.n = n
self.run('choose_keystore')
self.multisig_dialog(run_next=on_multisig)
def choose_keystore(self):
assert self.wallet_type in ['standard', 'multisig']
i = len(self.keystores)
title = _('Add cosigner') + ' (%d of %d)'%(i+1, self.n) if self.wallet_type=='multisig' else _('Keystore')
if self.wallet_type =='standard' or i==0:
message = _('Do you want to create a new seed, or to restore a wallet using an existing seed?')
choices = [
('choose_seed_type', _('Create a new seed')),
('restore_from_seed', _('I already have a seed')),
('restore_from_key', _('Use a master key')),
]
if not self.is_kivy:
choices.append(('choose_hw_device', _('Use a hardware device')))
else:
message = _('Add a cosigner to your multi-sig wallet')
choices = [
('restore_from_key', _('Enter cosigner key')),
('restore_from_seed', _('Enter cosigner seed')),
]
if not self.is_kivy:
choices.append(('choose_hw_device', _('Cosign with hardware device')))
self.choice_dialog(title=title, message=message, choices=choices, run_next=self.run)
def import_addresses_or_keys(self):
v = lambda x: keystore.is_address_list(x) or keystore.is_private_key_list(x, raise_on_error=True)
title = _("Import Bitcoin Addresses")
message = _("Enter a list of Bitcoin addresses (this will create a watching-only wallet), or a list of private keys.")
self.add_xpub_dialog(title=title, message=message, run_next=self.on_import,
is_valid=v, allow_multi=True, show_wif_help=True)
def on_import(self, text):
# text is already sanitized by is_address_list and is_private_keys_list
if keystore.is_address_list(text):
self.data['addresses'] = {}
for addr in text.split():
assert bitcoin.is_address(addr)
self.data['addresses'][addr] = {}
elif keystore.is_private_key_list(text):
self.data['addresses'] = {}
k = keystore.Imported_KeyStore({})
keys = keystore.get_private_keys(text)
for pk in keys:
assert bitcoin.is_private_key(pk)
txin_type, pubkey = k.import_privkey(pk, None)
addr = bitcoin.pubkey_to_address(txin_type, pubkey)
self.data['addresses'][addr] = {'type':txin_type, 'pubkey':pubkey, 'redeem_script':None}
self.keystores.append(k)
else:
return self.terminate()
return self.run('create_wallet')
def restore_from_key(self):
if self.wallet_type == 'standard':
v = keystore.is_master_key
title = _("Create keystore from a master key")
message = ' '.join([
_("To create a watching-only wallet, please enter your master public key (xpub/ypub/zpub)."),
_("To create a spending wallet, please enter a master private key (xprv/yprv/zprv).")
])
self.add_xpub_dialog(title=title, message=message, run_next=self.on_restore_from_key, is_valid=v)
else:
i = len(self.keystores) + 1
self.add_cosigner_dialog(index=i, run_next=self.on_restore_from_key, is_valid=keystore.is_bip32_key)
def on_restore_from_key(self, text):
k = keystore.from_master_key(text)
self.on_keystore(k)
def choose_hw_device(self, purpose=HWD_SETUP_NEW_WALLET, *, storage=None):
title = _('Hardware Keystore')
# check available plugins
supported_plugins = self.plugins.get_hardware_support()
devices = [] # type: List[Tuple[str, DeviceInfo]]
devmgr = self.plugins.device_manager
debug_msg = ''
def failed_getting_device_infos(name, e):
nonlocal debug_msg
err_str_oneline = ' // '.join(str(e).splitlines())
self.logger.warning(f'error getting device infos for {name}: {err_str_oneline}')
indented_error_msg = ' '.join([''] + str(e).splitlines(keepends=True))
debug_msg += f' {name}: (error getting device infos)\n{indented_error_msg}\n'
# scan devices
try:
scanned_devices = devmgr.scan_devices()
except BaseException as e:
self.logger.info('error scanning devices: {}'.format(repr(e)))
debug_msg = ' {}:\n {}'.format(_('Error scanning devices'), e)
else:
for splugin in supported_plugins:
name, plugin = splugin.name, splugin.plugin
# plugin init errored?
if not plugin:
e = splugin.exception
indented_error_msg = ' '.join([''] + str(e).splitlines(keepends=True))
debug_msg += f' {name}: (error during plugin init)\n'
debug_msg += ' {}\n'.format(_('You might have an incompatible library.'))
debug_msg += f'{indented_error_msg}\n'
continue
# see if plugin recognizes 'scanned_devices'
try:
# FIXME: side-effect: unpaired_device_info sets client.handler
device_infos = devmgr.unpaired_device_infos(None, plugin, devices=scanned_devices,
include_failing_clients=True)
except HardwarePluginLibraryUnavailable as e:
failed_getting_device_infos(name, e)
continue
except BaseException as e:
self.logger.exception('')
failed_getting_device_infos(name, e)
continue
device_infos_failing = list(filter(lambda di: di.exception is not None, device_infos))
for di in device_infos_failing:
failed_getting_device_infos(name, di.exception)
device_infos_working = list(filter(lambda di: di.exception is None, device_infos))
devices += list(map(lambda x: (name, x), device_infos_working))
if not debug_msg:
debug_msg = ' {}'.format(_('No exceptions encountered.'))
if not devices:
msg = (_('No hardware device detected.') + '\n' +
_('To trigger a rescan, press \'Next\'.') + '\n\n')
if sys.platform == 'win32':
msg += _('If your device is not detected on Windows, go to "Settings", "Devices", "Connected devices", '
'and do "Remove device". Then, plug your device again.') + '\n'
msg += _('While this is less than ideal, it might help if you run Electrum as Administrator.') + '\n'
else:
msg += _('On Linux, you might have to add a new permission to your udev rules.') + '\n'
msg += '\n\n'
msg += _('Debug message') + '\n' + debug_msg
self.confirm_dialog(title=title, message=msg,
run_next=lambda x: self.choose_hw_device(purpose, storage=storage))
return
# select device
self.devices = devices
choices = []
for name, info in devices:
state = _("initialized") if info.initialized else _("wiped")
label = info.label or _("An unnamed {}").format(name)
try: transport_str = info.device.transport_ui_string[:20]
except: transport_str = 'unknown transport'
descr = f"{label} [{name}, {state}, {transport_str}]"
choices.append(((name, info), descr))
msg = _('Select a device') + ':'
self.choice_dialog(title=title, message=msg, choices=choices,
run_next=lambda *args: self.on_device(*args, purpose=purpose, storage=storage))
def on_device(self, name, device_info, *, purpose, storage=None):
self.plugin = self.plugins.get_plugin(name) # type: HW_PluginBase
try:
self.plugin.setup_device(device_info, self, purpose)
except OSError as e:
self.show_error(_('We encountered an error while connecting to your device:')
+ '\n' + str(e) + '\n'
+ _('To try to fix this, we will now re-pair with your device.') + '\n'
+ _('Please try again.'))
devmgr = self.plugins.device_manager
devmgr.unpair_id(device_info.device.id_)
self.choose_hw_device(purpose, storage=storage)
return
except OutdatedHwFirmwareException as e:
if self.question(e.text_ignore_old_fw_and_continue(), title=_("Outdated device firmware")):
self.plugin.set_ignore_outdated_fw()
# will need to re-pair
devmgr = self.plugins.device_manager
devmgr.unpair_id(device_info.device.id_)
self.choose_hw_device(purpose, storage=storage)
return
except (UserCancelled, GoBack):
self.choose_hw_device(purpose, storage=storage)
return
except BaseException as e:
self.logger.exception('')
self.show_error(str(e))
self.choose_hw_device(purpose, storage=storage)
return
if purpose == HWD_SETUP_NEW_WALLET:
def f(derivation, script_type):
derivation = normalize_bip32_derivation(derivation)
self.run('on_hw_derivation', name, device_info, derivation, script_type)
self.derivation_and_script_type_dialog(f)
elif purpose == HWD_SETUP_DECRYPT_WALLET:
derivation = get_derivation_used_for_hw_device_encryption()
xpub = self.plugin.get_xpub(device_info.device.id_, derivation, 'standard', self)
password = keystore.Xpub.get_pubkey_from_xpub(xpub, ())
try:
storage.decrypt(password)
except InvalidPassword:
# try to clear session so that user can type another passphrase
devmgr = self.plugins.device_manager
client = devmgr.client_by_id(device_info.device.id_)
if hasattr(client, 'clear_session'): # FIXME not all hw wallet plugins have this
client.clear_session()
raise
else:
raise Exception('unknown purpose: %s' % purpose)
def derivation_and_script_type_dialog(self, f):
message1 = _('Choose the type of addresses in your wallet.')
message2 = ' '.join([
_('You can override the suggested derivation path.'),
_('If you are not sure what this is, leave this field unchanged.')
])
if self.wallet_type == 'multisig':
# There is no general standard for HD multisig.
# For legacy, this is partially compatible with BIP45; assumes index=0
# For segwit, a custom path is used, as there is no standard at all.
default_choice_idx = 2
choices = [
('standard', 'legacy multisig (p2sh)', "m/45'/0"),
('p2wsh-p2sh', 'p2sh-segwit multisig (p2wsh-p2sh)', purpose48_derivation(0, xtype='p2wsh-p2sh')),
('p2wsh', 'native segwit multisig (p2wsh)', purpose48_derivation(0, xtype='p2wsh')),
]
else:
default_choice_idx = 2
choices = [
('standard', 'legacy (p2pkh)', bip44_derivation(0, bip43_purpose=44)),
('p2wpkh-p2sh', 'p2sh-segwit (p2wpkh-p2sh)', bip44_derivation(0, bip43_purpose=49)),
('p2wpkh', 'native segwit (p2wpkh)', bip44_derivation(0, bip43_purpose=84)),
]
while True:
try:
self.choice_and_line_dialog(
run_next=f, title=_('Script type and Derivation path'), message1=message1,
message2=message2, choices=choices, test_text=is_bip32_derivation,
default_choice_idx=default_choice_idx)
return
except ScriptTypeNotSupported as e:
self.show_error(e)
# let the user choose again
def on_hw_derivation(self, name, device_info, derivation, xtype):
from .keystore import hardware_keystore
try:
xpub = self.plugin.get_xpub(device_info.device.id_, derivation, xtype, self)
except ScriptTypeNotSupported:
raise # this is handled in derivation_dialog
except BaseException as e:
self.logger.exception('')
self.show_error(e)
return
d = {
'type': 'hardware',
'hw_type': name,
'derivation': derivation,
'xpub': xpub,
'label': device_info.label,
}
k = hardware_keystore(d)
self.on_keystore(k)
def passphrase_dialog(self, run_next, is_restoring=False):
title = _('Seed extension')
message = '\n'.join([
_('You may extend your seed with custom words.'),
_('Your seed extension must be saved together with your seed.'),
])
warning = '\n'.join([
_('Note that this is NOT your encryption password.'),
_('If you do not know what this is, leave this field empty.'),
])
warn_issue4566 = is_restoring and self.seed_type == 'bip39'
self.line_dialog(title=title, message=message, warning=warning,
default='', test=lambda x:True, run_next=run_next,
warn_issue4566=warn_issue4566)
def restore_from_seed(self):
self.opt_bip39 = True
self.opt_ext = True
is_cosigning_seed = lambda x: mnemonic.seed_type(x) in ['standard', 'segwit']
test = mnemonic.is_seed if self.wallet_type == 'standard' else is_cosigning_seed
self.restore_seed_dialog(run_next=self.on_restore_seed, test=test)
def on_restore_seed(self, seed, is_bip39, is_ext):
self.seed_type = 'bip39' if is_bip39 else mnemonic.seed_type(seed)
if self.seed_type == 'bip39':
f = lambda passphrase: self.on_restore_bip39(seed, passphrase)
self.passphrase_dialog(run_next=f, is_restoring=True) if is_ext else f('')
elif self.seed_type in ['standard', 'segwit']:
f = lambda passphrase: self.run('create_keystore', seed, passphrase)
self.passphrase_dialog(run_next=f, is_restoring=True) if is_ext else f('')
elif self.seed_type == 'old':
self.run('create_keystore', seed, '')
elif mnemonic.is_any_2fa_seed_type(self.seed_type):
self.load_2fa()
self.run('on_restore_seed', seed, is_ext)
else:
raise Exception('Unknown seed type', self.seed_type)
def on_restore_bip39(self, seed, passphrase):
def f(derivation, script_type):
derivation = normalize_bip32_derivation(derivation)
self.run('on_bip43', seed, passphrase, derivation, script_type)
self.derivation_and_script_type_dialog(f)
def create_keystore(self, seed, passphrase):
k = keystore.from_seed(seed, passphrase, self.wallet_type == 'multisig')
self.on_keystore(k)
def on_bip43(self, seed, passphrase, derivation, script_type):
k = keystore.from_bip39_seed(seed, passphrase, derivation, xtype=script_type)
self.on_keystore(k)
def on_keystore(self, k):
has_xpub = isinstance(k, keystore.Xpub)
if has_xpub:
t1 = xpub_type(k.xpub)
if self.wallet_type == 'standard':
if has_xpub and t1 not in ['standard', 'p2wpkh', 'p2wpkh-p2sh']:
self.show_error(_('Wrong key type') + ' %s'%t1)
self.run('choose_keystore')
return
self.keystores.append(k)
self.run('create_wallet')
elif self.wallet_type == 'multisig':
assert has_xpub
if t1 not in ['standard', 'p2wsh', 'p2wsh-p2sh']:
self.show_error(_('Wrong key type') + ' %s'%t1)
self.run('choose_keystore')
return
if k.xpub in map(lambda x: x.xpub, self.keystores):
self.show_error(_('Error: duplicate master public key'))
self.run('choose_keystore')
return
if len(self.keystores)>0:
t2 = xpub_type(self.keystores[0].xpub)
if t1 != t2:
self.show_error(_('Cannot add this cosigner:') + '\n' + "Their key type is '%s', we are '%s'"%(t1, t2))
self.run('choose_keystore')
return
self.keystores.append(k)
if len(self.keystores) == 1:
xpub = k.get_master_public_key()
self.reset_stack()
self.run('show_xpub_and_add_cosigners', xpub)
elif len(self.keystores) < self.n:
self.run('choose_keystore')
else:
self.run('create_wallet')
def create_wallet(self):
encrypt_keystore = any(k.may_have_password() for k in self.keystores)
# note: the following condition ("if") is duplicated logic from
# wallet.get_available_storage_encryption_version()
if self.wallet_type == 'standard' and isinstance(self.keystores[0], keystore.Hardware_KeyStore):
# offer encrypting with a pw derived from the hw device
k = self.keystores[0]
try:
k.handler = self.plugin.create_handler(self)
password = k.get_password_for_storage_encryption()
except UserCancelled:
devmgr = self.plugins.device_manager
devmgr.unpair_xpub(k.xpub)
self.choose_hw_device()
return
except BaseException as e:
self.logger.exception('')
self.show_error(str(e))
return
self.request_storage_encryption(
run_next=lambda encrypt_storage: self.on_password(
password,
encrypt_storage=encrypt_storage,
storage_enc_version=STO_EV_XPUB_PW,
encrypt_keystore=False))
else:
# reset stack to disable 'back' button in password dialog
self.reset_stack()
# prompt the user to set an arbitrary password
self.request_password(
run_next=lambda password, encrypt_storage: self.on_password(
password,
encrypt_storage=encrypt_storage,
storage_enc_version=STO_EV_USER_PW,
encrypt_keystore=encrypt_keystore),
force_disable_encrypt_cb=not encrypt_keystore)
def on_password(self, password, *, encrypt_storage,
storage_enc_version=STO_EV_USER_PW, encrypt_keystore):
for k in self.keystores:
if k.may_have_password():
k.update_password(None, password)
if self.wallet_type == 'standard':
self.data['seed_type'] = self.seed_type
keys = self.keystores[0].dump()
self.data['keystore'] = keys
elif self.wallet_type == 'multisig':
for i, k in enumerate(self.keystores):
self.data['x%d/'%(i+1)] = k.dump()
elif self.wallet_type == 'imported':
if len(self.keystores) > 0:
keys = self.keystores[0].dump()
self.data['keystore'] = keys
else:
raise Exception('Unknown wallet type')
self.pw_args = password, encrypt_storage, storage_enc_version
self.terminate()
def create_storage(self, path):
if os.path.exists(path):
raise Exception('file already exists at path')
if not self.pw_args:
return
password, encrypt_storage, storage_enc_version = self.pw_args
self.pw_args = None # clean-up so that it can get GC-ed
storage = WalletStorage(path)
storage.set_keystore_encryption(bool(password))
if encrypt_storage:
storage.set_password(password, enc_version=storage_enc_version)
for key, value in self.data.items():
storage.put(key, value)
storage.write()
storage.load_plugins()
return storage
def terminate(self, *, storage: Optional[WalletStorage] = None):
raise NotImplementedError() # implemented by subclasses
def show_xpub_and_add_cosigners(self, xpub):
self.show_xpub_dialog(xpub=xpub, run_next=lambda x: self.run('choose_keystore'))
def choose_seed_type(self, message=None, choices=None):
title = _('Choose Seed type')
if message is None:
message = ' '.join([
_("The type of addresses used by your wallet will depend on your seed."),
_("Segwit wallets use bech32 addresses, defined in BIP173."),
_("Please note that websites and other wallets may not support these addresses yet."),
_("Thus, you might want to keep using a non-segwit wallet in order to be able to receive bitcoins during the transition period.")
])
if choices is None:
choices = [
('create_segwit_seed', _('Segwit')),
('create_standard_seed', _('Legacy')),
]
self.choice_dialog(title=title, message=message, choices=choices, run_next=self.run)
def create_segwit_seed(self): self.create_seed('segwit')
def create_standard_seed(self): self.create_seed('standard')
def create_seed(self, seed_type):
from . import mnemonic
self.seed_type = seed_type
seed = mnemonic.Mnemonic('en').make_seed(self.seed_type)
self.opt_bip39 = False
f = lambda x: self.request_passphrase(seed, x)
self.show_seed_dialog(run_next=f, seed_text=seed)
def request_passphrase(self, seed, opt_passphrase):
if opt_passphrase:
f = lambda x: self.confirm_seed(seed, x)
self.passphrase_dialog(run_next=f)
else:
self.run('confirm_seed', seed, '')
def confirm_seed(self, seed, passphrase):
f = lambda x: self.confirm_passphrase(seed, passphrase)
self.confirm_seed_dialog(run_next=f, test=lambda x: x==seed)
def confirm_passphrase(self, seed, passphrase):
f = lambda x: self.run('create_keystore', seed, x)
if passphrase:
title = _('Confirm Seed Extension')
message = '\n'.join([
_('Your seed extension must be saved together with your seed.'),
_('Please type it here.'),
])
self.line_dialog(run_next=f, title=title, message=message, default='', test=lambda x: x==passphrase)
else:
f('')
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_CONSENSUS_PARAMS_H
#define BITCOIN_CONSENSUS_PARAMS_H
#include <uint256.h>
#include <limits>
#include <map>
#include <string>
namespace Consensus {
enum DeploymentPos
{
DEPLOYMENT_TESTDUMMY,
// NOTE: Also add new deployments to VersionBitsDeploymentInfo in versionbits.cpp
MAX_VERSION_BITS_DEPLOYMENTS
};
/**
* Struct for each individual consensus rule change using BIP9.
*/
struct BIP9Deployment {
/** Bit position to select the particular bit in nVersion. */
int bit;
/** Start MedianTime for version bits miner confirmation. Can be a date in the past */
int64_t nStartTime;
/** Timeout/expiry MedianTime for the deployment attempt. */
int64_t nTimeout;
/** Constant for nTimeout very far in the future. */
static constexpr int64_t NO_TIMEOUT = std::numeric_limits<int64_t>::max();
/** Special value for nStartTime indicating that the deployment is always active.
* This is useful for testing, as it means tests don't need to deal with the activation
* process (which takes at least 3 BIP9 intervals). Only tests that specifically test the
* behaviour during activation cannot use this. */
static constexpr int64_t ALWAYS_ACTIVE = -1;
};
/**
* Parameters that influence chain consensus.
*/
struct Params {
uint256 hashGenesisBlock;
int nSubsidyHalvingInterval;
/* Block hash that is excepted from BIP16 enforcement */
uint256 BIP16Exception;
/** Block height and hash at which BIP34 becomes active */
int BIP34Height;
uint256 BIP34Hash;
/** Block height at which BIP65 becomes active */
int BIP65Height;
/** Block height at which BIP66 becomes active */
int BIP66Height;
/** Block height at which CSV (BIP68, BIP112 and BIP113) becomes active */
int CSVHeight;
/** Block height at which Segwit (BIP141, BIP143 and BIP147) becomes active.
* Note that segwit v0 script rules are enforced on all blocks except the
* BIP 16 exception blocks. */
int SegwitHeight;
/** Don't warn about unknown BIP 9 activations below this height.
* This prevents us from warning about the CSV and segwit activations. */
int MinBIP9WarningHeight;
/** Time at which OP_ISCOINSTAKE becomes active */
int64_t OpIsCoinstakeTime;
bool fAllowOpIsCoinstakeWithP2PKH;
/** Time at which Paid SMSG becomes active */
uint32_t nPaidSmsgTime;
/** Time at which csp2sh becomes active */
uint32_t csp2shTime;
/** Time at which variable SMSG fee become active */
uint32_t smsg_fee_time;
/** Time at which bulletproofs become active */
uint32_t bulletproof_time;
/** Time at which RCT become active */
uint32_t rct_time;
/** Time at which SMSG difficulty tokens are enforced */
uint32_t smsg_difficulty_time;
/** Time of fork to activate more data outputs for blind and anon txns */
uint32_t extra_dataoutput_time = 0xffffffff;
uint32_t smsg_fee_period;
int64_t smsg_fee_funding_tx_per_k;
int64_t smsg_fee_msg_per_day_per_k;
int64_t smsg_fee_max_delta_percent; /* Divided by 1000000 */
uint32_t smsg_min_difficulty;
uint32_t smsg_difficulty_max_delta;
/**
* Minimum blocks including miner confirmation of the total of 2016 blocks in a retargeting period,
* (nPowTargetTimespan / nPowTargetSpacing) which is also used for BIP9 deployments.
* Examples: 1916 for 95%, 1512 for testchains.
*/
uint32_t nRuleChangeActivationThreshold;
uint32_t nMinerConfirmationWindow;
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS];
/** Proof of work parameters */
uint256 powLimit;
bool fPowAllowMinDifficultyBlocks;
bool fPowNoRetargeting;
int64_t nPowTargetSpacing;
int64_t nPowTargetTimespan;
int64_t DifficultyAdjustmentInterval() const { return nPowTargetTimespan / nPowTargetSpacing; }
uint256 nMinimumChainWork;
uint256 defaultAssumeValid;
int nMinRCTOutputDepth;
};
} // namespace Consensus
#endif // BITCOIN_CONSENSUS_PARAMS_H
|
/**
@license
The MIT License
Copyright (c) 2016 Google, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {"use strict";
__webpack_require__(1);
var event_target_1 = __webpack_require__(2);
var define_property_1 = __webpack_require__(4);
var register_element_1 = __webpack_require__(5);
var property_descriptor_1 = __webpack_require__(6);
var timers_1 = __webpack_require__(8);
var utils_1 = __webpack_require__(3);
var set = 'set';
var clear = 'clear';
var blockingMethods = ['alert', 'prompt', 'confirm'];
var _global = typeof window == 'undefined' ? global : window;
timers_1.patchTimer(_global, set, clear, 'Timeout');
timers_1.patchTimer(_global, set, clear, 'Interval');
timers_1.patchTimer(_global, set, clear, 'Immediate');
timers_1.patchTimer(_global, 'request', 'cancelMacroTask', 'AnimationFrame');
timers_1.patchTimer(_global, 'mozRequest', 'mozCancel', 'AnimationFrame');
timers_1.patchTimer(_global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
for (var i = 0; i < blockingMethods.length; i++) {
var name = blockingMethods[i];
utils_1.patchMethod(_global, name, function (delegate, symbol, name) {
return function (s, args) {
return Zone.current.run(delegate, _global, args, name);
};
});
}
event_target_1.eventTargetPatch(_global);
property_descriptor_1.propertyDescriptorPatch(_global);
utils_1.patchClass('MutationObserver');
utils_1.patchClass('WebKitMutationObserver');
utils_1.patchClass('FileReader');
define_property_1.propertyPatch();
register_element_1.registerElementPatch(_global);
// Treat XMLHTTPRequest as a macrotask.
patchXHR(_global);
var XHR_TASK = utils_1.zoneSymbol('xhrTask');
function patchXHR(window) {
function findPendingTask(target) {
var pendingTask = target[XHR_TASK];
return pendingTask;
}
function scheduleTask(task) {
var data = task.data;
data.target.addEventListener('readystatechange', function () {
if (data.target.readyState === XMLHttpRequest.DONE) {
if (!data.aborted) {
task.invoke();
}
}
});
var storedTask = data.target[XHR_TASK];
if (!storedTask) {
data.target[XHR_TASK] = task;
}
setNative.apply(data.target, data.args);
return task;
}
function placeholderCallback() {
}
function clearTask(task) {
var data = task.data;
// Note - ideally, we would call data.target.removeEventListener here, but it's too late
// to prevent it from firing. So instead, we store info for the event listener.
data.aborted = true;
return clearNative.apply(data.target, data.args);
}
var setNative = utils_1.patchMethod(window.XMLHttpRequest.prototype, 'send', function () { return function (self, args) {
var zone = Zone.current;
var options = {
target: self,
isPeriodic: false,
delay: null,
args: args,
aborted: false
};
return zone.scheduleMacroTask('XMLHttpRequest.send', placeholderCallback, options, scheduleTask, clearTask);
}; });
var clearNative = utils_1.patchMethod(window.XMLHttpRequest.prototype, 'abort', function (delegate) { return function (self, args) {
var task = findPendingTask(self);
if (task && typeof task.type == 'string') {
// If the XHR has already completed, do nothing.
if (task.cancelFn == null) {
return;
}
task.zone.cancelTask(task);
}
// Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no task to cancel. Do nothing.
}; });
}
/// GEO_LOCATION
if (_global['navigator'] && _global['navigator'].geolocation) {
utils_1.patchPrototype(_global['navigator'].geolocation, [
'getCurrentPosition',
'watchPosition'
]);
}
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 1 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(global) {;
;
var Zone = (function (global) {
var Zone = (function () {
function Zone(parent, zoneSpec) {
this._properties = null;
this._parent = parent;
this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
this._properties = zoneSpec && zoneSpec.properties || {};
this._zoneDelegate = new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
}
Object.defineProperty(Zone, "current", {
get: function () { return _currentZone; },
enumerable: true,
configurable: true
});
;
Object.defineProperty(Zone, "currentTask", {
get: function () { return _currentTask; },
enumerable: true,
configurable: true
});
;
Object.defineProperty(Zone.prototype, "parent", {
get: function () { return this._parent; },
enumerable: true,
configurable: true
});
;
Object.defineProperty(Zone.prototype, "name", {
get: function () { return this._name; },
enumerable: true,
configurable: true
});
;
Zone.prototype.get = function (key) {
var current = this;
while (current) {
if (current._properties.hasOwnProperty(key)) {
return current._properties[key];
}
current = current._parent;
}
};
Zone.prototype.fork = function (zoneSpec) {
if (!zoneSpec)
throw new Error('ZoneSpec required!');
return this._zoneDelegate.fork(this, zoneSpec);
};
Zone.prototype.wrap = function (callback, source) {
if (typeof callback !== 'function') {
throw new Error('Expecting function got: ' + callback);
}
var _callback = this._zoneDelegate.intercept(this, callback, source);
var zone = this;
return function () {
return zone.runGuarded(_callback, this, arguments, source);
};
};
Zone.prototype.run = function (callback, applyThis, applyArgs, source) {
if (applyThis === void 0) { applyThis = null; }
if (applyArgs === void 0) { applyArgs = null; }
if (source === void 0) { source = null; }
var oldZone = _currentZone;
_currentZone = this;
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
}
finally {
_currentZone = oldZone;
}
};
Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {
if (applyThis === void 0) { applyThis = null; }
if (applyArgs === void 0) { applyArgs = null; }
if (source === void 0) { source = null; }
var oldZone = _currentZone;
_currentZone = this;
try {
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
}
catch (error) {
if (this._zoneDelegate.handleError(this, error)) {
throw error;
}
}
}
finally {
_currentZone = oldZone;
}
};
Zone.prototype.runTask = function (task, applyThis, applyArgs) {
task.runCount++;
if (task.zone != this)
throw new Error('A task can only be run in the zone which created it! (Creation: ' +
task.zone.name + '; Execution: ' + this.name + ')');
var previousTask = _currentTask;
_currentTask = task;
var oldZone = _currentZone;
_currentZone = this;
try {
if (task.type == 'macroTask' && task.data && !task.data.isPeriodic) {
task.cancelFn = null;
}
try {
return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
}
catch (error) {
if (this._zoneDelegate.handleError(this, error)) {
throw error;
}
}
}
finally {
_currentZone = oldZone;
_currentTask = previousTask;
}
};
Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {
return this._zoneDelegate.scheduleTask(this, new ZoneTask('microTask', this, source, callback, data, customSchedule, null));
};
Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {
return this._zoneDelegate.scheduleTask(this, new ZoneTask('macroTask', this, source, callback, data, customSchedule, customCancel));
};
Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) {
return this._zoneDelegate.scheduleTask(this, new ZoneTask('eventTask', this, source, callback, data, customSchedule, customCancel));
};
Zone.prototype.cancelTask = function (task) {
var value = this._zoneDelegate.cancelTask(this, task);
task.runCount = -1;
task.cancelFn = null;
return value;
};
Zone.__symbol__ = __symbol__;
return Zone;
}());
;
var ZoneDelegate = (function () {
function ZoneDelegate(zone, parentDelegate, zoneSpec) {
this._taskCounts = { microTask: 0, macroTask: 0, eventTask: 0 };
this.zone = zone;
this._parentDelegate = parentDelegate;
this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);
this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);
this._interceptZS = zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);
this._interceptDlgt = zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);
this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);
this._invokeDlgt = zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);
this._handleErrorZS = zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);
this._handleErrorDlgt = zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);
this._scheduleTaskZS = zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
this._scheduleTaskDlgt = zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
this._invokeTaskZS = zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);
this._invokeTaskDlgt = zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);
this._cancelTaskZS = zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);
this._cancelTaskDlgt = zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);
this._hasTaskZS = zoneSpec && (zoneSpec.onHasTask ? zoneSpec : parentDelegate._hasTaskZS);
this._hasTaskDlgt = zoneSpec && (zoneSpec.onHasTask ? parentDelegate : parentDelegate._hasTaskDlgt);
}
ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) {
return this._forkZS
? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec)
: new Zone(targetZone, zoneSpec);
};
ZoneDelegate.prototype.intercept = function (targetZone, callback, source) {
return this._interceptZS
? this._interceptZS.onIntercept(this._interceptDlgt, this.zone, targetZone, callback, source)
: callback;
};
ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {
return this._invokeZS
? this._invokeZS.onInvoke(this._invokeDlgt, this.zone, targetZone, callback, applyThis, applyArgs, source)
: callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.handleError = function (targetZone, error) {
return this._handleErrorZS
? this._handleErrorZS.onHandleError(this._handleErrorDlgt, this.zone, targetZone, error)
: true;
};
ZoneDelegate.prototype.scheduleTask = function (targetZone, task) {
try {
if (this._scheduleTaskZS) {
return this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this.zone, targetZone, task);
}
else if (task.scheduleFn) {
task.scheduleFn(task);
}
else if (task.type == 'microTask') {
scheduleMicroTask(task);
}
else {
throw new Error('Task is missing scheduleFn.');
}
return task;
}
finally {
if (targetZone == this.zone) {
this._updateTaskCount(task.type, 1);
}
}
};
ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {
try {
return this._invokeTaskZS
? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this.zone, targetZone, task, applyThis, applyArgs)
: task.callback.apply(applyThis, applyArgs);
}
finally {
if (targetZone == this.zone && (task.type != 'eventTask') && !(task.data && task.data.isPeriodic)) {
this._updateTaskCount(task.type, -1);
}
}
};
ZoneDelegate.prototype.cancelTask = function (targetZone, task) {
var value;
if (this._cancelTaskZS) {
value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this.zone, targetZone, task);
}
else if (!task.cancelFn) {
throw new Error('Task does not support cancellation, or is already canceled.');
}
else {
value = task.cancelFn(task);
}
if (targetZone == this.zone) {
// this should not be in the finally block, because exceptions assume not canceled.
this._updateTaskCount(task.type, -1);
}
return value;
};
ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) {
return this._hasTaskZS && this._hasTaskZS.onHasTask(this._hasTaskDlgt, this.zone, targetZone, isEmpty);
};
ZoneDelegate.prototype._updateTaskCount = function (type, count) {
var counts = this._taskCounts;
var prev = counts[type];
var next = counts[type] = prev + count;
if (next < 0) {
throw new Error('More tasks executed then were scheduled.');
}
if (prev == 0 || next == 0) {
var isEmpty = {
microTask: counts.microTask > 0,
macroTask: counts.macroTask > 0,
eventTask: counts.eventTask > 0,
change: type
};
try {
this.hasTask(this.zone, isEmpty);
}
finally {
if (this._parentDelegate) {
this._parentDelegate._updateTaskCount(type, count);
}
}
}
};
return ZoneDelegate;
}());
var ZoneTask = (function () {
function ZoneTask(type, zone, source, callback, options, scheduleFn, cancelFn) {
this.runCount = 0;
this.type = type;
this.zone = zone;
this.source = source;
this.data = options;
this.scheduleFn = scheduleFn;
this.cancelFn = cancelFn;
this.callback = callback;
var self = this;
this.invoke = function () {
try {
return zone.runTask(self, this, arguments);
}
finally {
drainMicroTaskQueue();
}
};
}
return ZoneTask;
}());
function __symbol__(name) { return '__zone_symbol__' + name; }
;
var symbolSetTimeout = __symbol__('setTimeout');
var symbolPromise = __symbol__('Promise');
var symbolThen = __symbol__('then');
var _currentZone = new Zone(null, null);
var _currentTask = null;
var _microTaskQueue = [];
var _isDrainingMicrotaskQueue = false;
var _uncaughtPromiseErrors = [];
var _drainScheduled = false;
function scheduleQueueDrain() {
if (!_drainScheduled && !_currentTask && _microTaskQueue.length == 0) {
// We are not running in Task, so we need to kickstart the microtask queue.
if (global[symbolPromise]) {
global[symbolPromise].resolve(0)[symbolThen](drainMicroTaskQueue);
}
else {
global[symbolSetTimeout](drainMicroTaskQueue, 0);
}
}
}
function scheduleMicroTask(task) {
scheduleQueueDrain();
_microTaskQueue.push(task);
}
function consoleError(e) {
var rejection = e && e.rejection;
if (rejection) {
console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection);
}
console.error(e);
}
function drainMicroTaskQueue() {
if (!_isDrainingMicrotaskQueue) {
_isDrainingMicrotaskQueue = true;
while (_microTaskQueue.length) {
var queue = _microTaskQueue;
_microTaskQueue = [];
for (var i = 0; i < queue.length; i++) {
var task = queue[i];
try {
task.zone.runTask(task, null, null);
}
catch (e) {
consoleError(e);
}
}
}
while (_uncaughtPromiseErrors.length) {
var uncaughtPromiseErrors = _uncaughtPromiseErrors;
_uncaughtPromiseErrors = [];
var _loop_1 = function(i) {
var uncaughtPromiseError = uncaughtPromiseErrors[i];
try {
uncaughtPromiseError.zone.runGuarded(function () { throw uncaughtPromiseError; });
}
catch (e) {
consoleError(e);
}
};
for (var i = 0; i < uncaughtPromiseErrors.length; i++) {
_loop_1(i);
}
}
_isDrainingMicrotaskQueue = false;
_drainScheduled = false;
}
}
function isThenable(value) {
return value && value.then;
}
function forwardResolution(value) { return value; }
function forwardRejection(rejection) { return ZoneAwarePromise.reject(rejection); }
var symbolState = __symbol__('state');
var symbolValue = __symbol__('value');
var source = 'Promise.then';
var UNRESOLVED = null;
var RESOLVED = true;
var REJECTED = false;
var REJECTED_NO_CATCH = 0;
function makeResolver(promise, state) {
return function (v) {
resolvePromise(promise, state, v);
// Do not return value or you will break the Promise spec.
};
}
function resolvePromise(promise, state, value) {
if (promise[symbolState] === UNRESOLVED) {
if (value instanceof ZoneAwarePromise && value[symbolState] !== UNRESOLVED) {
clearRejectedNoCatch(value);
resolvePromise(promise, value[symbolState], value[symbolValue]);
}
else if (isThenable(value)) {
value.then(makeResolver(promise, state), makeResolver(promise, false));
}
else {
promise[symbolState] = state;
var queue = promise[symbolValue];
promise[symbolValue] = value;
for (var i = 0; i < queue.length;) {
scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
}
if (queue.length == 0 && state == REJECTED) {
promise[symbolState] = REJECTED_NO_CATCH;
try {
throw new Error("Uncaught (in promise): " + value);
}
catch (e) {
var error = e;
error.rejection = value;
error.promise = promise;
error.zone = Zone.current;
error.task = Zone.currentTask;
_uncaughtPromiseErrors.push(error);
scheduleQueueDrain();
}
}
}
}
// Resolving an already resolved promise is a noop.
return promise;
}
function clearRejectedNoCatch(promise) {
if (promise[symbolState] === REJECTED_NO_CATCH) {
promise[symbolState] = REJECTED;
for (var i = 0; i < _uncaughtPromiseErrors.length; i++) {
if (promise === _uncaughtPromiseErrors[i].promise) {
_uncaughtPromiseErrors.splice(i, 1);
break;
}
}
}
}
function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
clearRejectedNoCatch(promise);
var delegate = promise[symbolState] ? onFulfilled || forwardResolution : onRejected || forwardRejection;
zone.scheduleMicroTask(source, function () {
try {
resolvePromise(chainPromise, true, zone.run(delegate, null, [promise[symbolValue]]));
}
catch (error) {
resolvePromise(chainPromise, false, error);
}
});
}
var ZoneAwarePromise = (function () {
function ZoneAwarePromise(executor) {
var promise = this;
promise[symbolState] = UNRESOLVED;
promise[symbolValue] = []; // queue;
try {
executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED));
}
catch (e) {
resolvePromise(promise, false, e);
}
}
ZoneAwarePromise.resolve = function (value) {
return resolvePromise(new this(null), RESOLVED, value);
};
ZoneAwarePromise.reject = function (error) {
return resolvePromise(new this(null), REJECTED, error);
};
ZoneAwarePromise.race = function (values) {
var resolve;
var reject;
var promise = new this(function (res, rej) { resolve = res; reject = rej; });
function onResolve(value) { promise && (promise = null || resolve(value)); }
function onReject(error) { promise && (promise = null || reject(error)); }
for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
var value = values_1[_i];
if (!isThenable(value)) {
value = this.resolve(value);
}
value.then(onResolve, onReject);
}
return promise;
};
ZoneAwarePromise.all = function (values) {
var resolve;
var reject;
var promise = new this(function (res, rej) { resolve = res; reject = rej; });
var count = 0;
var resolvedValues = [];
function onReject(error) { promise && reject(error); promise = null; }
for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
var value = values_2[_i];
if (!isThenable(value)) {
value = this.resolve(value);
}
value.then((function (index) { return function (value) {
resolvedValues[index] = value;
count--;
if (promise && !count) {
resolve(resolvedValues);
}
promise == null;
}; })(count), onReject);
count++;
}
if (!count)
resolve(resolvedValues);
return promise;
};
ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {
var chainPromise = new ZoneAwarePromise(null);
var zone = Zone.current;
if (this[symbolState] == UNRESOLVED) {
this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
}
else {
scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
}
return chainPromise;
};
ZoneAwarePromise.prototype.catch = function (onRejected) {
return this.then(null, onRejected);
};
return ZoneAwarePromise;
}());
var NativePromise = global[__symbol__('Promise')] = global.Promise;
global.Promise = ZoneAwarePromise;
if (NativePromise) {
var NativePromiseProtototype = NativePromise.prototype;
var NativePromiseThen_1 = NativePromiseProtototype[__symbol__('then')]
= NativePromiseProtototype.then;
NativePromiseProtototype.then = function (onResolve, onReject) {
var nativePromise = this;
return new ZoneAwarePromise(function (resolve, reject) {
NativePromiseThen_1.call(nativePromise, resolve, reject);
}).then(onResolve, onReject);
};
}
return global.Zone = Zone;
})(typeof window === 'undefined' ? global : window);
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var utils_1 = __webpack_require__(3);
var WTF_ISSUE_555 = 'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video';
var NO_EVENT_TARGET = 'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex'.split(',');
var EVENT_TARGET = 'EventTarget';
function eventTargetPatch(_global) {
var apis = [];
var isWtf = _global['wtf'];
if (isWtf) {
// Workaround for: https://github.com/google/tracing-framework/issues/555
apis = WTF_ISSUE_555.split(',').map(function (v) { return 'HTML' + v + 'Element'; }).concat(NO_EVENT_TARGET);
}
else if (_global[EVENT_TARGET]) {
apis.push(EVENT_TARGET);
}
else {
// Note: EventTarget is not available in all browsers,
// if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget
apis = NO_EVENT_TARGET;
}
for (var i = 0; i < apis.length; i++) {
var type = _global[apis[i]];
utils_1.patchEventTargetMethods(type && type.prototype);
}
}
exports.eventTargetPatch = eventTargetPatch;
/***/ },
/* 3 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(global) {/**
* Suppress closure compiler errors about unknown 'process' variable
* @fileoverview
* @suppress {undefinedVars}
*/
"use strict";
exports.zoneSymbol = Zone['__symbol__'];
var _global = typeof window == 'undefined' ? global : window;
function bindArguments(args, source) {
for (var i = args.length - 1; i >= 0; i--) {
if (typeof args[i] === 'function') {
args[i] = Zone.current.wrap(args[i], source + '_' + i);
}
}
return args;
}
exports.bindArguments = bindArguments;
;
function patchPrototype(prototype, fnNames) {
var source = prototype.constructor['name'];
var _loop_1 = function(i) {
var name_1 = fnNames[i];
var delegate = prototype[name_1];
if (delegate) {
prototype[name_1] = (function (delegate) {
return function () {
return delegate.apply(this, bindArguments(arguments, source + '.' + name_1));
};
})(delegate);
}
};
for (var i = 0; i < fnNames.length; i++) {
_loop_1(i);
}
}
exports.patchPrototype = patchPrototype;
;
exports.isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);
exports.isNode = (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]');
exports.isBrowser = !exports.isNode && !exports.isWebWorker && !!(typeof window !== 'undefined' && window['HTMLElement']);
function patchProperty(obj, prop) {
var desc = Object.getOwnPropertyDescriptor(obj, prop) || {
enumerable: true,
configurable: true
};
// A property descriptor cannot have getter/setter and be writable
// deleting the writable and value properties avoids this error:
//
// TypeError: property descriptors must not specify a value or be writable when a
// getter or setter has been specified
delete desc.writable;
delete desc.value;
// substr(2) cuz 'onclick' -> 'click', etc
var eventName = prop.substr(2);
var _prop = '_' + prop;
desc.set = function (fn) {
if (this[_prop]) {
this.removeEventListener(eventName, this[_prop]);
}
if (typeof fn === 'function') {
var wrapFn = function (event) {
var result;
result = fn.apply(this, arguments);
if (result != undefined && !result)
event.preventDefault();
};
this[_prop] = wrapFn;
this.addEventListener(eventName, wrapFn, false);
}
else {
this[_prop] = null;
}
};
desc.get = function () {
return this[_prop];
};
Object.defineProperty(obj, prop, desc);
}
exports.patchProperty = patchProperty;
;
function patchOnProperties(obj, properties) {
var onProperties = [];
for (var prop in obj) {
if (prop.substr(0, 2) == 'on') {
onProperties.push(prop);
}
}
for (var j = 0; j < onProperties.length; j++) {
patchProperty(obj, onProperties[j]);
}
if (properties) {
for (var i = 0; i < properties.length; i++) {
patchProperty(obj, 'on' + properties[i]);
}
}
}
exports.patchOnProperties = patchOnProperties;
;
var EVENT_TASKS = exports.zoneSymbol('eventTasks');
var ADD_EVENT_LISTENER = 'addEventListener';
var REMOVE_EVENT_LISTENER = 'removeEventListener';
var SYMBOL_ADD_EVENT_LISTENER = exports.zoneSymbol(ADD_EVENT_LISTENER);
var SYMBOL_REMOVE_EVENT_LISTENER = exports.zoneSymbol(REMOVE_EVENT_LISTENER);
function findExistingRegisteredTask(target, handler, name, capture, remove) {
var eventTasks = target[EVENT_TASKS];
if (eventTasks) {
for (var i = 0; i < eventTasks.length; i++) {
var eventTask = eventTasks[i];
var data = eventTask.data;
if (data.handler === handler
&& data.useCapturing === capture
&& data.eventName === name) {
if (remove) {
eventTasks.splice(i, 1);
}
return eventTask;
}
}
}
return null;
}
function attachRegisteredEvent(target, eventTask) {
var eventTasks = target[EVENT_TASKS];
if (!eventTasks) {
eventTasks = target[EVENT_TASKS] = [];
}
eventTasks.push(eventTask);
}
function scheduleEventListener(eventTask) {
var meta = eventTask.data;
attachRegisteredEvent(meta.target, eventTask);
return meta.target[SYMBOL_ADD_EVENT_LISTENER](meta.eventName, eventTask.invoke, meta.useCapturing);
}
function cancelEventListener(eventTask) {
var meta = eventTask.data;
findExistingRegisteredTask(meta.target, eventTask.invoke, meta.eventName, meta.useCapturing, true);
meta.target[SYMBOL_REMOVE_EVENT_LISTENER](meta.eventName, eventTask.invoke, meta.useCapturing);
}
function zoneAwareAddEventListener(self, args) {
var eventName = args[0];
var handler = args[1];
var useCapturing = args[2] || false;
// - Inside a Web Worker, `this` is undefined, the context is `global`
// - When `addEventListener` is called on the global context in strict mode, `this` is undefined
// see https://github.com/angular/zone.js/issues/190
var target = self || _global;
var delegate = null;
if (typeof handler == 'function') {
delegate = handler;
}
else if (handler && handler.handleEvent) {
delegate = function (event) { return handler.handleEvent(event); };
}
var validZoneHandler = false;
try {
// In cross site contexts (such as WebDriver frameworks like Selenium),
// accessing the handler object here will cause an exception to be thrown which
// will fail tests prematurely.
validZoneHandler = handler && handler.toString() === "[object FunctionWrapper]";
}
catch (e) {
// Returning nothing here is fine, because objects in a cross-site context are unusable
return;
}
// Ignore special listeners of IE11 & Edge dev tools, see https://github.com/angular/zone.js/issues/150
if (!delegate || validZoneHandler) {
return target[SYMBOL_ADD_EVENT_LISTENER](eventName, handler, useCapturing);
}
var eventTask = findExistingRegisteredTask(target, handler, eventName, useCapturing, false);
if (eventTask) {
// we already registered, so this will have noop.
return target[SYMBOL_ADD_EVENT_LISTENER](eventName, eventTask.invoke, useCapturing);
}
var zone = Zone.current;
var source = target.constructor['name'] + '.addEventListener:' + eventName;
var data = {
target: target,
eventName: eventName,
name: eventName,
useCapturing: useCapturing,
handler: handler
};
zone.scheduleEventTask(source, delegate, data, scheduleEventListener, cancelEventListener);
}
function zoneAwareRemoveEventListener(self, args) {
var eventName = args[0];
var handler = args[1];
var useCapturing = args[2] || false;
// - Inside a Web Worker, `this` is undefined, the context is `global`
// - When `addEventListener` is called on the global context in strict mode, `this` is undefined
// see https://github.com/angular/zone.js/issues/190
var target = self || _global;
var eventTask = findExistingRegisteredTask(target, handler, eventName, useCapturing, true);
if (eventTask) {
eventTask.zone.cancelTask(eventTask);
}
else {
target[SYMBOL_REMOVE_EVENT_LISTENER](eventName, handler, useCapturing);
}
}
function patchEventTargetMethods(obj) {
if (obj && obj.addEventListener) {
patchMethod(obj, ADD_EVENT_LISTENER, function () { return zoneAwareAddEventListener; });
patchMethod(obj, REMOVE_EVENT_LISTENER, function () { return zoneAwareRemoveEventListener; });
return true;
}
else {
return false;
}
}
exports.patchEventTargetMethods = patchEventTargetMethods;
;
var originalInstanceKey = exports.zoneSymbol('originalInstance');
// wrap some native API on `window`
function patchClass(className) {
var OriginalClass = _global[className];
if (!OriginalClass)
return;
_global[className] = function () {
var a = bindArguments(arguments, className);
switch (a.length) {
case 0:
this[originalInstanceKey] = new OriginalClass();
break;
case 1:
this[originalInstanceKey] = new OriginalClass(a[0]);
break;
case 2:
this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
break;
case 3:
this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
break;
case 4:
this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
break;
default: throw new Error('Arg list too long.');
}
};
var instance = new OriginalClass(function () { });
var prop;
for (prop in instance) {
(function (prop) {
if (typeof instance[prop] === 'function') {
_global[className].prototype[prop] = function () {
return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
};
}
else {
Object.defineProperty(_global[className].prototype, prop, {
set: function (fn) {
if (typeof fn === 'function') {
this[originalInstanceKey][prop] = Zone.current.wrap(fn, className + '.' + prop);
}
else {
this[originalInstanceKey][prop] = fn;
}
},
get: function () {
return this[originalInstanceKey][prop];
}
});
}
}(prop));
}
for (prop in OriginalClass) {
if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
_global[className][prop] = OriginalClass[prop];
}
}
}
exports.patchClass = patchClass;
;
function createNamedFn(name, delegate) {
try {
return (Function('f', "return function " + name + "(){return f(this, arguments)}"))(delegate);
}
catch (e) {
// if we fail, we must be CSP, just return delegate.
return function () {
return delegate(this, arguments);
};
}
}
exports.createNamedFn = createNamedFn;
function patchMethod(target, name, patchFn) {
var proto = target;
while (proto && !proto.hasOwnProperty(name)) {
proto = Object.getPrototypeOf(proto);
}
if (!proto && target[name]) {
// somehow we did not find it, but we can see it. This happens on IE for Window properties.
proto = target;
}
var delegateName = exports.zoneSymbol(name);
var delegate;
if (proto && !(delegate = proto[delegateName])) {
delegate = proto[delegateName] = proto[name];
proto[name] = createNamedFn(name, patchFn(delegate, delegateName, name));
}
return delegate;
}
exports.patchMethod = patchMethod;
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var utils_1 = __webpack_require__(3);
/*
* This is necessary for Chrome and Chrome mobile, to enable
* things like redefining `createdCallback` on an element.
*/
var _defineProperty = Object.defineProperty;
var _getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var _create = Object.create;
var unconfigurablesKey = utils_1.zoneSymbol('unconfigurables');
function propertyPatch() {
Object.defineProperty = function (obj, prop, desc) {
if (isUnconfigurable(obj, prop)) {
throw new TypeError('Cannot assign to read only property \'' + prop + '\' of ' + obj);
}
if (prop !== 'prototype') {
desc = rewriteDescriptor(obj, prop, desc);
}
return _defineProperty(obj, prop, desc);
};
Object.defineProperties = function (obj, props) {
Object.keys(props).forEach(function (prop) {
Object.defineProperty(obj, prop, props[prop]);
});
return obj;
};
Object.create = function (obj, proto) {
if (typeof proto === 'object') {
Object.keys(proto).forEach(function (prop) {
proto[prop] = rewriteDescriptor(obj, prop, proto[prop]);
});
}
return _create(obj, proto);
};
Object.getOwnPropertyDescriptor = function (obj, prop) {
var desc = _getOwnPropertyDescriptor(obj, prop);
if (isUnconfigurable(obj, prop)) {
desc.configurable = false;
}
return desc;
};
}
exports.propertyPatch = propertyPatch;
;
function _redefineProperty(obj, prop, desc) {
desc = rewriteDescriptor(obj, prop, desc);
return _defineProperty(obj, prop, desc);
}
exports._redefineProperty = _redefineProperty;
;
function isUnconfigurable(obj, prop) {
return obj && obj[unconfigurablesKey] && obj[unconfigurablesKey][prop];
}
function rewriteDescriptor(obj, prop, desc) {
desc.configurable = true;
if (!desc.configurable) {
if (!obj[unconfigurablesKey]) {
_defineProperty(obj, unconfigurablesKey, { writable: true, value: {} });
}
obj[unconfigurablesKey][prop] = true;
}
return desc;
}
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var define_property_1 = __webpack_require__(4);
var utils_1 = __webpack_require__(3);
function registerElementPatch(_global) {
if (!utils_1.isBrowser || !('registerElement' in _global.document)) {
return;
}
var _registerElement = document.registerElement;
var callbacks = [
'createdCallback',
'attachedCallback',
'detachedCallback',
'attributeChangedCallback'
];
document.registerElement = function (name, opts) {
if (opts && opts.prototype) {
callbacks.forEach(function (callback) {
var source = 'Document.registerElement::' + callback;
if (opts.prototype.hasOwnProperty(callback)) {
var descriptor = Object.getOwnPropertyDescriptor(opts.prototype, callback);
if (descriptor && descriptor.value) {
descriptor.value = Zone.current.wrap(descriptor.value, source);
define_property_1._redefineProperty(opts.prototype, callback, descriptor);
}
else {
opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source);
}
}
else if (opts.prototype[callback]) {
opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source);
}
});
}
return _registerElement.apply(document, [name, opts]);
};
}
exports.registerElementPatch = registerElementPatch;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var webSocketPatch = __webpack_require__(7);
var utils_1 = __webpack_require__(3);
var eventNames = 'copy cut paste abort blur focus canplay canplaythrough change click contextmenu dblclick drag dragend dragenter dragleave dragover dragstart drop durationchange emptied ended input invalid keydown keypress keyup load loadeddata loadedmetadata loadstart message mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup pause play playing progress ratechange reset scroll seeked seeking select show stalled submit suspend timeupdate volumechange waiting mozfullscreenchange mozfullscreenerror mozpointerlockchange mozpointerlockerror error webglcontextrestored webglcontextlost webglcontextcreationerror'.split(' ');
function propertyDescriptorPatch(_global) {
if (utils_1.isNode) {
return;
}
var supportsWebSocket = typeof WebSocket !== 'undefined';
if (canPatchViaPropertyDescriptor()) {
// for browsers that we can patch the descriptor: Chrome & Firefox
if (utils_1.isBrowser) {
utils_1.patchOnProperties(HTMLElement.prototype, eventNames);
}
utils_1.patchOnProperties(XMLHttpRequest.prototype, null);
if (typeof IDBIndex !== 'undefined') {
utils_1.patchOnProperties(IDBIndex.prototype, null);
utils_1.patchOnProperties(IDBRequest.prototype, null);
utils_1.patchOnProperties(IDBOpenDBRequest.prototype, null);
utils_1.patchOnProperties(IDBDatabase.prototype, null);
utils_1.patchOnProperties(IDBTransaction.prototype, null);
utils_1.patchOnProperties(IDBCursor.prototype, null);
}
if (supportsWebSocket) {
utils_1.patchOnProperties(WebSocket.prototype, null);
}
}
else {
// Safari, Android browsers (Jelly Bean)
patchViaCapturingAllTheEvents();
utils_1.patchClass('XMLHttpRequest');
if (supportsWebSocket) {
webSocketPatch.apply(_global);
}
}
}
exports.propertyDescriptorPatch = propertyDescriptorPatch;
function canPatchViaPropertyDescriptor() {
if (utils_1.isBrowser && !Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onclick')
&& typeof Element !== 'undefined') {
// WebKit https://bugs.webkit.org/show_bug.cgi?id=134364
// IDL interface attributes are not configurable
var desc = Object.getOwnPropertyDescriptor(Element.prototype, 'onclick');
if (desc && !desc.configurable)
return false;
}
Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {
get: function () {
return true;
}
});
var req = new XMLHttpRequest();
var result = !!req.onreadystatechange;
Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {});
return result;
}
;
var unboundKey = utils_1.zoneSymbol('unbound');
// Whenever any eventListener fires, we check the eventListener target and all parents
// for `onwhatever` properties and replace them with zone-bound functions
// - Chrome (for now)
function patchViaCapturingAllTheEvents() {
var _loop_1 = function(i) {
var property = eventNames[i];
var onproperty = 'on' + property;
document.addEventListener(property, function (event) {
var elt = event.target, bound, source;
if (elt) {
source = elt.constructor['name'] + '.' + onproperty;
}
else {
source = 'unknown.' + onproperty;
}
while (elt) {
if (elt[onproperty] && !elt[onproperty][unboundKey]) {
bound = Zone.current.wrap(elt[onproperty], source);
bound[unboundKey] = elt[onproperty];
elt[onproperty] = bound;
}
elt = elt.parentElement;
}
}, true);
};
for (var i = 0; i < eventNames.length; i++) {
_loop_1(i);
}
;
}
;
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var utils_1 = __webpack_require__(3);
// we have to patch the instance since the proto is non-configurable
function apply(_global) {
var WS = _global.WebSocket;
// On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener
// On older Chrome, no need since EventTarget was already patched
if (!_global.EventTarget) {
utils_1.patchEventTargetMethods(WS.prototype);
}
_global.WebSocket = function (a, b) {
var socket = arguments.length > 1 ? new WS(a, b) : new WS(a);
var proxySocket;
// Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance
var onmessageDesc = Object.getOwnPropertyDescriptor(socket, 'onmessage');
if (onmessageDesc && onmessageDesc.configurable === false) {
proxySocket = Object.create(socket);
['addEventListener', 'removeEventListener', 'send', 'close'].forEach(function (propName) {
proxySocket[propName] = function () {
return socket[propName].apply(socket, arguments);
};
});
}
else {
// we can patch the real socket
proxySocket = socket;
}
utils_1.patchOnProperties(proxySocket, ['close', 'error', 'message', 'open']);
return proxySocket;
};
for (var prop in WS) {
_global.WebSocket[prop] = WS[prop];
}
}
exports.apply = apply;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var utils_1 = __webpack_require__(3);
function patchTimer(window, setName, cancelName, nameSuffix) {
var setNative = null;
var clearNative = null;
setName += nameSuffix;
cancelName += nameSuffix;
function scheduleTask(task) {
var data = task.data;
data.args[0] = task.invoke;
data.handleId = setNative.apply(window, data.args);
return task;
}
function clearTask(task) {
return clearNative(task.data.handleId);
}
setNative = utils_1.patchMethod(window, setName, function (delegate) { return function (self, args) {
if (typeof args[0] === 'function') {
var zone = Zone.current;
var options = {
handleId: null,
isPeriodic: nameSuffix === 'Interval',
delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 : null,
args: args
};
return zone.scheduleMacroTask(setName, args[0], options, scheduleTask, clearTask);
}
else {
// cause an error by calling it directly.
return delegate.apply(window, args);
}
}; });
clearNative = utils_1.patchMethod(window, cancelName, function (delegate) { return function (self, args) {
var task = args[0];
if (task && typeof task.type === 'string') {
if (task.cancelFn && task.data.isPeriodic || task.runCount === 0) {
// Do not cancel already canceled functions
task.zone.cancelTask(task);
}
}
else {
// cause an error by calling it directly.
delegate.apply(window, args);
}
}; });
}
exports.patchTimer = patchTimer;
/***/ }
/******/ ]);
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {
'use strict';
(function () {
var NEWLINE = '\n';
var SEP = ' ------------- ';
var IGNORE_FRAMES = [];
var creationTrace = '__creationTrace__';
var LongStackTrace = (function () {
function LongStackTrace() {
this.error = getStacktrace();
this.timestamp = new Date();
}
return LongStackTrace;
}());
function getStacktraceWithUncaughtError() {
return new Error('STACKTRACE TRACKING');
}
function getStacktraceWithCaughtError() {
try {
throw getStacktraceWithUncaughtError();
}
catch (e) {
return e;
}
}
// Some implementations of exception handling don't create a stack trace if the exception
// isn't thrown, however it's faster not to actually throw the exception.
var error = getStacktraceWithUncaughtError();
var coughtError = getStacktraceWithCaughtError();
var getStacktrace = error.stack
? getStacktraceWithUncaughtError
: (coughtError.stack ? getStacktraceWithCaughtError : getStacktraceWithUncaughtError);
function getFrames(error) {
return error.stack ? error.stack.split(NEWLINE) : [];
}
function addErrorStack(lines, error) {
var trace = getFrames(error);
for (var i = 0; i < trace.length; i++) {
var frame = trace[i];
// Filter out the Frames which are part of stack capturing.
if (!(i < IGNORE_FRAMES.length && IGNORE_FRAMES[i] === frame)) {
lines.push(trace[i]);
}
}
}
function renderLongStackTrace(frames, stack) {
var longTrace = [stack];
if (frames) {
var timestamp = new Date().getTime();
for (var i = 0; i < frames.length; i++) {
var traceFrames = frames[i];
var lastTime = traceFrames.timestamp;
longTrace.push(SEP + " Elapsed: " + (timestamp - lastTime.getTime()) + " ms; At: " + lastTime + " " + SEP);
addErrorStack(longTrace, traceFrames.error);
timestamp = lastTime.getTime();
}
}
return longTrace.join(NEWLINE);
}
Zone['longStackTraceZoneSpec'] = {
name: 'long-stack-trace',
longStackTraceLimit: 10,
onScheduleTask: function (parentZoneDelegate, currentZone, targetZone, task) {
var currentTask = Zone.currentTask;
var trace = currentTask && currentTask.data && currentTask.data[creationTrace] || [];
trace = [new LongStackTrace()].concat(trace);
if (trace.length > this.longStackTraceLimit) {
trace.length = this.longStackTraceLimit;
}
if (!task.data)
task.data = {};
task.data[creationTrace] = trace;
return parentZoneDelegate.scheduleTask(targetZone, task);
},
onHandleError: function (parentZoneDelegate, currentZone, targetZone, error) {
var parentTask = Zone.currentTask;
if (error instanceof Error && parentTask) {
var descriptor = Object.getOwnPropertyDescriptor(error, 'stack');
if (descriptor) {
var delegateGet_1 = descriptor.get;
var value_1 = descriptor.value;
descriptor = {
get: function () {
return renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], delegateGet_1 ? delegateGet_1.apply(this) : value_1);
}
};
Object.defineProperty(error, 'stack', descriptor);
}
else {
error.stack = renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], error.stack);
}
}
return parentZoneDelegate.handleError(targetZone, error);
}
};
function captureStackTraces(stackTraces, count) {
if (count > 0) {
stackTraces.push(getFrames((new LongStackTrace()).error));
captureStackTraces(stackTraces, count - 1);
}
}
function computeIgnoreFrames() {
var frames = [];
captureStackTraces(frames, 2);
var frames1 = frames[0];
var frames2 = frames[1];
for (var i = 0; i < frames1.length; i++) {
var frame1 = frames1[i];
var frame2 = frames2[i];
if (frame1 === frame2) {
IGNORE_FRAMES.push(frame1);
}
else {
break;
}
}
}
computeIgnoreFrames();
})();
/***/ }
/******/ ]);
/**
@license
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
*/
/*! *****************************************************************************
Copyright (C) Microsoft. 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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
"use strict";
var Reflect;
(function (Reflect) {
// Load global or shim versions of Map, Set, and WeakMap
var functionPrototype = Object.getPrototypeOf(Function);
var _Map = typeof Map === "function" ? Map : CreateMapPolyfill();
var _Set = typeof Set === "function" ? Set : CreateSetPolyfill();
var _WeakMap = typeof WeakMap === "function" ? WeakMap : CreateWeakMapPolyfill();
// [[Metadata]] internal slot
var __Metadata__ = new _WeakMap();
/**
* Applies a set of decorators to a property of a target object.
* @param decorators An array of decorators.
* @param target The target object.
* @param targetKey (Optional) The property key to decorate.
* @param targetDescriptor (Optional) The property descriptor for the target key
* @remarks Decorators are applied in reverse order.
* @example
*
* class C {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* C = Reflect.decorate(decoratorsArray, C);
*
* // property (on constructor)
* Reflect.decorate(decoratorsArray, C, "staticProperty");
*
* // property (on prototype)
* Reflect.decorate(decoratorsArray, C.prototype, "property");
*
* // method (on constructor)
* Object.defineProperty(C, "staticMethod",
* Reflect.decorate(decoratorsArray, C, "staticMethod",
* Object.getOwnPropertyDescriptor(C, "staticMethod")));
*
* // method (on prototype)
* Object.defineProperty(C.prototype, "method",
* Reflect.decorate(decoratorsArray, C.prototype, "method",
* Object.getOwnPropertyDescriptor(C.prototype, "method")));
*
*/
function decorate(decorators, target, targetKey, targetDescriptor) {
if (!IsUndefined(targetDescriptor)) {
if (!IsArray(decorators)) {
throw new TypeError();
}
else if (!IsObject(target)) {
throw new TypeError();
}
else if (IsUndefined(targetKey)) {
throw new TypeError();
}
else if (!IsObject(targetDescriptor)) {
throw new TypeError();
}
targetKey = ToPropertyKey(targetKey);
return DecoratePropertyWithDescriptor(decorators, target, targetKey, targetDescriptor);
}
else if (!IsUndefined(targetKey)) {
if (!IsArray(decorators)) {
throw new TypeError();
}
else if (!IsObject(target)) {
throw new TypeError();
}
targetKey = ToPropertyKey(targetKey);
return DecoratePropertyWithoutDescriptor(decorators, target, targetKey);
}
else {
if (!IsArray(decorators)) {
throw new TypeError();
}
else if (!IsConstructor(target)) {
throw new TypeError();
}
return DecorateConstructor(decorators, target);
}
}
Reflect.decorate = decorate;
/**
* A default metadata decorator factory that can be used on a class, class member, or parameter.
* @param metadataKey The key for the metadata entry.
* @param metadataValue The value for the metadata entry.
* @returns A decorator function.
* @remarks
* If `metadataKey` is already defined for the target and target key, the
* metadataValue for that key will be overwritten.
* @example
*
* // constructor
* @Reflect.metadata(key, value)
* class C {
* }
*
* // property (on constructor, TypeScript only)
* class C {
* @Reflect.metadata(key, value)
* static staticProperty;
* }
*
* // property (on prototype, TypeScript only)
* class C {
* @Reflect.metadata(key, value)
* property;
* }
*
* // method (on constructor)
* class C {
* @Reflect.metadata(key, value)
* static staticMethod() { }
* }
*
* // method (on prototype)
* class C {
* @Reflect.metadata(key, value)
* method() { }
* }
*
*/
function metadata(metadataKey, metadataValue) {
function decorator(target, targetKey) {
if (!IsUndefined(targetKey)) {
if (!IsObject(target)) {
throw new TypeError();
}
targetKey = ToPropertyKey(targetKey);
OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, targetKey);
}
else {
if (!IsConstructor(target)) {
throw new TypeError();
}
OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, undefined);
}
}
return decorator;
}
Reflect.metadata = metadata;
/**
* Define a unique metadata entry on the target.
* @param metadataKey A key used to store and retrieve metadata.
* @param metadataValue A value that contains attached metadata.
* @param target The target object on which to define metadata.
* @param targetKey (Optional) The property key for the target.
* @example
*
* class C {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* Reflect.defineMetadata("custom:annotation", options, C);
*
* // property (on constructor)
* Reflect.defineMetadata("custom:annotation", options, C, "staticProperty");
*
* // property (on prototype)
* Reflect.defineMetadata("custom:annotation", options, C.prototype, "property");
*
* // method (on constructor)
* Reflect.defineMetadata("custom:annotation", options, C, "staticMethod");
*
* // method (on prototype)
* Reflect.defineMetadata("custom:annotation", options, C.prototype, "method");
*
* // decorator factory as metadata-producing annotation.
* function MyAnnotation(options): Decorator {
* return (target, key?) => Reflect.defineMetadata("custom:annotation", options, target, key);
* }
*
*/
function defineMetadata(metadataKey, metadataValue, target, targetKey) {
if (!IsObject(target)) {
throw new TypeError();
}
else if (!IsUndefined(targetKey)) {
targetKey = ToPropertyKey(targetKey);
}
return OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, targetKey);
}
Reflect.defineMetadata = defineMetadata;
/**
* Gets a value indicating whether the target object or its prototype chain has the provided metadata key defined.
* @param metadataKey A key used to store and retrieve metadata.
* @param target The target object on which the metadata is defined.
* @param targetKey (Optional) The property key for the target.
* @returns `true` if the metadata key was defined on the target object or its prototype chain; otherwise, `false`.
* @example
*
* class C {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* result = Reflect.hasMetadata("custom:annotation", C);
*
* // property (on constructor)
* result = Reflect.hasMetadata("custom:annotation", C, "staticProperty");
*
* // property (on prototype)
* result = Reflect.hasMetadata("custom:annotation", C.prototype, "property");
*
* // method (on constructor)
* result = Reflect.hasMetadata("custom:annotation", C, "staticMethod");
*
* // method (on prototype)
* result = Reflect.hasMetadata("custom:annotation", C.prototype, "method");
*
*/
function hasMetadata(metadataKey, target, targetKey) {
if (!IsObject(target)) {
throw new TypeError();
}
else if (!IsUndefined(targetKey)) {
targetKey = ToPropertyKey(targetKey);
}
return OrdinaryHasMetadata(metadataKey, target, targetKey);
}
Reflect.hasMetadata = hasMetadata;
/**
* Gets a value indicating whether the target object has the provided metadata key defined.
* @param metadataKey A key used to store and retrieve metadata.
* @param target The target object on which the metadata is defined.
* @param targetKey (Optional) The property key for the target.
* @returns `true` if the metadata key was defined on the target object; otherwise, `false`.
* @example
*
* class C {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* result = Reflect.hasOwnMetadata("custom:annotation", C);
*
* // property (on constructor)
* result = Reflect.hasOwnMetadata("custom:annotation", C, "staticProperty");
*
* // property (on prototype)
* result = Reflect.hasOwnMetadata("custom:annotation", C.prototype, "property");
*
* // method (on constructor)
* result = Reflect.hasOwnMetadata("custom:annotation", C, "staticMethod");
*
* // method (on prototype)
* result = Reflect.hasOwnMetadata("custom:annotation", C.prototype, "method");
*
*/
function hasOwnMetadata(metadataKey, target, targetKey) {
if (!IsObject(target)) {
throw new TypeError();
}
else if (!IsUndefined(targetKey)) {
targetKey = ToPropertyKey(targetKey);
}
return OrdinaryHasOwnMetadata(metadataKey, target, targetKey);
}
Reflect.hasOwnMetadata = hasOwnMetadata;
/**
* Gets the metadata value for the provided metadata key on the target object or its prototype chain.
* @param metadataKey A key used to store and retrieve metadata.
* @param target The target object on which the metadata is defined.
* @param targetKey (Optional) The property key for the target.
* @returns The metadata value for the metadata key if found; otherwise, `undefined`.
* @example
*
* class C {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* result = Reflect.getMetadata("custom:annotation", C);
*
* // property (on constructor)
* result = Reflect.getMetadata("custom:annotation", C, "staticProperty");
*
* // property (on prototype)
* result = Reflect.getMetadata("custom:annotation", C.prototype, "property");
*
* // method (on constructor)
* result = Reflect.getMetadata("custom:annotation", C, "staticMethod");
*
* // method (on prototype)
* result = Reflect.getMetadata("custom:annotation", C.prototype, "method");
*
*/
function getMetadata(metadataKey, target, targetKey) {
if (!IsObject(target)) {
throw new TypeError();
}
else if (!IsUndefined(targetKey)) {
targetKey = ToPropertyKey(targetKey);
}
return OrdinaryGetMetadata(metadataKey, target, targetKey);
}
Reflect.getMetadata = getMetadata;
/**
* Gets the metadata value for the provided metadata key on the target object.
* @param metadataKey A key used to store and retrieve metadata.
* @param target The target object on which the metadata is defined.
* @param targetKey (Optional) The property key for the target.
* @returns The metadata value for the metadata key if found; otherwise, `undefined`.
* @example
*
* class C {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* result = Reflect.getOwnMetadata("custom:annotation", C);
*
* // property (on constructor)
* result = Reflect.getOwnMetadata("custom:annotation", C, "staticProperty");
*
* // property (on prototype)
* result = Reflect.getOwnMetadata("custom:annotation", C.prototype, "property");
*
* // method (on constructor)
* result = Reflect.getOwnMetadata("custom:annotation", C, "staticMethod");
*
* // method (on prototype)
* result = Reflect.getOwnMetadata("custom:annotation", C.prototype, "method");
*
*/
function getOwnMetadata(metadataKey, target, targetKey) {
if (!IsObject(target)) {
throw new TypeError();
}
else if (!IsUndefined(targetKey)) {
targetKey = ToPropertyKey(targetKey);
}
return OrdinaryGetOwnMetadata(metadataKey, target, targetKey);
}
Reflect.getOwnMetadata = getOwnMetadata;
/**
* Gets the metadata keys defined on the target object or its prototype chain.
* @param target The target object on which the metadata is defined.
* @param targetKey (Optional) The property key for the target.
* @returns An array of unique metadata keys.
* @example
*
* class C {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* result = Reflect.getMetadataKeys(C);
*
* // property (on constructor)
* result = Reflect.getMetadataKeys(C, "staticProperty");
*
* // property (on prototype)
* result = Reflect.getMetadataKeys(C.prototype, "property");
*
* // method (on constructor)
* result = Reflect.getMetadataKeys(C, "staticMethod");
*
* // method (on prototype)
* result = Reflect.getMetadataKeys(C.prototype, "method");
*
*/
function getMetadataKeys(target, targetKey) {
if (!IsObject(target)) {
throw new TypeError();
}
else if (!IsUndefined(targetKey)) {
targetKey = ToPropertyKey(targetKey);
}
return OrdinaryMetadataKeys(target, targetKey);
}
Reflect.getMetadataKeys = getMetadataKeys;
/**
* Gets the unique metadata keys defined on the target object.
* @param target The target object on which the metadata is defined.
* @param targetKey (Optional) The property key for the target.
* @returns An array of unique metadata keys.
* @example
*
* class C {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* result = Reflect.getOwnMetadataKeys(C);
*
* // property (on constructor)
* result = Reflect.getOwnMetadataKeys(C, "staticProperty");
*
* // property (on prototype)
* result = Reflect.getOwnMetadataKeys(C.prototype, "property");
*
* // method (on constructor)
* result = Reflect.getOwnMetadataKeys(C, "staticMethod");
*
* // method (on prototype)
* result = Reflect.getOwnMetadataKeys(C.prototype, "method");
*
*/
function getOwnMetadataKeys(target, targetKey) {
if (!IsObject(target)) {
throw new TypeError();
}
else if (!IsUndefined(targetKey)) {
targetKey = ToPropertyKey(targetKey);
}
return OrdinaryOwnMetadataKeys(target, targetKey);
}
Reflect.getOwnMetadataKeys = getOwnMetadataKeys;
/**
* Deletes the metadata entry from the target object with the provided key.
* @param metadataKey A key used to store and retrieve metadata.
* @param target The target object on which the metadata is defined.
* @param targetKey (Optional) The property key for the target.
* @returns `true` if the metadata entry was found and deleted; otherwise, false.
* @example
*
* class C {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* result = Reflect.deleteMetadata("custom:annotation", C);
*
* // property (on constructor)
* result = Reflect.deleteMetadata("custom:annotation", C, "staticProperty");
*
* // property (on prototype)
* result = Reflect.deleteMetadata("custom:annotation", C.prototype, "property");
*
* // method (on constructor)
* result = Reflect.deleteMetadata("custom:annotation", C, "staticMethod");
*
* // method (on prototype)
* result = Reflect.deleteMetadata("custom:annotation", C.prototype, "method");
*
*/
function deleteMetadata(metadataKey, target, targetKey) {
if (!IsObject(target)) {
throw new TypeError();
}
else if (!IsUndefined(targetKey)) {
targetKey = ToPropertyKey(targetKey);
}
// https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#deletemetadata-metadatakey-p-
var metadataMap = GetOrCreateMetadataMap(target, targetKey, false);
if (IsUndefined(metadataMap)) {
return false;
}
if (!metadataMap.delete(metadataKey)) {
return false;
}
if (metadataMap.size > 0) {
return true;
}
var targetMetadata = __Metadata__.get(target);
targetMetadata.delete(targetKey);
if (targetMetadata.size > 0) {
return true;
}
__Metadata__.delete(target);
return true;
}
Reflect.deleteMetadata = deleteMetadata;
function DecorateConstructor(decorators, target) {
for (var i = decorators.length - 1; i >= 0; --i) {
var decorator = decorators[i];
var decorated = decorator(target);
if (!IsUndefined(decorated)) {
if (!IsConstructor(decorated)) {
throw new TypeError();
}
target = decorated;
}
}
return target;
}
function DecoratePropertyWithDescriptor(decorators, target, propertyKey, descriptor) {
for (var i = decorators.length - 1; i >= 0; --i) {
var decorator = decorators[i];
var decorated = decorator(target, propertyKey, descriptor);
if (!IsUndefined(decorated)) {
if (!IsObject(decorated)) {
throw new TypeError();
}
descriptor = decorated;
}
}
return descriptor;
}
function DecoratePropertyWithoutDescriptor(decorators, target, propertyKey) {
for (var i = decorators.length - 1; i >= 0; --i) {
var decorator = decorators[i];
decorator(target, propertyKey);
}
}
// https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#getorcreatemetadatamap--o-p-create-
function GetOrCreateMetadataMap(target, targetKey, create) {
var targetMetadata = __Metadata__.get(target);
if (!targetMetadata) {
if (!create) {
return undefined;
}
targetMetadata = new _Map();
__Metadata__.set(target, targetMetadata);
}
var keyMetadata = targetMetadata.get(targetKey);
if (!keyMetadata) {
if (!create) {
return undefined;
}
keyMetadata = new _Map();
targetMetadata.set(targetKey, keyMetadata);
}
return keyMetadata;
}
// https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#ordinaryhasmetadata--metadatakey-o-p-
function OrdinaryHasMetadata(MetadataKey, O, P) {
var hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P);
if (hasOwn) {
return true;
}
var parent = GetPrototypeOf(O);
if (parent !== null) {
return OrdinaryHasMetadata(MetadataKey, parent, P);
}
return false;
}
// https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#ordinaryhasownmetadata--metadatakey-o-p-
function OrdinaryHasOwnMetadata(MetadataKey, O, P) {
var metadataMap = GetOrCreateMetadataMap(O, P, false);
if (metadataMap === undefined) {
return false;
}
return Boolean(metadataMap.has(MetadataKey));
}
// https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#ordinarygetmetadata--metadatakey-o-p-
function OrdinaryGetMetadata(MetadataKey, O, P) {
var hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P);
if (hasOwn) {
return OrdinaryGetOwnMetadata(MetadataKey, O, P);
}
var parent = GetPrototypeOf(O);
if (parent !== null) {
return OrdinaryGetMetadata(MetadataKey, parent, P);
}
return undefined;
}
// https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#ordinarygetownmetadata--metadatakey-o-p-
function OrdinaryGetOwnMetadata(MetadataKey, O, P) {
var metadataMap = GetOrCreateMetadataMap(O, P, false);
if (metadataMap === undefined) {
return undefined;
}
return metadataMap.get(MetadataKey);
}
// https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#ordinarydefineownmetadata--metadatakey-metadatavalue-o-p-
function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) {
var metadataMap = GetOrCreateMetadataMap(O, P, true);
metadataMap.set(MetadataKey, MetadataValue);
}
// https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#ordinarymetadatakeys--o-p-
function OrdinaryMetadataKeys(O, P) {
var ownKeys = OrdinaryOwnMetadataKeys(O, P);
var parent = GetPrototypeOf(O);
if (parent === null) {
return ownKeys;
}
var parentKeys = OrdinaryMetadataKeys(parent, P);
if (parentKeys.length <= 0) {
return ownKeys;
}
if (ownKeys.length <= 0) {
return parentKeys;
}
var set = new _Set();
var keys = [];
for (var _i = 0; _i < ownKeys.length; _i++) {
var key = ownKeys[_i];
var hasKey = set.has(key);
if (!hasKey) {
set.add(key);
keys.push(key);
}
}
for (var _a = 0; _a < parentKeys.length; _a++) {
var key = parentKeys[_a];
var hasKey = set.has(key);
if (!hasKey) {
set.add(key);
keys.push(key);
}
}
return keys;
}
// https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#ordinaryownmetadatakeys--o-p-
function OrdinaryOwnMetadataKeys(target, targetKey) {
var metadataMap = GetOrCreateMetadataMap(target, targetKey, false);
var keys = [];
if (metadataMap) {
metadataMap.forEach(function (_, key) { return keys.push(key); });
}
return keys;
}
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-ecmascript-language-types-undefined-type
function IsUndefined(x) {
return x === undefined;
}
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isarray
function IsArray(x) {
return Array.isArray(x);
}
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object-type
function IsObject(x) {
return typeof x === "object" ? x !== null : typeof x === "function";
}
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isconstructor
function IsConstructor(x) {
return typeof x === "function";
}
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-ecmascript-language-types-symbol-type
function IsSymbol(x) {
return typeof x === "symbol";
}
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-topropertykey
function ToPropertyKey(value) {
if (IsSymbol(value)) {
return value;
}
return String(value);
}
function GetPrototypeOf(O) {
var proto = Object.getPrototypeOf(O);
if (typeof O !== "function" || O === functionPrototype) {
return proto;
}
// TypeScript doesn't set __proto__ in ES5, as it's non-standard.
// Try to determine the superclass constructor. Compatible implementations
// must either set __proto__ on a subclass constructor to the superclass constructor,
// or ensure each class has a valid `constructor` property on its prototype that
// points back to the constructor.
// If this is not the same as Function.[[Prototype]], then this is definately inherited.
// This is the case when in ES6 or when using __proto__ in a compatible browser.
if (proto !== functionPrototype) {
return proto;
}
// If the super prototype is Object.prototype, null, or undefined, then we cannot determine the heritage.
var prototype = O.prototype;
var prototypeProto = Object.getPrototypeOf(prototype);
if (prototypeProto == null || prototypeProto === Object.prototype) {
return proto;
}
// if the constructor was not a function, then we cannot determine the heritage.
var constructor = prototypeProto.constructor;
if (typeof constructor !== "function") {
return proto;
}
// if we have some kind of self-reference, then we cannot determine the heritage.
if (constructor === O) {
return proto;
}
// we have a pretty good guess at the heritage.
return constructor;
}
// naive Map shim
function CreateMapPolyfill() {
var cacheSentinel = {};
function Map() {
this._keys = [];
this._values = [];
this._cache = cacheSentinel;
}
Map.prototype = {
get size() {
return this._keys.length;
},
has: function (key) {
if (key === this._cache) {
return true;
}
if (this._find(key) >= 0) {
this._cache = key;
return true;
}
return false;
},
get: function (key) {
var index = this._find(key);
if (index >= 0) {
this._cache = key;
return this._values[index];
}
return undefined;
},
set: function (key, value) {
this.delete(key);
this._keys.push(key);
this._values.push(value);
this._cache = key;
return this;
},
delete: function (key) {
var index = this._find(key);
if (index >= 0) {
this._keys.splice(index, 1);
this._values.splice(index, 1);
this._cache = cacheSentinel;
return true;
}
return false;
},
clear: function () {
this._keys.length = 0;
this._values.length = 0;
this._cache = cacheSentinel;
},
forEach: function (callback, thisArg) {
var size = this.size;
for (var i = 0; i < size; ++i) {
var key = this._keys[i];
var value = this._values[i];
this._cache = key;
callback.call(this, value, key, this);
}
},
_find: function (key) {
var keys = this._keys;
var size = keys.length;
for (var i = 0; i < size; ++i) {
if (keys[i] === key) {
return i;
}
}
return -1;
}
};
return Map;
}
// naive Set shim
function CreateSetPolyfill() {
var cacheSentinel = {};
function Set() {
this._map = new _Map();
}
Set.prototype = {
get size() {
return this._map.length;
},
has: function (value) {
return this._map.has(value);
},
add: function (value) {
this._map.set(value, value);
return this;
},
delete: function (value) {
return this._map.delete(value);
},
clear: function () {
this._map.clear();
},
forEach: function (callback, thisArg) {
this._map.forEach(callback, thisArg);
}
};
return Set;
}
// naive WeakMap shim
function CreateWeakMapPolyfill() {
var UUID_SIZE = 16;
var isNode = typeof global !== "undefined" && Object.prototype.toString.call(global.process) === '[object process]';
var nodeCrypto = isNode && require("crypto");
var hasOwn = Object.prototype.hasOwnProperty;
var keys = {};
var rootKey = CreateUniqueKey();
function WeakMap() {
this._key = CreateUniqueKey();
}
WeakMap.prototype = {
has: function (target) {
var table = GetOrCreateWeakMapTable(target, false);
if (table) {
return this._key in table;
}
return false;
},
get: function (target) {
var table = GetOrCreateWeakMapTable(target, false);
if (table) {
return table[this._key];
}
return undefined;
},
set: function (target, value) {
var table = GetOrCreateWeakMapTable(target, true);
table[this._key] = value;
return this;
},
delete: function (target) {
var table = GetOrCreateWeakMapTable(target, false);
if (table && this._key in table) {
return delete table[this._key];
}
return false;
},
clear: function () {
// NOTE: not a real clear, just makes the previous data unreachable
this._key = CreateUniqueKey();
}
};
function FillRandomBytes(buffer, size) {
for (var i = 0; i < size; ++i) {
buffer[i] = Math.random() * 255 | 0;
}
}
function GenRandomBytes(size) {
if (nodeCrypto) {
var data = nodeCrypto.randomBytes(size);
return data;
}
else if (typeof Uint8Array === "function") {
var data = new Uint8Array(size);
if (typeof crypto !== "undefined") {
crypto.getRandomValues(data);
}
else if (typeof msCrypto !== "undefined") {
msCrypto.getRandomValues(data);
}
else {
FillRandomBytes(data, size);
}
return data;
}
else {
var data = new Array(size);
FillRandomBytes(data, size);
return data;
}
}
function CreateUUID() {
var data = GenRandomBytes(UUID_SIZE);
// mark as random - RFC 4122 § 4.4
data[6] = data[6] & 0x4f | 0x40;
data[8] = data[8] & 0xbf | 0x80;
var result = "";
for (var offset = 0; offset < UUID_SIZE; ++offset) {
var byte = data[offset];
if (offset === 4 || offset === 6 || offset === 8) {
result += "-";
}
if (byte < 16) {
result += "0";
}
result += byte.toString(16).toLowerCase();
}
return result;
}
function CreateUniqueKey() {
var key;
do {
key = "@@WeakMap@@" + CreateUUID();
} while (hasOwn.call(keys, key));
keys[key] = true;
return key;
}
function GetOrCreateWeakMapTable(target, create) {
if (!hasOwn.call(target, rootKey)) {
if (!create) {
return undefined;
}
Object.defineProperty(target, rootKey, { value: Object.create(null) });
}
return target[rootKey];
}
return WeakMap;
}
// hook global Reflect
(function (__global) {
if (typeof __global.Reflect !== "undefined") {
if (__global.Reflect !== Reflect) {
for (var p in Reflect) {
__global.Reflect[p] = Reflect[p];
}
}
}
else {
__global.Reflect = Reflect;
}
})(typeof window !== "undefined" ? window :
typeof WorkerGlobalScope !== "undefined" ? self :
typeof global !== "undefined" ? global :
Function("return this;")());
})(Reflect || (Reflect = {}));
//# sourceMappingURLDisabled=Reflect.js.map |
"""Contains definition for ResNeSt."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import logging
import numpy as np
import tensorflow.compat.v1 as tf
from dropblock import DropBlock2D
from splat import SplAtConv2D
from utils import TpuBatchNormalization
class Bottleneck(tf.keras.Model):
"""ResNet Bottleneck"""
expansion = 4
def __init__(
self, filters, strides=1, downsample=None, radix=2, cardinality=1, bottleneck_width=64,
avd=False, avd_first=False, dilation=1, is_first=False, norm_layer=None,
dropblock_prob=0.0, use_tpu=False):
"""Initializes a Bottleneck block.
Args:
filters: number of filters (i.e. output channels) for conv layer.
strides: convolutional stride.
downsample: a tf.keras.Sequential of downsampling layers.
radix: number of splits within a cardinal group.
cardinality: number of cardinal groups (i.e. feature-map groups).
bottleneck_width: default 64 so that number of filters is multiplied just by cardinality.
avd: boolean to use average downsampling.
avd_first: boolean to use average pooling layer before conv (used in fast setting).
dilation: default 1 for classification tasks, >1 for segmentation tasks.
is_first: previous dilation != current dilation.
norm_layer: normalization layer used in backbone network.
dropblock_prob: DropBlock keep probability.
"""
super(Bottleneck, self).__init__()
group_width = int(filters * (bottleneck_width / 64.)) * cardinality
self.conv1 = tf.keras.layers.Conv2D(
filters=group_width, kernel_size=1, strides=1, padding='same',
kernel_initializer='he_normal', use_bias=False)
self.bn1 = norm_layer(axis=-1, epsilon=1.001e-5)
self.dropblock_prob = dropblock_prob
self.radix = radix
self.avd = avd and (strides > 1 or is_first)
self.avd_first = avd_first
self.use_tpu = use_tpu
if self.avd:
self.avd_layer = tf.keras.layers.AveragePooling2D(
pool_size=3, strides=strides, padding='same')
strides = 1
if dropblock_prob > 0.0:
self.dropblock1 = DropBlock2D(keep_prob=dropblock_prob, block_size=3)
self.dropblock2 = DropBlock2D(keep_prob=dropblock_prob, block_size=3)
self.dropblock3 = DropBlock2D(keep_prob=dropblock_prob, block_size=3)
if radix >= 1:
# using split-attention
self.conv2 = SplAtConv2D(
in_channels=group_width, channels=group_width, kernel_size=3,
padding='same', dilation=dilation, groups=cardinality, use_bias=False, radix=radix,
norm_layer=norm_layer, dropblock_prob=dropblock_prob, use_tpu=use_tpu)
else:
self.conv2 = tf.keras.layers.Conv2D(
filters=group_width, kernel_size=3, strides=strides, padding='same',
dilation_rate=dilation, use_bias=False)
self.bn2 = norm_layer(axis=-1, epsilon=1.001e-5)
self.conv3 = tf.keras.layers.Conv2D(
filters=filters*4, kernel_size=1, strides=1, padding="same",
kernel_initializer='he_normal', dilation_rate=dilation, use_bias=False)
self.bn3 = norm_layer(axis=-1, epsilon=1.001e-5)
self.relu = tf.keras.layers.Activation('relu')
self.downsample = downsample
self.dilation = dilation
self.strides = strides
def call(self, inputs):
"""Implementation of call() for Bottleneck.
Args:
inputs: input tensor.
Returns:
output tensor.
"""
residual = inputs
out = self.conv1(inputs)
out = self.bn1(out)
if self.use_tpu:
out = tf.cast(out, tf.bfloat16)
if self.dropblock_prob > 0.0:
out = self.dropblock1(out)
out = self.relu(out)
if self.avd and self.avd_first:
out = self.avd_layer(out)
out = self.conv2(out)
if self.radix >= 1:
# using split-attention
if self.dropblock_prob > 0.0:
out = self.dropblock2(out)
else:
out = self.bn2(out)
if self.use_tpu:
out = tf.cast(out, tf.bfloat16)
if self.dropblock_prob > 0.0:
out = self.dropblock2(out)
out = self.relu(out)
if self.avd and not self.avd_first:
out = self.avd_layer(out)
out = self.conv3(out)
out = self.bn3(out)
if self.use_tpu:
out = tf.cast(out, tf.bfloat16)
if self.dropblock_prob > 0.0:
out = self.dropblock3(out)
if self.downsample is not None:
residual = self.downsample(inputs)
out += residual
out = self.relu(out)
return out
class ResNet(tf.keras.Model):
def __init__(
self, block, layers, input_shape=(224, 224, 3), radix=2, groups=1, bottleneck_width=64,
num_classes=1000, dilated=False, dilation=1, deep_stem=True, stem_width=64,
avg_down=True, avd=True, avd_first=False, final_drop=0.2, dropblock_prob=0, use_tpu=False):
"""Initializes a ResNet variant (default: ResNeSt).
Args:
block: class for residual block (e.g. Bottleneck).
layers: list of 4 integers indicating number of blocks in each layer.
input_shape: (H, W, C) of input.
radix: number of splits within a cardinal group.
groups: number of cardinal groups (i.e. feature-map groups).
bottleneck_width: default 64 so that number of filters is multiplied just by cardinality.
num_classes: number of classification buckets in dataset.
dilated: boolean if applying dilation strategy to pretrained ResNet yielding a stride-8 model,
typically used in Semantic Segmentation (default: False).
dilation: default 1 for classification tasks, >1 for segmentation tasks.
deep_stem: boolean to replace the usual single conv7x7 (64 filters, stride 2) stem with:
conv3x3 (stride 2, stem_width filters),
batchnorm,
relu,
conv3x3 (stem_width filters, stride 1),
batchnorm,
relu,
conv3x3 (stem_width*2 filters, stride 1)
stem_width: width of beginning of deep stem.
avg_down: boolean to use average downsampling in shortcut connection (default: True).
avd: boolean to use average downsampling in residual block (default: True).
avd_first: boolean to use average pooling layer before conv (default: False).
Used in fast setting.
final_drop: dropout layer keep probability.
dropblock_prob: DropBlock keep probability.
use_tpu: boolean if running on TPU.
"""
self.cardinality = groups
self.bottleneck_width = bottleneck_width
# ResNet-D params
self.in_channels = stem_width*2 if deep_stem else 64
self.deep_stem = deep_stem
self.avg_down = avg_down
# ResNeSt params
self.radix = radix
self.avd = avd
self.avd_first = avd_first
self.use_tpu = use_tpu
super(ResNet, self).__init__()
conv_layer = tf.keras.layers.Conv2D
norm_layer = TpuBatchNormalization if use_tpu else tf.keras.layers.BatchNormalization
if deep_stem:
self.conv_stem_1 = conv_layer(
filters=stem_width, kernel_size=3, strides=2, padding='same',
kernel_initializer='he_normal', use_bias=False, input_shape=input_shape)
self.bn_stem_1 = norm_layer(axis=-1, epsilon=1.001e-5)
self.relu_stem_1 = tf.keras.layers.Activation('relu')
self.conv_stem_2 = conv_layer(
filters=stem_width, kernel_size=3, strides=1, padding='same',
kernel_initializer='he_normal', use_bias=False)
self.bn_stem_2 = norm_layer(axis=-1, epsilon=1.001e-5)
self.relu_stem_2 = tf.keras.layers.Activation('relu')
self.conv_stem_3 = conv_layer(
filters=stem_width*2, kernel_size=3, strides=1, padding='same',
kernel_initializer='he_normal', use_bias=False)
else:
self.conv_stem_1 = conv_layer(
filters=64, kernel_size=7, strides=2, padding='same', use_bias=False,
input_shape=input_shape)
self.bn1 = norm_layer(axis=-1, epsilon=1.001e-5)
self.relu = tf.keras.layers.Activation('relu')
self.maxpool = tf.keras.layers.MaxPool2D(pool_size=3, strides=2, padding='same')
self.layer1 = self._make_layer(block, 64, layers[0], norm_layer=norm_layer, is_first=False)
self.layer2 = self._make_layer(block, 128, layers[1], strides=2, norm_layer=norm_layer)
if dilated or dilation == 4:
self.layer3 = self._make_layer(
block=block, filters=256, num_blocks=layers[2], strides=1, dilation=2,
norm_layer=norm_layer, dropblock_prob=dropblock_prob)
self.layer4 = self._make_layer(
block=block, filters=512, num_blocks=layers[3], strides=1, dilation=4,
norm_layer=norm_layer, dropblock_prob=dropblock_prob)
elif dilation==2:
self.layer3 = self._make_layer(
block=block, filters=256, num_blocks=layers[2], strides=2, dilation=1,
norm_layer=norm_layer, dropblock_prob=dropblock_prob)
self.layer4 = self._make_layer(
block=block, filters=512, num_blocks=layers[3], strides=1, dilation=2,
norm_layer=norm_layer, dropblock_prob=dropblock_prob)
else:
self.layer3 = self._make_layer(
block=block, filters=256, num_blocks=layers[2], strides=2, norm_layer=norm_layer,
dropblock_prob=dropblock_prob)
self.layer4 = self._make_layer(
block=block, filters=512, num_blocks=layers[3], strides=2, norm_layer=norm_layer,
dropblock_prob=dropblock_prob)
self.avgpool = tf.keras.layers.GlobalAveragePooling2D(name='avg_pool')
self.flatten = tf.keras.layers.Flatten()
self.drop = tf.keras.layers.Dropout(
final_drop, noise_shape=None) if final_drop > 0.0 else None
self.fc = tf.keras.layers.Dense(
units=num_classes, kernel_initializer="he_normal", use_bias=False, name="fc")
def _make_layer(
self, block, filters, num_blocks, strides=1, dilation=1, norm_layer=None,
dropblock_prob=0.0, is_first=True):
"""Creates a layer of blocks for the ResNet.
Args:
block: class for residual block (e.g. Bottleneck).
filters: number of filters (i.e. output channels) for conv layer.
num_blocks: number of blocks to be used in this layer.
strides: convolutional stride.
dilation: default 1 for classification tasks, >1 for segmentation tasks.
norm_layer: normalization layer used in backbone network.
dropblock_prob: DropBlock keep probability.
is_first: previous dilation != current dilation.
Returns:
a tf.keras.Sequential of blocks.
"""
downsample = None
if strides != 1 or self.in_channels != filters * block.expansion:
down_layers = []
if self.avg_down:
if dilation == 1:
down_layers.append(tf.keras.layers.AveragePooling2D(
pool_size=strides, strides=strides, padding='same'))
else:
down_layers.append(tf.keras.layers.AveragePooling2D(
pool_size=1, strides=1, padding='same'))
down_layers.append(tf.keras.layers.Conv2D(
filters * block.expansion, kernel_size=1, strides=1, padding='same',
kernel_initializer='he_normal', use_bias=False))
else:
down_layers.append(tf.keras.layers.Conv2D(
filters * block.expansion, kernel_size=1, strides=stride, padding='same',
kernel_initializer='he_normal', use_bias=False))
down_layers.append(norm_layer(
axis=-1, epsilon=1.001e-5))
downsample = tf.keras.Sequential(down_layers)
blocks = []
if dilation == 1 or dilation == 2:
blocks.append(block(
filters=filters, strides=strides, downsample=downsample, radix=self.radix,
cardinality=self.cardinality, bottleneck_width=self.bottleneck_width, avd=self.avd,
avd_first=self.avd_first, dilation=1, is_first=is_first, norm_layer=norm_layer,
dropblock_prob=dropblock_prob))
elif dilation == 4:
blocks.append(block(
filters=filters, strides=strides, downsample=downsample, radix=self.radix,
cardinality=self.cardinality, bottleneck_width=self.bottleneck_width, avd=self.avd,
avd_first=self.avd_first, dilation=2, is_first=is_first, norm_layer=norm_layer,
dropblock_prob=dropblock_prob))
else:
raise RuntimeError("=> unknown dilation size: {}".format(dilation))
for i in range(1, num_blocks):
blocks.append(block(
filters=filters, strides=1, downsample=None, radix=self.radix,
cardinality=self.cardinality, bottleneck_width=self.bottleneck_width, avd=self.avd,
avd_first=self.avd_first, dilation=dilation, norm_layer=norm_layer,
dropblock_prob=dropblock_prob))
return tf.keras.Sequential(blocks)
def call(self, inputs):
"""Implementation of call() for ResNet.
Args:
inputs: input tensor.
Returns:
output tensor.
"""
if self.deep_stem:
out = self.conv_stem_1(inputs)
out = self.bn_stem_1(out)
if self.use_tpu:
out = tf.cast(out, tf.bfloat16)
out = self.relu_stem_1(out)
out = self.conv_stem_2(out)
out = self.bn_stem_2(out)
if self.use_tpu:
out = tf.cast(out, tf.bfloat16)
out = self.relu_stem_2(out)
out = self.conv_stem_3(out)
else:
out = self.conv_stem_1(inputs)
out = self.bn1(out)
if self.use_tpu:
out = tf.cast(out, tf.bfloat16)
out = self.relu(out)
out = self.maxpool(out)
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = self.layer4(out)
out = self.avgpool(out)
out = self.flatten(out)
if self.drop:
out = self.drop(out)
out = self.fc(out)
return out
def resnest50(input_shape=(224, 224, 3), num_classes=1000, use_tpu=False, **kwargs):
"""ResNeSt-50 config."""
model = ResNet(Bottleneck, layers=[3, 4, 6, 3], input_shape=input_shape,
radix=2, groups=1, bottleneck_width=64, num_classes=1000,
deep_stem=True, stem_width=32, avg_down=True,
avd=True, avd_first=False, use_tpu=use_tpu, **kwargs)
return model
def resnest101(input_shape=(224, 224, 3), num_classes=1000, use_tpu=False, **kwargs):
"""ResNeSt-101 config."""
model = ResNet(Bottleneck, layers=[3, 4, 23, 3], input_shape=input_shape,
radix=2, groups=1, bottleneck_width=64, num_classes=1000,
deep_stem=True, stem_width=64, avg_down=True,
avd=True, avd_first=False, use_tpu=use_tpu, **kwargs)
return model
def resnest200(input_shape=(224, 224, 3), num_classes=1000, use_tpu=False, **kwargs):
"""ResNeSt-200 config."""
model = ResNet(Bottleneck, layers=[3, 24, 36, 3], input_shape=input_shape,
radix=2, groups=1, bottleneck_width=64, num_classes=1000,
deep_stem=True, stem_width=64, avg_down=True,
avd=True, avd_first=False, use_tpu=use_tpu, **kwargs)
return model
def resnest269(input_shape=(224, 224, 3), num_classes=1000, use_tpu=False, **kwargs):
"""ResNeSt-269 config."""
model = ResNet(Bottleneck, layers=[3, 30, 48, 8], input_shape=input_shape,
radix=2, groups=1, bottleneck_width=64, num_classes=1000,
deep_stem=True, stem_width=64, avg_down=True,
avd=True, avd_first=False, use_tpu=use_tpu, **kwargs)
return model
|
!function(t){var s;window.UIkit2&&(s=t(UIkit2)),"function"==typeof define&&define.amd&&define("uikit-nestable",["uikit"],function(){return s||t(UIkit2)})}(function(v){"use strict";var o,a="ontouchstart"in window,h=v.$html,E=[],i=v.$win,n=a?"touchstart":"mousedown",r=a?"touchmove":"mousemove",d=a?"touchend":"mouseup",p=a?"touchcancel":"mouseup";return v.component("nestable",{defaults:{listBaseClass:"uk-nestable",listClass:"uk-nestable-list",listItemClass:"uk-nestable-item",dragClass:"uk-nestable-dragged",movingClass:"uk-nestable-moving",noChildrenClass:"uk-nestable-nochildren",emptyClass:"uk-nestable-empty",handleClass:"",collapsedClass:"uk-collapsed",placeholderClass:"uk-nestable-placeholder",noDragClass:"uk-nestable-nodrag",group:!1,maxDepth:10,threshold:20,idlethreshold:10},boot:function(){v.$html.on("mousemove touchmove",function(t){if(o){var s=o.offset().top;s<v.$win.scrollTop()?v.$win.scrollTop(v.$win.scrollTop()-Math.ceil(o.height()/2)):s+o.height()>window.innerHeight+v.$win.scrollTop()&&v.$win.scrollTop(v.$win.scrollTop()+Math.ceil(o.height()/2))}}),v.ready(function(t){v.$("[data-uk-nestable]",t).each(function(){var t=v.$(this);t.data("nestable")||v.nestable(t,v.Utils.options(t.attr("data-uk-nestable")))})})},init:function(){var l=this;Object.keys(this.options).forEach(function(t){-1!=String(t).indexOf("Class")&&(l.options["_"+t]="."+l.options[t])}),this.find(this.options._listItemClass).find(">ul").addClass(this.options.listClass),this.checkEmptyList(),this.reset(),this.element.data("nestable-group",this.options.group||v.Utils.uid("nestable-group")),this.find(this.options._listItemClass).each(function(){l.setParent(v.$(this))}),this.on("click","[data-nestable-action]",function(t){if(!l.dragEl&&(a||0===t.button)){t.preventDefault();var s=v.$(t.currentTarget),e=s.data("nestableAction"),i=s.closest(l.options._listItemClass);"collapse"===e&&l.collapseItem(i),"expand"===e&&l.expandItem(i),"toggle"===e&&l.toggleItem(i)}});var t=function(s){var t=v.$(s.target),e=t.is("a[href]")?t:t.parents("a[href]");s.target!==l.element[0]&&(t.is(l.options._noDragClass)||t.closest(l.options._noDragClass).length||t.is("[data-nestable-action]")||t.closest("[data-nestable-action]").length||(l.options.handleClass&&!t.hasClass(l.options.handleClass)&&l.options.handleClass&&(t=t.closest(l.options._handleClass)),!t.length||l.dragEl||!a&&0!==s.button||a&&1!==s.touches.length||(s.originalEvent&&s.originalEvent.touches&&(s=evt.originalEvent.touches[0]),l.delayMove=function(t){e=!1,t.preventDefault(),l.dragStart(s),l.trigger("start.uk.nestable",[l]),l.delayMove=!1},l.delayMove.x=parseInt(s.pageX,10),l.delayMove.y=parseInt(s.pageY,10),l.delayMove.threshold=l.options.idlethreshold,e.length&&"touchend"==d&&l.one(d,function(){e&&e.attr("href").trim()&&(location.href=e.attr("href"))}),s.preventDefault())))},s=function(t){t.originalEvent&&t.originalEvent.touches&&(t=t.originalEvent.touches[0]),l.delayMove&&(Math.abs(t.pageX-l.delayMove.x)>l.delayMove.threshold||Math.abs(t.pageY-l.delayMove.y)>l.delayMove.threshold)&&(window.getSelection().toString()?l.delayMove=!1:l.delayMove(t)),l.dragEl&&(t.preventDefault(),l.dragMove(t),l.trigger("move.uk.nestable",[l]))},e=function(t){l.dragEl&&(t.preventDefault(),l.dragStop(a?t.touches[0]:t)),o=!1,l.delayMove=!1};a?(this.element[0].addEventListener(n,t,!1),window.addEventListener(r,s,!1),window.addEventListener(d,e,!1),window.addEventListener(p,e,!1)):(this.on(n,t),i.on(r,s),i.on(d,e))},serialize:function(){var r=this,d=function(t,o){var h=[];return t.children(r.options._listItemClass).each(function(){for(var t,s,e,i=v.$(this),l={},a=i.children(r.options._listClass),n=0;n<i[0].attributes.length;n++)0===(t=i[0].attributes[n]).name.indexOf("data-")&&(s=t.name.substr(5),e=v.Utils.str2json(t.value),l[s]=e||"false"==t.value||"0"==t.value?e:t.value);a.length&&(l.children=d(a,o+1)),h.push(l)}),h};return d(r.element,0)},list:function(n){var o=[],h=function(t,l,a){t.children(n._listItemClass).each(function(t){var s=v.$(this),e=v.$.extend({parent_id:a||null,depth:l,order:t},s.data()),i=s.children(n._listClass);o.push(e),i.length&&h(i,l+1,s.data(n.idProperty||"id"))})};return n=v.$.extend({},this.options,n),h(this.element,0),o},reset:function(){this.mouse={offsetX:0,offsetY:0,startX:0,startY:0,lastX:0,lastY:0,nowX:0,nowY:0,distX:0,distY:0,dirAx:0,dirX:0,dirY:0,lastDirX:0,lastDirY:0,distAxX:0,distAxY:0},this.moving=!1,this.dragEl=null,this.dragRootEl=null,this.dragDepth=0,this.hasNewRoot=!1,this.pointEl=null;for(var t=0;t<E.length;t++)this.checkEmptyList(E[t]);E=[]},toggleItem:function(t){this[t.hasClass(this.options.collapsedClass)?"expandItem":"collapseItem"](t)},expandItem:function(t){t.removeClass(this.options.collapsedClass)},collapseItem:function(t){t.children(this.options._listClass).length&&t.addClass(this.options.collapsedClass)},expandAll:function(){var t=this;this.find(t.options._listItemClass).each(function(){t.expandItem(v.$(this))})},collapseAll:function(){var t=this;this.find(t.options._listItemClass).each(function(){t.collapseItem(v.$(this))})},setParent:function(t){t.children(this.options._listClass).length&&t.addClass("uk-parent")},unsetParent:function(t){t.removeClass("uk-parent "+this.options.collapsedClass),t.children(this.options._listClass).remove()},dragStart:function(t){var s=this.mouse,e=v.$(t.target).closest(this.options._listItemClass),i=e.offset();this.placeEl=e,s.offsetX=t.pageX-i.left,s.offsetY=t.pageY-i.top,s.startX=s.lastX=i.left,s.startY=s.lastY=i.top,this.dragRootEl=this.element,this.dragEl=v.$("<ul></ul>").addClass(this.options.listClass+" "+this.options.dragClass).append(e.clone()),this.dragEl.css("width",e.width()),this.placeEl.addClass(this.options.placeholderClass),o=this.dragEl,this.tmpDragOnSiblings=[e[0].previousSibling,e[0].nextSibling],v.$body.append(this.dragEl),this.dragEl.css({left:i.left,top:i.top});var l,a,n=this.dragEl.find(this.options._listItemClass);for(l=0;l<n.length;l++)(a=v.$(n[l]).parents(this.options._listClass+","+this.options._listBaseClass).length)>this.dragDepth&&(this.dragDepth=a);h.addClass(this.options.movingClass)},dragStop:function(t){var s=v.$(this.placeEl),e=this.placeEl.parents(this.options._listBaseClass+":first");this.placeEl.removeClass(this.options.placeholderClass),this.dragEl.remove(),this.element[0]!==e[0]?(e.trigger("change.uk.nestable",[e.data("nestable"),s,"added"]),this.element.trigger("change.uk.nestable",[this,s,"removed"])):this.element.trigger("change.uk.nestable",[this,s,"moved"]),this.trigger("stop.uk.nestable",[this,s]),this.reset(),h.removeClass(this.options.movingClass)},dragMove:function(t){var s,e,i,l=this.options,a=this.mouse,n=this.dragRootEl?this.dragRootEl.data("nestable").options.maxDepth:l.maxDepth;this.dragEl.css({left:t.pageX-a.offsetX,top:t.pageY-a.offsetY}),a.lastX=a.nowX,a.lastY=a.nowY,a.nowX=t.pageX,a.nowY=t.pageY,a.distX=a.nowX-a.lastX,a.distY=a.nowY-a.lastY,a.lastDirX=a.dirX,a.lastDirY=a.dirY,a.dirX=0===a.distX?0:0<a.distX?1:-1,a.dirY=0===a.distY?0:0<a.distY?1:-1;var o=Math.abs(a.distX)>Math.abs(a.distY)?1:0;if(!a.moving)return a.dirAx=o,void(a.moving=!0);if(a.dirAx!==o?(a.distAxX=0,a.distAxY=0):(a.distAxX+=Math.abs(a.distX),0!==a.dirX&&a.dirX!==a.lastDirX&&(a.distAxX=0),a.distAxY+=Math.abs(a.distY),0!==a.dirY&&a.dirY!==a.lastDirY&&(a.distAxY=0)),a.dirAx=o,a.dirAx&&a.distAxX>=l.threshold&&(a.distAxX=0,i=this.placeEl.prev("li"),0<a.distX&&i.length&&!i.hasClass(l.collapsedClass)&&!i.hasClass(l.noChildrenClass)&&(s=i.find(l._listClass).last(),this.placeEl.parents(l._listClass+","+l._listBaseClass).length+this.dragDepth<=n&&(s.length?(s=i.children(l._listClass).last()).append(this.placeEl):((s=v.$("<ul/>").addClass(l.listClass)).append(this.placeEl),i.append(s),this.setParent(i)))),a.distX<0&&!this.placeEl.next(l._listItemClass).length)){var h=this.placeEl.closest([l._listBaseClass,l._listClass].join(",")),r=h.closest(l._listItemClass);r.length&&(r.after(this.placeEl),h.children().length||this.unsetParent(r))}var d=!1,p=t.pageX-(window.pageXOffset||document.scrollLeft||0),c=t.pageY-(window.pageYOffset||document.documentElement.scrollTop);if(this.pointEl=v.$(document.elementFromPoint(p,c)),l.handleClass&&this.pointEl.hasClass(l.handleClass))this.pointEl=this.pointEl.closest(l._listItemClass);else{var g=this.pointEl.closest(l._listItemClass);g.length&&(this.pointEl=g)}if(!this.placeEl.find(this.pointEl).length){if(this.pointEl.data("nestable")&&!this.pointEl.children().length)d=!0,this.checkEmptyList(this.pointEl);else if(!this.pointEl.length||!this.pointEl.hasClass(l.listItemClass))return;var u=this.element,f=this.pointEl.closest(this.options._listBaseClass),m=u[0]!=f[0];if(!a.dirAx||m||d){if(m&&l.group!==f.data("nestable-group"))return;if(E.push(u),n<this.dragDepth-1+this.pointEl.parents(l._listClass+","+l._listBaseClass).length)return;var C=t.pageY<this.pointEl.offset().top+this.pointEl.height()/2;e=this.placeEl.parent(),d?this.pointEl.append(this.placeEl):C?this.pointEl.before(this.placeEl):this.pointEl.after(this.placeEl),e.children().length||e.data("nestable")||this.unsetParent(e.parent()),this.checkEmptyList(this.dragRootEl),this.checkEmptyList(u),m&&(this.dragRootEl=f,this.hasNewRoot=this.element[0]!==this.dragRootEl[0])}}},checkEmptyList:function(t){t=t?v.$(t):this.element,this.options.emptyClass&&t[t.children().length?"removeClass":"addClass"](this.options.emptyClass)}}),v.nestable});
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImNvbXBvbmVudHMvbmVzdGFibGUuanMiXSwibmFtZXMiOlsiYWRkb24iLCJjb21wb25lbnQiLCJ3aW5kb3ciLCJVSWtpdDIiLCJkZWZpbmUiLCJhbWQiLCJVSSIsImRyYWdnaW5nRWxlbWVudCIsImhhc1RvdWNoIiwiaHRtbCIsIiRodG1sIiwidG91Y2hlZGxpc3RzIiwiJHdpbiIsImVTdGFydCIsImVNb3ZlIiwiZUVuZCIsImVDYW5jZWwiLCJkZWZhdWx0cyIsImxpc3RCYXNlQ2xhc3MiLCJsaXN0Q2xhc3MiLCJsaXN0SXRlbUNsYXNzIiwiZHJhZ0NsYXNzIiwibW92aW5nQ2xhc3MiLCJub0NoaWxkcmVuQ2xhc3MiLCJlbXB0eUNsYXNzIiwiaGFuZGxlQ2xhc3MiLCJjb2xsYXBzZWRDbGFzcyIsInBsYWNlaG9sZGVyQ2xhc3MiLCJub0RyYWdDbGFzcyIsImdyb3VwIiwibWF4RGVwdGgiLCJ0aHJlc2hvbGQiLCJpZGxldGhyZXNob2xkIiwiYm9vdCIsIm9uIiwiZSIsInRvcCIsIm9mZnNldCIsInNjcm9sbFRvcCIsIk1hdGgiLCJjZWlsIiwiaGVpZ2h0IiwiaW5uZXJIZWlnaHQiLCJyZWFkeSIsImNvbnRleHQiLCIkIiwiZWFjaCIsImVsZSIsInRoaXMiLCJkYXRhIiwibmVzdGFibGUiLCJVdGlscyIsIm9wdGlvbnMiLCJhdHRyIiwiaW5pdCIsIiR0aGlzIiwiT2JqZWN0Iiwia2V5cyIsImZvckVhY2giLCJrZXkiLCJTdHJpbmciLCJpbmRleE9mIiwiZmluZCIsIl9saXN0SXRlbUNsYXNzIiwiYWRkQ2xhc3MiLCJjaGVja0VtcHR5TGlzdCIsInJlc2V0IiwiZWxlbWVudCIsInVpZCIsInNldFBhcmVudCIsImRyYWdFbCIsImJ1dHRvbiIsInByZXZlbnREZWZhdWx0IiwidGFyZ2V0IiwiY3VycmVudFRhcmdldCIsImFjdGlvbiIsIml0ZW0iLCJjbG9zZXN0IiwiY29sbGFwc2VJdGVtIiwiZXhwYW5kSXRlbSIsInRvZ2dsZUl0ZW0iLCJvblN0YXJ0RXZlbnQiLCJoYW5kbGUiLCJsaW5rIiwiaXMiLCJwYXJlbnRzIiwiX25vRHJhZ0NsYXNzIiwibGVuZ3RoIiwiaGFzQ2xhc3MiLCJfaGFuZGxlQ2xhc3MiLCJ0b3VjaGVzIiwib3JpZ2luYWxFdmVudCIsImV2dCIsImRlbGF5TW92ZSIsImRyYWdTdGFydCIsInRyaWdnZXIiLCJ4IiwicGFyc2VJbnQiLCJwYWdlWCIsInkiLCJwYWdlWSIsIm9uZSIsInRyaW0iLCJsb2NhdGlvbiIsImhyZWYiLCJvbk1vdmVFdmVudCIsImFicyIsImdldFNlbGVjdGlvbiIsInRvU3RyaW5nIiwiZHJhZ01vdmUiLCJvbkVuZEV2ZW50IiwiZHJhZ1N0b3AiLCJhZGRFdmVudExpc3RlbmVyIiwic2VyaWFsaXplIiwibGlzdCIsInN0ZXAiLCJsZXZlbCIsImRlcHRoIiwiYXJyYXkiLCJjaGlsZHJlbiIsImF0dHJpYnV0ZSIsInZhbCIsImxpIiwic3ViIiwiX2xpc3RDbGFzcyIsImkiLCJhdHRyaWJ1dGVzIiwibmFtZSIsInN1YnN0ciIsInN0cjJqc29uIiwidmFsdWUiLCJwdXNoIiwicGFyZW50IiwiaW5kZXgiLCJleHRlbmQiLCJwYXJlbnRfaWQiLCJvcmRlciIsImlkUHJvcGVydHkiLCJtb3VzZSIsIm9mZnNldFgiLCJvZmZzZXRZIiwic3RhcnRYIiwic3RhcnRZIiwibGFzdFgiLCJsYXN0WSIsIm5vd1giLCJub3dZIiwiZGlzdFgiLCJkaXN0WSIsImRpckF4IiwiZGlyWCIsImRpclkiLCJsYXN0RGlyWCIsImxhc3REaXJZIiwiZGlzdEF4WCIsImRpc3RBeFkiLCJtb3ZpbmciLCJkcmFnUm9vdEVsIiwiZHJhZ0RlcHRoIiwiaGFzTmV3Um9vdCIsInBvaW50RWwiLCJyZW1vdmVDbGFzcyIsImV4cGFuZEFsbCIsImNvbGxhcHNlQWxsIiwidW5zZXRQYXJlbnQiLCJyZW1vdmUiLCJkcmFnSXRlbSIsInBsYWNlRWwiLCJsZWZ0IiwiYXBwZW5kIiwiY2xvbmUiLCJjc3MiLCJ3aWR0aCIsInRtcERyYWdPblNpYmxpbmdzIiwicHJldmlvdXNTaWJsaW5nIiwibmV4dFNpYmxpbmciLCIkYm9keSIsIml0ZW1zIiwiX2xpc3RCYXNlQ2xhc3MiLCJlbCIsInJvb3QiLCJwcmV2Iiwib3B0IiwibmV3QXgiLCJsYXN0IiwibmV4dCIsInBhcmVudFVsIiwiam9pbiIsInN1cnJvdW5kaW5nTGkiLCJhZnRlciIsImlzRW1wdHkiLCJwb2ludFgiLCJwYWdlWE9mZnNldCIsImRvY3VtZW50Iiwic2Nyb2xsTGVmdCIsInBvaW50WSIsInBhZ2VZT2Zmc2V0IiwiZG9jdW1lbnRFbGVtZW50IiwiZWxlbWVudEZyb21Qb2ludCIsIm5lc3RhYmxlaXRlbSIsInBvaW50RWxSb290IiwidG1wUm9vdCIsImlzTmV3Um9vdCIsImJlZm9yZSJdLCJtYXBwaW5ncyI6IkNBSUEsU0FBVUEsR0FFTixJQUFJQyxFQUVBQyxPQUFPQyxTQUNQRixFQUFZRCxFQUFNRyxTQUdELG1CQUFWQyxRQUF3QkEsT0FBT0MsS0FDdENELE9BQU8saUJBQWtCLENBQUMsU0FBVSxXQUNoQyxPQUFPSCxHQUFhRCxFQUFNRyxVQVZ0QyxDQWNHLFNBQVNHLEdBRVIsYUFFQSxJQUlJQyxFQUpBQyxFQUFlLGlCQUFrQk4sT0FDakNPLEVBQWVILEVBQUdJLE1BQ2xCQyxFQUFlLEdBQ2ZDLEVBQWVOLEVBQUdNLEtBR2xCQyxFQUFVTCxFQUFXLGFBQWdCLFlBQ3JDTSxFQUFVTixFQUFXLFlBQWdCLFlBQ3JDTyxFQUFVUCxFQUFXLFdBQWdCLFVBQ3JDUSxFQUFVUixFQUFXLGNBQWdCLFVBNG1CekMsT0F6bUJBRixFQUFHTCxVQUFVLFdBQVksQ0FFckJnQixTQUFVLENBQ05DLGNBQWtCLGNBQ2xCQyxVQUFrQixtQkFDbEJDLGNBQWtCLG1CQUNsQkMsVUFBa0Isc0JBQ2xCQyxZQUFrQixxQkFDbEJDLGdCQUFrQix5QkFDbEJDLFdBQWtCLG9CQUNsQkMsWUFBa0IsR0FDbEJDLGVBQWtCLGVBQ2xCQyxpQkFBa0IsMEJBQ2xCQyxZQUFrQixxQkFDbEJDLE9BQWtCLEVBQ2xCQyxTQUFrQixHQUNsQkMsVUFBa0IsR0FDbEJDLGNBQWtCLElBR3RCQyxLQUFNLFdBR0YzQixFQUFHSSxNQUFNd0IsR0FBRyxzQkFBdUIsU0FBU0MsR0FFeEMsR0FBSTVCLEVBQWlCLENBRWpCLElBQUk2QixFQUFNN0IsRUFBZ0I4QixTQUFTRCxJQUUvQkEsRUFBTTlCLEVBQUdNLEtBQUswQixZQUNkaEMsRUFBR00sS0FBSzBCLFVBQVVoQyxFQUFHTSxLQUFLMEIsWUFBY0MsS0FBS0MsS0FBS2pDLEVBQWdCa0MsU0FBUyxJQUNsRUwsRUFBTTdCLEVBQWdCa0MsU0FBYXZDLE9BQU93QyxZQUFjcEMsRUFBR00sS0FBSzBCLGFBQ3pFaEMsRUFBR00sS0FBSzBCLFVBQVVoQyxFQUFHTSxLQUFLMEIsWUFBY0MsS0FBS0MsS0FBS2pDLEVBQWdCa0MsU0FBUyxPQU12Rm5DLEVBQUdxQyxNQUFNLFNBQVNDLEdBRWR0QyxFQUFHdUMsRUFBRSxxQkFBc0JELEdBQVNFLEtBQUssV0FFckMsSUFBSUMsRUFBTXpDLEVBQUd1QyxFQUFFRyxNQUVWRCxFQUFJRSxLQUFLLGFBQ1YzQyxFQUFHNEMsU0FBU0gsRUFBS3pDLEVBQUc2QyxNQUFNQyxRQUFRTCxFQUFJTSxLQUFLLDJCQU0zREMsS0FBTSxXQUVGLElBQUlDLEVBQVFQLEtBRVpRLE9BQU9DLEtBQUtULEtBQUtJLFNBQVNNLFFBQVEsU0FBU0MsSUFFTCxHQUEvQkMsT0FBT0QsR0FBS0UsUUFBUSxXQUNuQk4sRUFBTUgsUUFBUSxJQUFJTyxHQUFPLElBQU1KLEVBQU1ILFFBQVFPLE1BSXJEWCxLQUFLYyxLQUFLZCxLQUFLSSxRQUFRVyxnQkFBZ0JELEtBQUssT0FBT0UsU0FBU2hCLEtBQUtJLFFBQVFqQyxXQUV6RTZCLEtBQUtpQixpQkFFTGpCLEtBQUtrQixRQUNMbEIsS0FBS21CLFFBQVFsQixLQUFLLGlCQUFrQkQsS0FBS0ksUUFBUXZCLE9BQVN2QixFQUFHNkMsTUFBTWlCLElBQUksbUJBRXZFcEIsS0FBS2MsS0FBS2QsS0FBS0ksUUFBUVcsZ0JBQWdCakIsS0FBSyxXQUN4Q1MsRUFBTWMsVUFBVS9ELEVBQUd1QyxFQUFFRyxTQUd6QkEsS0FBS2QsR0FBRyxRQUFTLHlCQUEwQixTQUFTQyxHQUVoRCxJQUFJb0IsRUFBTWUsU0FBWTlELEdBQXlCLElBQWIyQixFQUFFb0MsUUFBcEMsQ0FJQXBDLEVBQUVxQyxpQkFFRixJQUFJQyxFQUFTbkUsRUFBR3VDLEVBQUVWLEVBQUV1QyxlQUNoQkMsRUFBU0YsRUFBT3hCLEtBQUssa0JBQ3JCMkIsRUFBU0gsRUFBT0ksUUFBUXRCLEVBQU1ILFFBQVFXLGdCQUUzQixhQUFYWSxHQUNBcEIsRUFBTXVCLGFBQWFGLEdBRVIsV0FBWEQsR0FDQXBCLEVBQU13QixXQUFXSCxHQUVOLFdBQVhELEdBQ0FwQixFQUFNeUIsV0FBV0osTUFJekIsSUFBSUssRUFBZSxTQUFTOUMsR0FFeEIsSUFBSStDLEVBQVM1RSxFQUFHdUMsRUFBRVYsRUFBRXNDLFFBQ2hCVSxFQUFTRCxFQUFPRSxHQUFHLFdBQWFGLEVBQU9BLEVBQU9HLFFBQVEsV0FFdERsRCxFQUFFc0MsU0FBV2xCLEVBQU1ZLFFBQVEsS0FJM0JlLEVBQU9FLEdBQUc3QixFQUFNSCxRQUFRa0MsZUFBaUJKLEVBQU9MLFFBQVF0QixFQUFNSCxRQUFRa0MsY0FBY0MsUUFJcEZMLEVBQU9FLEdBQUcsMkJBQTZCRixFQUFPTCxRQUFRLDBCQUEwQlUsU0FJaEZoQyxFQUFNSCxRQUFRM0IsY0FBZ0J5RCxFQUFPTSxTQUFTakMsRUFBTUgsUUFBUTNCLGNBRXhEOEIsRUFBTUgsUUFBUTNCLGNBQ2R5RCxFQUFTQSxFQUFPTCxRQUFRdEIsRUFBTUgsUUFBUXFDLGdCQUl6Q1AsRUFBT0ssUUFBVWhDLEVBQU1lLFNBQVk5RCxHQUF5QixJQUFiMkIsRUFBRW9DLFFBQWtCL0QsR0FBaUMsSUFBckIyQixFQUFFdUQsUUFBUUgsU0FJMUZwRCxFQUFFd0QsZUFBaUJ4RCxFQUFFd0QsY0FBY0QsVUFDbkN2RCxFQUFJeUQsSUFBSUQsY0FBY0QsUUFBUSxJQUdsQ25DLEVBQU1zQyxVQUFZLFNBQVNELEdBRXZCVCxHQUFPLEVBRVBTLEVBQUlwQixpQkFDSmpCLEVBQU11QyxVQUFVM0QsR0FDaEJvQixFQUFNd0MsUUFBUSxvQkFBcUIsQ0FBQ3hDLElBRXBDQSxFQUFNc0MsV0FBWSxHQUd0QnRDLEVBQU1zQyxVQUFVRyxFQUFZQyxTQUFTOUQsRUFBRStELE1BQU8sSUFDOUMzQyxFQUFNc0MsVUFBVU0sRUFBWUYsU0FBUzlELEVBQUVpRSxNQUFPLElBQzlDN0MsRUFBTXNDLFVBQVU5RCxVQUFZd0IsRUFBTUgsUUFBUXBCLGNBRXRDbUQsRUFBS0ksUUFBa0IsWUFBUnhFLEdBRWZ3QyxFQUFNOEMsSUFBSXRGLEVBQU0sV0FDUm9FLEdBQVFBLEVBQUs5QixLQUFLLFFBQVFpRCxTQUMxQkMsU0FBU0MsS0FBT3JCLEVBQUs5QixLQUFLLFdBS3RDbEIsRUFBRXFDLHFCQUdGaUMsRUFBYyxTQUFTdEUsR0FFbkJBLEVBQUV3RCxlQUFpQnhELEVBQUV3RCxjQUFjRCxVQUNuQ3ZELEVBQUlBLEVBQUV3RCxjQUFjRCxRQUFRLElBRzVCbkMsRUFBTXNDLFlBQWN0RCxLQUFLbUUsSUFBSXZFLEVBQUUrRCxNQUFRM0MsRUFBTXNDLFVBQVVHLEdBQUt6QyxFQUFNc0MsVUFBVTlELFdBQWFRLEtBQUttRSxJQUFJdkUsRUFBRWlFLE1BQVE3QyxFQUFNc0MsVUFBVU0sR0FBSzVDLEVBQU1zQyxVQUFVOUQsYUFFNUk3QixPQUFPeUcsZUFBZUMsV0FHdkJyRCxFQUFNc0MsV0FBWSxFQUZsQnRDLEVBQU1zQyxVQUFVMUQsSUFNcEJvQixFQUFNZSxTQUNObkMsRUFBRXFDLGlCQUNGakIsRUFBTXNELFNBQVMxRSxHQUNmb0IsRUFBTXdDLFFBQVEsbUJBQW9CLENBQUN4QyxNQUl2Q3VELEVBQWEsU0FBUzNFLEdBRWxCb0IsRUFBTWUsU0FDTm5DLEVBQUVxQyxpQkFDRmpCLEVBQU13RCxTQUFTdkcsRUFBVzJCLEVBQUV1RCxRQUFRLEdBQUt2RCxJQUc3QzVCLEdBQWtCLEVBQ2xCZ0QsRUFBTXNDLFdBQVksR0FHbEJyRixHQUNBd0MsS0FBS21CLFFBQVEsR0FBRzZDLGlCQUFpQm5HLEVBQVFvRSxHQUFjLEdBQ3ZEL0UsT0FBTzhHLGlCQUFpQmxHLEVBQU8yRixHQUFhLEdBQzVDdkcsT0FBTzhHLGlCQUFpQmpHLEVBQU0rRixHQUFZLEdBQzFDNUcsT0FBTzhHLGlCQUFpQmhHLEVBQVM4RixHQUFZLEtBRTdDOUQsS0FBS2QsR0FBR3JCLEVBQVFvRSxHQUNoQnJFLEVBQUtzQixHQUFHcEIsRUFBTzJGLEdBQ2Y3RixFQUFLc0IsR0FBR25CLEVBQU0rRixLQUt0QkcsVUFBVyxXQUVQLElBRUlDLEVBQVFsRSxLQUNSbUUsRUFBUSxTQUFTQyxFQUFPQyxHQUVwQixJQUFJQyxFQUFRLEdBd0JaLE9BeEJ5QkYsRUFBTUcsU0FBU0wsRUFBSzlELFFBQVFXLGdCQUUvQ2pCLEtBQUssV0FNUCxJQUpBLElBQ2dCMEUsRUFHQW5FLEVBQU1vRSxFQUpsQkMsRUFBUXBILEVBQUd1QyxFQUFFRyxNQUNiNEIsRUFBUSxHQUNSK0MsRUFBUUQsRUFBR0gsU0FBU0wsRUFBSzlELFFBQVF3RSxZQUU1QkMsRUFBSSxFQUFjQSxFQUFJSCxFQUFHLEdBQUdJLFdBQVd2QyxPQUFRc0MsSUFFWixLQUR4Q0wsRUFBWUUsRUFBRyxHQUFHSSxXQUFXRCxJQUNmRSxLQUFLbEUsUUFBUSxXQUN2QlIsRUFBYW1FLEVBQVVPLEtBQUtDLE9BQU8sR0FDbkNQLEVBQWNuSCxFQUFHNkMsTUFBTThFLFNBQVNULEVBQVVVLE9BQzFDdEQsRUFBS3ZCLEdBQVNvRSxHQUF3QixTQUFqQkQsRUFBVVUsT0FBbUMsS0FBakJWLEVBQVVVLE1BQWNULEVBQUlELEVBQVVVLE9BSTNGUCxFQUFJcEMsU0FDSlgsRUFBSzJDLFNBQVdKLEVBQUtRLEVBQUtOLEVBQVEsSUFHdENDLEVBQU1hLEtBQUt2RCxLQUdSMEMsR0FLZixPQUZPSCxFQUFLRCxFQUFLL0MsUUEvQkwsSUFvQ2hCK0MsS0FBTSxTQUFTOUQsR0FFWCxJQUFJSCxFQUFRLEdBR1JrRSxFQUFRLFNBQVNDLEVBQU9DLEVBQU9lLEdBRWZoQixFQUFNRyxTQUFTbkUsRUFBUVcsZ0JBRTdCakIsS0FBSyxTQUFTdUYsR0FDaEIsSUFBSVgsRUFBT3BILEVBQUd1QyxFQUFFRyxNQUNaNEIsRUFBT3RFLEVBQUd1QyxFQUFFeUYsT0FBTyxDQUFDQyxVQUFZSCxHQUFrQixLQUFPZixNQUFPQSxFQUFPbUIsTUFBT0gsR0FBUVgsRUFBR3pFLFFBQ3pGMEUsRUFBT0QsRUFBR0gsU0FBU25FLEVBQVF3RSxZQUUvQjNFLEVBQUtrRixLQUFLdkQsR0FFTitDLEVBQUlwQyxRQUNKNEIsRUFBS1EsRUFBS04sRUFBUSxFQUFHSyxFQUFHekUsS0FBS0csRUFBUXFGLFlBQWMsVUFTbkUsT0FKQXJGLEVBQVU5QyxFQUFHdUMsRUFBRXlGLE9BQU8sR0FuQlZ0RixLQW1CbUJJLFFBQVNBLEdBRXhDK0QsRUFyQlluRSxLQXFCRm1CLFFBcEJFLEdBc0JMbEIsR0FHWGlCLE1BQU8sV0FFSGxCLEtBQUswRixNQUFRLENBQ1RDLFFBQVksRUFDWkMsUUFBWSxFQUNaQyxPQUFZLEVBQ1pDLE9BQVksRUFDWkMsTUFBWSxFQUNaQyxNQUFZLEVBQ1pDLEtBQVksRUFDWkMsS0FBWSxFQUNaQyxNQUFZLEVBQ1pDLE1BQVksRUFDWkMsTUFBWSxFQUNaQyxLQUFZLEVBQ1pDLEtBQVksRUFDWkMsU0FBWSxFQUNaQyxTQUFZLEVBQ1pDLFFBQVksRUFDWkMsUUFBWSxHQUVoQjNHLEtBQUs0RyxRQUFhLEVBQ2xCNUcsS0FBS3NCLE9BQWEsS0FDbEJ0QixLQUFLNkcsV0FBYSxLQUNsQjdHLEtBQUs4RyxVQUFhLEVBQ2xCOUcsS0FBSytHLFlBQWEsRUFDbEIvRyxLQUFLZ0gsUUFBYSxLQUVsQixJQUFLLElBQUluQyxFQUFFLEVBQUdBLEVBQUVsSCxFQUFhNEUsT0FBUXNDLElBQ2pDN0UsS0FBS2lCLGVBQWV0RCxFQUFha0gsSUFHckNsSCxFQUFlLElBR25CcUUsV0FBWSxTQUFTMEMsR0FDakIxRSxLQUFLMEUsRUFBR2xDLFNBQVN4QyxLQUFLSSxRQUFRMUIsZ0JBQWtCLGFBQWEsZ0JBQWdCZ0csSUFHakYzQyxXQUFZLFNBQVMyQyxHQUNqQkEsRUFBR3VDLFlBQVlqSCxLQUFLSSxRQUFRMUIsaUJBR2hDb0QsYUFBYyxTQUFTNEMsR0FDUEEsRUFBR0gsU0FBU3ZFLEtBQUtJLFFBQVF3RSxZQUMzQnJDLFFBQ05tQyxFQUFHMUQsU0FBU2hCLEtBQUtJLFFBQVExQixpQkFJakN3SSxVQUFXLFdBQ1AsSUFBSWhELEVBQU9sRSxLQUNYQSxLQUFLYyxLQUFLb0QsRUFBSzlELFFBQVFXLGdCQUFnQmpCLEtBQUssV0FDeENvRSxFQUFLbkMsV0FBV3pFLEVBQUd1QyxFQUFFRyxVQUk3Qm1ILFlBQWEsV0FDVCxJQUFJakQsRUFBT2xFLEtBQ1hBLEtBQUtjLEtBQUtvRCxFQUFLOUQsUUFBUVcsZ0JBQWdCakIsS0FBSyxXQUN4Q29FLEVBQUtwQyxhQUFheEUsRUFBR3VDLEVBQUVHLFVBSS9CcUIsVUFBVyxTQUFTcUQsR0FFWkEsRUFBR0gsU0FBU3ZFLEtBQUtJLFFBQVF3RSxZQUFZckMsUUFDckNtQyxFQUFHMUQsU0FBUyxjQUlwQm9HLFlBQWEsU0FBUzFDLEdBQ2xCQSxFQUFHdUMsWUFBWSxhQUFhakgsS0FBS0ksUUFBUTFCLGdCQUN6Q2dHLEVBQUdILFNBQVN2RSxLQUFLSSxRQUFRd0UsWUFBWXlDLFVBR3pDdkUsVUFBVyxTQUFTM0QsR0FFaEIsSUFBSXVHLEVBQVcxRixLQUFLMEYsTUFFaEI0QixFQURXaEssRUFBR3VDLEVBQUVWLEVBQUVzQyxRQUNBSSxRQUFRN0IsS0FBS0ksUUFBUVcsZ0JBQ3ZDMUIsRUFBV2lJLEVBQVNqSSxTQUV4QlcsS0FBS3VILFFBQVVELEVBRWY1QixFQUFNQyxRQUFVeEcsRUFBRStELE1BQVE3RCxFQUFPbUksS0FDakM5QixFQUFNRSxRQUFVekcsRUFBRWlFLE1BQVEvRCxFQUFPRCxJQUVqQ3NHLEVBQU1HLE9BQVNILEVBQU1LLE1BQVExRyxFQUFPbUksS0FDcEM5QixFQUFNSSxPQUFTSixFQUFNTSxNQUFRM0csRUFBT0QsSUFFcENZLEtBQUs2RyxXQUFhN0csS0FBS21CLFFBRXZCbkIsS0FBS3NCLE9BQVNoRSxFQUFHdUMsRUFBRSxhQUFhbUIsU0FBU2hCLEtBQUtJLFFBQVFqQyxVQUFZLElBQU02QixLQUFLSSxRQUFRL0IsV0FBV29KLE9BQU9ILEVBQVNJLFNBQ2hIMUgsS0FBS3NCLE9BQU9xRyxJQUFJLFFBQVNMLEVBQVNNLFNBQ2xDNUgsS0FBS3VILFFBQVF2RyxTQUFTaEIsS0FBS0ksUUFBUXpCLGtCQUVuQ3BCLEVBQWtCeUMsS0FBS3NCLE9BRXZCdEIsS0FBSzZILGtCQUFvQixDQUFDUCxFQUFTLEdBQUdRLGdCQUFpQlIsRUFBUyxHQUFHUyxhQUVuRXpLLEVBQUcwSyxNQUFNUCxPQUFPekgsS0FBS3NCLFFBRXJCdEIsS0FBS3NCLE9BQU9xRyxJQUFJLENBQ1pILEtBQU9uSSxFQUFPbUksS0FDZHBJLElBQU9DLEVBQU9ELE1BSWxCLElBQUl5RixFQUFHUixFQUFPNEQsRUFBUWpJLEtBQUtzQixPQUFPUixLQUFLZCxLQUFLSSxRQUFRVyxnQkFFcEQsSUFBSzhELEVBQUksRUFBR0EsRUFBSW9ELEVBQU0xRixPQUFRc0MsS0FDMUJSLEVBQVEvRyxFQUFHdUMsRUFBRW9JLEVBQU1wRCxJQUFJeEMsUUFBUXJDLEtBQUtJLFFBQVF3RSxXQUFXLElBQUk1RSxLQUFLSSxRQUFROEgsZ0JBQWdCM0YsUUFDNUV2QyxLQUFLOEcsWUFDYjlHLEtBQUs4RyxVQUFZekMsR0FJekI1RyxFQUFLdUQsU0FBU2hCLEtBQUtJLFFBQVE5QixjQUcvQnlGLFNBQVUsU0FBUzVFLEdBRWYsSUFBSWdKLEVBQVc3SyxFQUFHdUMsRUFBRUcsS0FBS3VILFNBQ3JCYSxFQUFXcEksS0FBS3VILFFBQVFsRixRQUFRckMsS0FBS0ksUUFBUThILGVBQWUsVUFFaEVsSSxLQUFLdUgsUUFBUU4sWUFBWWpILEtBQUtJLFFBQVF6QixrQkFDdENxQixLQUFLc0IsT0FBTytGLFNBRVJySCxLQUFLbUIsUUFBUSxLQUFPaUgsRUFBSyxJQUV6QkEsRUFBS3JGLFFBQVEscUJBQXFCLENBQUNxRixFQUFLbkksS0FBSyxZQUFha0ksRUFBSSxVQUM5RG5JLEtBQUttQixRQUFRNEIsUUFBUSxxQkFBc0IsQ0FBQy9DLEtBQU1tSSxFQUFJLGFBR3REbkksS0FBS21CLFFBQVE0QixRQUFRLHFCQUFxQixDQUFDL0MsS0FBTW1JLEVBQUksVUFHekRuSSxLQUFLK0MsUUFBUSxtQkFBb0IsQ0FBQy9DLEtBQU1tSSxJQUV4Q25JLEtBQUtrQixRQUVMekQsRUFBS3dKLFlBQVlqSCxLQUFLSSxRQUFROUIsY0FHbEN1RixTQUFVLFNBQVMxRSxHQUNmLElBQUkrRSxFQUFNa0IsRUFBUWlELEVBQ2RDLEVBQVd0SSxLQUFLSSxRQUNoQnNGLEVBQVcxRixLQUFLMEYsTUFDaEI1RyxFQUFXa0IsS0FBSzZHLFdBQWE3RyxLQUFLNkcsV0FBVzVHLEtBQUssWUFBWUcsUUFBUXRCLFNBQVd3SixFQUFJeEosU0FFekZrQixLQUFLc0IsT0FBT3FHLElBQUksQ0FDWkgsS0FBT3JJLEVBQUUrRCxNQUFRd0MsRUFBTUMsUUFDdkJ2RyxJQUFPRCxFQUFFaUUsTUFBUXNDLEVBQU1FLFVBSTNCRixFQUFNSyxNQUFRTCxFQUFNTyxLQUNwQlAsRUFBTU0sTUFBUU4sRUFBTVEsS0FFcEJSLEVBQU1PLEtBQVE5RyxFQUFFK0QsTUFDaEJ3QyxFQUFNUSxLQUFRL0csRUFBRWlFLE1BRWhCc0MsRUFBTVMsTUFBUVQsRUFBTU8sS0FBT1AsRUFBTUssTUFDakNMLEVBQU1VLE1BQVFWLEVBQU1RLEtBQU9SLEVBQU1NLE1BRWpDTixFQUFNYyxTQUFXZCxFQUFNWSxLQUN2QlosRUFBTWUsU0FBV2YsRUFBTWEsS0FFdkJiLEVBQU1ZLEtBQXVCLElBQWhCWixFQUFNUyxNQUFjLEVBQWtCLEVBQWRULEVBQU1TLE1BQVksR0FBSyxFQUM1RFQsRUFBTWEsS0FBdUIsSUFBaEJiLEVBQU1VLE1BQWMsRUFBa0IsRUFBZFYsRUFBTVUsTUFBWSxHQUFLLEVBRTVELElBQUltQyxFQUFVaEosS0FBS21FLElBQUlnQyxFQUFNUyxPQUFTNUcsS0FBS21FLElBQUlnQyxFQUFNVSxPQUFTLEVBQUksRUFHbEUsSUFBS1YsRUFBTWtCLE9BR1AsT0FGQWxCLEVBQU1XLE1BQVNrQyxPQUNmN0MsRUFBTWtCLFFBQVMsR0F1Qm5CLEdBbEJJbEIsRUFBTVcsUUFBVWtDLEdBQ2hCN0MsRUFBTWdCLFFBQVUsRUFDaEJoQixFQUFNaUIsUUFBVSxJQUVoQmpCLEVBQU1nQixTQUFXbkgsS0FBS21FLElBQUlnQyxFQUFNUyxPQUNiLElBQWZULEVBQU1ZLE1BQWNaLEVBQU1ZLE9BQVNaLEVBQU1jLFdBQ3pDZCxFQUFNZ0IsUUFBVSxHQUVwQmhCLEVBQU1pQixTQUFXcEgsS0FBS21FLElBQUlnQyxFQUFNVSxPQUNiLElBQWZWLEVBQU1hLE1BQWNiLEVBQU1hLE9BQVNiLEVBQU1lLFdBQ3pDZixFQUFNaUIsUUFBVSxJQUd4QmpCLEVBQU1XLE1BQVFrQyxFQUtWN0MsRUFBTVcsT0FBU1gsRUFBTWdCLFNBQVc0QixFQUFJdkosWUFFcEMyRyxFQUFNZ0IsUUFBVSxFQUNoQjJCLEVBQU9ySSxLQUFLdUgsUUFBUWMsS0FBSyxNQUdQLEVBQWQzQyxFQUFNUyxPQUFha0MsRUFBSzlGLFNBQVc4RixFQUFLN0YsU0FBUzhGLEVBQUk1SixrQkFBb0IySixFQUFLN0YsU0FBUzhGLEVBQUkvSixtQkFHM0YyRixFQUFPbUUsRUFBS3ZILEtBQUt3SCxFQUFJMUQsWUFBWTRELE9BR3pCeEksS0FBS3VILFFBQVFsRixRQUFRaUcsRUFBSTFELFdBQVcsSUFBSTBELEVBQUlKLGdCQUFnQjNGLE9BRXhEdkMsS0FBSzhHLFdBQWFoSSxJQUdyQm9GLEVBQUszQixRQU9OMkIsRUFBT21FLEVBQUs5RCxTQUFTK0QsRUFBSTFELFlBQVk0RCxRQUNoQ2YsT0FBT3pILEtBQUt1SCxXQVBqQnJELEVBQU81RyxFQUFHdUMsRUFBRSxTQUFTbUIsU0FBU3NILEVBQUluSyxZQUM3QnNKLE9BQU96SCxLQUFLdUgsU0FDakJjLEVBQUtaLE9BQU92RCxHQUNabEUsS0FBS3FCLFVBQVVnSCxNQVV2QjNDLEVBQU1TLE1BQVEsSUFHUG5HLEtBQUt1SCxRQUFRa0IsS0FBS0gsRUFBSXZILGdCQUNuQndCLFFBQVEsQ0FHZCxJQUFJbUcsRUFBVzFJLEtBQUt1SCxRQUFRMUYsUUFBUSxDQUFDeUcsRUFBSUosZUFBZ0JJLEVBQUkxRCxZQUFZK0QsS0FBSyxNQUUxRUMsRUFBZ0JGLEVBQVM3RyxRQUFReUcsRUFBSXZILGdCQUdyQzZILEVBQWNyRyxTQUVkcUcsRUFBY0MsTUFBTTdJLEtBQUt1SCxTQUVwQm1CLEVBQVNuRSxXQUFXaEMsUUFDckJ2QyxLQUFLb0gsWUFBWXdCLElBT3JDLElBQUlFLEdBQVUsRUFHVkMsRUFBUzVKLEVBQUUrRCxPQUFTaEcsT0FBTzhMLGFBQWVDLFNBQVNDLFlBQWMsR0FDakVDLEVBQVNoSyxFQUFFaUUsT0FBU2xHLE9BQU9rTSxhQUFlSCxTQUFTSSxnQkFBZ0IvSixXQUd2RSxHQUZBVSxLQUFLZ0gsUUFBVTFKLEVBQUd1QyxFQUFFb0osU0FBU0ssaUJBQWlCUCxFQUFRSSxJQUVsRGIsRUFBSTdKLGFBQWV1QixLQUFLZ0gsUUFBUXhFLFNBQVM4RixFQUFJN0osYUFFN0N1QixLQUFLZ0gsUUFBVWhILEtBQUtnSCxRQUFRbkYsUUFBUXlHLEVBQUl2SCxvQkFFckMsQ0FFSCxJQUFJd0ksRUFBZXZKLEtBQUtnSCxRQUFRbkYsUUFBUXlHLEVBQUl2SCxnQkFFeEN3SSxFQUFhaEgsU0FDYnZDLEtBQUtnSCxRQUFVdUMsR0FJdkIsSUFBSXZKLEtBQUt1SCxRQUFRekcsS0FBS2QsS0FBS2dILFNBQVN6RSxPQUFwQyxDQUlBLEdBQUl2QyxLQUFLZ0gsUUFBUS9HLEtBQUssY0FBZ0JELEtBQUtnSCxRQUFRekMsV0FBV2hDLE9BQzFEdUcsR0FBVSxFQUNWOUksS0FBS2lCLGVBQWVqQixLQUFLZ0gsY0FDdEIsSUFBS2hILEtBQUtnSCxRQUFRekUsU0FBV3ZDLEtBQUtnSCxRQUFReEUsU0FBUzhGLEVBQUlsSyxlQUMxRCxPQUlKLElBQUlvTCxFQUFjeEosS0FBS21CLFFBQ25Cc0ksRUFBY3pKLEtBQUtnSCxRQUFRbkYsUUFBUTdCLEtBQUtJLFFBQVE4SCxnQkFDaER3QixFQUFjRixFQUFZLElBQU1DLEVBQVEsR0FLNUMsSUFBSy9ELEVBQU1XLE9BQVNxRCxHQUFhWixFQUFTLENBR3RDLEdBQUlZLEdBQWFwQixFQUFJekosUUFBVTRLLEVBQVF4SixLQUFLLGtCQUN4QyxPQVFKLEdBTkl0QyxFQUFhd0gsS0FBS3FFLEdBTVYxSyxFQUZKa0IsS0FBSzhHLFVBQVksRUFBSTlHLEtBQUtnSCxRQUFRM0UsUUFBUWlHLEVBQUkxRCxXQUFXLElBQUkwRCxFQUFJSixnQkFBZ0IzRixPQUdyRixPQUdKLElBQUlvSCxFQUFTeEssRUFBRWlFLE1BQVNwRCxLQUFLZ0gsUUFBUTNILFNBQVNELElBQU1ZLEtBQUtnSCxRQUFRdkgsU0FBVyxFQUU1RTJGLEVBQVNwRixLQUFLdUgsUUFBUW5DLFNBRWxCMEQsRUFDQTlJLEtBQUtnSCxRQUFRUyxPQUFPekgsS0FBS3VILFNBQ2xCb0MsRUFDUDNKLEtBQUtnSCxRQUFRMkMsT0FBTzNKLEtBQUt1SCxTQUV6QnZILEtBQUtnSCxRQUFRNkIsTUFBTTdJLEtBQUt1SCxTQUd2Qm5DLEVBQU9iLFdBQVdoQyxRQUNkNkMsRUFBT25GLEtBQUssYUFBYUQsS0FBS29ILFlBQVloQyxFQUFPQSxVQUcxRHBGLEtBQUtpQixlQUFlakIsS0FBSzZHLFlBQ3pCN0csS0FBS2lCLGVBQWV1SSxHQUdoQkUsSUFDQTFKLEtBQUs2RyxXQUFhNEMsRUFDbEJ6SixLQUFLK0csV0FBYS9HLEtBQUttQixRQUFRLEtBQU9uQixLQUFLNkcsV0FBVyxPQUtsRTVGLGVBQWdCLFNBQVNpRCxHQUVyQkEsRUFBUUEsRUFBTzVHLEVBQUd1QyxFQUFFcUUsR0FBUWxFLEtBQUttQixRQUU3Qm5CLEtBQUtJLFFBQVE1QixZQUNiMEYsRUFBTUEsRUFBS0ssV0FBV2hDLE9BQW9CLGNBQVgsWUFBMEJ2QyxLQUFLSSxRQUFRNUIsZUFNM0VsQixFQUFHNEMiLCJmaWxlIjoiY29tcG9uZW50cy9uZXN0YWJsZS5qcyIsInNvdXJjZXNDb250ZW50IjpbIi8qISBVSWtpdCAyLjI3LjIgfCBodHRwOi8vd3d3LmdldHVpa2l0LmNvbSB8IChjKSAyMDE0IFlPT3RoZW1lIHwgTUlUIExpY2Vuc2UgKi9cclxuLypcclxuICogQmFzZWQgb24gTmVzdGFibGUgalF1ZXJ5IFBsdWdpbiAtIENvcHlyaWdodCAoYykgMjAxMiBEYXZpZCBCdXNoZWxsIC0gaHR0cDovL2RidXNoZWxsLmNvbS9cclxuICovXHJcbihmdW5jdGlvbihhZGRvbikge1xyXG5cclxuICAgIHZhciBjb21wb25lbnQ7XHJcblxyXG4gICAgaWYgKHdpbmRvdy5VSWtpdDIpIHtcclxuICAgICAgICBjb21wb25lbnQgPSBhZGRvbihVSWtpdDIpO1xyXG4gICAgfVxyXG5cclxuICAgIGlmICh0eXBlb2YgZGVmaW5lID09ICdmdW5jdGlvbicgJiYgZGVmaW5lLmFtZCkge1xyXG4gICAgICAgIGRlZmluZSgndWlraXQtbmVzdGFibGUnLCBbJ3Vpa2l0J10sIGZ1bmN0aW9uKCl7XHJcbiAgICAgICAgICAgIHJldHVybiBjb21wb25lbnQgfHwgYWRkb24oVUlraXQyKTtcclxuICAgICAgICB9KTtcclxuICAgIH1cclxuXHJcbn0pKGZ1bmN0aW9uKFVJKSB7XHJcblxyXG4gICAgXCJ1c2Ugc3RyaWN0XCI7XHJcblxyXG4gICAgdmFyIGhhc1RvdWNoICAgICA9ICdvbnRvdWNoc3RhcnQnIGluIHdpbmRvdyxcclxuICAgICAgICBodG1sICAgICAgICAgPSBVSS4kaHRtbCxcclxuICAgICAgICB0b3VjaGVkbGlzdHMgPSBbXSxcclxuICAgICAgICAkd2luICAgICAgICAgPSBVSS4kd2luLFxyXG4gICAgICAgIGRyYWdnaW5nRWxlbWVudDtcclxuXHJcbiAgICB2YXIgZVN0YXJ0ICA9IGhhc1RvdWNoID8gJ3RvdWNoc3RhcnQnICA6ICdtb3VzZWRvd24nLFxyXG4gICAgICAgIGVNb3ZlICAgPSBoYXNUb3VjaCA/ICd0b3VjaG1vdmUnICAgOiAnbW91c2Vtb3ZlJyxcclxuICAgICAgICBlRW5kICAgID0gaGFzVG91Y2ggPyAndG91Y2hlbmQnICAgIDogJ21vdXNldXAnLFxyXG4gICAgICAgIGVDYW5jZWwgPSBoYXNUb3VjaCA/ICd0b3VjaGNhbmNlbCcgOiAnbW91c2V1cCc7XHJcblxyXG5cclxuICAgIFVJLmNvbXBvbmVudCgnbmVzdGFibGUnLCB7XHJcblxyXG4gICAgICAgIGRlZmF1bHRzOiB7XHJcbiAgICAgICAgICAgIGxpc3RCYXNlQ2xhc3MgICA6ICd1ay1uZXN0YWJsZScsXHJcbiAgICAgICAgICAgIGxpc3RDbGFzcyAgICAgICA6ICd1ay1uZXN0YWJsZS1saXN0JyxcclxuICAgICAgICAgICAgbGlzdEl0ZW1DbGFzcyAgIDogJ3VrLW5lc3RhYmxlLWl0ZW0nLFxyXG4gICAgICAgICAgICBkcmFnQ2xhc3MgICAgICAgOiAndWstbmVzdGFibGUtZHJhZ2dlZCcsXHJcbiAgICAgICAgICAgIG1vdmluZ0NsYXNzICAgICA6ICd1ay1uZXN0YWJsZS1tb3ZpbmcnLFxyXG4gICAgICAgICAgICBub0NoaWxkcmVuQ2xhc3MgOiAndWstbmVzdGFibGUtbm9jaGlsZHJlbicsXHJcbiAgICAgICAgICAgIGVtcHR5Q2xhc3MgICAgICA6ICd1ay1uZXN0YWJsZS1lbXB0eScsXHJcbiAgICAgICAgICAgIGhhbmRsZUNsYXNzICAgICA6ICcnLFxyXG4gICAgICAgICAgICBjb2xsYXBzZWRDbGFzcyAgOiAndWstY29sbGFwc2VkJyxcclxuICAgICAgICAgICAgcGxhY2Vob2xkZXJDbGFzczogJ3VrLW5lc3RhYmxlLXBsYWNlaG9sZGVyJyxcclxuICAgICAgICAgICAgbm9EcmFnQ2xhc3MgICAgIDogJ3VrLW5lc3RhYmxlLW5vZHJhZycsXHJcbiAgICAgICAgICAgIGdyb3VwICAgICAgICAgICA6IGZhbHNlLFxyXG4gICAgICAgICAgICBtYXhEZXB0aCAgICAgICAgOiAxMCxcclxuICAgICAgICAgICAgdGhyZXNob2xkICAgICAgIDogMjAsXHJcbiAgICAgICAgICAgIGlkbGV0aHJlc2hvbGQgICA6IDEwLFxyXG4gICAgICAgIH0sXHJcblxyXG4gICAgICAgIGJvb3Q6IGZ1bmN0aW9uKCkge1xyXG5cclxuICAgICAgICAgICAgLy8gYWRqdXN0IGRvY3VtZW50IHNjcm9sbGluZ1xyXG4gICAgICAgICAgICBVSS4kaHRtbC5vbignbW91c2Vtb3ZlIHRvdWNobW92ZScsIGZ1bmN0aW9uKGUpIHtcclxuXHJcbiAgICAgICAgICAgICAgICBpZiAoZHJhZ2dpbmdFbGVtZW50KSB7XHJcblxyXG4gICAgICAgICAgICAgICAgICAgIHZhciB0b3AgPSBkcmFnZ2luZ0VsZW1lbnQub2Zmc2V0KCkudG9wO1xyXG5cclxuICAgICAgICAgICAgICAgICAgICBpZiAodG9wIDwgVUkuJHdpbi5zY3JvbGxUb3AoKSkge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICBVSS4kd2luLnNjcm9sbFRvcChVSS4kd2luLnNjcm9sbFRvcCgpIC0gTWF0aC5jZWlsKGRyYWdnaW5nRWxlbWVudC5oZWlnaHQoKS8yKSk7XHJcbiAgICAgICAgICAgICAgICAgICAgfSBlbHNlIGlmICggKHRvcCArIGRyYWdnaW5nRWxlbWVudC5oZWlnaHQoKSkgPiAod2luZG93LmlubmVySGVpZ2h0ICsgVUkuJHdpbi5zY3JvbGxUb3AoKSkgKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIFVJLiR3aW4uc2Nyb2xsVG9wKFVJLiR3aW4uc2Nyb2xsVG9wKCkgKyBNYXRoLmNlaWwoZHJhZ2dpbmdFbGVtZW50LmhlaWdodCgpLzIpKTtcclxuICAgICAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgIH0pO1xyXG5cclxuICAgICAgICAgICAgLy8gaW5pdCBjb2RlXHJcbiAgICAgICAgICAgIFVJLnJlYWR5KGZ1bmN0aW9uKGNvbnRleHQpIHtcclxuXHJcbiAgICAgICAgICAgICAgICBVSS4kKFwiW2RhdGEtdWstbmVzdGFibGVdXCIsIGNvbnRleHQpLmVhY2goZnVuY3Rpb24oKXtcclxuXHJcbiAgICAgICAgICAgICAgICAgICAgdmFyIGVsZSA9IFVJLiQodGhpcyk7XHJcblxyXG4gICAgICAgICAgICAgICAgICAgIGlmICghZWxlLmRhdGEoXCJuZXN0YWJsZVwiKSkge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICBVSS5uZXN0YWJsZShlbGUsIFVJLlV0aWxzLm9wdGlvbnMoZWxlLmF0dHIoXCJkYXRhLXVrLW5lc3RhYmxlXCIpKSk7XHJcbiAgICAgICAgICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICAgICAgfSk7XHJcbiAgICAgICAgICAgIH0pO1xyXG4gICAgICAgIH0sXHJcblxyXG4gICAgICAgIGluaXQ6IGZ1bmN0aW9uKCkge1xyXG5cclxuICAgICAgICAgICAgdmFyICR0aGlzID0gdGhpcztcclxuXHJcbiAgICAgICAgICAgIE9iamVjdC5rZXlzKHRoaXMub3B0aW9ucykuZm9yRWFjaChmdW5jdGlvbihrZXkpe1xyXG5cclxuICAgICAgICAgICAgICAgIGlmKFN0cmluZyhrZXkpLmluZGV4T2YoJ0NsYXNzJykhPS0xKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgJHRoaXMub3B0aW9uc1snXycra2V5XSA9ICcuJyArICR0aGlzLm9wdGlvbnNba2V5XTtcclxuICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgfSk7XHJcblxyXG4gICAgICAgICAgICB0aGlzLmZpbmQodGhpcy5vcHRpb25zLl9saXN0SXRlbUNsYXNzKS5maW5kKFwiPnVsXCIpLmFkZENsYXNzKHRoaXMub3B0aW9ucy5saXN0Q2xhc3MpO1xyXG5cclxuICAgICAgICAgICAgdGhpcy5jaGVja0VtcHR5TGlzdCgpO1xyXG5cclxuICAgICAgICAgICAgdGhpcy5yZXNldCgpO1xyXG4gICAgICAgICAgICB0aGlzLmVsZW1lbnQuZGF0YSgnbmVzdGFibGUtZ3JvdXAnLCB0aGlzLm9wdGlvbnMuZ3JvdXAgfHwgVUkuVXRpbHMudWlkKCduZXN0YWJsZS1ncm91cCcpKTtcclxuXHJcbiAgICAgICAgICAgIHRoaXMuZmluZCh0aGlzLm9wdGlvbnMuX2xpc3RJdGVtQ2xhc3MpLmVhY2goZnVuY3Rpb24oKSB7XHJcbiAgICAgICAgICAgICAgICAkdGhpcy5zZXRQYXJlbnQoVUkuJCh0aGlzKSk7XHJcbiAgICAgICAgICAgIH0pO1xyXG5cclxuICAgICAgICAgICAgdGhpcy5vbignY2xpY2snLCAnW2RhdGEtbmVzdGFibGUtYWN0aW9uXScsIGZ1bmN0aW9uKGUpIHtcclxuXHJcbiAgICAgICAgICAgICAgICBpZiAoJHRoaXMuZHJhZ0VsIHx8ICghaGFzVG91Y2ggJiYgZS5idXR0b24gIT09IDApKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgcmV0dXJuO1xyXG4gICAgICAgICAgICAgICAgfVxyXG5cclxuICAgICAgICAgICAgICAgIGUucHJldmVudERlZmF1bHQoKTtcclxuXHJcbiAgICAgICAgICAgICAgICB2YXIgdGFyZ2V0ID0gVUkuJChlLmN1cnJlbnRUYXJnZXQpLFxyXG4gICAgICAgICAgICAgICAgICAgIGFjdGlvbiA9IHRhcmdldC5kYXRhKCduZXN0YWJsZUFjdGlvbicpLFxyXG4gICAgICAgICAgICAgICAgICAgIGl0ZW0gICA9IHRhcmdldC5jbG9zZXN0KCR0aGlzLm9wdGlvbnMuX2xpc3RJdGVtQ2xhc3MpO1xyXG5cclxuICAgICAgICAgICAgICAgIGlmIChhY3Rpb24gPT09ICdjb2xsYXBzZScpIHtcclxuICAgICAgICAgICAgICAgICAgICAkdGhpcy5jb2xsYXBzZUl0ZW0oaXRlbSk7XHJcbiAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICBpZiAoYWN0aW9uID09PSAnZXhwYW5kJykge1xyXG4gICAgICAgICAgICAgICAgICAgICR0aGlzLmV4cGFuZEl0ZW0oaXRlbSk7XHJcbiAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICBpZiAoYWN0aW9uID09PSAndG9nZ2xlJykge1xyXG4gICAgICAgICAgICAgICAgICAgICR0aGlzLnRvZ2dsZUl0ZW0oaXRlbSk7XHJcbiAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgIH0pO1xyXG5cclxuICAgICAgICAgICAgdmFyIG9uU3RhcnRFdmVudCA9IGZ1bmN0aW9uKGUpIHtcclxuXHJcbiAgICAgICAgICAgICAgICB2YXIgaGFuZGxlID0gVUkuJChlLnRhcmdldCksXHJcbiAgICAgICAgICAgICAgICAgICAgbGluayAgID0gaGFuZGxlLmlzKCdhW2hyZWZdJykgPyBoYW5kbGU6aGFuZGxlLnBhcmVudHMoJ2FbaHJlZl0nKTtcclxuXHJcbiAgICAgICAgICAgICAgICBpZiAoZS50YXJnZXQgPT09ICR0aGlzLmVsZW1lbnRbMF0pIHtcclxuICAgICAgICAgICAgICAgICAgICByZXR1cm47XHJcbiAgICAgICAgICAgICAgICB9XHJcblxyXG4gICAgICAgICAgICAgICAgaWYgKGhhbmRsZS5pcygkdGhpcy5vcHRpb25zLl9ub0RyYWdDbGFzcykgfHwgaGFuZGxlLmNsb3Nlc3QoJHRoaXMub3B0aW9ucy5fbm9EcmFnQ2xhc3MpLmxlbmd0aCkge1xyXG4gICAgICAgICAgICAgICAgICAgIHJldHVybjtcclxuICAgICAgICAgICAgICAgIH1cclxuXHJcbiAgICAgICAgICAgICAgICBpZiAoaGFuZGxlLmlzKCdbZGF0YS1uZXN0YWJsZS1hY3Rpb25dJykgfHwgaGFuZGxlLmNsb3Nlc3QoJ1tkYXRhLW5lc3RhYmxlLWFjdGlvbl0nKS5sZW5ndGgpIHtcclxuICAgICAgICAgICAgICAgICAgICByZXR1cm47XHJcbiAgICAgICAgICAgICAgICB9XHJcblxyXG4gICAgICAgICAgICAgICAgaWYgKCR0aGlzLm9wdGlvbnMuaGFuZGxlQ2xhc3MgJiYgIWhhbmRsZS5oYXNDbGFzcygkdGhpcy5vcHRpb25zLmhhbmRsZUNsYXNzKSkge1xyXG5cclxuICAgICAgICAgICAgICAgICAgICBpZiAoJHRoaXMub3B0aW9ucy5oYW5kbGVDbGFzcykge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICBoYW5kbGUgPSBoYW5kbGUuY2xvc2VzdCgkdGhpcy5vcHRpb25zLl9oYW5kbGVDbGFzcyk7XHJcbiAgICAgICAgICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICAgICAgfVxyXG5cclxuICAgICAgICAgICAgICAgIGlmICghaGFuZGxlLmxlbmd0aCB8fCAkdGhpcy5kcmFnRWwgfHwgKCFoYXNUb3VjaCAmJiBlLmJ1dHRvbiAhPT0gMCkgfHwgKGhhc1RvdWNoICYmIGUudG91Y2hlcy5sZW5ndGggIT09IDEpKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgcmV0dXJuO1xyXG4gICAgICAgICAgICAgICAgfVxyXG5cclxuICAgICAgICAgICAgICAgIGlmIChlLm9yaWdpbmFsRXZlbnQgJiYgZS5vcmlnaW5hbEV2ZW50LnRvdWNoZXMpIHtcclxuICAgICAgICAgICAgICAgICAgICBlID0gZXZ0Lm9yaWdpbmFsRXZlbnQudG91Y2hlc1swXTtcclxuICAgICAgICAgICAgICAgIH1cclxuXHJcbiAgICAgICAgICAgICAgICAkdGhpcy5kZWxheU1vdmUgPSBmdW5jdGlvbihldnQpIHtcclxuXHJcbiAgICAgICAgICAgICAgICAgICAgbGluayA9IGZhbHNlO1xyXG5cclxuICAgICAgICAgICAgICAgICAgICBldnQucHJldmVudERlZmF1bHQoKTtcclxuICAgICAgICAgICAgICAgICAgICAkdGhpcy5kcmFnU3RhcnQoZSk7XHJcbiAgICAgICAgICAgICAgICAgICAgJHRoaXMudHJpZ2dlcignc3RhcnQudWsubmVzdGFibGUnLCBbJHRoaXNdKTtcclxuXHJcbiAgICAgICAgICAgICAgICAgICAgJHRoaXMuZGVsYXlNb3ZlID0gZmFsc2U7XHJcbiAgICAgICAgICAgICAgICB9O1xyXG5cclxuICAgICAgICAgICAgICAgICR0aGlzLmRlbGF5TW92ZS54ICAgICAgICAgPSBwYXJzZUludChlLnBhZ2VYLCAxMCk7XHJcbiAgICAgICAgICAgICAgICAkdGhpcy5kZWxheU1vdmUueSAgICAgICAgID0gcGFyc2VJbnQoZS5wYWdlWSwgMTApO1xyXG4gICAgICAgICAgICAgICAgJHRoaXMuZGVsYXlNb3ZlLnRocmVzaG9sZCA9ICR0aGlzLm9wdGlvbnMuaWRsZXRocmVzaG9sZDtcclxuXHJcbiAgICAgICAgICAgICAgICBpZiAobGluay5sZW5ndGggJiYgZUVuZCA9PSAndG91Y2hlbmQnKSB7XHJcblxyXG4gICAgICAgICAgICAgICAgICAgICR0aGlzLm9uZShlRW5kLCBmdW5jdGlvbigpe1xyXG4gICAgICAgICAgICAgICAgICAgICAgICBpZiAobGluayAmJiBsaW5rLmF0dHIoJ2hyZWYnKS50cmltKCkpIHtcclxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIGxvY2F0aW9uLmhyZWYgPSBsaW5rLmF0dHIoJ2hyZWYnKTtcclxuICAgICAgICAgICAgICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICAgICAgICAgIH0pO1xyXG4gICAgICAgICAgICAgICAgfVxyXG5cclxuICAgICAgICAgICAgICAgIGUucHJldmVudERlZmF1bHQoKTtcclxuICAgICAgICAgICAgfTtcclxuXHJcbiAgICAgICAgICAgIHZhciBvbk1vdmVFdmVudCA9IGZ1bmN0aW9uKGUpIHtcclxuXHJcbiAgICAgICAgICAgICAgICBpZiAoZS5vcmlnaW5hbEV2ZW50ICYmIGUub3JpZ2luYWxFdmVudC50b3VjaGVzKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgZSA9IGUub3JpZ2luYWxFdmVudC50b3VjaGVzWzBdO1xyXG4gICAgICAgICAgICAgICAgfVxyXG5cclxuICAgICAgICAgICAgICAgIGlmICgkdGhpcy5kZWxheU1vdmUgJiYgKE1hdGguYWJzKGUucGFnZVggLSAkdGhpcy5kZWxheU1vdmUueCkgPiAkdGhpcy5kZWxheU1vdmUudGhyZXNob2xkIHx8IE1hdGguYWJzKGUucGFnZVkgLSAkdGhpcy5kZWxheU1vdmUueSkgPiAkdGhpcy5kZWxheU1vdmUudGhyZXNob2xkKSkge1xyXG5cclxuICAgICAgICAgICAgICAgICAgICBpZiAoIXdpbmRvdy5nZXRTZWxlY3Rpb24oKS50b1N0cmluZygpKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgICR0aGlzLmRlbGF5TW92ZShlKTtcclxuICAgICAgICAgICAgICAgICAgICB9IGVsc2Uge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAkdGhpcy5kZWxheU1vdmUgPSBmYWxzZTtcclxuICAgICAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICB9XHJcblxyXG4gICAgICAgICAgICAgICAgaWYgKCR0aGlzLmRyYWdFbCkge1xyXG4gICAgICAgICAgICAgICAgICAgIGUucHJldmVudERlZmF1bHQoKTtcclxuICAgICAgICAgICAgICAgICAgICAkdGhpcy5kcmFnTW92ZShlKTtcclxuICAgICAgICAgICAgICAgICAgICAkdGhpcy50cmlnZ2VyKCdtb3ZlLnVrLm5lc3RhYmxlJywgWyR0aGlzXSk7XHJcbiAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgIH07XHJcblxyXG4gICAgICAgICAgICB2YXIgb25FbmRFdmVudCA9IGZ1bmN0aW9uKGUpIHtcclxuXHJcbiAgICAgICAgICAgICAgICBpZiAoJHRoaXMuZHJhZ0VsKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgZS5wcmV2ZW50RGVmYXVsdCgpO1xyXG4gICAgICAgICAgICAgICAgICAgICR0aGlzLmRyYWdTdG9wKGhhc1RvdWNoID8gZS50b3VjaGVzWzBdIDogZSk7XHJcbiAgICAgICAgICAgICAgICB9XHJcblxyXG4gICAgICAgICAgICAgICAgZHJhZ2dpbmdFbGVtZW50ID0gZmFsc2U7XHJcbiAgICAgICAgICAgICAgICAkdGhpcy5kZWxheU1vdmUgPSBmYWxzZTtcclxuICAgICAgICAgICAgfTtcclxuXHJcbiAgICAgICAgICAgIGlmIChoYXNUb3VjaCkge1xyXG4gICAgICAgICAgICAgICAgdGhpcy5lbGVtZW50WzBdLmFkZEV2ZW50TGlzdGVuZXIoZVN0YXJ0LCBvblN0YXJ0RXZlbnQsIGZhbHNlKTtcclxuICAgICAgICAgICAgICAgIHdpbmRvdy5hZGRFdmVudExpc3RlbmVyKGVNb3ZlLCBvbk1vdmVFdmVudCwgZmFsc2UpO1xyXG4gICAgICAgICAgICAgICAgd2luZG93LmFkZEV2ZW50TGlzdGVuZXIoZUVuZCwgb25FbmRFdmVudCwgZmFsc2UpO1xyXG4gICAgICAgICAgICAgICAgd2luZG93LmFkZEV2ZW50TGlzdGVuZXIoZUNhbmNlbCwgb25FbmRFdmVudCwgZmFsc2UpO1xyXG4gICAgICAgICAgICB9IGVsc2Uge1xyXG4gICAgICAgICAgICAgICAgdGhpcy5vbihlU3RhcnQsIG9uU3RhcnRFdmVudCk7XHJcbiAgICAgICAgICAgICAgICAkd2luLm9uKGVNb3ZlLCBvbk1vdmVFdmVudCk7XHJcbiAgICAgICAgICAgICAgICAkd2luLm9uKGVFbmQsIG9uRW5kRXZlbnQpO1xyXG4gICAgICAgICAgICB9XHJcblxyXG4gICAgICAgIH0sXHJcblxyXG4gICAgICAgIHNlcmlhbGl6ZTogZnVuY3Rpb24oKSB7XHJcblxyXG4gICAgICAgICAgICB2YXIgZGF0YSxcclxuICAgICAgICAgICAgICAgIGRlcHRoID0gMCxcclxuICAgICAgICAgICAgICAgIGxpc3QgID0gdGhpcyxcclxuICAgICAgICAgICAgICAgIHN0ZXAgID0gZnVuY3Rpb24obGV2ZWwsIGRlcHRoKSB7XHJcblxyXG4gICAgICAgICAgICAgICAgICAgIHZhciBhcnJheSA9IFsgXSwgaXRlbXMgPSBsZXZlbC5jaGlsZHJlbihsaXN0Lm9wdGlvbnMuX2xpc3RJdGVtQ2xhc3MpO1xyXG5cclxuICAgICAgICAgICAgICAgICAgICBpdGVtcy5lYWNoKGZ1bmN0aW9uKCkge1xyXG5cclxuICAgICAgICAgICAgICAgICAgICAgICAgdmFyIGxpICAgID0gVUkuJCh0aGlzKSxcclxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIGl0ZW0gID0ge30sIGF0dHJpYnV0ZSxcclxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIHN1YiAgID0gbGkuY2hpbGRyZW4obGlzdC5vcHRpb25zLl9saXN0Q2xhc3MpO1xyXG5cclxuICAgICAgICAgICAgICAgICAgICAgICAgZm9yICh2YXIgaSA9IDAsIGF0dHIsIHZhbDsgaSA8IGxpWzBdLmF0dHJpYnV0ZXMubGVuZ3RoOyBpKyspIHtcclxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIGF0dHJpYnV0ZSA9IGxpWzBdLmF0dHJpYnV0ZXNbaV07XHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBpZiAoYXR0cmlidXRlLm5hbWUuaW5kZXhPZignZGF0YS0nKSA9PT0gMCkge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGF0dHIgICAgICAgPSBhdHRyaWJ1dGUubmFtZS5zdWJzdHIoNSk7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgdmFsICAgICAgICA9ICBVSS5VdGlscy5zdHIyanNvbihhdHRyaWJ1dGUudmFsdWUpO1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGl0ZW1bYXR0cl0gPSAodmFsIHx8IGF0dHJpYnV0ZS52YWx1ZT09J2ZhbHNlJyB8fCBhdHRyaWJ1dGUudmFsdWU9PScwJykgPyB2YWw6YXR0cmlidXRlLnZhbHVlO1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICAgICAgICAgICAgICB9XHJcblxyXG4gICAgICAgICAgICAgICAgICAgICAgICBpZiAoc3ViLmxlbmd0aCkge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgaXRlbS5jaGlsZHJlbiA9IHN0ZXAoc3ViLCBkZXB0aCArIDEpO1xyXG4gICAgICAgICAgICAgICAgICAgICAgICB9XHJcblxyXG4gICAgICAgICAgICAgICAgICAgICAgICBhcnJheS5wdXNoKGl0ZW0pO1xyXG5cclxuICAgICAgICAgICAgICAgICAgICB9KTtcclxuICAgICAgICAgICAgICAgICAgICByZXR1cm4gYXJyYXk7XHJcbiAgICAgICAgICAgICAgICB9O1xyXG5cclxuICAgICAgICAgICAgZGF0YSA9IHN0ZXAobGlzdC5lbGVtZW50LCBkZXB0aCk7XHJcblxyXG4gICAgICAgICAgICByZXR1cm4gZGF0YTtcclxuICAgICAgICB9LFxyXG5cclxuICAgICAgICBsaXN0OiBmdW5jdGlvbihvcHRpb25zKSB7XHJcblxyXG4gICAgICAgICAgICB2YXIgZGF0YSAgPSBbXSxcclxuICAgICAgICAgICAgICAgIGxpc3QgID0gdGhpcyxcclxuICAgICAgICAgICAgICAgIGRlcHRoID0gMCxcclxuICAgICAgICAgICAgICAgIHN0ZXAgID0gZnVuY3Rpb24obGV2ZWwsIGRlcHRoLCBwYXJlbnQpIHtcclxuXHJcbiAgICAgICAgICAgICAgICAgICAgdmFyIGl0ZW1zID0gbGV2ZWwuY2hpbGRyZW4ob3B0aW9ucy5fbGlzdEl0ZW1DbGFzcyk7XHJcblxyXG4gICAgICAgICAgICAgICAgICAgIGl0ZW1zLmVhY2goZnVuY3Rpb24oaW5kZXgpIHtcclxuICAgICAgICAgICAgICAgICAgICAgICAgdmFyIGxpICAgPSBVSS4kKHRoaXMpLFxyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgaXRlbSA9IFVJLiQuZXh0ZW5kKHtwYXJlbnRfaWQ6IChwYXJlbnQgPyBwYXJlbnQgOiBudWxsKSwgZGVwdGg6IGRlcHRoLCBvcmRlcjogaW5kZXh9LCBsaS5kYXRhKCkpLFxyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgc3ViICA9IGxpLmNoaWxkcmVuKG9wdGlvbnMuX2xpc3RDbGFzcyk7XHJcblxyXG4gICAgICAgICAgICAgICAgICAgICAgICBkYXRhLnB1c2goaXRlbSk7XHJcblxyXG4gICAgICAgICAgICAgICAgICAgICAgICBpZiAoc3ViLmxlbmd0aCkge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgc3RlcChzdWIsIGRlcHRoICsgMSwgbGkuZGF0YShvcHRpb25zLmlkUHJvcGVydHkgfHwgJ2lkJykpO1xyXG4gICAgICAgICAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICAgICAgfSk7XHJcbiAgICAgICAgICAgICAgICB9O1xyXG5cclxuICAgICAgICAgICAgb3B0aW9ucyA9IFVJLiQuZXh0ZW5kKHt9LCBsaXN0Lm9wdGlvbnMsIG9wdGlvbnMpO1xyXG5cclxuICAgICAgICAgICAgc3RlcChsaXN0LmVsZW1lbnQsIGRlcHRoKTtcclxuXHJcbiAgICAgICAgICAgIHJldHVybiBkYXRhO1xyXG4gICAgICAgIH0sXHJcblxyXG4gICAgICAgIHJlc2V0OiBmdW5jdGlvbigpIHtcclxuXHJcbiAgICAgICAgICAgIHRoaXMubW91c2UgPSB7XHJcbiAgICAgICAgICAgICAgICBvZmZzZXRYICAgOiAwLFxyXG4gICAgICAgICAgICAgICAgb2Zmc2V0WSAgIDogMCxcclxuICAgICAgICAgICAgICAgIHN0YXJ0WCAgICA6IDAsXHJcbiAgICAgICAgICAgICAgICBzdGFydFkgICAgOiAwLFxyXG4gICAgICAgICAgICAgICAgbGFzdFggICAgIDogMCxcclxuICAgICAgICAgICAgICAgIGxhc3RZICAgICA6IDAsXHJcbiAgICAgICAgICAgICAgICBub3dYICAgICAgOiAwLFxyXG4gICAgICAgICAgICAgICAgbm93WSAgICAgIDogMCxcclxuICAgICAgICAgICAgICAgIGRpc3RYICAgICA6IDAsXHJcbiAgICAgICAgICAgICAgICBkaXN0WSAgICAgOiAwLFxyXG4gICAgICAgICAgICAgICAgZGlyQXggICAgIDogMCxcclxuICAgICAgICAgICAgICAgIGRpclggICAgICA6IDAsXHJcbiAgICAgICAgICAgICAgICBkaXJZICAgICAgOiAwLFxyXG4gICAgICAgICAgICAgICAgbGFzdERpclggIDogMCxcclxuICAgICAgICAgICAgICAgIGxhc3REaXJZICA6IDAsXHJcbiAgICAgICAgICAgICAgICBkaXN0QXhYICAgOiAwLFxyXG4gICAgICAgICAgICAgICAgZGlzdEF4WSAgIDogMFxyXG4gICAgICAgICAgICB9O1xyXG4gICAgICAgICAgICB0aGlzLm1vdmluZyAgICAgPSBmYWxzZTtcclxuICAgICAgICAgICAgdGhpcy5kcmFnRWwgICAgID0gbnVsbDtcclxuICAgICAgICAgICAgdGhpcy5kcmFnUm9vdEVsID0gbnVsbDtcclxuICAgICAgICAgICAgdGhpcy5kcmFnRGVwdGggID0gMDtcclxuICAgICAgICAgICAgdGhpcy5oYXNOZXdSb290ID0gZmFsc2U7XHJcbiAgICAgICAgICAgIHRoaXMucG9pbnRFbCAgICA9IG51bGw7XHJcblxyXG4gICAgICAgICAgICBmb3IgKHZhciBpPTA7IGk8dG91Y2hlZGxpc3RzLmxlbmd0aDsgaSsrKSB7XHJcbiAgICAgICAgICAgICAgICB0aGlzLmNoZWNrRW1wdHlMaXN0KHRvdWNoZWRsaXN0c1tpXSk7XHJcbiAgICAgICAgICAgIH1cclxuXHJcbiAgICAgICAgICAgIHRvdWNoZWRsaXN0cyA9IFtdO1xyXG4gICAgICAgIH0sXHJcblxyXG4gICAgICAgIHRvZ2dsZUl0ZW06IGZ1bmN0aW9uKGxpKSB7XHJcbiAgICAgICAgICAgIHRoaXNbbGkuaGFzQ2xhc3ModGhpcy5vcHRpb25zLmNvbGxhcHNlZENsYXNzKSA/ICdleHBhbmRJdGVtJzonY29sbGFwc2VJdGVtJ10obGkpO1xyXG4gICAgICAgIH0sXHJcblxyXG4gICAgICAgIGV4cGFuZEl0ZW06IGZ1bmN0aW9uKGxpKSB7XHJcbiAgICAgICAgICAgIGxpLnJlbW92ZUNsYXNzKHRoaXMub3B0aW9ucy5jb2xsYXBzZWRDbGFzcyk7XHJcbiAgICAgICAgfSxcclxuXHJcbiAgICAgICAgY29sbGFwc2VJdGVtOiBmdW5jdGlvbihsaSkge1xyXG4gICAgICAgICAgICB2YXIgbGlzdHMgPSBsaS5jaGlsZHJlbih0aGlzLm9wdGlvbnMuX2xpc3RDbGFzcyk7XHJcbiAgICAgICAgICAgIGlmIChsaXN0cy5sZW5ndGgpIHtcclxuICAgICAgICAgICAgICAgIGxpLmFkZENsYXNzKHRoaXMub3B0aW9ucy5jb2xsYXBzZWRDbGFzcyk7XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICB9LFxyXG5cclxuICAgICAgICBleHBhbmRBbGw6IGZ1bmN0aW9uKCkge1xyXG4gICAgICAgICAgICB2YXIgbGlzdCA9IHRoaXM7XHJcbiAgICAgICAgICAgIHRoaXMuZmluZChsaXN0Lm9wdGlvbnMuX2xpc3RJdGVtQ2xhc3MpLmVhY2goZnVuY3Rpb24oKSB7XHJcbiAgICAgICAgICAgICAgICBsaXN0LmV4cGFuZEl0ZW0oVUkuJCh0aGlzKSk7XHJcbiAgICAgICAgICAgIH0pO1xyXG4gICAgICAgIH0sXHJcblxyXG4gICAgICAgIGNvbGxhcHNlQWxsOiBmdW5jdGlvbigpIHtcclxuICAgICAgICAgICAgdmFyIGxpc3QgPSB0aGlzO1xyXG4gICAgICAgICAgICB0aGlzLmZpbmQobGlzdC5vcHRpb25zLl9saXN0SXRlbUNsYXNzKS5lYWNoKGZ1bmN0aW9uKCkge1xyXG4gICAgICAgICAgICAgICAgbGlzdC5jb2xsYXBzZUl0ZW0oVUkuJCh0aGlzKSk7XHJcbiAgICAgICAgICAgIH0pO1xyXG4gICAgICAgIH0sXHJcblxyXG4gICAgICAgIHNldFBhcmVudDogZnVuY3Rpb24obGkpIHtcclxuXHJcbiAgICAgICAgICAgIGlmIChsaS5jaGlsZHJlbih0aGlzLm9wdGlvbnMuX2xpc3RDbGFzcykubGVuZ3RoKSB7XHJcbiAgICAgICAgICAgICAgICBsaS5hZGRDbGFzcygndWstcGFyZW50Jyk7XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICB9LFxyXG5cclxuICAgICAgICB1bnNldFBhcmVudDogZnVuY3Rpb24obGkpIHtcclxuICAgICAgICAgICAgbGkucmVtb3ZlQ2xhc3MoJ3VrLXBhcmVudCAnK3RoaXMub3B0aW9ucy5jb2xsYXBzZWRDbGFzcyk7XHJcbiAgICAgICAgICAgIGxpLmNoaWxkcmVuKHRoaXMub3B0aW9ucy5fbGlzdENsYXNzKS5yZW1vdmUoKTtcclxuICAgICAgICB9LFxyXG5cclxuICAgICAgICBkcmFnU3RhcnQ6IGZ1bmN0aW9uKGUpIHtcclxuXHJcbiAgICAgICAgICAgIHZhciBtb3VzZSAgICA9IHRoaXMubW91c2UsXHJcbiAgICAgICAgICAgICAgICB0YXJnZXQgICA9IFVJLiQoZS50YXJnZXQpLFxyXG4gICAgICAgICAgICAgICAgZHJhZ0l0ZW0gPSB0YXJnZXQuY2xvc2VzdCh0aGlzLm9wdGlvbnMuX2xpc3RJdGVtQ2xhc3MpLFxyXG4gICAgICAgICAgICAgICAgb2Zmc2V0ICAgPSBkcmFnSXRlbS5vZmZzZXQoKTtcclxuXHJcbiAgICAgICAgICAgIHRoaXMucGxhY2VFbCA9IGRyYWdJdGVtO1xyXG5cclxuICAgICAgICAgICAgbW91c2Uub2Zmc2V0WCA9IGUucGFnZVggLSBvZmZzZXQubGVmdDtcclxuICAgICAgICAgICAgbW91c2Uub2Zmc2V0WSA9IGUucGFnZVkgLSBvZmZzZXQudG9wO1xyXG5cclxuICAgICAgICAgICAgbW91c2Uuc3RhcnRYID0gbW91c2UubGFzdFggPSBvZmZzZXQubGVmdDtcclxuICAgICAgICAgICAgbW91c2Uuc3RhcnRZID0gbW91c2UubGFzdFkgPSBvZmZzZXQudG9wO1xyXG5cclxuICAgICAgICAgICAgdGhpcy5kcmFnUm9vdEVsID0gdGhpcy5lbGVtZW50O1xyXG5cclxuICAgICAgICAgICAgdGhpcy5kcmFnRWwgPSBVSS4kKCc8dWw+PC91bD4nKS5hZGRDbGFzcyh0aGlzLm9wdGlvbnMubGlzdENsYXNzICsgJyAnICsgdGhpcy5vcHRpb25zLmRyYWdDbGFzcykuYXBwZW5kKGRyYWdJdGVtLmNsb25lKCkpO1xyXG4gICAgICAgICAgICB0aGlzLmRyYWdFbC5jc3MoJ3dpZHRoJywgZHJhZ0l0ZW0ud2lkdGgoKSk7XHJcbiAgICAgICAgICAgIHRoaXMucGxhY2VFbC5hZGRDbGFzcyh0aGlzLm9wdGlvbnMucGxhY2Vob2xkZXJDbGFzcyk7XHJcblxyXG4gICAgICAgICAgICBkcmFnZ2luZ0VsZW1lbnQgPSB0aGlzLmRyYWdFbDtcclxuXHJcbiAgICAgICAgICAgIHRoaXMudG1wRHJhZ09uU2libGluZ3MgPSBbZHJhZ0l0ZW1bMF0ucHJldmlvdXNTaWJsaW5nLCBkcmFnSXRlbVswXS5uZXh0U2libGluZ107XHJcblxyXG4gICAgICAgICAgICBVSS4kYm9keS5hcHBlbmQodGhpcy5kcmFnRWwpO1xyXG5cclxuICAgICAgICAgICAgdGhpcy5kcmFnRWwuY3NzKHtcclxuICAgICAgICAgICAgICAgIGxlZnQgOiBvZmZzZXQubGVmdCxcclxuICAgICAgICAgICAgICAgIHRvcCAgOiBvZmZzZXQudG9wXHJcbiAgICAgICAgICAgIH0pO1xyXG5cclxuICAgICAgICAgICAgLy8gdG90YWwgZGVwdGggb2YgZHJhZ2dpbmcgaXRlbVxyXG4gICAgICAgICAgICB2YXIgaSwgZGVwdGgsIGl0ZW1zID0gdGhpcy5kcmFnRWwuZmluZCh0aGlzLm9wdGlvbnMuX2xpc3RJdGVtQ2xhc3MpO1xyXG5cclxuICAgICAgICAgICAgZm9yIChpID0gMDsgaSA8IGl0ZW1zLmxlbmd0aDsgaSsrKSB7XHJcbiAgICAgICAgICAgICAgICBkZXB0aCA9IFVJLiQoaXRlbXNbaV0pLnBhcmVudHModGhpcy5vcHRpb25zLl9saXN0Q2xhc3MrJywnK3RoaXMub3B0aW9ucy5fbGlzdEJhc2VDbGFzcykubGVuZ3RoO1xyXG4gICAgICAgICAgICAgICAgaWYgKGRlcHRoID4gdGhpcy5kcmFnRGVwdGgpIHtcclxuICAgICAgICAgICAgICAgICAgICB0aGlzLmRyYWdEZXB0aCA9IGRlcHRoO1xyXG4gICAgICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICB9XHJcblxyXG4gICAgICAgICAgICBodG1sLmFkZENsYXNzKHRoaXMub3B0aW9ucy5tb3ZpbmdDbGFzcyk7XHJcbiAgICAgICAgfSxcclxuXHJcbiAgICAgICAgZHJhZ1N0b3A6IGZ1bmN0aW9uKGUpIHtcclxuXHJcbiAgICAgICAgICAgIHZhciBlbCAgICAgICA9IFVJLiQodGhpcy5wbGFjZUVsKSxcclxuICAgICAgICAgICAgICAgIHJvb3QgICAgID0gdGhpcy5wbGFjZUVsLnBhcmVudHModGhpcy5vcHRpb25zLl9saXN0QmFzZUNsYXNzKyc6Zmlyc3QnKTtcclxuXHJcbiAgICAgICAgICAgIHRoaXMucGxhY2VFbC5yZW1vdmVDbGFzcyh0aGlzLm9wdGlvbnMucGxhY2Vob2xkZXJDbGFzcyk7XHJcbiAgICAgICAgICAgIHRoaXMuZHJhZ0VsLnJlbW92ZSgpO1xyXG5cclxuICAgICAgICAgICAgaWYgKHRoaXMuZWxlbWVudFswXSAhPT0gcm9vdFswXSkge1xyXG5cclxuICAgICAgICAgICAgICAgIHJvb3QudHJpZ2dlcignY2hhbmdlLnVrLm5lc3RhYmxlJyxbcm9vdC5kYXRhKCduZXN0YWJsZScpLCBlbCwgJ2FkZGVkJ10pO1xyXG4gICAgICAgICAgICAgICAgdGhpcy5lbGVtZW50LnRyaWdnZXIoJ2NoYW5nZS51ay5uZXN0YWJsZScsIFt0aGlzLCBlbCwgJ3JlbW92ZWQnXSk7XHJcblxyXG4gICAgICAgICAgICB9IGVsc2Uge1xyXG4gICAgICAgICAgICAgICAgdGhpcy5lbGVtZW50LnRyaWdnZXIoJ2NoYW5nZS51ay5uZXN0YWJsZScsW3RoaXMsIGVsLCBcIm1vdmVkXCJdKTtcclxuICAgICAgICAgICAgfVxyXG5cclxuICAgICAgICAgICAgdGhpcy50cmlnZ2VyKCdzdG9wLnVrLm5lc3RhYmxlJywgW3RoaXMsIGVsXSk7XHJcblxyXG4gICAgICAgICAgICB0aGlzLnJlc2V0KCk7XHJcblxyXG4gICAgICAgICAgICBodG1sLnJlbW92ZUNsYXNzKHRoaXMub3B0aW9ucy5tb3ZpbmdDbGFzcyk7XHJcbiAgICAgICAgfSxcclxuXHJcbiAgICAgICAgZHJhZ01vdmU6IGZ1bmN0aW9uKGUpIHtcclxuICAgICAgICAgICAgdmFyIGxpc3QsIHBhcmVudCwgcHJldiwgbmV4dCwgZGVwdGgsXHJcbiAgICAgICAgICAgICAgICBvcHQgICAgICA9IHRoaXMub3B0aW9ucyxcclxuICAgICAgICAgICAgICAgIG1vdXNlICAgID0gdGhpcy5tb3VzZSxcclxuICAgICAgICAgICAgICAgIG1heERlcHRoID0gdGhpcy5kcmFnUm9vdEVsID8gdGhpcy5kcmFnUm9vdEVsLmRhdGEoJ25lc3RhYmxlJykub3B0aW9ucy5tYXhEZXB0aCA6IG9wdC5tYXhEZXB0aDtcclxuXHJcbiAgICAgICAgICAgIHRoaXMuZHJhZ0VsLmNzcyh7XHJcbiAgICAgICAgICAgICAgICBsZWZ0IDogZS5wYWdlWCAtIG1vdXNlLm9mZnNldFgsXHJcbiAgICAgICAgICAgICAgICB0b3AgIDogZS5wYWdlWSAtIG1vdXNlLm9mZnNldFlcclxuICAgICAgICAgICAgfSk7XHJcblxyXG4gICAgICAgICAgICAvLyBtb3VzZSBwb3NpdGlvbiBsYXN0IGV2ZW50c1xyXG4gICAgICAgICAgICBtb3VzZS5sYXN0WCA9IG1vdXNlLm5vd1g7XHJcbiAgICAgICAgICAgIG1vdXNlLmxhc3RZID0gbW91c2Uubm93WTtcclxuICAgICAgICAgICAgLy8gbW91c2UgcG9zaXRpb24gdGhpcyBldmVudHNcclxuICAgICAgICAgICAgbW91c2Uubm93WCAgPSBlLnBhZ2VYO1xyXG4gICAgICAgICAgICBtb3VzZS5ub3dZICA9IGUucGFnZVk7XHJcbiAgICAgICAgICAgIC8vIGRpc3RhbmNlIG1vdXNlIG1vdmVkIGJldHdlZW4gZXZlbnRzXHJcbiAgICAgICAgICAgIG1vdXNlLmRpc3RYID0gbW91c2Uubm93WCAtIG1vdXNlLmxhc3RYO1xyXG4gICAgICAgICAgICBtb3VzZS5kaXN0WSA9IG1vdXNlLm5vd1kgLSBtb3VzZS5sYXN0WTtcclxuICAgICAgICAgICAgLy8gZGlyZWN0aW9uIG1vdXNlIHdhcyBtb3ZpbmdcclxuICAgICAgICAgICAgbW91c2UubGFzdERpclggPSBtb3VzZS5kaXJYO1xyXG4gICAgICAgICAgICBtb3VzZS5sYXN0RGlyWSA9IG1vdXNlLmRpclk7XHJcbiAgICAgICAgICAgIC8vIGRpcmVjdGlvbiBtb3VzZSBpcyBub3cgbW92aW5nIChvbiBib3RoIGF4aXMpXHJcbiAgICAgICAgICAgIG1vdXNlLmRpclggPSBtb3VzZS5kaXN0WCA9PT0gMCA/IDAgOiBtb3VzZS5kaXN0WCA+IDAgPyAxIDogLTE7XHJcbiAgICAgICAgICAgIG1vdXNlLmRpclkgPSBtb3VzZS5kaXN0WSA9PT0gMCA/IDAgOiBtb3VzZS5kaXN0WSA+IDAgPyAxIDogLTE7XHJcbiAgICAgICAgICAgIC8vIGF4aXMgbW91c2UgaXMgbm93IG1vdmluZyBvblxyXG4gICAgICAgICAgICB2YXIgbmV3QXggICA9IE1hdGguYWJzKG1vdXNlLmRpc3RYKSA+IE1hdGguYWJzKG1vdXNlLmRpc3RZKSA/IDEgOiAwO1xyXG5cclxuICAgICAgICAgICAgLy8gZG8gbm90aGluZyBvbiBmaXJzdCBtb3ZlXHJcbiAgICAgICAgICAgIGlmICghbW91c2UubW92aW5nKSB7XHJcbiAgICAgICAgICAgICAgICBtb3VzZS5kaXJBeCAgPSBuZXdBeDtcclxuICAgICAgICAgICAgICAgIG1vdXNlLm1vdmluZyA9IHRydWU7XHJcbiAgICAgICAgICAgICAgICByZXR1cm47XHJcbiAgICAgICAgICAgIH1cclxuXHJcbiAgICAgICAgICAgIC8vIGNhbGMgZGlzdGFuY2UgbW92ZWQgb24gdGhpcyBheGlzIChhbmQgZGlyZWN0aW9uKVxyXG4gICAgICAgICAgICBpZiAobW91c2UuZGlyQXggIT09IG5ld0F4KSB7XHJcbiAgICAgICAgICAgICAgICBtb3VzZS5kaXN0QXhYID0gMDtcclxuICAgICAgICAgICAgICAgIG1vdXNlLmRpc3RBeFkgPSAwO1xyXG4gICAgICAgICAgICB9IGVsc2Uge1xyXG4gICAgICAgICAgICAgICAgbW91c2UuZGlzdEF4WCArPSBNYXRoLmFicyhtb3VzZS5kaXN0WCk7XHJcbiAgICAgICAgICAgICAgICBpZiAobW91c2UuZGlyWCAhPT0gMCAmJiBtb3VzZS5kaXJYICE9PSBtb3VzZS5sYXN0RGlyWCkge1xyXG4gICAgICAgICAgICAgICAgICAgIG1vdXNlLmRpc3RBeFggPSAwO1xyXG4gICAgICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICAgICAgbW91c2UuZGlzdEF4WSArPSBNYXRoLmFicyhtb3VzZS5kaXN0WSk7XHJcbiAgICAgICAgICAgICAgICBpZiAobW91c2UuZGlyWSAhPT0gMCAmJiBtb3VzZS5kaXJZICE9PSBtb3VzZS5sYXN0RGlyWSkge1xyXG4gICAgICAgICAgICAgICAgICAgIG1vdXNlLmRpc3RBeFkgPSAwO1xyXG4gICAgICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICB9XHJcbiAgICAgICAgICAgIG1vdXNlLmRpckF4ID0gbmV3QXg7XHJcblxyXG4gICAgICAgICAgICAvKipcclxuICAgICAgICAgICAgICogbW92ZSBob3Jpem9udGFsXHJcbiAgICAgICAgICAgICAqL1xyXG4gICAgICAgICAgICBpZiAobW91c2UuZGlyQXggJiYgbW91c2UuZGlzdEF4WCA+PSBvcHQudGhyZXNob2xkKSB7XHJcbiAgICAgICAgICAgICAgICAvLyByZXNldCBtb3ZlIGRpc3RhbmNlIG9uIHgtYXhpcyBmb3IgbmV3IHBoYXNlXHJcbiAgICAgICAgICAgICAgICBtb3VzZS5kaXN0QXhYID0gMDtcclxuICAgICAgICAgICAgICAgIHByZXYgPSB0aGlzLnBsYWNlRWwucHJldignbGknKTtcclxuXHJcbiAgICAgICAgICAgICAgICAvLyBpbmNyZWFzZSBob3Jpem9udGFsIGxldmVsIGlmIHByZXZpb3VzIHNpYmxpbmcgZXhpc3RzLCBpcyBub3QgY29sbGFwc2VkLCBhbmQgZG9lcyBub3QgaGF2ZSBhICdubyBjaGlsZHJlbicgY2xhc3NcclxuICAgICAgICAgICAgICAgIGlmIChtb3VzZS5kaXN0WCA+IDAgJiYgcHJldi5sZW5ndGggJiYgIXByZXYuaGFzQ2xhc3Mob3B0LmNvbGxhcHNlZENsYXNzKSAmJiAhcHJldi5oYXNDbGFzcyhvcHQubm9DaGlsZHJlbkNsYXNzKSkge1xyXG5cclxuICAgICAgICAgICAgICAgICAgICAvLyBjYW5ub3QgaW5jcmVhc2UgbGV2ZWwgd2hlbiBpdGVtIGFib3ZlIGlzIGNvbGxhcHNlZFxyXG4gICAgICAgICAgICAgICAgICAgIGxpc3QgPSBwcmV2LmZpbmQob3B0Ll9saXN0Q2xhc3MpLmxhc3QoKTtcclxuXHJcbiAgICAgICAgICAgICAgICAgICAgLy8gY2hlY2sgaWYgZGVwdGggbGltaXQgaGFzIHJlYWNoZWRcclxuICAgICAgICAgICAgICAgICAgICBkZXB0aCA9IHRoaXMucGxhY2VFbC5wYXJlbnRzKG9wdC5fbGlzdENsYXNzKycsJytvcHQuX2xpc3RCYXNlQ2xhc3MpLmxlbmd0aDtcclxuXHJcbiAgICAgICAgICAgICAgICAgICAgaWYgKGRlcHRoICsgdGhpcy5kcmFnRGVwdGggPD0gbWF4RGVwdGgpIHtcclxuXHJcbiAgICAgICAgICAgICAgICAgICAgICAgIC8vIGNyZWF0ZSBuZXcgc3ViLWxldmVsIGlmIG9uZSBkb2Vzbid0IGV4aXN0XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIGlmICghbGlzdC5sZW5ndGgpIHtcclxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIGxpc3QgPSBVSS4kKCc8dWwvPicpLmFkZENsYXNzKG9wdC5saXN0Q2xhc3MpO1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgbGlzdC5hcHBlbmQodGhpcy5wbGFjZUVsKTtcclxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIHByZXYuYXBwZW5kKGxpc3QpO1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5zZXRQYXJlbnQocHJldik7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIH0gZWxzZSB7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAvLyBlbHNlIGFwcGVuZCB0byBuZXh0IGxldmVsIHVwXHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBsaXN0ID0gcHJldi5jaGlsZHJlbihvcHQuX2xpc3RDbGFzcykubGFzdCgpO1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgbGlzdC5hcHBlbmQodGhpcy5wbGFjZUVsKTtcclxuICAgICAgICAgICAgICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgICAgIH1cclxuXHJcbiAgICAgICAgICAgICAgICAvLyBkZWNyZWFzZSBob3Jpem9udGFsIGxldmVsXHJcbiAgICAgICAgICAgICAgICBpZiAobW91c2UuZGlzdFggPCAwKSB7XHJcblxyXG4gICAgICAgICAgICAgICAgICAgIC8vIHdlIGNhbm5vdCBkZWNyZWFzZSB0aGUgbGV2ZWwgaWYgYW4gaXRlbSBwcmVjZWRlcyB0aGUgY3VycmVudCBvbmVcclxuICAgICAgICAgICAgICAgICAgICBuZXh0ID0gdGhpcy5wbGFjZUVsLm5leHQob3B0Ll9saXN0SXRlbUNsYXNzKTtcclxuICAgICAgICAgICAgICAgICAgICBpZiAoIW5leHQubGVuZ3RoKSB7XHJcblxyXG4gICAgICAgICAgICAgICAgICAgICAgICAvLyBnZXQgcGFyZW50IHVsIG9mIHRoZSBsaXN0IGl0ZW1cclxuICAgICAgICAgICAgICAgICAgICAgICAgdmFyIHBhcmVudFVsID0gdGhpcy5wbGFjZUVsLmNsb3Nlc3QoW29wdC5fbGlzdEJhc2VDbGFzcywgb3B0Ll9saXN0Q2xhc3NdLmpvaW4oJywnKSk7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIC8vIHRyeSB0byBnZXQgdGhlIGxpIHN1cnJvdW5kaW5nIHRoZSB1bFxyXG4gICAgICAgICAgICAgICAgICAgICAgICB2YXIgc3Vycm91bmRpbmdMaSA9IHBhcmVudFVsLmNsb3Nlc3Qob3B0Ll9saXN0SXRlbUNsYXNzKTtcclxuXHJcbiAgICAgICAgICAgICAgICAgICAgICAgIC8vIGlmIHRoZSB1bCBpcyBpbnNpZGUgb2YgYSBsaSAobWVhbmluZyBpdCBpcyBuZXN0ZWQpXHJcbiAgICAgICAgICAgICAgICAgICAgICAgIGlmIChzdXJyb3VuZGluZ0xpLmxlbmd0aCkge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgLy8gd2UgY2FuIGRlY3JlYXNlIHRoZSBob3Jpem9udGFsIGxldmVsXHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBzdXJyb3VuZGluZ0xpLmFmdGVyKHRoaXMucGxhY2VFbCk7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAvLyBpZiB0aGUgcHJldmlvdXMgcGFyZW50IHVsIGlzIG5vdyBlbXB0eVxyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgaWYgKCFwYXJlbnRVbC5jaGlsZHJlbigpLmxlbmd0aCkge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHRoaXMudW5zZXRQYXJlbnQoc3Vycm91bmRpbmdMaSk7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgIH1cclxuXHJcbiAgICAgICAgICAgIHZhciBpc0VtcHR5ID0gZmFsc2U7XHJcblxyXG4gICAgICAgICAgICAvLyBmaW5kIGxpc3QgaXRlbSB1bmRlciBjdXJzb3JcclxuICAgICAgICAgICAgdmFyIHBvaW50WCA9IGUucGFnZVggLSAod2luZG93LnBhZ2VYT2Zmc2V0IHx8IGRvY3VtZW50LnNjcm9sbExlZnQgfHwgMCksXHJcbiAgICAgICAgICAgICAgICBwb2ludFkgPSBlLnBhZ2VZIC0gKHdpbmRvdy5wYWdlWU9mZnNldCB8fCBkb2N1bWVudC5kb2N1bWVudEVsZW1lbnQuc2Nyb2xsVG9wKTtcclxuICAgICAgICAgICAgdGhpcy5wb2ludEVsID0gVUkuJChkb2N1bWVudC5lbGVtZW50RnJvbVBvaW50KHBvaW50WCwgcG9pbnRZKSk7XHJcblxyXG4gICAgICAgICAgICBpZiAob3B0LmhhbmRsZUNsYXNzICYmIHRoaXMucG9pbnRFbC5oYXNDbGFzcyhvcHQuaGFuZGxlQ2xhc3MpKSB7XHJcblxyXG4gICAgICAgICAgICAgICAgdGhpcy5wb2ludEVsID0gdGhpcy5wb2ludEVsLmNsb3Nlc3Qob3B0Ll9saXN0SXRlbUNsYXNzKTtcclxuXHJcbiAgICAgICAgICAgIH0gZWxzZSB7XHJcblxyXG4gICAgICAgICAgICAgICAgdmFyIG5lc3RhYmxlaXRlbSA9IHRoaXMucG9pbnRFbC5jbG9zZXN0KG9wdC5fbGlzdEl0ZW1DbGFzcyk7XHJcblxyXG4gICAgICAgICAgICAgICAgaWYgKG5lc3RhYmxlaXRlbS5sZW5ndGgpIHtcclxuICAgICAgICAgICAgICAgICAgICB0aGlzLnBvaW50RWwgPSBuZXN0YWJsZWl0ZW07XHJcbiAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgIH1cclxuXHJcbiAgICAgICAgICAgIGlmICh0aGlzLnBsYWNlRWwuZmluZCh0aGlzLnBvaW50RWwpLmxlbmd0aCkge1xyXG4gICAgICAgICAgICAgICAgcmV0dXJuO1xyXG4gICAgICAgICAgICB9XHJcblxyXG4gICAgICAgICAgICBpZiAodGhpcy5wb2ludEVsLmRhdGEoJ25lc3RhYmxlJykgJiYgIXRoaXMucG9pbnRFbC5jaGlsZHJlbigpLmxlbmd0aCkge1xyXG4gICAgICAgICAgICAgICAgaXNFbXB0eSA9IHRydWU7XHJcbiAgICAgICAgICAgICAgICB0aGlzLmNoZWNrRW1wdHlMaXN0KHRoaXMucG9pbnRFbCk7XHJcbiAgICAgICAgICAgIH0gZWxzZSBpZiAoIXRoaXMucG9pbnRFbC5sZW5ndGggfHwgIXRoaXMucG9pbnRFbC5oYXNDbGFzcyhvcHQubGlzdEl0ZW1DbGFzcykpIHtcclxuICAgICAgICAgICAgICAgIHJldHVybjtcclxuICAgICAgICAgICAgfVxyXG5cclxuICAgICAgICAgICAgLy8gZmluZCBwYXJlbnQgbGlzdCBvZiBpdGVtIHVuZGVyIGN1cnNvclxyXG4gICAgICAgICAgICB2YXIgcG9pbnRFbFJvb3QgPSB0aGlzLmVsZW1lbnQsXHJcbiAgICAgICAgICAgICAgICB0bXBSb290ICAgICA9IHRoaXMucG9pbnRFbC5jbG9zZXN0KHRoaXMub3B0aW9ucy5fbGlzdEJhc2VDbGFzcyksXHJcbiAgICAgICAgICAgICAgICBpc05ld1Jvb3QgICA9IHBvaW50RWxSb290WzBdICE9IHRtcFJvb3RbMF07XHJcblxyXG4gICAgICAgICAgICAvKipcclxuICAgICAgICAgICAgICogbW92ZSB2ZXJ0aWNhbFxyXG4gICAgICAgICAgICAgKi9cclxuICAgICAgICAgICAgaWYgKCFtb3VzZS5kaXJBeCB8fCBpc05ld1Jvb3QgfHwgaXNFbXB0eSkge1xyXG5cclxuICAgICAgICAgICAgICAgIC8vIGNoZWNrIGlmIGdyb3VwcyBtYXRjaCBpZiBkcmFnZ2luZyBvdmVyIG5ldyByb290XHJcbiAgICAgICAgICAgICAgICBpZiAoaXNOZXdSb290ICYmIG9wdC5ncm91cCAhPT0gdG1wUm9vdC5kYXRhKCduZXN0YWJsZS1ncm91cCcpKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgcmV0dXJuO1xyXG4gICAgICAgICAgICAgICAgfSBlbHNlIHtcclxuICAgICAgICAgICAgICAgICAgICB0b3VjaGVkbGlzdHMucHVzaChwb2ludEVsUm9vdCk7XHJcbiAgICAgICAgICAgICAgICB9XHJcblxyXG4gICAgICAgICAgICAgICAgLy8gY2hlY2sgZGVwdGggbGltaXRcclxuICAgICAgICAgICAgICAgIGRlcHRoID0gdGhpcy5kcmFnRGVwdGggLSAxICsgdGhpcy5wb2ludEVsLnBhcmVudHMob3B0Ll9saXN0Q2xhc3MrJywnK29wdC5fbGlzdEJhc2VDbGFzcykubGVuZ3RoO1xyXG5cclxuICAgICAgICAgICAgICAgIGlmIChkZXB0aCA+IG1heERlcHRoKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgcmV0dXJuO1xyXG4gICAgICAgICAgICAgICAgfVxyXG5cclxuICAgICAgICAgICAgICAgIHZhciBiZWZvcmUgPSBlLnBhZ2VZIDwgKHRoaXMucG9pbnRFbC5vZmZzZXQoKS50b3AgKyB0aGlzLnBvaW50RWwuaGVpZ2h0KCkgLyAyKTtcclxuXHJcbiAgICAgICAgICAgICAgICBwYXJlbnQgPSB0aGlzLnBsYWNlRWwucGFyZW50KCk7XHJcblxyXG4gICAgICAgICAgICAgICAgaWYgKGlzRW1wdHkpIHtcclxuICAgICAgICAgICAgICAgICAgICB0aGlzLnBvaW50RWwuYXBwZW5kKHRoaXMucGxhY2VFbCk7XHJcbiAgICAgICAgICAgICAgICB9IGVsc2UgaWYgKGJlZm9yZSkge1xyXG4gICAgICAgICAgICAgICAgICAgIHRoaXMucG9pbnRFbC5iZWZvcmUodGhpcy5wbGFjZUVsKTtcclxuICAgICAgICAgICAgICAgIH0gZWxzZSB7XHJcbiAgICAgICAgICAgICAgICAgICAgdGhpcy5wb2ludEVsLmFmdGVyKHRoaXMucGxhY2VFbCk7XHJcbiAgICAgICAgICAgICAgICB9XHJcblxyXG4gICAgICAgICAgICAgICAgaWYgKCFwYXJlbnQuY2hpbGRyZW4oKS5sZW5ndGgpIHtcclxuICAgICAgICAgICAgICAgICAgICBpZiAoIXBhcmVudC5kYXRhKCduZXN0YWJsZScpKSB0aGlzLnVuc2V0UGFyZW50KHBhcmVudC5wYXJlbnQoKSk7XHJcbiAgICAgICAgICAgICAgICB9XHJcblxyXG4gICAgICAgICAgICAgICAgdGhpcy5jaGVja0VtcHR5TGlzdCh0aGlzLmRyYWdSb290RWwpO1xyXG4gICAgICAgICAgICAgICAgdGhpcy5jaGVja0VtcHR5TGlzdChwb2ludEVsUm9vdCk7XHJcblxyXG4gICAgICAgICAgICAgICAgLy8gcGFyZW50IHJvb3QgbGlzdCBoYXMgY2hhbmdlZFxyXG4gICAgICAgICAgICAgICAgaWYgKGlzTmV3Um9vdCkge1xyXG4gICAgICAgICAgICAgICAgICAgIHRoaXMuZHJhZ1Jvb3RFbCA9IHRtcFJvb3Q7XHJcbiAgICAgICAgICAgICAgICAgICAgdGhpcy5oYXNOZXdSb290ID0gdGhpcy5lbGVtZW50WzBdICE9PSB0aGlzLmRyYWdSb290RWxbMF07XHJcbiAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICB9LFxyXG5cclxuICAgICAgICBjaGVja0VtcHR5TGlzdDogZnVuY3Rpb24obGlzdCkge1xyXG5cclxuICAgICAgICAgICAgbGlzdCAgPSBsaXN0ID8gVUkuJChsaXN0KSA6IHRoaXMuZWxlbWVudDtcclxuXHJcbiAgICAgICAgICAgIGlmICh0aGlzLm9wdGlvbnMuZW1wdHlDbGFzcykge1xyXG4gICAgICAgICAgICAgICAgbGlzdFshbGlzdC5jaGlsZHJlbigpLmxlbmd0aCA/ICdhZGRDbGFzcyc6J3JlbW92ZUNsYXNzJ10odGhpcy5vcHRpb25zLmVtcHR5Q2xhc3MpO1xyXG4gICAgICAgICAgICB9XHJcbiAgICAgICAgfVxyXG5cclxuICAgIH0pO1xyXG5cclxuICAgIHJldHVybiBVSS5uZXN0YWJsZTtcclxufSk7Il19
|
#!/usr/bin/env python3
from fnmatch import fnmatch
from os import path
import argparse
import json
import os
import stat
import re
import subprocess
import sys
import time
from urllib import request
import zipfile
import shutil
import ntpath
# Configuration
## Where do we fetch the list of releases from?
## Get the latest Z3 release like this:
## Z3_RELEASES_URL = "https://api.github.com/repos/Z3Prover/z3/releases/latest"
## Get a specific Z3 release like this:
Z3_RELEASES_URL = "https://api.github.com/repos/Z3Prover/z3/releases/tags/Z3-4.8.5"
## How do we extract info from the name of a Z3 release file?
Z3_RELEASE_REGEXP = re.compile(r"^(?P<directory>z3-[0-9a-z\.]+-(?P<platform>x86|x64)-(?P<os>[a-z0-9\.\-]+)).zip$", re.IGNORECASE)
## Allowed Dafny release names
DAFNY_RELEASE_REGEX = re.compile("\\d+\\.\\d+\\.\\d+(-[\w\d_-]+)?$")
## Where are the sources?
SOURCE_DIRECTORY = "Source"
## Where do the binaries get put?
BINARIES_DIRECTORY = "Binaries"
## Where do we store the built packages and cache files?
DESTINATION_DIRECTORY = "Package"
## What's the root folder of the archive?
DAFNY_PACKAGE_PREFIX = path.join("dafny")
## What sub-folder of the packages does z3 go into?
Z3_PACKAGE_PREFIX = path.join("z3")
## What do we take from the z3 archive? (Glob syntax)
Z3_INTERESTING_FILES = ["LICENSE.txt", "bin/*"]
## On unix systems, which Dafny files should be marked as executable? (Glob syntax; Z3's permissions are preserved)
UNIX_EXECUTABLES = ["dafny", "dafny-server"]
ETCs = ["DafnyPrelude.bpl", "DafnyRuntime.js", "DafnyRuntime.go", "DafnyRuntime.jar", "DafnyRuntime.h"]
# Constants
THIS_FILE = path.realpath(__file__)
ROOT_DIRECTORY = path.dirname(path.dirname(THIS_FILE))
SOURCE_DIRECTORY = path.join(ROOT_DIRECTORY, SOURCE_DIRECTORY)
BINARIES_DIRECTORY = path.join(ROOT_DIRECTORY, BINARIES_DIRECTORY)
DESTINATION_DIRECTORY = path.join(ROOT_DIRECTORY, DESTINATION_DIRECTORY)
CACHE_DIRECTORY = path.join(DESTINATION_DIRECTORY, "cache")
OTHERS = ( [ "Scripts/quicktest.sh" , "Scripts/quicktest.out", "Scripts/allow_on_mac.sh" ] ) ## Other files to include in zip
OTHER_UPLOADS = ( ["docs/DafnyRef/out/DafnyRef.pdf"] )
z3ToDotNetOSMapping = {
"ubuntu": "linux",
"debian": "linux",
"osx": "osx",
"win": "win"
}
def flush(*args, **kwargs):
print(*args, **kwargs)
sys.stdout.flush()
class Release:
@staticmethod
def parse_zip_name(name):
m = Z3_RELEASE_REGEXP.match(name)
if not m:
raise Exception("{} does not match Z3_RELEASE_REGEXP".format(name))
return m.group('platform'), m.group('os'), m.group("directory")
def __init__(self, js, version, out):
self.z3_name = js["name"]
self.size = js["size"]
self.url = js["browser_download_url"]
self.platform, self.os, self.directory = Release.parse_zip_name(js["name"])
self.os_name = self.os.split("-")[0]
self.z3_zip = path.join(CACHE_DIRECTORY, self.z3_name)
self.dafny_name = "dafny-{}-{}-{}.zip".format(version, self.platform, self.os)
if out != None:
self.dafny_name = out
self.target = "{}-{}".format(z3ToDotNetOSMapping[self.os_name], self.platform)
self.dafny_zip = path.join(DESTINATION_DIRECTORY, self.dafny_name)
self.buildDirectory = path.join(BINARIES_DIRECTORY, self.target, "publish")
@property
def cached(self):
return path.exists(self.z3_zip) and path.getsize(self.z3_zip) == self.size
@property
def MB(self):
return self.size / 1e6
def download(self):
if self.cached:
print("cached!")
else:
flush("downloading {:.2f}MB...".format(self.MB), end=' ')
with request.urlopen(self.url) as reader:
with open(self.z3_zip, mode="wb") as writer:
writer.write(reader.read())
flush("done!")
@staticmethod
def zipify_path(fpath):
"""Zip entries always use '/' as the path separator."""
return fpath.replace(os.path.sep, '/')
def build(self):
os.chdir(ROOT_DIRECTORY)
flush(" - Building")
if path.exists(self.buildDirectory):
shutil.rmtree(self.buildDirectory)
run(["make", "--quiet", "clean"])
run(["make", "--quiet", "runtime"])
run(["dotnet", "publish", path.join(SOURCE_DIRECTORY, "DafnyServer", "DafnyServer.csproj"),
"--nologo",
"-f", "net5.0",
"-o", self.buildDirectory,
"-r", self.target,
"-c", "Checked"])
run(["dotnet", "publish", path.join(SOURCE_DIRECTORY, "DafnyDriver", "DafnyDriver.csproj"),
"--nologo",
"-f", "net5.0",
"-o", self.buildDirectory,
"-r", self.target,
"-c", "Checked"])
def pack(self):
try:
os.remove(self.dafny_zip)
except FileNotFoundError:
pass
missing = []
with zipfile.ZipFile(self.dafny_zip, 'w', zipfile.ZIP_DEFLATED) as archive:
with zipfile.ZipFile(self.z3_zip) as Z3_archive:
z3_files_count = 0
for fileinfo in Z3_archive.infolist():
fname = path.relpath(fileinfo.filename, self.directory)
if any(fnmatch(fname, pattern) for pattern in Z3_INTERESTING_FILES):
z3_files_count += 1
contents = Z3_archive.read(fileinfo)
fileinfo.filename = Release.zipify_path(path.join(DAFNY_PACKAGE_PREFIX, Z3_PACKAGE_PREFIX, fname))
archive.writestr(fileinfo, contents)
uppercaseDafny = path.join(self.buildDirectory, "Dafny")
if os.path.exists(uppercaseDafny):
lowercaseDafny = path.join(self.buildDirectory, "dafny")
shutil.move(uppercaseDafny, lowercaseDafny)
os.chmod(lowercaseDafny, stat.S_IEXEC| os.lstat(lowercaseDafny).st_mode)
paths = pathsInDirectory(self.buildDirectory) + list(map(lambda etc: path.join(BINARIES_DIRECTORY, etc), ETCs)) + OTHERS
for fpath in paths:
if os.path.isdir(fpath):
continue
fname = ntpath.basename(fpath)
if path.exists(fpath):
fileinfo = zipfile.ZipInfo(fname, time.localtime(os.stat(fpath).st_mtime)[:6])
if self.os_name != 'win':
# http://stackoverflow.com/questions/434641/
fileinfo.external_attr = 0o100755 << 16
fileinfo.create_system = 3 # lie about this zip file's source OS to preserve permissions
contents = open(fpath, mode='rb').read()
fileinfo.compress_type = zipfile.ZIP_DEFLATED
fileinfo.filename = Release.zipify_path(path.join(DAFNY_PACKAGE_PREFIX, fname))
archive.writestr(fileinfo, contents)
else:
missing.append(fname)
for fpath in OTHER_UPLOADS:
shutil.copy(fpath, DESTINATION_DIRECTORY)
flush("done! (imported {} files from z3's sources)".format(z3_files_count))
if missing:
flush(" WARNING: Not all files were found: {} were missing".format(", ".join(missing)))
def discover(args):
flush(" - Getting information about latest release")
options = {"Authorization": "Bearer " + args.github_secret} if args.github_secret else {}
req = request.Request(Z3_RELEASES_URL, None, options)
with request.urlopen(req) as reader:
js = json.loads(reader.read().decode("utf-8"))
for release_js in js["assets"]:
release = Release(release_js, args.version, args.out)
if release.platform == "x64":
flush(" + Selecting {} ({:.2f}MB, {})".format(release.z3_name, release.MB, release.size))
yield release
else:
flush(" + Rejecting {}".format(release.z3_name))
def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
def pathsInDirectory(directory):
return list(map(lambda file: path.join(directory, file), os.listdir(directory)))
def download(releases):
flush(" - Downloading {} z3 archives".format(len(releases)))
for release in releases:
flush(" + {}:".format(release.z3_name), end=' ')
release.download()
def run(cmd):
flush(" + {}...".format(" ".join(cmd)), end=' ')
retv = subprocess.call(cmd)
if retv != 0:
flush("failed! (Is Dafny or the Dafny server running?)")
sys.exit(1)
else:
flush("done!")
def pack(args, releases):
flush(" - Packaging {} Dafny archives".format(len(releases)))
for release in releases:
flush(" + {}:".format(release.dafny_name), end=' ')
release.build()
release.pack()
if not args.skip_manual:
run(["make", "--quiet", "refman-release"])
def check_version_cs(args):
# Checking version.cs
fp = open(path.join(SOURCE_DIRECTORY,"version.cs"))
lines = fp.readlines()
qstart = lines[2].index('"')
qend = lines[2].index('"', qstart+1)
lastdot = lines[2].rindex('.',qstart)
v1 = lines[2][qstart+1:lastdot]
v2 = lines[2][lastdot+1:qend]
now = time.localtime()
year = now[0]
month = now[1]
day = now[2]
v3 = str(year-2018) + str(month).zfill(2) + str(day).zfill(2)
if v2 != v3:
flush("The date in version.cs does not agree with today's date: " + v3 + " vs. " + v2)
if "-" in args.version:
hy = args.version[:args.version.index('-')]
else:
hy = args.version
if hy != v1:
flush("The version number in version.cs does not agree with the given version: " + hy + " vs. " + v1)
if (v2 != v3 or hy != v1) and not args.trial:
return False
fp.close()
flush("Creating release files for release \"" + args.version + "\" and internal version information: "+ lines[2][qstart+1:qend])
return True
def parse_arguments():
parser = argparse.ArgumentParser(description="Prepare a Dafny release. Configuration is hardcoded; edit the `# Configuration' section of this script to change it.")
parser.add_argument("version", help="Version number for this release")
parser.add_argument("--os", help="operating system name for which to make a release")
parser.add_argument("--skip_manual", help="do not create the reference manual")
parser.add_argument("--trial", help="ignore version.cs discrepancies")
parser.add_argument("--github_secret", help="access token for making an authenticated GitHub call, to prevent being rate limited.")
parser.add_argument("--out", help="output zip file")
return parser.parse_args()
def main():
args = parse_arguments()
if not DAFNY_RELEASE_REGEX.match(args.version):
flush("Release number is in wrong format: should be d.d.d or d.d.d-text without spaces")
return
os.makedirs(CACHE_DIRECTORY, exist_ok=True)
if not check_version_cs(args):
return
# Z3
flush("* Finding and downloading Z3 releases")
releases = list(discover(args))
if args.os:
releases = list(filter(lambda release: release.os_name == args.os, releases))
download(releases)
flush("* Building and packaging Dafny")
pack(args, releases)
if __name__ == '__main__':
main()
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
__all__ = ['ReadWriteDatabaseArgs', 'ReadWriteDatabase']
@pulumi.input_type
class ReadWriteDatabaseArgs:
def __init__(__self__, *,
cluster_name: pulumi.Input[str],
resource_group_name: pulumi.Input[str],
database_name: Optional[pulumi.Input[str]] = None,
hot_cache_period: Optional[pulumi.Input[str]] = None,
kind: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
soft_delete_period: Optional[pulumi.Input[str]] = None):
"""
The set of arguments for constructing a ReadWriteDatabase resource.
:param pulumi.Input[str] cluster_name: The name of the Kusto cluster.
:param pulumi.Input[str] resource_group_name: The name of the resource group containing the Kusto cluster.
:param pulumi.Input[str] database_name: The name of the database in the Kusto cluster.
:param pulumi.Input[str] hot_cache_period: The time the data should be kept in cache for fast queries in TimeSpan.
:param pulumi.Input[str] kind: Kind of the database
Expected value is 'ReadWrite'.
:param pulumi.Input[str] location: Resource location.
:param pulumi.Input[str] soft_delete_period: The time the data should be kept before it stops being accessible to queries in TimeSpan.
"""
pulumi.set(__self__, "cluster_name", cluster_name)
pulumi.set(__self__, "resource_group_name", resource_group_name)
if database_name is not None:
pulumi.set(__self__, "database_name", database_name)
if hot_cache_period is not None:
pulumi.set(__self__, "hot_cache_period", hot_cache_period)
if kind is not None:
pulumi.set(__self__, "kind", 'ReadWrite')
if location is not None:
pulumi.set(__self__, "location", location)
if soft_delete_period is not None:
pulumi.set(__self__, "soft_delete_period", soft_delete_period)
@property
@pulumi.getter(name="clusterName")
def cluster_name(self) -> pulumi.Input[str]:
"""
The name of the Kusto cluster.
"""
return pulumi.get(self, "cluster_name")
@cluster_name.setter
def cluster_name(self, value: pulumi.Input[str]):
pulumi.set(self, "cluster_name", value)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Input[str]:
"""
The name of the resource group containing the Kusto cluster.
"""
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: pulumi.Input[str]):
pulumi.set(self, "resource_group_name", value)
@property
@pulumi.getter(name="databaseName")
def database_name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the database in the Kusto cluster.
"""
return pulumi.get(self, "database_name")
@database_name.setter
def database_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "database_name", value)
@property
@pulumi.getter(name="hotCachePeriod")
def hot_cache_period(self) -> Optional[pulumi.Input[str]]:
"""
The time the data should be kept in cache for fast queries in TimeSpan.
"""
return pulumi.get(self, "hot_cache_period")
@hot_cache_period.setter
def hot_cache_period(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "hot_cache_period", value)
@property
@pulumi.getter
def kind(self) -> Optional[pulumi.Input[str]]:
"""
Kind of the database
Expected value is 'ReadWrite'.
"""
return pulumi.get(self, "kind")
@kind.setter
def kind(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "kind", value)
@property
@pulumi.getter
def location(self) -> Optional[pulumi.Input[str]]:
"""
Resource location.
"""
return pulumi.get(self, "location")
@location.setter
def location(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "location", value)
@property
@pulumi.getter(name="softDeletePeriod")
def soft_delete_period(self) -> Optional[pulumi.Input[str]]:
"""
The time the data should be kept before it stops being accessible to queries in TimeSpan.
"""
return pulumi.get(self, "soft_delete_period")
@soft_delete_period.setter
def soft_delete_period(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "soft_delete_period", value)
class ReadWriteDatabase(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
cluster_name: Optional[pulumi.Input[str]] = None,
database_name: Optional[pulumi.Input[str]] = None,
hot_cache_period: Optional[pulumi.Input[str]] = None,
kind: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
soft_delete_period: Optional[pulumi.Input[str]] = None,
__props__=None):
"""
Class representing a read write database.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] cluster_name: The name of the Kusto cluster.
:param pulumi.Input[str] database_name: The name of the database in the Kusto cluster.
:param pulumi.Input[str] hot_cache_period: The time the data should be kept in cache for fast queries in TimeSpan.
:param pulumi.Input[str] kind: Kind of the database
Expected value is 'ReadWrite'.
:param pulumi.Input[str] location: Resource location.
:param pulumi.Input[str] resource_group_name: The name of the resource group containing the Kusto cluster.
:param pulumi.Input[str] soft_delete_period: The time the data should be kept before it stops being accessible to queries in TimeSpan.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: ReadWriteDatabaseArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
Class representing a read write database.
:param str resource_name: The name of the resource.
:param ReadWriteDatabaseArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(ReadWriteDatabaseArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
cluster_name: Optional[pulumi.Input[str]] = None,
database_name: Optional[pulumi.Input[str]] = None,
hot_cache_period: Optional[pulumi.Input[str]] = None,
kind: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
soft_delete_period: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = ReadWriteDatabaseArgs.__new__(ReadWriteDatabaseArgs)
if cluster_name is None and not opts.urn:
raise TypeError("Missing required property 'cluster_name'")
__props__.__dict__["cluster_name"] = cluster_name
__props__.__dict__["database_name"] = database_name
__props__.__dict__["hot_cache_period"] = hot_cache_period
__props__.__dict__["kind"] = 'ReadWrite'
__props__.__dict__["location"] = location
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__.__dict__["resource_group_name"] = resource_group_name
__props__.__dict__["soft_delete_period"] = soft_delete_period
__props__.__dict__["name"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["statistics"] = None
__props__.__dict__["type"] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:kusto/v20190907:ReadWriteDatabase"), pulumi.Alias(type_="azure-native:kusto:ReadWriteDatabase"), pulumi.Alias(type_="azure-nextgen:kusto:ReadWriteDatabase"), pulumi.Alias(type_="azure-native:kusto/v20170907privatepreview:ReadWriteDatabase"), pulumi.Alias(type_="azure-nextgen:kusto/v20170907privatepreview:ReadWriteDatabase"), pulumi.Alias(type_="azure-native:kusto/v20180907preview:ReadWriteDatabase"), pulumi.Alias(type_="azure-nextgen:kusto/v20180907preview:ReadWriteDatabase"), pulumi.Alias(type_="azure-native:kusto/v20190121:ReadWriteDatabase"), pulumi.Alias(type_="azure-nextgen:kusto/v20190121:ReadWriteDatabase"), pulumi.Alias(type_="azure-native:kusto/v20190515:ReadWriteDatabase"), pulumi.Alias(type_="azure-nextgen:kusto/v20190515:ReadWriteDatabase"), pulumi.Alias(type_="azure-native:kusto/v20191109:ReadWriteDatabase"), pulumi.Alias(type_="azure-nextgen:kusto/v20191109:ReadWriteDatabase"), pulumi.Alias(type_="azure-native:kusto/v20200215:ReadWriteDatabase"), pulumi.Alias(type_="azure-nextgen:kusto/v20200215:ReadWriteDatabase"), pulumi.Alias(type_="azure-native:kusto/v20200614:ReadWriteDatabase"), pulumi.Alias(type_="azure-nextgen:kusto/v20200614:ReadWriteDatabase"), pulumi.Alias(type_="azure-native:kusto/v20200918:ReadWriteDatabase"), pulumi.Alias(type_="azure-nextgen:kusto/v20200918:ReadWriteDatabase"), pulumi.Alias(type_="azure-native:kusto/v20210101:ReadWriteDatabase"), pulumi.Alias(type_="azure-nextgen:kusto/v20210101:ReadWriteDatabase"), pulumi.Alias(type_="azure-native:kusto/v20210827:ReadWriteDatabase"), pulumi.Alias(type_="azure-nextgen:kusto/v20210827:ReadWriteDatabase")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(ReadWriteDatabase, __self__).__init__(
'azure-native:kusto/v20190907:ReadWriteDatabase',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'ReadWriteDatabase':
"""
Get an existing ReadWriteDatabase resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = ReadWriteDatabaseArgs.__new__(ReadWriteDatabaseArgs)
__props__.__dict__["hot_cache_period"] = None
__props__.__dict__["kind"] = None
__props__.__dict__["location"] = None
__props__.__dict__["name"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["soft_delete_period"] = None
__props__.__dict__["statistics"] = None
__props__.__dict__["type"] = None
return ReadWriteDatabase(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="hotCachePeriod")
def hot_cache_period(self) -> pulumi.Output[Optional[str]]:
"""
The time the data should be kept in cache for fast queries in TimeSpan.
"""
return pulumi.get(self, "hot_cache_period")
@property
@pulumi.getter
def kind(self) -> pulumi.Output[Optional[str]]:
"""
Kind of the database
Expected value is 'ReadWrite'.
"""
return pulumi.get(self, "kind")
@property
@pulumi.getter
def location(self) -> pulumi.Output[Optional[str]]:
"""
Resource location.
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
The name of the resource
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> pulumi.Output[str]:
"""
The provisioned state of the resource.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="softDeletePeriod")
def soft_delete_period(self) -> pulumi.Output[Optional[str]]:
"""
The time the data should be kept before it stops being accessible to queries in TimeSpan.
"""
return pulumi.get(self, "soft_delete_period")
@property
@pulumi.getter
def statistics(self) -> pulumi.Output['outputs.DatabaseStatisticsResponse']:
"""
The statistics of the database.
"""
return pulumi.get(self, "statistics")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
"""
return pulumi.get(self, "type")
|
const { describe, it, beforeEach, afterEach } = require('mocha')
const action = require('../')
const assert = require('assert')
const core = require('@actions/core')
const sinon = require('sinon')
const { factory, GitHubRelease } = require('release-please/build/src')
const { Node } = require('release-please/build/src/releasers/node')
// As defined in action.yml
const defaultInput = {
fork: 'false',
clean: 'true',
'bump-minor-pre-major': 'false',
path: '',
'monorepo-tags': 'false',
'changelog-path': '',
'changelog-types': '',
command: '',
'version-file': '',
'default-branch': '',
// eslint-disable-next-line no-template-curly-in-string
'pull-request-title-pattern': 'chore${scope}: release${component} ${version}'
}
let input
let output
const sandbox = sinon.createSandbox()
process.env.GITHUB_REPOSITORY = 'google/cloud'
describe('release-please-action', () => {
beforeEach(() => {
input = {}
output = {}
core.setOutput = (name, value) => {
output[name] = value
}
core.getInput = name => {
if (input[name] === undefined || input[name] == null) {
return defaultInput[name]
} else {
return input[name]
}
}
})
afterEach(() => {
sandbox.restore()
})
const trueValue = ['true', 'True', 'TRUE', 'yes', 'Yes', 'YES', 'y', 'Y', 'on', 'On', 'ON']
const falseValue = ['false', 'False', 'FALSE', 'no', 'No', 'NO', 'n', 'N', 'off', 'Off', 'OFF']
trueValue.forEach(value => {
it(`get the boolean true with the input of '${value}'`, () => {
input = {
fork: value
}
const actual = action.getBooleanInput('fork')
assert.strictEqual(actual, true)
})
})
falseValue.forEach(value => {
it(`get the boolean with the input of '${value}'`, () => {
input = {
fork: value
}
const actual = action.getBooleanInput('fork')
assert.strictEqual(actual, false)
})
})
it('get an error when inputting the wrong boolean value', () => {
input = {
fork: 'wrong'
}
assert.throws(
() => {
action.getBooleanInput('fork')
},
{ name: 'TypeError', message: "Wrong boolean value of the input 'fork'" }
)
})
it('sets pull pullRequestTitlePattern to undefined, if empty string provided', async () => {
input = {
'release-type': 'node',
// eslint-disable-next-line no-template-curly-in-string
'pull-request-title-pattern': ''
}
const runCommandStub = sandbox.stub(factory, 'runCommand')
const githubReleasePRStub = runCommandStub.withArgs('release-pr').returns(25)
await action.main()
sinon.assert.calledOnce(githubReleasePRStub)
sinon.assert.calledWith(
githubReleasePRStub,
'release-pr',
// eslint-disable-next-line no-template-curly-in-string
sinon.match.hasOwn('pullRequestTitlePattern', undefined)
)
})
it('opens PR with custom changelogSections', async () => {
input = {
'release-type': 'node',
'changelog-types':
'[{"type":"feat","section":"Features","hidden":false},{"type":"fix","section":"Bug Fixes","hidden":false},{"type":"chore","section":"Miscellaneous","hidden":false}]'
}
const runCommandStub = sandbox.stub(factory, 'runCommand')
const githubReleasePRStub = runCommandStub.withArgs('release-pr').returns(25)
await action.main()
sinon.assert.calledOnce(githubReleasePRStub)
sinon.assert.calledWith(
githubReleasePRStub,
'release-pr',
sinon.match.hasOwn(
'changelogSections',
JSON.parse(
'[{"type":"feat","section":"Features","hidden":false},{"type":"fix","section":"Bug Fixes","hidden":false},{"type":"chore","section":"Miscellaneous","hidden":false}]'
)
)
)
})
it('both opens PR to the default branch and tags GitHub releases by default', async () => {
input = {
'release-type': 'node'
}
const runCommandStub = sandbox.stub(factory, 'runCommand')
const githubReleaseStub = runCommandStub.withArgs('github-release').returns({
upload_url: 'http://example.com',
tag_name: 'v1.0.0'
})
const githubReleasePRStub = runCommandStub.withArgs('release-pr').returns(25)
await action.main()
sinon.assert.calledOnce(githubReleaseStub)
sinon.assert.calledOnce(githubReleasePRStub)
sinon.assert.calledWith(
githubReleaseStub,
'github-release',
sinon.match.hasOwn('defaultBranch', undefined)
)
sinon.assert.calledWith(
githubReleasePRStub,
'release-pr',
sinon.match.hasOwn('defaultBranch', undefined)
)
assert.deepStrictEqual(output, {
release_created: true,
upload_url: 'http://example.com',
tag_name: 'v1.0.0',
pr: 25
})
})
it('both opens PR to a different default branch and tags GitHub releases by default', async () => {
input = {
'release-type': 'node',
'default-branch': 'dev'
}
const runCommandStub = sandbox.stub(factory, 'runCommand')
const githubReleaseStub = runCommandStub.withArgs('github-release').returns({
upload_url: 'http://example.com',
tag_name: 'v1.0.0'
})
const githubReleasePRStub = runCommandStub.withArgs('release-pr').returns(25)
await action.main()
sinon.assert.calledOnce(githubReleaseStub)
sinon.assert.calledWith(
githubReleaseStub,
'github-release',
sinon.match.hasOwn('defaultBranch', 'dev')
)
sinon.assert.calledOnce(githubReleasePRStub)
sinon.assert.calledWith(
githubReleasePRStub,
'release-pr',
sinon.match.hasOwn('defaultBranch', 'dev')
)
assert.deepStrictEqual(output, {
release_created: true,
upload_url: 'http://example.com',
tag_name: 'v1.0.0',
pr: 25
})
})
it('only opens PR, if command set to release-pr', async () => {
input = {
'release-type': 'node',
command: 'release-pr'
}
const runCommandStub = sandbox.stub(factory, 'runCommand')
const githubReleaseStub = runCommandStub.withArgs('github-release').returns({
upload_url: 'http://example.com',
tag_name: 'v1.0.0'
})
const githubReleasePRStub = runCommandStub.withArgs('release-pr').returns(25)
await action.main()
sinon.assert.notCalled(githubReleaseStub)
sinon.assert.calledOnce(githubReleasePRStub)
})
it('only creates GitHub release, if command set to github-release', async () => {
input = {
'release-type': 'node',
command: 'github-release'
}
const runCommandStub = sandbox.stub(factory, 'runCommand')
const githubReleaseStub = runCommandStub.withArgs('github-release').returns({
upload_url: 'http://example.com',
tag_name: 'v1.0.0'
})
const githubReleasePRStub = runCommandStub.withArgs('release-pr').returns(25)
await action.main()
sinon.assert.calledOnce(githubReleaseStub)
sinon.assert.notCalled(githubReleasePRStub)
})
it('sets appropriate outputs when GitHub release created', async () => {
const expected = {
release_created: true,
upload_url: 'http://example.com',
html_url: 'http://example2.com',
tag_name: 'v1.0.0',
major: 1,
minor: 2,
patch: 3,
version: 'v1.2.3',
sha: 'abc123',
pr: 33
}
input = {
'release-type': 'node',
command: 'github-release'
}
const runCommandStub = sandbox.stub(factory, 'runCommand')
runCommandStub.withArgs('github-release').returns(expected)
runCommandStub.withArgs('release-pr').returns(25)
await action.main()
assert.deepStrictEqual(output, expected)
})
it('sets appropriate outputs when release PR opened', async () => {
input = {
'release-type': 'node',
command: 'release-pr'
}
const runCommandStub = sandbox.stub(factory, 'runCommand')
runCommandStub.withArgs('release-pr').returns(95)
await action.main()
assert.strictEqual(output.pr, 95)
})
it('does not set PR output, when no release PR is returned', async () => {
input = {
'release-type': 'node',
command: 'release-pr'
}
const runCommandStub = sandbox.stub(factory, 'runCommand')
runCommandStub.withArgs('release-pr').returns(undefined)
await action.main()
assert.strictEqual(Object.hasOwnProperty.call(output, 'pr'), false)
})
it('creates and runs a ReleasePR instance, using factory', async () => {
let maybeReleasePR
sandbox.replace(factory, 'call', runnable => {
maybeReleasePR = runnable
})
input = {
'release-type': 'node',
command: 'release-pr'
}
await action.main()
assert.ok(maybeReleasePR instanceof Node)
})
it('creates and runs a GitHubRelease, using factory', async () => {
let maybeGitHubRelease
sandbox.replace(factory, 'call', runnable => {
maybeGitHubRelease = runnable
})
input = {
'release-type': 'node',
command: 'github-release'
}
await action.main()
assert.ok(maybeGitHubRelease instanceof GitHubRelease)
})
})
|
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
import pytest
import mindspore.context as context
import mindspore.nn as nn
from mindspore.ops import operations as P
context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
class Net(nn.Cell):
def __init__(self, shape, seed=0, seed2=0):
super(Net, self).__init__()
self.shape = shape
self.seed = seed
self.seed2 = seed2
self.stdnormal = P.StandardNormal(seed, seed2)
def construct(self):
return self.stdnormal(self.shape)
@pytest.mark.level0
@pytest.mark.platform_x86_gpu_training
@pytest.mark.env_onecard
def test_net():
seed = 10
seed2 = 10
shape = (3, 2, 4)
net = Net(shape, seed, seed2)
output = net()
assert output.shape == (3, 2, 4)
|
const jwt = require('jsonwebtoken')
const { matchesId } = require('@kansa/common/auth-user')
const { AuthError, InputError } = require('@kansa/common/errors')
const { sendMail } = require('@kansa/common/mail')
class Vote {
constructor(pgp, db) {
this.db = db
this.getFinalists = this.getFinalists.bind(this)
this.getPacket = this.getPacket.bind(this)
this.packetSeriesExtra = this.packetSeriesExtra.bind(this)
this.getVotes = this.getVotes.bind(this)
this.setVotes = this.setVotes.bind(this)
const svCS = new pgp.helpers.ColumnSet(
[
'client_ip',
'client_ua',
'person_id',
'signature',
'category',
{ name: 'votes', cast: 'integer[]' }
],
{ table: 'votes' }
)
this._setVoteData = data =>
db.many(`${pgp.helpers.insert(data, svCS)} RETURNING time`)
}
access(req, requireVoter) {
if (!requireVoter) return matchesId(this.db, req, 'hugo_admin')
const id = parseInt(req.params.id)
const { user } = req.session
if (isNaN(id) || id < 0)
return Promise.reject(new InputError('Bad id number'))
if (!user || !user.email) return Promise.reject(new AuthError())
if (user.hugo_admin) return Promise.resolve(id)
return this.db
.oneOrNone(
`SELECT wsfs_member
FROM kansa.people LEFT JOIN kansa.membership_types USING (membership)
WHERE id = $1 AND email = $2`,
id
)
.then(data => {
if (!data) throw new AuthError()
if (!data.wsfs_member) throw new AuthError('Not a Hugo voter')
return id
})
}
getFinalists(req, res, next) {
this.db
.any(
`SELECT category, id, title, subtitle FROM Finalists ORDER BY sortindex, id`
)
.then(data =>
res.json(
data.reduce((res, { category, id, title, subtitle }) => {
const finalist = { id, title, subtitle: subtitle || undefined }
if (res[category]) res[category].push(finalist)
else res[category] = [finalist]
return res
}, {})
)
)
.catch(next)
}
getPacket(req, res, next) {
const options = { httpOnly: true, path: '/hugo-packet', secure: true }
this.access(req, true)
.then(
id =>
new Promise((resolve, reject) => {
jwt.sign(
{ scope: 'wsfs' },
process.env.JWT_SECRET,
{
expiresIn: 120 * 60,
subject: String(id)
},
(err, token) => {
if (err) reject(err)
else resolve(token)
}
)
})
)
.then(token => {
res.cookie('packet', token, options)
return this.db.any(`SELECT * FROM Packet ORDER BY category, format`)
})
.then(data =>
res.json(
data.reduce((set, { category, filename, filesize, format }) => {
const ss =
filesize < 800 * 1024
? `${(filesize / 10240).toFixed(0)}0kB`
: `${(filesize / (1024 * 1024)).toFixed(0)}MB`
const obj = {
label: `${format.toUpperCase()}, ${ss}`,
url: `${options.path}/${filename}`
}
if (set[category]) set[category][format] = obj
else set[category] = { [format]: obj }
return set
}, {})
)
)
.catch(error => {
res.clearCookie('packet', options)
next(error)
})
}
packetSeriesExtra(req, res, next) {
this.access(req, true)
.then(id =>
this.db.one(
`SELECT email, kansa.preferred_name(p) AS name
FROM kansa.people AS p WHERE id = $1`,
id
)
)
.then(({ email, name }) =>
sendMail('hugo-packet-series-extra', { email, name })
)
.then(() => res.json({ status: 'success' }))
.catch(next)
}
getVotes(req, res, next) {
this.access(req, false)
.then(id =>
this.db.any(
`SELECT DISTINCT ON (category) category, votes, time
FROM Votes WHERE person_id = $1
ORDER BY category, time DESC`,
id
)
)
.then(data =>
res.json(
data.reduce((set, { category, time, votes }) => {
set[category] = { time, votes }
return set
}, {})
)
)
.catch(next)
}
sendVoteEmail(id) {
this.db
.task(t =>
t.batch([
t.one(
`
SELECT k.email, k.key, kansa.preferred_name(p) as name
FROM kansa.People AS p
JOIN kansa.Keys AS k USING (email)
WHERE id = $1`,
id
),
t.any(
`
SELECT category,
array_agg(
CASE id
WHEN 0 THEN '[No entry]'
WHEN -1 THEN 'No award'
ELSE coalesce(title, '[No entry]')
END
ORDER BY ordinality
) AS finalists
FROM ( SELECT DISTINCT ON (category) category, votes
FROM Votes WHERE person_id = $1
ORDER BY category, time DESC ) AS s
JOIN unnest(votes) WITH ORDINALITY AS id ON TRUE
LEFT JOIN Finalists f USING (id, category)
GROUP BY category
ORDER BY category`,
id
)
])
)
.then(([person, votes]) =>
sendMail(
'hugo-update-votes',
Object.assign({ memberId: id, votes }, person),
30
)
)
.catch(err => console.error(err))
}
setVotes(req, res, next) {
let { lastmod, signature, votes } = req.body
if (!signature || !votes)
return next(new InputError('Required parameters: signature, votes'))
if (typeof votes === 'string')
try {
votes = JSON.parse(votes)
} catch (e) {
return next(new InputError(e.message))
}
let data = null
this.access(req, true)
.then(id => {
data = Object.keys(votes).map(category => ({
client_ip: req.ip,
client_ua: req.headers['user-agent'] || null,
person_id: id,
signature,
category,
votes: votes[category]
}))
return this.db.one(`SELECT max(time) from Votes where person_id=$1`, id)
})
.then(({ max }) => {
if (max) {
const dm = new Date(lastmod)
if (!lastmod || isNaN(dm) || dm < max)
throw new InputError('Client has stale data')
}
return this._setVoteData(data)
})
.then(([{ time }, ...rest]) => {
res.status(200).json({ status: 'success', time, votes })
this.sendVoteEmail(data[0].person_id)
})
.catch(next)
}
}
module.exports = Vote
|
"""Sound Field Analysis Toolbox.
"""
__version__ = "0.0.1"
from . import modal
from . import util
|
const assert = require("assert");
const analyzer = require("../analyzer.js");
const babelParser = require("@babel/parser");
const AnalyzerError = analyzer.AnalyzerError;
describe("Analyzer", function() {
describe("findImports()", function() {
it("Works with default ES6 import", function() {
const code = "import { union } from 'tagmeme'";
const ast = babelParser.parse(code, { sourceType: "module" });
const foundImports = analyzer.findImports(ast.program.body);
assert.equal(1, foundImports.length);
assert.equal("union", foundImports[0].local);
assert.equal("union", foundImports[0].imported);
});
it("Works with aliased ES6 import", function() {
const code = "import { union as makeUnion } from 'tagmeme'";
const ast = babelParser.parse(code, { sourceType: "module" });
const foundImports = analyzer.findImports(ast.program.body);
assert.equal(1, foundImports.length);
assert.equal("makeUnion", foundImports[0].local);
assert.equal("union", foundImports[0].imported);
});
it("Works with default ES5 require", function() {
const code = "const union = require('tagmeme').union;"
const ast = babelParser.parse(code, { sourceType: "module" });
const foundImports = analyzer.findImports(ast.program.body);
assert.equal(1, foundImports.length);
assert.equal("union", foundImports[0].local);
assert.equal("union", foundImports[0].imported);
});
it("Works with aliased ES5 require", function() {
const code = "const makeUnion = require('tagmeme').union;"
const ast = babelParser.parse(code, { sourceType: "module" });
const foundImports = analyzer.findImports(ast.program.body);
assert.equal(1, foundImports.length);
assert.equal("makeUnion", foundImports[0].local);
assert.equal("union", foundImports[0].imported);
});
it("Does not import from other libraries in ES5 syntax", function() {
const code = "const makeUnion = require('some-library').union;"
const ast = babelParser.parse(code, { sourceType: "module" });
const foundImports = analyzer.findImports(ast.program.body);
assert.equal(0, foundImports.length);
});
it("Does not import from other libraries in ES6 syntax", function() {
const code = "import { union as makeUnion } from 'some-library'"
const ast = babelParser.parse(code, { sourceType: "module" });
const foundImports = analyzer.findImports(ast.program.body);
assert.equal(0, foundImports.length);
});
});
describe("findExports()", function() {
it("Returns the exported declarations", function() {
const code = [
"import { union } from 'tagmeme'",
"export const Option = union([ 'Some', 'None' ])",
"export const Result = union([ 'Ok', 'Error' ])"
]
const ast = babelParser.parse(code.join("\n"), { sourceType: "module" });
const foundExports = analyzer.findExports(ast.program.body);
assert.equal(2, foundExports.length);
});
});
describe("groupBy()", function() {
it("hopefully works...", function() {
const declaration = {
unionType: 'Option',
cases: ['Some', 'None', 'None']
}
const groups = analyzer.groupBy(declaration.cases, caseName => caseName);
const keys = Object.keys(groups);
assert.equal(2, keys.length);
assert.equal(1, groups['Some'].length);
assert.equal(2, groups['None'].length);
})
});
describe("findUnionDeclarations()", function() {
it("finds declarations constructed using 'union'", function() {
const code = [
"import { union } from 'tagmeme'",
"const Option = union([ 'Some', 'None' ])"
];
const ast = babelParser.parse(code.join("\n"), { sourceType: "module" });
const irrelevantFile = "./irrelevant"
const irrelevantReader = filePath => "Some content";
const declarations = analyzer.findUnionDeclarations(ast.program.body, irrelevantFile, irrelevantReader);
assert.equal(1, declarations.length);
assert.equal("Option", declarations[0].unionType);
assert.deepEqual([ 'Some', 'None' ], declarations[0].cases);
});
it("finds declarations constructed using aliased 'union'", function() {
const code = [
"import { union as makeUnion } from 'tagmeme'",
"const Option = makeUnion([ 'Some', 'None' ])"
];
const ast = babelParser.parse(code.join("\n"), { sourceType: "module" });
const irrelevantFile = "./irrelevant"
const irrelevantReader = filePath => "Some content";
const declarations = analyzer.findUnionDeclarations(ast.program.body, irrelevantFile, irrelevantReader);
assert.equal(1, declarations.length);
assert.equal("Option", declarations[0].unionType);
assert.deepEqual([ 'Some', 'None' ], declarations[0].cases);
});
it("finds multiple declarations constructed using aliased 'union'", function() {
const code = [
"import { union as makeUnion } from 'tagmeme'",
"const Option = makeUnion([ 'Some', 'None' ])",
"const Result = makeUnion([ 'Ok', 'Error' ])"
];
const ast = babelParser.parse(code.join("\n"), { sourceType: "module" });
const irrelevantFile = "./irrelevant"
const irrelevantReader = filePath => "Some irrelevant content that will not be read";
const declarations = analyzer.findUnionDeclarations(ast.program.body, irrelevantFile, irrelevantReader);
assert.equal(2, declarations.length);
assert.equal("Option", declarations[0].unionType);
assert.deepEqual([ 'Some', 'None' ], declarations[0].cases);
assert.equal("Result", declarations[1].unionType);
assert.deepEqual([ 'Ok', 'Error' ], declarations[1].cases);
});
it("finds exported declarations", function() {
const code = [
"import { union as makeUnion } from 'tagmeme'",
"export const Option = makeUnion([ 'Some', 'None' ])",
"export const Result = makeUnion([ 'Ok', 'Error' ])"
];
const ast = babelParser.parse(code.join("\n"), { sourceType: "module" });
const irrelevantFile = "./irrelevant"
const irrelevantReader = filePath => "Some irrelevant content that will not be read";
const declarations = analyzer.findUnionDeclarations(ast.program.body, irrelevantFile, irrelevantReader);
assert.equal(2, declarations.length);
assert.equal("Option", declarations[0].unionType);
assert.deepEqual([ 'Some', 'None' ], declarations[0].cases);
assert.equal("Result", declarations[1].unionType);
assert.deepEqual([ 'Ok', 'Error' ], declarations[1].cases);
});
it("finds external declarations", function() {
const types = [
"import { union } from 'tagmeme'",
"export const Result = union([ 'Ok', 'Error' ])",
"export const Option = union([ 'Some', 'None' ])"
];
const app = [
"import { Option } from './types'",
"import { Result } from './types'"
]
const ast = babelParser.parse(app.join("\n"), { sourceType: "module" });
const irrelevantFile = "./irrelevant"
const typesReader = filePath => types.join("\n");
const declarations = analyzer.findUnionDeclarations(ast.program.body, irrelevantFile, typesReader);
assert.equal(2, declarations.length);
assert.equal("Option", declarations[1].unionType);
assert.deepEqual([ 'Some', 'None' ], declarations[1].cases);
assert.equal("Result", declarations[0].unionType);
assert.deepEqual([ 'Ok', 'Error' ], declarations[0].cases);
});
});
describe("analyze()", function() {
it("returns no errors for valid use of pattern matching", function() {
const code = [
"import { union as makeUnion } from 'tagmeme';",
"const Result = makeUnion([ 'Ok', 'Error' ]);",
"const success = Result.Ok(1);",
"const value = Result.match(success, {",
" Ok: n => n + 1,",
" Error: () => 0",
"})",
];
const mockReader = filename => code.join("\n");
const errors = analyzer.analyze("cwd", "./irrelevant-filename", mockReader);
assert.equal(0, errors.length);
});
it("returns an error when type name is incorrect", function() {
const code = [
"import { union as makeUnion } from 'tagmeme';",
"const Result = makeUnion([ 'Ok', 'Error' ]);",
"const success = Result.Ok(1);",
// Detect typo: => used 'Tesult' instead of 'Result'
"const value = Tesult.match(success, {",
" Ok: n => n + 1,",
" Error: () => 0",
"})",
];
const mockReader = filename => code.join("\n");
const errors = analyzer.analyze("cwd", "./irrelevant-filename", mockReader);
assert.equal(1, errors.length);
AnalyzerError.match(errors[0], {
UnionTypeNameIncorrect: errorInfo => {
assert.equal('Tesult', errorInfo.usedTypeName);
assert.deepEqual([ 'Result' ], errorInfo.possibleAlternatives);
}
}, () => assert.fail('Expected analyzer error of union case UnionTypeNameIncorrect'));
});
it("returns an error when a union case is declared but not handled", function() {
const code = [
"import { union as makeUnion } from 'tagmeme';",
"const Result = makeUnion([ 'Ok', 'Error' ]);",
"const success = Result.Ok(1);",
// Error => forgot to handle 'Error' union case
"const value = Result.match(success, { Ok: n => n + 1 })"
];
const mockReader = filename => code.join("\n");
const errors = analyzer.analyze("cwd", "./irrelevant-filename", mockReader);
assert.equal(1, errors.length);
AnalyzerError.match(errors[0], {
UnionCaseDeclaredButNotHandled: errorInfo => {
assert.equal('Result', errorInfo.usedUnionType);
assert.deepEqual('Error', errorInfo.declaredUnionCase);
}
}, () => assert.fail('Expected analyzer error of union case UnionTypeNameIncorrect'));
});
it("returns no error if catchAll argument is present to handle other cases", function() {
const code = [
"import { union as makeUnion } from 'tagmeme';",
"const Result = makeUnion([ 'Ok', 'Error' ]);",
"const success = Result.Ok(1);",
"const value = Result.match(success, { Ok: n => n + 1 }, () => 0)"
];
const mockReader = filename => code.join("\n");
const errors = analyzer.analyze("cwd", "./irrelevant-filename", mockReader);
assert.equal(0, errors.length);
});
it("returns an error when a case is handled but not declared in the type", function() {
const code = [
"import { union as makeUnion } from 'tagmeme';",
"const Result = makeUnion([ 'Ok', 'Error' ]);",
"const success = Result.Ok(1);",
// Error => handling too many cases, the 'Other' case in not declared in the `Result`
"const value = Result.match(success, { Ok: n => n + 1, Error: () => 1, Other: () => 3 })"
];
const mockReader = filename => code.join("\n");
const errors = analyzer.analyze("cwd", "./irrelevant-filename", mockReader);
assert.equal(1, errors.length);
AnalyzerError.match(errors[0], {
UnionCaseHandledButNotDeclared: errorInfo => {
assert.equal('Result', errorInfo.usedUnionType);
assert.equal('Other', errorInfo.usedUnionCase);
}
}, () => assert.fail('Expected analyzer error of union case UnionCaseHandledButNotDeclared'));
});
it("returns an error when a case is handled but not declared in the type with multiple possible alternatives", function() {
const code = [
"import { union as makeUnion } from 'tagmeme';",
"const Result = makeUnion([ 'Erro', 'Error' ]);",
"const success = Result.Erro(1);",
// Error => handling too many cases, the 'Other' case in not declared in the `Result`
"const value = Result.match(success, { Erro: n => n + 1, Error: () => 1, Erron: () => 3 })"
];
const mockReader = filename => code.join("\n");
const errors = analyzer.analyze("cwd", "./irrelevant-filename", mockReader);
assert.equal(1, errors.length);
AnalyzerError.match(errors[0], {
UnionCaseHandledButNotDeclared: errorInfo => {
assert.equal('Result', errorInfo.usedUnionType);
assert.equal('Erron', errorInfo.usedUnionCase);
}
}, () => assert.fail('Expected analyzer error of union case UnionCaseHandledButNotDeclared'));
});
it("returns an error when a case has a duplicate declaration", function() {
const code = [
"import { union as makeUnion } from 'tagmeme';",
"const Duplicated = makeUnion([ 'Ok', 'Ok' ]);"
];
const mockReader = filename => code.join("\n");
const errors = analyzer.analyze("cwd", "./irrelevant-filename", mockReader);
assert.equal(1, errors.length);
AnalyzerError.match(errors[0], {
DuplicateUnionCaseDeclaration: errorInfo => assert.ok(true)
}, () => assert.fail('Expected analyzer error of union case UnionCaseHandledButNotDeclared'));
});
it("returns an error when 'match' is used as a union case", function() {
const code = [
"import { union as makeUnion } from 'tagmeme';",
"const UsesMatch = makeUnion([ 'Ok', 'Error', 'match' ]);"
];
const mockReader = filename => code.join("\n");
const errors = analyzer.analyze("cwd", "./irrelevant-filename", mockReader);
assert.equal(1, errors.length);
AnalyzerError.match(errors[0], {
UsingMatchAsUnionCase: errorInfo => assert.ok(true)
}, () => assert.fail('Expected analyzer error of union case UnionCaseHandledButNotDeclared'));
});
it("returns an error when all cases are handled and catchAll is redundant", function() {
const code = [
"import { union as makeUnion } from 'tagmeme';",
"const Result = makeUnion([ 'Ok', 'Error' ]);",
"const success = Result.Ok(1);",
// Error => catchAll (2nd arg) is redundant
"const value = Result.match(success, { Ok: n => n + 1, Error: () => 1 }, () => 0)"
];
const mockReader = filename => code.join("\n");
const errors = analyzer.analyze("cwd", "./irrelevant-filename", mockReader);
assert.equal(1, errors.length);
AnalyzerError.match(errors[0],
{ RedundantCatchAllArgument: errorInfo => assert.ok(true) },
() => assert.fail('Expected analyzer error of union case UnionCaseHandledButNotDeclared')
);
});
it("returns errors from imported union declarations", function() {
const types = [
"import { union } from 'tagmeme';",
"export const Result = union([ 'Ok', 'Error' ]);"
];
const code = [
"import { Result } from './types'",
"const success = Result.Ok(1);",
// Error => handling too many cases, the 'Other' case in not declared in the `Result`
"const value = Result.match(success, { Ok: n => n + 1, Error: () => 1, Other: () => 3 })"
];
const mockReader = filename => {
if (filename.indexOf("code") !== -1 && filename.indexOf("types") === -1) {
return code.join("\n");
} else {
return types.join("\n");
}
};
const errors = analyzer.analyze("cwd", "./code", mockReader);
assert.equal(1, errors.length);
AnalyzerError.match(errors[0], {
UnionCaseHandledButNotDeclared: errorInfo => {
assert.equal('Result', errorInfo.usedUnionType);
assert.equal('Other', errorInfo.usedUnionCase);
}
}, () => assert.fail('Expected analyzer error of union case UnionCaseHandledButNotDeclared'));
});
});
describe("logErrorAndExit()", function() {
it("Exits process with exit code 0 when there are no errors", function() {
const errors = [ ];
const mockProccess = { exit: n => assert.equal(0, n) };
const logs = [ ];
const logger = log => logs.push(log);
analyzer.logErrorsAndExit(errors, logger, mockProccess);
});
it("Exits process with exit code 1 when there are errors", function() {
const code = [
"import { union as makeUnion } from 'tagmeme';",
"const Result = makeUnion([ 'Ok', 'Error' ]);",
"const success = Result.Ok(1);",
// Error => catchAll (2nd arg) is redundant
"const value = Result.match(success, { Ok: n => n + 1, Error: () => 1 }, () => 0)"
];
const mockReader = filename => code.join("\n");
const errors = analyzer.analyze("cwd", "./irrelevant-filename", mockReader);
assert.equal(1, errors.length);
const mockProccess = { exit: n => assert.equal(1, n) };
const logs = [ ];
const logger = log => logs.push(log);
analyzer.logErrorsAndExit(errors, logger, mockProccess);
});
});
}); |
var newBlock = require('./new-block.js');
/**
* lost-align: Align nested elements. Apply this to a parent container.
*
* @param {string} [reset|horizontal|vertical|top-left|top-center|top|
* top-right|middle-left|left|middle-center|center|middle-right|right|
* bottom-left|bottom-center|bottom|bottom-right] - The position the nested
* element takes relative to the containing element.
*
* @param {string} [flex|no-flex] - Determines whether this element should
* use Flexbox or not.
*
* @example
* .parent {
* lost-align: right;
* width: 600px;
* height: 400px;
* }
* .child {
* width: 300px;
* height: 150px;
* }
*/
module.exports = function lostAlign(css) {
css.walkDecls('lost-align', function alignDirectionFunction(decl) {
var declArr = [];
var alignDirection;
declArr = decl.value.split(' ');
alignDirection = declArr[0];
if (declArr[1] !== 'flex') {
if (alignDirection === 'reset') {
decl.cloneBefore({
prop: 'position',
value: 'static'
});
newBlock(
decl,
' > *',
['position', 'top', 'right', 'bottom', 'left', 'transform'],
['static', 'auto', 'auto', 'auto', 'auto', 'translate(0, 0)']
);
} else {
decl.cloneBefore({
prop: 'position',
value: 'relative'
});
if (alignDirection === 'horizontal') {
newBlock(
decl,
' > *',
['position', 'top', 'right', 'bottom', 'left', 'transform'],
['absolute', 'auto', 'auto', 'auto', '50%', 'translate(-50%, 0)']
);
} else if (alignDirection === 'vertical') {
newBlock(
decl,
' > *',
['position', 'top', 'right', 'bottom', 'left', 'transform'],
['absolute', '50%', 'auto', 'auto', 'auto', 'translate(0, -50%)']
);
} else if (alignDirection === 'top-left') {
newBlock(
decl,
' > *',
['position', 'top', 'right', 'bottom', 'left', 'transform'],
['absolute', '0', 'auto', 'auto', '0', 'translate(0, 0)']
);
} else if (alignDirection === 'top-center' || alignDirection === 'top') {
newBlock(
decl,
' > *',
['position', 'top', 'right', 'bottom', 'left', 'transform'],
['absolute', '0', 'auto', 'auto', '50%', 'translate(-50%, 0)']
);
} else if (alignDirection === 'top-right') {
newBlock(
decl,
' > *',
['position', 'top', 'right', 'bottom', 'left', 'transform'],
['absolute', '0', '0', 'auto', 'auto', 'translate(0, 0)']
);
} else if (alignDirection === 'middle-left' || alignDirection === 'left') {
newBlock(
decl,
' > *',
['position', 'top', 'right', 'bottom', 'left', 'transform'],
['absolute', '50%', 'auto', 'auto', '0', 'translate(0, -50%)']
);
} else if (alignDirection === 'middle-center' || alignDirection === 'center') {
newBlock(
decl,
' > *',
['position', 'top', 'right', 'bottom', 'left', 'transform'],
['absolute', '50%', 'auto', 'auto', '50%', 'translate(-50%, -50%)']
);
} else if (alignDirection === 'middle-right' || alignDirection === 'right') {
newBlock(
decl,
' > *',
['position', 'top', 'right', 'bottom', 'left', 'transform'],
['absolute', '50%', '0', 'auto', 'auto', 'translate(0, -50%)']
);
} else if (alignDirection === 'bottom-left') {
newBlock(
decl,
' > *',
['position', 'top', 'right', 'bottom', 'left', 'transform'],
['absolute', 'auto', 'auto', '0', '0', 'translate(0, 0)']
);
} else if (alignDirection === 'bottom-center' || alignDirection === 'bottom') {
newBlock(
decl,
' > *',
['position', 'top', 'right', 'bottom', 'left', 'transform'],
['absolute', 'auto', 'auto', '0', '50%', 'translate(-50%, 0)']
);
} else if (alignDirection === 'bottom-right') {
newBlock(
decl,
' > *',
['position', 'top', 'right', 'bottom', 'left', 'transform'],
['absolute', 'auto', '0', '0', 'auto', 'translate(0, 0)']
);
}
}
} else if (alignDirection === 'reset') {
decl.cloneBefore({
prop: 'display',
value: 'initial'
});
newBlock(
decl,
' > *',
['justify-content', 'align-items'],
['inherit', 'inherit']
);
} else {
decl.cloneBefore({
prop: 'display',
value: 'flex'
});
if (alignDirection === 'horizontal') {
newBlock(
decl,
' > *',
['justify-content', 'align-items'],
['center', 'inherit']
);
} else if (alignDirection === 'vertical') {
newBlock(
decl,
' > *',
['justify-content', 'align-items'],
['inherit', 'center']
);
} else if (alignDirection === 'top-left') {
newBlock(
decl,
' > *',
['justify-content', 'align-items'],
['flex-start', 'flex-start']
);
} else if (alignDirection === 'top-center' || alignDirection === 'top') {
newBlock(
decl,
' > *',
['justify-content', 'align-items'],
['center', 'flex-start']
);
} else if (alignDirection === 'top-right') {
newBlock(
decl,
' > *',
['justify-content', 'align-items'],
['flex-end', 'flex-start']
);
} else if (alignDirection === 'middle-left' || alignDirection === 'left') {
newBlock(
decl,
' > *',
['justify-content', 'align-items'],
['flex-start', 'center']
);
} else if (alignDirection === 'middle-center' || alignDirection === 'center') {
newBlock(
decl,
' > *',
['justify-content', 'align-items'],
['center', 'center']
);
} else if (alignDirection === 'middle-right' || alignDirection === 'right') {
newBlock(
decl,
' > *',
['justify-content', 'align-items'],
['flex-end', 'center']
);
} else if (alignDirection === 'bottom-left') {
newBlock(
decl,
' > *',
['justify-content', 'align-items'],
['flex-start', 'flex-end']
);
} else if (alignDirection === 'bottom-center' || alignDirection === 'bottom') {
newBlock(
decl,
' > *',
['justify-content', 'align-items'],
['center', 'flex-end']
);
} else if (alignDirection === 'bottom-right') {
newBlock(
decl,
' > *',
['justify-content', 'align-items'],
['flex-end', 'flex-end']
);
}
}
decl.remove();
});
};
|
"""
Dummy Nuqql Backend
"""
import logging
from pathlib import Path
from typing import Callable, List
import nuqql.config
from .backend import Backend
logger = logging.getLogger(__name__)
class NuqqlBackend(Backend):
"""
Class for the nuqql dummy backend
"""
def __init__(self, name: str) -> None:
Backend.__init__(self, name)
self.version = ""
# function for (re)starting backends
self.restart_func: Callable[[str], None]
def _handle_nuqql_global_status(self, parts: List[str]) -> None:
"""
Handle nuqql command: global-status
Call getter and setter funcions
"""
if not parts:
return
sub_command = parts[0]
if sub_command == "set":
if len(parts) < 2:
return
self._handle_nuqql_global_status_set(parts[1])
elif sub_command == "get":
self._handle_nuqql_global_status_get()
def _handle_nuqql_global_status_set(self, status: str) -> None:
"""
Handle nuqql command: global-status set
Set status and store it in global_status file
"""
# only use the first word as status
if not status or status == "":
return
logger.debug("setting global status to %s", status)
# write status
self._write_global_status(status)
# set status in all backends and their accounts
for backend in self.backends.values():
for acc in backend.accounts.values():
if backend.client:
backend.client.send_status_set(acc.aid, status)
# log message
msg = "global-status: " + status
if self.conversation:
self.conversation.log("nuqql", msg)
def _handle_nuqql_global_status_get(self) -> None:
"""
Handle nuqql command: global-status get
Read status from global_status file
"""
logger.debug("getting global status")
# read status
status = self.read_global_status()
if status == "":
return
logger.debug("global status is %s", status)
# log message
msg = "global-status: " + status
if self.conversation:
self.conversation.log("nuqql", msg)
@staticmethod
def _write_global_status(status: str) -> None:
"""
Write global status to global_status file
"""
logger.debug("writing global status %s to file", status)
# write status to file
global_status_dir = str(nuqql.config.get("dir"))
Path(global_status_dir).mkdir(parents=True, exist_ok=True)
global_status_file = global_status_dir + "/global_status"
line = status + "\n"
lines = []
lines.append(line)
with open(global_status_file, "w+", encoding='UTF-8') as status_file:
status_file.writelines(lines)
def _handle_stop(self, parts: List[str]) -> None:
"""
Handle stop command, stop a backend
"""
if not parts:
return
backend_name = parts[0]
logger.debug("stopping backend %s", backend_name)
if backend_name in self.backends:
self.backends[backend_name].stop()
def _handle_start(self, parts: List[str]) -> None:
"""
Handle start command, start a backend
"""
if not parts:
return
backend_name = parts[0]
logger.debug("starting backend %s", backend_name)
assert self.restart_func
self.restart_func(backend_name)
def _handle_restart(self, parts: List[str]) -> None:
"""
Handle restart command, stop and start a backend
"""
if not parts:
return
backend_name = parts[0]
logger.debug("restarting backend %s", backend_name)
self._handle_stop(parts)
self._handle_start(parts)
def _handle_quit(self, _parts: List[str]) -> None:
"""
Handle quit command, quit nuqql
"""
logger.debug("quitting nuqql")
if self.conversation:
self.conversation.wins.input_win.state.active = False
self.conversation.wins.list_win.state.active = False
def _handle_version(self, _parts: List[str]) -> None:
"""
Handle version command, print nuqql version
"""
# log message
msg = f"version: nuqql v{self.version}"
logger.debug("getting nuqql version: %s", msg)
if self.conversation:
self.conversation.log("nuqql", msg)
def handle_nuqql_command(self, msg: str) -> None:
"""
Handle a nuqql command (from the nuqql conversation)
"""
logger.debug("handling nuqql command %s", msg)
# parse message
parts = msg.split()
if not parts:
return
# check command and call helper functions
command_map = {
"global-status": self._handle_nuqql_global_status,
"stop": self._handle_stop,
"start": self._handle_start,
"restart": self._handle_restart,
"quit": self._handle_quit,
"version": self._handle_version,
}
command = parts[0]
if command in command_map:
command_map[command](parts[1:])
|
Subsets and Splits