text
stringlengths 3
1.05M
|
|---|
import './module.js';
import GeoJSON from 'ol/format/GeoJSON';
angular.module('anol.savemanager')
/**
* @ngdoc object
* @name anol.savemanager.SaveManagerServiceProvider
*/
.provider('SaveManagerService', ['LayersServiceProvider', function(LayersServiceProvider) {
// handles layer source change events and store listener keys for removing
// listeners nicely
var LayerListener = function(layer, saveManager) {
this.layer = layer;
this.saveManager = saveManager;
this.source = layer.olLayer.getSource();
this.addListenerKey = undefined;
this.changeListenerKey = undefined;
this.removeListenerKey = undefined;
};
LayerListener.prototype.register = function(addHandler, changeHandler, removeHandler) {
var self = this;
var _register = function(type, handler, key) {
if(angular.isUndefined(handler)) {
return;
}
if(angular.isDefined(key)) {
self.source.unByKey(key);
}
return self.source.on(
type,
function(evt) {
handler.apply(self.saveManager, [evt, self.layer]);
}
);
};
self.addListenerKey = _register(
'addfeature',
addHandler,
self.addListenerKey
);
self.changeListenerKey = _register(
'changefeature',
changeHandler,
self.changeListenerKey
);
self.removeListenerKey = _register(
'removefeature',
removeHandler,
self.removeListenerKey
);
};
LayerListener.prototype.unregister = function() {
var self = this;
if(angular.isDefined(self.addListenerKey)) {
self.source.unByKey(self.addListenerKey);
self.addListenerKey = undefined;
}
if(angular.isDefined(self.changeListenerKey)) {
self.source.unByKey(self.changeListenerKey);
self.changeListenerKey = undefined;
}
if(angular.isDefined(self.removeListenerKey)) {
self.source.unByKey(self.removeListenerKey);
self.removeListenerKey = undefined;
}
};
var _saveManagerInstance;
var _saveUrl;
var _saveableLayers = [];
/**
* @ngdoc method
* @name setSaveUrl
* @methodOf anol.savemanager.SaveManagerServiceProvider
* @param {String} saveUrl url to save changes to. Might be overwritten by layer.saveUrl
*/
this.setSaveUrl = function(saveUrl) {
_saveUrl = saveUrl;
};
LayersServiceProvider.registerAddLayerHandler(function(layer) {
if(layer.saveable !== true) {
return;
}
if(angular.isDefined(_saveManagerInstance)) {
_saveManagerInstance.addLayer(layer);
} else {
_saveableLayers.push(layer);
}
});
this.$get = ['$rootScope', '$q', '$http', '$timeout', '$translate', function($rootScope, $q, $http, $timeout, $translate) {
/**
* @ngdoc service
* @name anol.savemanager.SaveManagerService
*
* @description
* Collects changes in saveable layers and send them to given saveUrl
*/
var SaveManager = function(saveUrl, saveableLayers) {
var self = this;
this.saveUrl = saveUrl;
this.changedLayers = {};
this.changedFeatures = {};
angular.forEach(saveableLayers, function(layer) {
self.addLayer(layer);
});
var translate = function() {
$translate('anol.savemanager.SERVICE_UNAVAILABLE').then(
function(translation) {
self.serviceUnavailableMessage = translation;
});
};
$rootScope.$on('$translateChangeSuccess', translate);
translate();
};
/**
* @ngdoc method
* @name addLayer
* @methodOd anol.savemanager.SaveManagerService
* @param {anol.layer.Feature} layer layer to watch for changes
*/
SaveManager.prototype.addLayer = function(layer) {
var self = this;
var layerListener = new LayerListener(layer, self);
$rootScope.$watch(function() {
return layer.loaded;
}, function(loaded) {
if(loaded === true) {
layerListener.register(
self.featureAddedHandler,
self.featureChangedHandler,
self.featureRemovedHandler
);
} else {
layerListener.unregister();
}
});
};
/**
* private function
*
* handler for ol3 feature added event
*/
SaveManager.prototype.featureAddedHandler = function(evt, layer) {
var self = this;
self.addChangedLayer(layer);
};
/**
* private function
*
* handler for ol3 feature changed event
*/
SaveManager.prototype.featureChangedHandler = function(evt, layer) {
var self = this;
self.addChangedLayer(layer);
};
/**
* private function
*
* handler for ol3 feature removed event
*/
SaveManager.prototype.featureRemovedHandler = function(evt, layer) {
var self = this;
self.addChangedLayer(layer);
};
/**
* private function
*
* adds a layer to list of layers with changes
*/
SaveManager.prototype.addChangedLayer = function(layer) {
var self = this;
if(!(layer.name in self.changedLayers)) {
// TODO find out why $apply already in progress
$timeout(function() {
$rootScope.$apply(function() {
self.changedLayers[layer.name] = layer;
});
});
}
};
/**
* private function
*
* cleans up after changes done
*/
SaveManager.prototype.changesDone = function(layerName) {
delete this.changedLayers[layerName];
};
/**
* @ngdoc method
* @name commit
* @methodOd anol.savemanager.SaveManagerService
* @param {anol.layer.Feature} layer
* @description
* Commits changes for given layer
*/
SaveManager.prototype.commit = function(layer) {
var self = this;
var deferred = $q.defer();
var format = new GeoJSON();
if(layer.name in self.changedLayers) {
var data = {
name: layer.name,
featureCollection: format.writeFeaturesObject(
layer.olLayer.getSource().getFeatures()
)
};
var promise = $http.post(self.saveUrl, data);
promise.then(function(response) {
self.changesDone(layer.name);
deferred.resolve(response.data);
}, function(response) {
if(response.status === -1) {
deferred.reject({'message': self.serviceUnavailableMessage});
} else {
deferred.reject(response.data);
}
});
} else {
deferred.reject('No changes for layer ' + layer.name + ' present');
}
return deferred.promise;
};
/**
* @ngdoc method
* @name commitAll
* @methodOf anol.savemanager.SaveManagerService
*
* @description
* Commit all changed layers
*/
SaveManager.prototype.commitAll = function() {
var self = this;
var promises = [];
angular.forEach(self.changedLayers, function(layer) {
promises.push(self.commit(layer));
});
return $q.all(promises);
};
_saveManagerInstance = new SaveManager(_saveUrl, _saveableLayers);
return _saveManagerInstance;
}];
}]);
|
!function(t){var n={};function r(e){if(n[e])return n[e].exports;var o=n[e]={i:e,l:!1,exports:{}};return t[e].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=t,r.c=n,r.d=function(t,n,e){r.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:e})},r.r=function(t){Object.defineProperty(t,"__esModule",{value:!0})},r.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(n,"a",n),n},r.o=function(t,n){return Object.prototype.hasOwnProperty.call(t,n)},r.p="",r(r.s=48)}([function(t,n,r){var e=r(13),o=r(5),u=4294967295;function c(t){this.__wrapped__=t,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=u,this.__views__=[]}c.prototype=e(o.prototype),c.prototype.constructor=c,t.exports=c},function(t,n){var r=Array.isArray;t.exports=r},function(t,n){t.exports=function(t){return null!=t&&"object"==typeof t}},function(t,n,r){var e=r(41),o="object"==typeof self&&self&&self.Object===Object&&self,u=e||o||Function("return this")();t.exports=u},function(t,n,r){var e=r(3).Symbol;t.exports=e},function(t,n){t.exports=function(){}},function(t,n){t.exports=function(t){var n=typeof t;return null!=t&&("object"==n||"function"==n)}},function(t,n,r){var e=r(13),o=r(5);function u(t,n){this.__wrapped__=t,this.__actions__=[],this.__chain__=!!n,this.__index__=0,this.__values__=void 0}u.prototype=e(o.prototype),u.prototype.constructor=u,t.exports=u},function(t,n,r){var e=r(47)();t.exports=e},function(t,n,r){var e=r(18),o=Object.prototype.hasOwnProperty;t.exports=function(t){for(var n=t.name+"",r=e[n],u=o.call(e,n)?r.length:0;u--;){var c=r[u],i=c.func;if(null==i||i==t)return c.name}return n}},function(t,n,r){var e=r(21),o=r(19),u=e?function(t){return e.get(t)}:o;t.exports=u},function(t,n,r){var e=r(29),o=r(24);t.exports=function(t,n){var r=o(t,n);return e(r)?r:void 0}},function(t,n,r){var e=r(4),o=r(37),u=r(36),c="[object Null]",i="[object Undefined]",a=e?e.toStringTag:void 0;t.exports=function(t){return null==t?void 0===t?i:c:a&&a in Object(t)?o(t):u(t)}},function(t,n,r){var e=r(6),o=Object.create,u=function(){function t(){}return function(n){if(!e(n))return{};if(o)return o(n);t.prototype=n;var r=new t;return t.prototype=void 0,r}}();t.exports=u},function(t,n){t.exports=function(t,n){var r=-1,e=t.length;for(n||(n=Array(e));++r<e;)n[r]=t[r];return n}},function(t,n,r){var e=r(0),o=r(7),u=r(14);t.exports=function(t){if(t instanceof e)return t.clone();var n=new o(t.__wrapped__,t.__chain__);return n.__actions__=u(t.__actions__),n.__index__=t.__index__,n.__values__=t.__values__,n}},function(t,n,r){var e=r(0),o=r(7),u=r(5),c=r(1),i=r(2),a=r(15),f=Object.prototype.hasOwnProperty;function p(t){if(i(t)&&!c(t)&&!(t instanceof e)){if(t instanceof o)return t;if(f.call(t,"__wrapped__"))return a(t)}return new o(t)}p.prototype=u.prototype,p.prototype.constructor=p,t.exports=p},function(t,n,r){var e=r(0),o=r(10),u=r(9),c=r(16);t.exports=function(t){var n=u(t),r=c[n];if("function"!=typeof r||!(n in e.prototype))return!1;if(t===r)return!0;var i=o(r);return!!i&&t===i[0]}},function(t,n){t.exports={}},function(t,n){t.exports=function(){}},function(t,n,r){var e=r(11)(r(3),"WeakMap");t.exports=e},function(t,n,r){var e=r(20),o=e&&new e;t.exports=o},function(t,n){var r=800,e=16,o=Date.now;t.exports=function(t){var n=0,u=0;return function(){var c=o(),i=e-(c-u);if(u=c,i>0){if(++n>=r)return arguments[0]}else n=0;return t.apply(void 0,arguments)}}},function(t,n){t.exports=function(t){return t}},function(t,n){t.exports=function(t,n){return null==t?void 0:t[n]}},function(t,n){var r=Function.prototype.toString;t.exports=function(t){if(null!=t){try{return r.call(t)}catch(t){}try{return t+""}catch(t){}}return""}},function(t,n,r){var e=r(3)["__core-js_shared__"];t.exports=e},function(t,n,r){var e,o=r(26),u=(e=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||""))?"Symbol(src)_1."+e:"";t.exports=function(t){return!!u&&u in t}},function(t,n,r){var e=r(12),o=r(6),u="[object AsyncFunction]",c="[object Function]",i="[object GeneratorFunction]",a="[object Proxy]";t.exports=function(t){if(!o(t))return!1;var n=e(t);return n==c||n==i||n==u||n==a}},function(t,n,r){var e=r(28),o=r(27),u=r(6),c=r(25),i=/^\[object .+?Constructor\]$/,a=Function.prototype,f=Object.prototype,p=a.toString,l=f.hasOwnProperty,s=RegExp("^"+p.call(l).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=function(t){return!(!u(t)||o(t))&&(e(t)?s:i).test(c(t))}},function(t,n,r){var e=r(11),o=function(){try{var t=e(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();t.exports=o},function(t,n){t.exports=function(t){return function(){return t}}},function(t,n,r){var e=r(31),o=r(30),u=r(23),c=o?function(t,n){return o(t,"toString",{configurable:!0,enumerable:!1,value:e(n),writable:!0})}:u;t.exports=c},function(t,n,r){var e=r(32),o=r(22)(e);t.exports=o},function(t,n){t.exports=function(t,n,r){switch(r.length){case 0:return t.call(n);case 1:return t.call(n,r[0]);case 2:return t.call(n,r[0],r[1]);case 3:return t.call(n,r[0],r[1],r[2])}return t.apply(n,r)}},function(t,n,r){var e=r(34),o=Math.max;t.exports=function(t,n,r){return n=o(void 0===n?t.length-1:n,0),function(){for(var u=arguments,c=-1,i=o(u.length-n,0),a=Array(i);++c<i;)a[c]=u[n+c];c=-1;for(var f=Array(n+1);++c<n;)f[c]=u[c];return f[n]=r(a),e(t,this,f)}}},function(t,n){var r=Object.prototype.toString;t.exports=function(t){return r.call(t)}},function(t,n,r){var e=r(4),o=Object.prototype,u=o.hasOwnProperty,c=o.toString,i=e?e.toStringTag:void 0;t.exports=function(t){var n=u.call(t,i),r=t[i];try{t[i]=void 0;var e=!0}catch(t){}var o=c.call(t);return e&&(n?t[i]=r:delete t[i]),o}},function(t,n,r){var e=r(12),o=r(2),u="[object Arguments]";t.exports=function(t){return o(t)&&e(t)==u}},function(t,n,r){var e=r(38),o=r(2),u=Object.prototype,c=u.hasOwnProperty,i=u.propertyIsEnumerable,a=e(function(){return arguments}())?e:function(t){return o(t)&&c.call(t,"callee")&&!i.call(t,"callee")};t.exports=a},function(t,n){var r;r=function(){return this}();try{r=r||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(r=window)}t.exports=r},function(t,n,r){(function(n){var r="object"==typeof n&&n&&n.Object===Object&&n;t.exports=r}).call(this,r(40))},function(t,n,r){var e=r(4),o=r(39),u=r(1),c=e?e.isConcatSpreadable:void 0;t.exports=function(t){return u(t)||o(t)||!!(c&&t&&t[c])}},function(t,n){t.exports=function(t,n){for(var r=-1,e=n.length,o=t.length;++r<e;)t[o+r]=n[r];return t}},function(t,n,r){var e=r(43),o=r(42);t.exports=function t(n,r,u,c,i){var a=-1,f=n.length;for(u||(u=o),i||(i=[]);++a<f;){var p=n[a];r>0&&u(p)?r>1?t(p,r-1,u,c,i):e(i,p):c||(i[i.length]=p)}return i}},function(t,n,r){var e=r(44);t.exports=function(t){return null!=t&&t.length?e(t,1):[]}},function(t,n,r){var e=r(45),o=r(35),u=r(33);t.exports=function(t){return u(o(t,void 0,e),t+"")}},function(t,n,r){var e=r(7),o=r(46),u=r(10),c=r(9),i=r(1),a=r(17),f="Expected a function",p=8,l=32,s=128,v=256;t.exports=function(t){return o(function(n){var r=n.length,o=r,_=e.prototype.thru;for(t&&n.reverse();o--;){var d=n[o];if("function"!=typeof d)throw new TypeError(f);if(_&&!y&&"wrapper"==c(d))var y=new e([],!0)}for(o=y?o:r;++o<r;){d=n[o];var x=c(d),h="wrapper"==x?u(d):void 0;y=h&&a(h[0])&&h[1]==(s|p|l|v)&&!h[4].length&&1==h[9]?y[c(h[0])].apply(y,h[3]):1==d.length&&a(d)?y[x]():y.thru(d)}return function(){var t=arguments,e=t[0];if(y&&1==t.length&&i(e))return y.plant(e).value();for(var o=0,u=r?n[o].apply(this,t):e;++o<r;)u=n[o].call(this,u);return u}})}},function(t,n,r){"use strict";r.r(n);var e=r(8),o=r.n(e);function u(t){if(Array.isArray(t)){for(var n=0,r=Array(t.length);n<t.length;n++)r[n]=t[n];return r}return Array.from(t)}var c=function(t){var n=t.currentTarget;switch(t.target.type){case"checkbox":return[].concat(u(n.querySelectorAll('[name="bundled_products_ids[]"]:checked')));case"number":return[].concat(u(n.querySelectorAll('[name="bundled_products_ids[]"]'))).filter(function(t){return 0<t.nextElementSibling.value})}},i=function(t){return t.map(function(t){return t.value})},a=function(t){return function(n){return n.map(function(n){return t[n]})}},f=function(t){return t.map(function(t){return+t.price})},p=function(t){return t.reduce(function(t,n){return t+n},0)},l=function(t){return function(n){var r=n*(1+taxRate/100),e=[].concat(u(document.querySelectorAll("#quantityDiscount table tbody tr")));productPriceTaxExcluded=t+n,productPriceTaxIncluded=productPriceTaxExcluded*(1+taxRate/100),e.length?e.filter(function(t){return"none"!==t.style.display}).forEach(function(t){return t.setAttribute("real-discount-value",t.getAttribute("real-discount-value")+(1===displayPrice?n:r))}):(document.getElementById("our_price_display").setAttribute("content",productPriceTaxIncluded),document.getElementById("quantity_wanted").dispatchEvent(new Event("change",{bubbles:!0,cancelable:!0})))}};window.bundledProducts=window.bundledProducts||{},0<Object.keys(bundledProducts).length&&document.addEventListener("DOMContentLoaded",function(){var t=o()(c,i,a(bundledProducts),f,p),n=o()(t,l(productPriceTaxExcluded));document.getElementById("bundle").addEventListener("change",n)})}]);
|
/*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2020 Metrological
*
* 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.
*/
#pragma once
#ifndef MODULE_NAME
#define MODULE_NAME Plugin_DIALServer
#endif
#include <plugins/plugins.h>
#include <interfaces/definitions.h>
#undef EXTERNAL
#define EXTERNAL
|
import variables from "../components/variables";
export default function () {
const formSkripsi = $('#form-skripsi');
const selectStudent = formSkripsi.find('#student');
const selectPembimbing = formSkripsi.find('#pembimbing');
const selectPembimbingId = formSkripsi.find('#id_pembimbing');
selectStudent.on('change', function (e) {
e.preventDefault();
selectPembimbing.val('');
selectPembimbingId.val('');
selectPembimbing.attr("placeholder",'Fetching data...');
fetch(variables.baseUrl + 'master/student/ajax-get-pembimbing?id_student=' + formSkripsi.find('#student').val())
.then(result => result.json())
.then(data => {
if(data.nama_pembimbing != null){
selectPembimbing.val(data.nama_pembimbing);
selectPembimbingId.val(data.id_pembimbing);
}else{
selectPembimbing.attr("placeholder",'Pembimbing not set');
}
})
.catch(err => {
console.log(err);
});
});
};
|
#ifndef CONFIG_PARSER_H
#define CONFIG_PARSER_H
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <fstream>
#include "ConfigValue.h"
// a macro to auto generate enum2str and str2enum
// name mapping begins at bias and continuously increase, split by '|'
// an example:
// enum ABC {a = 3, b, c};
// ENUM_MAP(ABC, 3, "a|b|c")
// ABC2str(3) = "a"
// str2ABC("b") = 4
#define ENUM_MAP(type, bias, strings) \
static std::string type ## 2str(int T) \
{ \
return ConfigParser::get_split_part(T - (bias), strings, '|'); \
}; \
static type str2 ## type(const char *str) \
{ \
return static_cast<type>(bias + ConfigParser::get_part_count(str, strings, '|')); \
}
// config parser class
class ConfigParser
{
typedef std::pair<std::string, std::string> string_pair;
public:
struct Format
{
struct StrPair { std::string open, close; };
std::string split; // element splitters (chars)
std::string white; // white spaces (chars)
std::string delim; // line delimiter (string)
std::string glue; // line glue (string)
std::string linecmt; // comment marks (string), until the line breaker '\n'
StrPair blockcmt; // block commenting marks (open string, close string)
StrPair quote; // quote marks (open string, close string)
static Format Basic() { return {" \t,", " \t", "\n", "", "", {"", ""}, {"\"", "\""}}; }
static Format BashLike() { return {" \t,", " \t", "\n", "\\", "#", {"\'", "\'"}, {"\"", "\""}}; }
static Format CLike() { return {" \t,\n", " \t\n", ";", "", "//", {"/*", "*/"}, {"\"", "\""}}; }
};
public:
ConfigParser(Format f = Format::BashLike());
// format related
inline void SetFormat(Format &&f) { fmt = f; }
inline void SetFormat(const Format &f) { fmt = f; }
inline void SetSplitters(std::string s) { fmt.split = s; }
inline void SetWhiteSpaces(std::string w) { fmt.white = w; }
inline void SetCommentMark(std::string c) { fmt.linecmt = c; }
inline void SetCommentPair(std::string o, std::string c) { fmt.blockcmt = {o, c}; }
inline void SetLineGlues(std::string g) { fmt.glue = g; }
inline void SetLineBreaks(std::string b) { fmt.delim = b; }
inline void SetQuotePair(std::string o, std::string c) { fmt.quote = {o, c}; }
const Format &GetFormat() const {return fmt;}
// dealing with file/buffer
bool ReadFile(const std::string &path);
void ReadBuffer(const char*);
void Clear();
// parse line, return false if no more line to parse
bool ParseLine();
// parse the whole file or buffer, return false if no elements found
bool ParseAll();
// parse a string, trim and split it into elements
int ParseString(const std::string &line);
// get current parsing status
bool CheckElements(int num, int optional = 0);
int NbofElements() const { return elements.size(); }
int LineNumber() const { return line_number; }
std::string CurrentLine() const;
// take the elements
ConfigValue TakeFirst();
template<typename T>
T TakeFirst()
{
return TakeFirst().Convert<T>();
}
template<typename T>
ConfigParser &operator >>(T &t)
{
t = (*this).TakeFirst().Convert<T>();
return *this;
}
template<class BidirIt>
int Take(BidirIt first, BidirIt last)
{
int count = 0;
for(auto it = first; it != last; ++it, ++count)
{
if(elements.empty())
break;
*it = elements.front();
elements.pop_front();
}
return count;
}
template<template<class, class> class Container>
Container<ConfigValue, std::allocator<ConfigValue>> TakeAll()
{
Container<ConfigValue, std::allocator<ConfigValue>> res;
while(elements.size())
{
res.emplace_back(std::move(elements.front()));
elements.pop_front();
}
return res;
}
template<template<class, class> class Container, class T>
Container<T, std::allocator<T>> TakeAll()
{
Container<T, std::allocator<T>> res;
while(elements.size())
{
ConfigValue tmp(std::move(elements.front()));
elements.pop_front();
res.emplace_back(tmp.Convert<T>());
}
return res;
}
private:
// private functions
void toLines(std::string buf);
void parseBuffer();
void retrieveLine();
private:
// private members
Format fmt;
int line_number;
std::string curr_line;
std::vector<std::string> quotes;
std::deque<std::string> lines, elements;
public:
// static functions
static void comment_line(std::string &str, const std::string &cmt, const std::string &brk);
static void comment_line(std::string &str, const std::string &cmt, const std::string &brk,
const std::string &qmark);
static void comment_between(std::string &str, const std::string &open, const std::string &close);
static void comment_between(std::string &str, const std::string &open, const std::string &close,
const std::string &qmark);
static void tokenize(std::string &str, std::vector<std::string> &contents, const std::string &token,
const std::string &open, const std::string &close);
static inline void tokenize(std::string &str, std::vector<std::string> &contents, const std::string &token,
const std::string &qmark) { tokenize(str, contents, token, qmark, qmark); }
static void untokenize(std::string &str, const std::vector<std::string> &contents, const std::string &token,
const std::string &open, const std::string &close);
static inline void untokenize(std::string &str, const std::vector<std::string> &contents, const std::string &token,
const std::string &qmark = "") { untokenize(str, contents, token, qmark, qmark); }
static std::string trim(const std::string &str, const std::string &w);
static std::deque<std::string> split(const std::string &str, const std::string &s);
static std::deque<std::string> split(const char* str, const size_t &len, const std::string &s);
static std::string get_split_part(int num, const char *str, const char &s);
static int get_part_count(const char *cmp, const char *str, const char &s);
static std::vector<int> stois(const std::string &str, const std::string &s, const std::string &w);
static std::vector<float> stofs(const std::string &str, const std::string &s, const std::string &w);
static std::vector<double> stods(const std::string &str, const std::string &s, const std::string &w);
static std::string str_remove(const std::string &str, const std::string &ignore);
static std::string str_replace(const std::string &str, const std::string &ignore, const char &rc = ' ');
static std::string str_lower(const std::string &str);
static std::string str_upper(const std::string &str);
static std::pair<size_t, size_t> find_pair(const std::string &str,
const std::string &open,
const std::string &close,
size_t pos = 0);
static bool case_ins_equal(const std::string &str1, const std::string &str2);
static int find_integer(const std::string &str, const size_t &pos = 0);
static std::vector<int> find_integers(const std::string &str);
static void find_integer_helper(const std::string &str, std::vector<int> &result);
struct PathInfo { std::string dir, name, ext; };
static PathInfo decompose_path(const std::string &path);
static std::string compose_path(const PathInfo &path);
static std::string form_path(const std::string &dir, const std::string &file);
static std::string file_to_string(const std::string &path);
// break text file into several blocks in the format
// <label> <open_mark> <content> <close_mark>, this structure can be separated by sep characters
// return extracted <residual> {<label> <content>} with white characters trimmed
struct TextBlock {std::string label, content;};
struct TextBlocks {std::string residual; std::vector<TextBlock> blocks;};
static TextBlocks break_into_blocks(const std::string &buf,
const std::string &open = "{",
const std::string &close = "}",
const std::string &seps = " \t\n");
};
#endif
|
from gundala import EPP, Contact
from config import config, contacts, nameserver
data = {
'name': 'Admin 2 updated',
'org': 'Biznetgio',
'street': 'Jl. Sudirman',
'city': 'Jakarta Pusat',
'sp': '',
'pc': '',
'cc': 'ID',
'voice': '',
'fax': '',
'email': 'admin@biznetgio.com',
}
epp = EPP(**config)
""" Update contact. """
contact = Contact(epp, 7654322, **data)
print(contact.update())
|
# --------------------------------------------------------------------------
# Logic for the 'serve' command.
# --------------------------------------------------------------------------
import sys
import os
import http.server
import webbrowser
import shutil
from .. import site
# Command help text.
helptext = """
Usage: %s serve [FLAGS] [OPTIONS]
Serve the site's output directory using Python's builtin web server. The
default web browser is automatically launched to view the site.
Host IP defaults to localhost (127.0.0.1). Specify an IP address to serve
only on that address or '0.0.0.0' to serve on all available IPs.
Port number defaults to 0 which randomly selects an available port. Note
that port numbers below 1024 require root authorization.
Options:
-b, --browser <str> Specify a browser to open by name.
-d, --directory <path> Specify a custom directory to serve.
-h, --host <str> Host IP address. Defaults to localhost.
-p, --port <int> Port number. Defaults to 0, i.e. random.
Flags:
--help Print this command's help text and exit.
--no-browser Do not launch the default web browser.
""" % os.path.basename(sys.argv[0])
# Command callback.
def callback(parser):
if parser['directory']:
if not os.path.exists(parser['directory']):
sys.exit("Error: '%s' does not exist." % parser['directory'])
os.chdir(parser['directory'])
else:
if not site.home():
sys.exit("Error: cannot locate the site's home directory.")
if not os.path.exists(site.out()):
sys.exit("Error: cannot locate the site's output directory.")
os.chdir(site.out())
try:
server = http.server.HTTPServer(
(parser['host'], parser['port']),
http.server.SimpleHTTPRequestHandler
)
except PermissionError:
sys.exit("Error: use 'sudo' to run on a port below 1024.")
except OSError:
sys.exit("Error: address already in use. Choose a different port.")
address = server.socket.getsockname()
if parser['browser']:
try:
browser = webbrowser.get(parser['browser'])
except webbrowser.Error:
sys.exit("Error: cannot locate browser '%s'." % parser['browser'])
browser.open("http://%s:%s" % (parser['host'], address[1]))
elif not parser['no-browser']:
webbrowser.open("http://%s:%s" % (parser['host'], address[1]))
cols, _ = shutil.get_terminal_size()
print("─" * cols)
print("Root: %s" % site.out())
print("Host: %s" % address[0])
print("Port: %s" % address[1])
print("Stop: Ctrl-C")
print("─" * cols)
try:
server.serve_forever()
except KeyboardInterrupt:
print("\n" + "─" * cols)
print("Stopping server...")
print("─" * cols)
server.server_close()
|
/**
* @fileoverview Implements ol WysiwygCommand
* @author NHN Ent. FE Development Lab <dl_javascript@nhnent.com>
*/
import CommandManager from '../commandManager';
import domUtil from '../domUtils';
/**
* OL
* Add OL to selected wysiwyg editor content
* @extends Command
* @module wysiwygCommands/OL
* @ignore
*/
const OL = CommandManager.command('wysiwyg', /** @lends OL */{
name: 'OL',
keyMap: ['CTRL+O', 'META+O'],
/**
* Command Handler
* @param {WysiwygEditor} wwe WYSIWYGEditor instance
*/
exec(wwe) {
const sq = wwe.getEditor();
let range = sq.getSelection();
const listManager = wwe.componentManager.getManager('list');
const {
startContainer,
startOffset,
endContainer,
endOffset
} = range;
wwe.focus();
sq.saveUndoState(range);
const lines = listManager.getLinesOfSelection(startContainer, endContainer);
const newLIs = [];
for (let i = 0; i < lines.length; i += 1) {
const newLI = this._changeFormatToOrderedListIfNeed(wwe, lines[i]);
newLIs.push(newLI);
}
const newStartContainer = domUtil.containsNode(newLIs[0], startContainer)
? startContainer : newLIs[0];
const newEndContainer = domUtil.containsNode(newLIs[newLIs.length - 1], endContainer)
? endContainer : newLIs[newLIs.length - 1];
range = wwe.setSelectionByContainerAndOffset(newStartContainer, startOffset, newEndContainer, endOffset);
sq.saveUndoState(range);
},
/**
* Change format to unordered list if need
* @param {WysiwygEditor} wwe Wysiwyg editor instance
* @param {HTMLElement} target Element target for change
* @returns {HTMLElement} newly created list item
* @private
*/
_changeFormatToOrderedListIfNeed(wwe, target) {
const sq = wwe.getEditor();
const range = sq.getSelection();
const taskManager = wwe.componentManager.getManager('task');
let newLI = range.startContainer;
if (!sq.hasFormat('TABLE') && !sq.hasFormat('PRE')) {
range.setStart(target, 0);
range.collapse(true);
sq.setSelection(range);
if (sq.hasFormat('LI')) {
wwe.saveSelection(range);
taskManager.unformatTask(range.startContainer);
sq.replaceParent(range.startContainer, 'ul', 'ol');
wwe.restoreSavedSelection();
} else {
wwe.unwrapBlockTag();
sq.makeOrderedList();
}
newLI = sq.getSelection().startContainer;
}
return newLI;
}
});
export default OL;
|
resources = {
u'/user/times': {
u'get': {
'parameters': {}
}
},
u'/repos/{owner}/{repo}/issues/{index}/times': {
u'post': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False,
u'id': True
}
},
u'get': {
'parameters': {
u'owner': True,
u'repo': True
}
}
},
u'/repos/{owner}/{repo}/statuses/{sha}': {
u'post': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False,
u'sha': True
}
},
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'sha': True
}
}
},
u'/orgs/{org}/members': {
u'get': {
'parameters': {
u'org': True
}
}
},
u'/users/search': {
u'get': {
'parameters': {
u'q': False,
u'limit': False
}
}
},
u'/repos/{owner}/{repo}/branches/{branch}': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'branch': True
}
}
},
u'/users/{username}/repos': {
u'get': {
'parameters': {
u'username': True
}
}
},
u'/repos/{owner}/{repo}/issues/comments/{id}': {
u'delete': {
'parameters': {
u'owner': True,
u'repo': True,
u'id': True
}
},
u'patch': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False,
u'id': True
}
}
},
u'/admin/users/{username}/orgs': {
u'post': {
'parameters': {
u'username': True
}
}
},
u'/user/gpg_keys': {
u'post': {
'parameters': {
u'Form': False
}
},
u'get': {
'parameters': {}
}
},
u'/repos/{owner}/{repo}/keys/{id}': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'id': True
}
},
u'delete': {
'parameters': {
u'owner': True,
u'repo': True,
u'id': True
}
}
},
u'/repos/{owner}/{repo}/keys': {
u'post': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False
}
},
u'get': {
'parameters': {
u'owner': True,
u'repo': True
}
}
},
u'/orgs/{org}/public_members': {
u'get': {
'parameters': {
u'org': True
}
}
},
u'/teams/{id}': {
u'get': {
'parameters': {
u'id': True
}
},
u'delete': {
'parameters': {
u'id': True
}
},
u'patch': {
'parameters': {
u'body': False,
u'id': True
}
}
},
u'/user/gpg_keys/{id}': {
u'get': {
'parameters': {
u'id': True
}
},
u'delete': {
'parameters': {
u'id': True
}
}
},
u'/repos/{owner}/{repo}': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True
}
},
u'delete': {
'parameters': {
u'owner': True,
u'repo': True
}
}
},
u'/repos/{owner}/{repo}/times': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True
}
}
},
u'/users/{username}/tokens': {
u'post': {
'parameters': {
u'name': False
}
},
u'get': {
'parameters': {}
}
},
u'/user/following/{username}': {
u'put': {
'parameters': {
u'username': True
}
},
u'delete': {
'parameters': {
u'username': True
}
}
},
u'/teams/{id}/repos': {
u'get': {
'parameters': {
u'id': True
}
}
},
u'/markdown/raw': {
u'post': {
'parameters': {
u'body': False
}
}
},
u'/orgs': {
u'post': {
"parameters": {
u'body': False
}
}
},
u'/orgs/{org}': {
u'get': {
'parameters': {
u'org': True
}
},
u'patch': {
'parameters': {
u'body': False,
u'org': True
}
},
u'delete': {
'parameters': {
u'org': True
}
}
},
u'/users/{username}/followers': {
u'get': {
'parameters': {
u'username': True
}
}
},
u'/repos/{owner}/{repo}/releases': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False
}
}
},
u'/teams/{id}/members/{username}': {
u'put': {
'parameters': {
u'username': True,
u'id': True
}
},
u'delete': {
'parameters': {
u'username': True,
u'id': True
}
}
},
u'/repos/{owner}/{repo}/milestones': {
u'post': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False
}
},
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'id': True
}
}
},
u'/repos/{owner}/{repo}/collaborators': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True
}
}
},
u'/repos/{owner}/{repo}/releases/{id}': {
u'delete': {
'parameters': {
u'owner': True,
u'repo': True,
u'id': True
}
},
u'patch': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False,
u'id': True
}
}
},
u'/repos/{owner}/{repo}/subscription': {
u'put': {
'parameters': {
u'owner': True,
u'repo': True
}
},
u'get': {
'parameters': {
u'owner': True,
u'repo': True
}
},
u'delete': {
'parameters': {
u'owner': True,
u'repo': True
}
}
},
u'/repos/{owner}/{repo}/issues/comments': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'string': False
}
}
},
u'/teams/{id}/members': {
u'get': {
'parameters': {
u'id': True
}
}
},
u'/repos/{owner}/{repo}/raw/{filepath}': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'filepath': True
}
}
},
u'/orgs/{org}/hooks': {
u'get': {
'parameters': {}
}
},
u'/repos/{owner}/{repo}/issue/{index}/labels/{id}': {
u'delete': {
'parameters': {
u'owner': True,
u'repo': True,
u'id': True,
u'index': True
}
}
},
u'/repos/{owner}/{repo}/branches': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True
}
}
},
u'/users/{username}': {
u'get': {
'parameters': {
u'username': True
}
}
},
u'/user/orgs': {
u'get': {
'parameters': {}
}
},
u'/repos/{owner}/{repo}/hooks': {
u'post': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False
}
},
u'get': {
'parameters': {
u'owner': True,
u'repo': True
}
}
},
u'/repos/{owner}/{repo}/subscribers': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True
}
}
},
u'/admin/users': {
u'post': {
'parameters': {
u'body': False
}
}
},
u'/orgs/{org}/repos': {
u'get': {
'parameters': {
u'org': True
}
}
},
u'/users/{username}/following': {
u'get': {
'parameters': {
u'username': True
}
}
},
u'/repos/{owner}/{repo}/mirror-sync': {
u'post': {
'parameters': {
u'owner': True,
u'repo': True
}
}
},
u'/repos/{owner}/{repo}/editorconfig/{filepath}': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'filepath': True
}
}
},
u'/user/following': {
u'get': {
'parameters': {}
}
},
u'/admin/users/{username}/repos': {
u'post': {
'parameters': {
u'username': True
}
}
},
u'/org/{org}/repos': {
u'post': {
'parameters': {
u'body': False,
u'org': True
}
}
},
u'/repos/{owner}/{repo}/issue/{index}/labels': {
u'put': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False,
u'index': True
}
},
u'post': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False,
u'index': True
}
},
u'delete': {
'parameters': {
u'owner': True,
u'repo': True,
u'index': True
}
}
},
u'/repos/{owner}/{repo}/pulls/{index}/merge': {
u'post': {
'parameters': {
u'owner': True,
u'repo': True,
u'index': True
}
},
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'index': True
}
}
},
u'/user/repos': {
u'post': {
'parameters': {
u'body': False
}
},
u'get': {
'parameters': {}
}
},
u'/users/{follower}/following/{followee}': {
u'get': {
'parameters': {
u'follower': True,
u'followee': True
}
}
},
u'/repos/{owner}/{repo}/collaborators/{collaborator}': {
u'put': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False,
u'collaborator': True
}
},
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'collaborator': True
}
},
u'delete': {
'parameters': {
u'owner': True,
u'repo': True,
u'collaborator': True
}
}
},
u'/user/keys': {
u'post': {
'parameters': {
u'body': False
}
},
u'get': {
'parameters': {}
}
},
u'/repos/{owner}/{repo}/times/{tracker}': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'user': True
}
}
},
u'/repos/search': {
u'get': {
'parameters': {
u'exclusive': False,
u'uid': False,
u'q': False,
u'limit': False,
u'mode': False,
u'page': False
}
}
},
u'/users/{username}/gpg_keys': {
u'get': {
'parameters': {
u'username': True
}
}
},
u'/orgs/{org}/hooks/': {
u'post': {
'parameters': {}
}
},
u'/user/subscriptions': {
u'get': {
'parameters': {}
}
},
u'/markdown': {
u'post': {
'parameters': {
u'body': False
}
}
},
u'/repos/{owner}/{repo}/issue/{index}/comments': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'id': True,
u'string': False
}
}
},
u'/orgs/{org}/teams': {
u'post': {
'parameters': {
u'body': False,
u'org': True
}
},
u'get': {
'parameters': {
u'org': True
}
}
},
u'/user/emails': {
u'post': {
'parameters': {
u'body': False
}
},
u'get': {
'parameters': {}
},
u'delete': {
'parameters': {
u'body': False
}
}
},
u'/repos/{owner}/{repo}/issues': {
u'post': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False
}
},
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'state': False,
u'page': False
}
}
},
u'/user/following/{followee}': {
u'get': {
'parameters': {
u'followee': True
}
}
},
u'/user/{username}/orgs': {
u'get': {
'parameters': {
u'username': False
}
}
},
u'/repos/migrate': {
u'post': {
'parameters': {
u'body': False
}
}
},
u'/users/{username}/subscriptions': {
u'get': {
'parameters': {
u'username': False
}
}
},
u'/user/starred/{owner}/{repo}': {
u'put': {
'parameters': {
u'owner': True,
u'repo': True
}
},
u'get': {
'parameters': {
u'owner': True,
u'repo': True
}
},
u'delete': {
'parameters': {
u'owner': True,
u'repo': True
}
}
},
u'/orgs/{org}/hooks/{id}': {
u'get': {
'parameters': {}
},
u'delete': {
'parameters': {}
},
u'patch': {
'parameters': {}
}
},
u'/repos/{owner}/{repo}/hooks/{id}': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'id': True
}
},
u'patch': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False
}
}
},
u'/repos/{owner}/{repo}/archive/{filepath}': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'archive': True
}
}
},
u'/repos/{owner}/{repo}/stargazers': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True
}
}
},
u'/user/keys/{id}': {
u'get': {
'parameters': {
u'id': True
}
},
u'delete': {
'parameters': {
u'id': True
}
}
},
u'/user': {
u'get': {
'parameters': {}
}
},
u'/admin/users/{username}': {
u'delete': {
'parameters': {
u'username': True
}
},
u'patch': {
'parameters': {
u'username': True,
u'body': False
}
}
},
u'/repos/{owner}/{repo}/milestones/{id}': {
u'get': {
'parameters': {}
},
u'delete': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': True
}
},
u'patch': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False
}
}
},
u'/admin/users/{username}/keys': {
u'post': {
'parameters': {
u'username': True
}
}
},
u'/orgs/{org}/members/{username}': {
u'get': {
'parameters': {
u'username': True,
u'org': True
}
},
u'delete': {
'parameters': {
u'username': True,
u'org': True
}
}
},
u'/orgs/{org}/public_members/{username}': {
u'put': {
'parameters': {
u'username': True,
u'org': True
}
},
u'get': {
'parameters': {
u'username': True,
u'org': True
}
},
u'delete': {
'parameters': {
u'username': True,
u'org': True
}
}
},
u'/repos/{owner}/{repo}/commits/{ref}/statuses': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'ref': True
}
}
},
u'/users/{username}/keys': {
u'get': {
'parameters': {
u'username': True
}
}
},
u'/repos/{owner}/{repo}/labels': {
u'post': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False
}
},
u'get': {
'parameters': {
u'owner': True,
u'repo': True
}
}
},
u'/repos/{owner}/{repo}/issues/{index}': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'index': True
}
},
u'patch': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False,
u'index': True
}
}
},
u'/repos/{owner}/{repo}/issues/{index}/labels': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'index': True
}
}
},
u'/repos/{owner}/{repo}/forks': {
u'post': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False
}
},
u'get': {
'parameters': {
u'owner': True,
u'repo': True
}
}
},
u'/repos/{owner}/{repo}/pulls': {
u'post': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False
}
},
u'get': {
'parameters': {
u'owner': True,
u'repo': True
}
}
},
u'/user/starred': {
u'get': {
'parameters': {}
}
},
u'/repos/{owner}/{repo}/pulls/{index}': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'index': True
}
},
u'patch': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False,
u'index': True
}
}
},
u'/repos/{owner}/{repo}/labels/{id}': {
u'get': {
'parameters': {
u'owner': True,
u'repo': True,
u'id': True
}
},
u'delete': {
'parameters': {
u'owner': True,
u'repo': True,
u'id': True
}
},
u'patch': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False,
u'id': True
}
}
},
u'/repositories/{id}': {
u'get': {
'parameters': {
u'id': True
}
}
},
u'/repos/{user}/{repo}/hooks/{id}': {
u'delete': {
'parameters': {
u'owner': True,
u'repo': True,
u'id': True
}
}
},
u'/repos/{owner}/{repo}/issues/{index}/comments': {
u'post': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False,
u'id': True
}
}
},
u'/admin/users/{username}/keys/{id}': {
u'delete': {
'parameters': {
u'username': True,
u'id': True
}
}
},
u'/users/{username}/starred': {
u'get': {
'parameters': {
u'username': True
}
}
},
u'/user/followers': {
u'get': {
'parameters': {}
}
},
u'/repos/{owner}/{repo}/issues/{index}/comments/{id}': {
u'delete': {
'parameters': {
u'owner': True,
u'repo': True,
u'id': True,
u'index': True
}
},
u'patch': {
'parameters': {
u'owner': True,
u'repo': True,
u'body': False,
u'id': True,
u'index': True
}
}
},
u'/teams/{id}/repos/{org}/{repo}': {
u'put': {
'parameters': {
u'repo': True,
u'org': True,
u'id': True
}
},
u'delete': {
'parameters': {
u'repo': True,
u'org': True,
u'id': True
}
}
},
u'/version': {
u'get': {
'parameters': {}
}
}
}
|
// David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2020
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 4.0.2019.08.13
#pragma once
#include <Mathematics/GVector.h>
#include <functional>
// The differential equation is dx/dt = F(t,x). The TVector template
// parameter allows you to create solvers with Vector<N,Real> when the
// dimension N is known at compile time or GVector<Real> when the dimension
// N is known at run time. Both classes have 'int GetSize() const' that
// allow OdeSolver-derived classes to query for the dimension.
namespace gte
{
template <typename Real, typename TVector>
class OdeSolver
{
public:
// Abstract base class.
virtual ~OdeSolver() = default;
protected:
OdeSolver(Real tDelta, std::function<TVector(Real, TVector const&)> const& F)
:
mTDelta(tDelta),
mFunction(F)
{
}
public:
// Member access.
inline void SetTDelta(Real tDelta)
{
mTDelta = tDelta;
}
inline Real GetTDelta() const
{
return mTDelta;
}
// Estimate x(t + tDelta) from x(t) using dx/dt = F(t,x). The
// derived classes implement this so that it is possible for xIn and
// xOut to be the same object.
virtual void Update(Real tIn, TVector const& xIn, Real& tOut, TVector& xOut) = 0;
protected:
Real mTDelta;
std::function<TVector(Real, TVector const&)> mFunction;
};
}
|
// @flow
declare type MapOptions = {
container: string,
style: string,
center?: Array<number>,
zoom?: number,
bearing?: number,
pitch?: number
}
|
{
"targets": [
{
"target_name": "test_general",
"sources": [ "test_general.c" ]
}
]
}
|
const WEBSITE_URL = process.env.WEBSITE_URL || "http://localhost:3000" || "https://staging.opencollective.com";
const fill = (fieldname, value) => {
cy.get(`.inputField.${fieldname} input`).type(value);
}
describe("collective.createOrder page", () => {
it ("loads custom donate page", () => {
cy.visit(`${WEBSITE_URL}/apex/donate/50/month/custom%20description`)
cy.get('.tier .description').contains("custom description");
cy.get('.tier .amount').contains("$50");
cy.get('.tier .amount').contains("per month");
});
it ("makes an order as a new organization", () => {
cy.visit(`${WEBSITE_URL}/apex/donate`);
cy.get('.inputField.email input').type('testuser@opencollective.com');
cy.wait(400)
cy.get('.actions .submit button').click();
cy.get('.result .error').contains("Credit card missing");
cy.get('.fromCollectiveSelector select').select('organization');
cy.wait(400)
cy.get('.actions .submit button').click();
cy.get('.result .error').contains("Please provide a name for the new organization");
cy.get('.organizationDetailsForm .organization_name input').type('new org');
cy.wait(400)
cy.get('.actions .submit button').click();
cy.get('.result .error').contains("Please provide a website for the new organization");
cy.get('.organizationDetailsForm .organization_website input').type('neworg.com');
cy.wait(400)
cy.get('.actions .submit button').click();
cy.get('.result .error').contains("Credit card missing");
});
it ("shows the bitcoin payment method type", () => {
cy.visit(`${WEBSITE_URL}/apex/donate`)
cy.get('.paymentMethodTypeSelector select option').should('have.length', 2);
cy.get('.paymentMethodTypeSelector select').select('bitcoin');
cy.get('.paymentDetails .error').contains("We can't generate a bitcoin address without a valid email address.");
fill('email', 'test@test.com');
cy.get('.btcAddress').contains("to this BTC address");
cy.get('.intervalBtn.month').click();
cy.get('.paymentMethodTypeSelector select option').should('have.length', 1);
});
})
|
module.exports = (options)=>{
let opt = options || {};
let l = [];
let spam = false || opt.spam;
return {
log(msg){
if(msg===undefined) return l;
if(spam) console.log(msg);
l.push(msg);
return this;
}
};
}
|
// Test the bar controller
describe('Bar controller tests', function() {
it('should be constructed', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: []},
{data: []}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.type).toEqual('bar');
expect(meta.data).toEqual([]);
expect(meta.hidden).toBe(null);
expect(meta.controller).not.toBe(undefined);
expect(meta.controller.index).toBe(1);
expect(meta.xAxisID).not.toBe(null);
expect(meta.yAxisID).not.toBe(null);
meta.controller.updateIndex(0);
expect(meta.controller.index).toBe(0);
});
it('should use the first scale IDs if the dataset does not specify them', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
xAxes: [{
id: 'firstXScaleID'
}],
yAxes: [{
id: 'firstYScaleID'
}]
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.xAxisID).toBe('firstXScaleID');
expect(meta.yAxisID).toBe('firstYScaleID');
});
it('should correctly count the number of stacks ignoring datasets of other types and hidden datasets', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: [], type: 'line'},
{data: [], hidden: true},
{data: []},
{data: []}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller.getStackCount()).toBe(2);
});
});
it('should correctly count the number of stacks when a group is not specified', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: []},
{data: []},
{data: []},
{data: []}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller.getStackCount()).toBe(4);
});
});
it('should correctly count the number of stacks when a group is not specified and the scale is stacked', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: []},
{data: []},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller.getStackCount()).toBe(1);
});
});
it('should correctly count the number of stacks when a group is not specified and the scale is not stacked', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: []},
{data: []},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
xAxes: [{
stacked: false
}],
yAxes: [{
stacked: false
}]
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller.getStackCount()).toBe(4);
});
});
it('should correctly count the number of stacks when a group is specified for some', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: []},
{data: []}
],
labels: []
}
});
var meta = chart.getDatasetMeta(3);
expect(meta.controller.getStackCount()).toBe(3);
});
});
it('should correctly count the number of stacks when a group is specified for some and the scale is stacked', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
var meta = chart.getDatasetMeta(3);
expect(meta.controller.getStackCount()).toBe(2);
});
});
it('should correctly count the number of stacks when a group is specified for some and the scale is not stacked', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
xAxes: [{
stacked: false
}],
yAxes: [{
stacked: false
}]
}
}
});
var meta = chart.getDatasetMeta(3);
expect(meta.controller.getStackCount()).toBe(4);
});
});
it('should correctly count the number of stacks when a group is specified for all', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: [], stack: 'stack2'},
{data: [], stack: 'stack2'}
],
labels: []
}
});
var meta = chart.getDatasetMeta(3);
expect(meta.controller.getStackCount()).toBe(2);
});
});
it('should correctly count the number of stacks when a group is specified for all and the scale is stacked', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: [], stack: 'stack2'},
{data: [], stack: 'stack2'}
],
labels: []
},
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
var meta = chart.getDatasetMeta(3);
expect(meta.controller.getStackCount()).toBe(2);
});
});
it('should correctly count the number of stacks when a group is specified for all and the scale is not stacked', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: [], stack: 'stack2'},
{data: [], stack: 'stack2'}
],
labels: []
},
options: {
scales: {
xAxes: [{
stacked: false
}],
yAxes: [{
stacked: false
}]
}
}
});
var meta = chart.getDatasetMeta(3);
expect(meta.controller.getStackCount()).toBe(4);
});
});
it('should correctly get the stack index accounting for datasets of other types and hidden datasets', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: []},
{data: [], hidden: true},
{data: [], type: 'line'},
{data: []}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller.getStackIndex(0)).toBe(0);
expect(meta.controller.getStackIndex(3)).toBe(1);
});
});
it('should correctly get the stack index when a group is not specified', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: []},
{data: []},
{data: []},
{data: []}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller.getStackIndex(0)).toBe(0);
expect(meta.controller.getStackIndex(1)).toBe(1);
expect(meta.controller.getStackIndex(2)).toBe(2);
expect(meta.controller.getStackIndex(3)).toBe(3);
});
});
it('should correctly get the stack index when a group is not specified and the scale is stacked', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: []},
{data: []},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller.getStackIndex(0)).toBe(0);
expect(meta.controller.getStackIndex(1)).toBe(0);
expect(meta.controller.getStackIndex(2)).toBe(0);
expect(meta.controller.getStackIndex(3)).toBe(0);
});
});
it('should correctly get the stack index when a group is not specified and the scale is not stacked', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: []},
{data: []},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
xAxes: [{
stacked: false
}],
yAxes: [{
stacked: false
}]
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller.getStackIndex(0)).toBe(0);
expect(meta.controller.getStackIndex(1)).toBe(1);
expect(meta.controller.getStackIndex(2)).toBe(2);
expect(meta.controller.getStackIndex(3)).toBe(3);
});
});
it('should correctly get the stack index when a group is specified for some', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: []},
{data: []}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller.getStackIndex(0)).toBe(0);
expect(meta.controller.getStackIndex(1)).toBe(0);
expect(meta.controller.getStackIndex(2)).toBe(1);
expect(meta.controller.getStackIndex(3)).toBe(2);
});
});
it('should correctly get the stack index when a group is specified for some and the scale is stacked', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller.getStackIndex(0)).toBe(0);
expect(meta.controller.getStackIndex(1)).toBe(0);
expect(meta.controller.getStackIndex(2)).toBe(1);
expect(meta.controller.getStackIndex(3)).toBe(1);
});
});
it('should correctly get the stack index when a group is specified for some and the scale is not stacked', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
xAxes: [{
stacked: false
}],
yAxes: [{
stacked: false
}]
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller.getStackIndex(0)).toBe(0);
expect(meta.controller.getStackIndex(1)).toBe(1);
expect(meta.controller.getStackIndex(2)).toBe(2);
expect(meta.controller.getStackIndex(3)).toBe(3);
});
});
it('should correctly get the stack index when a group is specified for all', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: [], stack: 'stack2'},
{data: [], stack: 'stack2'}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller.getStackIndex(0)).toBe(0);
expect(meta.controller.getStackIndex(1)).toBe(0);
expect(meta.controller.getStackIndex(2)).toBe(1);
expect(meta.controller.getStackIndex(3)).toBe(1);
});
});
it('should correctly get the stack index when a group is specified for all and the scale is stacked', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: [], stack: 'stack2'},
{data: [], stack: 'stack2'}
],
labels: []
},
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller.getStackIndex(0)).toBe(0);
expect(meta.controller.getStackIndex(1)).toBe(0);
expect(meta.controller.getStackIndex(2)).toBe(1);
expect(meta.controller.getStackIndex(3)).toBe(1);
});
});
it('should correctly get the stack index when a group is specified for all and the scale is not stacked', function() {
[
'bar',
'horizontalBar'
].forEach(function(barType) {
var chart = window.acquireChart({
type: barType,
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: [], stack: 'stack2'},
{data: [], stack: 'stack2'}
],
labels: []
},
options: {
scales: {
xAxes: [{
stacked: false
}],
yAxes: [{
stacked: false
}]
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller.getStackIndex(0)).toBe(0);
expect(meta.controller.getStackIndex(1)).toBe(1);
expect(meta.controller.getStackIndex(2)).toBe(2);
expect(meta.controller.getStackIndex(3)).toBe(3);
});
});
it('should create rectangle elements for each data item during initialization', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: []},
{data: [10, 15, 0, -4]}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.data.length).toBe(4); // 4 rectangles created
expect(meta.data[0] instanceof Chart.elements.Rectangle).toBe(true);
expect(meta.data[1] instanceof Chart.elements.Rectangle).toBe(true);
expect(meta.data[2] instanceof Chart.elements.Rectangle).toBe(true);
expect(meta.data[3] instanceof Chart.elements.Rectangle).toBe(true);
});
it('should update elements when modifying data', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [1, 2],
label: 'dataset1'
}, {
data: [10, 15, 0, -4],
label: 'dataset2',
borderColor: 'blue'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
elements: {
rectangle: {
backgroundColor: 'red',
borderSkipped: 'top',
borderColor: 'green',
borderWidth: 2,
}
},
scales: {
xAxes: [{
id: 'firstXScaleID',
type: 'category'
}],
yAxes: [{
id: 'firstYScaleID',
type: 'linear'
}]
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.data.length).toBe(4);
chart.data.datasets[1].data = [1, 2]; // remove 2 items
chart.data.datasets[1].borderWidth = 1;
chart.update();
expect(meta.data.length).toBe(2);
[
{x: 113, y: 484},
{x: 229, y: 32}
].forEach(function(expected, i) {
expect(meta.data[i]._datasetIndex).toBe(1);
expect(meta.data[i]._index).toBe(i);
expect(meta.data[i]._xScale).toBe(chart.scales.firstXScaleID);
expect(meta.data[i]._yScale).toBe(chart.scales.firstYScaleID);
expect(meta.data[i]._model.x).toBeCloseToPixel(expected.x);
expect(meta.data[i]._model.y).toBeCloseToPixel(expected.y);
expect(meta.data[i]._model.base).toBeCloseToPixel(936);
expect(meta.data[i]._model.width).toBeCloseToPixel(40);
expect(meta.data[i]._model).toEqual(jasmine.objectContaining({
datasetLabel: chart.data.datasets[1].label,
label: chart.data.labels[i],
backgroundColor: 'red',
borderSkipped: 'top',
borderColor: 'blue',
borderWidth: 1
}));
});
chart.data.datasets[1].data = [1, 2, 3]; // add 1 items
chart.update();
expect(meta.data.length).toBe(3); // should add a new meta data item
});
it('should get the correct bar points when datasets of different types exist', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [1, 2],
label: 'dataset1'
}, {
type: 'line',
data: [4, 6],
label: 'dataset2'
}, {
data: [8, 10],
label: 'dataset3'
}],
labels: ['label1', 'label2']
},
options: {
scales: {
xAxes: [{
type: 'category'
}],
yAxes: [{
type: 'linear'
}]
}
}
});
var meta = chart.getDatasetMeta(2);
expect(meta.data.length).toBe(2);
var bar1 = meta.data[0];
var bar2 = meta.data[1];
expect(bar1._model.x).toBeCloseToPixel(187);
expect(bar1._model.y).toBeCloseToPixel(132);
expect(bar2._model.x).toBeCloseToPixel(422);
expect(bar2._model.y).toBeCloseToPixel(32);
});
it('should update elements when the scales are stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [10, -10, 10, -10],
label: 'dataset1'
}, {
data: [10, 15, 0, -4],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
scales: {
xAxes: [{
type: 'category'
}],
yAxes: [{
type: 'linear',
stacked: true
}]
}
}
});
var meta0 = chart.getDatasetMeta(0);
[
{b: 290, w: 83 / 2, x: 63, y: 161},
{b: 290, w: 83 / 2, x: 179, y: 419},
{b: 290, w: 83 / 2, x: 295, y: 161},
{b: 290, w: 83 / 2, x: 411, y: 419}
].forEach(function(values, i) {
expect(meta0.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta0.data[i]._model.width).toBeCloseToPixel(values.w);
expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x);
expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
[
{b: 161, w: 83 / 2, x: 109, y: 32},
{b: 290, w: 83 / 2, x: 225, y: 97},
{b: 161, w: 83 / 2, x: 341, y: 161},
{b: 419, w: 83 / 2, x: 457, y: 471}
].forEach(function(values, i) {
expect(meta1.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta1.data[i]._model.width).toBeCloseToPixel(values.w);
expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x);
expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y);
});
});
it('should update elements when the scales are stacked and the y axis has a user defined minimum', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [50, 20, 10, 100],
label: 'dataset1'
}, {
data: [50, 80, 90, 0],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
scales: {
xAxes: [{
type: 'category'
}],
yAxes: [{
type: 'linear',
stacked: true,
ticks: {
min: 50,
max: 100
}
}]
}
}
});
var meta0 = chart.getDatasetMeta(0);
[
{b: 936, w: 83 / 2, x: 65.5, y: 484},
{b: 936, w: 83 / 2, x: 180.5, y: 755},
{b: 936, w: 83 / 2, x: 296.5, y: 846},
{b: 936, w: 83 / 2, x: 411.5, y: 32}
].forEach(function(values, i) {
expect(meta0.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta0.data[i]._model.width).toBeCloseToPixel(values.w);
expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x);
expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
[
{b: 484, w: 83 / 2, x: 111.5, y: 32},
{b: 755, w: 83 / 2, x: 226.5, y: 32},
{b: 846, w: 83 / 2, x: 342.5, y: 32},
{b: 32, w: 83 / 2, x: 457.5, y: 32}
].forEach(function(values, i) {
expect(meta1.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta1.data[i]._model.width).toBeCloseToPixel(values.w);
expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x);
expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y);
});
});
it('should update elements when only the category scale is stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [20, -10, 10, -10],
label: 'dataset1'
}, {
data: [10, 15, 0, -14],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
scales: {
xAxes: [{
type: 'category',
stacked: true
}],
yAxes: [{
type: 'linear'
}]
}
}
});
var meta0 = chart.getDatasetMeta(0);
[
{b: 290, w: 83, x: 86, y: 32},
{b: 290, w: 83, x: 202, y: 419},
{b: 290, w: 83, x: 318, y: 161},
{b: 290, w: 83, x: 434, y: 419}
].forEach(function(values, i) {
expect(meta0.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta0.data[i]._model.width).toBeCloseToPixel(values.w);
expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x);
expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
[
{b: 290, w: 83, x: 86, y: 161},
{b: 290, w: 83, x: 202, y: 97},
{b: 290, w: 83, x: 318, y: 290},
{b: 290, w: 83, x: 434, y: 471}
].forEach(function(values, i) {
expect(meta1.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta1.data[i]._model.width).toBeCloseToPixel(values.w);
expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x);
expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y);
});
});
it('should update elements when the scales are stacked and data is strings', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: ['10', '-10', '10', '-10'],
label: 'dataset1'
}, {
data: ['10', '15', '0', '-4'],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
scales: {
xAxes: [{
type: 'category'
}],
yAxes: [{
type: 'linear',
stacked: true
}]
}
}
});
var meta0 = chart.getDatasetMeta(0);
[
{b: 290, w: 83 / 2, x: 63, y: 161},
{b: 290, w: 83 / 2, x: 179, y: 419},
{b: 290, w: 83 / 2, x: 295, y: 161},
{b: 290, w: 83 / 2, x: 411, y: 419}
].forEach(function(values, i) {
expect(meta0.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta0.data[i]._model.width).toBeCloseToPixel(values.w);
expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x);
expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
[
{b: 161, w: 83 / 2, x: 109, y: 32},
{b: 290, w: 83 / 2, x: 225, y: 97},
{b: 161, w: 83 / 2, x: 341, y: 161},
{b: 419, w: 83 / 2, x: 457, y: 471}
].forEach(function(values, i) {
expect(meta1.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta1.data[i]._model.width).toBeCloseToPixel(values.w);
expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x);
expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y);
});
});
it('should get the correct bar points for grouped stacked chart if the group name is same', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [10, -10, 10, -10],
label: 'dataset1',
stack: 'stack1'
}, {
data: [10, 15, 0, -4],
label: 'dataset2',
stack: 'stack1'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
scales: {
xAxes: [{
type: 'category'
}],
yAxes: [{
type: 'linear',
stacked: true
}]
}
}
});
var meta0 = chart.getDatasetMeta(0);
[
{b: 290, w: 83, x: 86, y: 161},
{b: 290, w: 83, x: 202, y: 419},
{b: 290, w: 83, x: 318, y: 161},
{b: 290, w: 83, x: 434, y: 419}
].forEach(function(values, i) {
expect(meta0.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta0.data[i]._model.width).toBeCloseToPixel(values.w);
expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x);
expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y);
});
var meta = chart.getDatasetMeta(1);
[
{b: 161, w: 83, x: 86, y: 32},
{b: 290, w: 83, x: 202, y: 97},
{b: 161, w: 83, x: 318, y: 161},
{b: 419, w: 83, x: 434, y: 471}
].forEach(function(values, i) {
expect(meta.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta.data[i]._model.width).toBeCloseToPixel(values.w);
expect(meta.data[i]._model.x).toBeCloseToPixel(values.x);
expect(meta.data[i]._model.y).toBeCloseToPixel(values.y);
});
});
it('should get the correct bar points for grouped stacked chart if the group name is different', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [1, 2],
stack: 'stack1'
}, {
data: [1, 2],
stack: 'stack2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
scales: {
xAxes: [{
type: 'category'
}],
yAxes: [{
stacked: true,
type: 'linear'
}]
}
}
});
var meta = chart.getDatasetMeta(1);
[
{x: 108, y: 258},
{x: 224, y: 32}
].forEach(function(values, i) {
expect(meta.data[i]._model.base).toBeCloseToPixel(484);
expect(meta.data[i]._model.width).toBeCloseToPixel(42);
expect(meta.data[i]._model.x).toBeCloseToPixel(values.x);
expect(meta.data[i]._model.y).toBeCloseToPixel(values.y);
});
});
it('should get the correct bar points for grouped stacked chart', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [1, 2],
stack: 'stack1'
}, {
data: [0.5, 1],
stack: 'stack2'
}, {
data: [0.5, 1],
stack: 'stack2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
scales: {
xAxes: [{
type: 'category'
}],
yAxes: [{
stacked: true,
type: 'linear'
}]
}
}
});
var meta = chart.getDatasetMeta(2);
[
{b: 371, x: 108, y: 258},
{b: 258, x: 224, y: 32}
].forEach(function(values, i) {
expect(meta.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta.data[i]._model.width).toBeCloseToPixel(42);
expect(meta.data[i]._model.x).toBeCloseToPixel(values.x);
expect(meta.data[i]._model.y).toBeCloseToPixel(values.y);
});
});
it('should update elements when the scales are stacked and the y axis is logarithmic', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [10, 100, 10, 100],
label: 'dataset1'
}, {
data: [100, 10, 0, 100],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
scales: {
xAxes: [{
type: 'category',
stacked: true,
barPercentage: 1
}],
yAxes: [{
type: 'logarithmic',
stacked: true,
}]
}
}
});
var meta0 = chart.getDatasetMeta(0);
[
{b: 484, w: 92, x: 94, y: 484},
{b: 484, w: 92, x: 208, y: 136},
{b: 484, w: 92, x: 322, y: 484},
{b: 484, w: 92, x: 436, y: 136}
].forEach(function(values, i) {
expect(meta0.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta0.data[i]._model.width).toBeCloseToPixel(values.w);
expect(meta0.data[i]._model.x).toBeCloseToPixel(values.x);
expect(meta0.data[i]._model.y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
[
{b: 484, w: 92, x: 94, y: 122},
{b: 136, w: 92, x: 208, y: 122},
{b: 484, w: 92, x: 322, y: 484},
{b: 136, w: 92, x: 436, y: 32}
].forEach(function(values, i) {
expect(meta1.data[i]._model.base).toBeCloseToPixel(values.b);
expect(meta1.data[i]._model.width).toBeCloseToPixel(values.w);
expect(meta1.data[i]._model.x).toBeCloseToPixel(values.x);
expect(meta1.data[i]._model.y).toBeCloseToPixel(values.y);
});
});
it('should draw all bars', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [],
}, {
data: [10, 15, 0, -4],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
}
});
var meta = chart.getDatasetMeta(1);
spyOn(meta.data[0], 'draw');
spyOn(meta.data[1], 'draw');
spyOn(meta.data[2], 'draw');
spyOn(meta.data[3], 'draw');
chart.update();
expect(meta.data[0].draw.calls.count()).toBe(1);
expect(meta.data[1].draw.calls.count()).toBe(1);
expect(meta.data[2].draw.calls.count()).toBe(1);
expect(meta.data[3].draw.calls.count()).toBe(1);
});
it('should set hover styles on rectangles', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [],
}, {
data: [10, 15, 0, -4],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
elements: {
rectangle: {
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgb(0, 0, 255)',
borderWidth: 2,
}
}
}
});
var meta = chart.getDatasetMeta(1);
var bar = meta.data[0];
meta.controller.setHoverStyle(bar);
expect(bar._model.backgroundColor).toBe('rgb(230, 0, 0)');
expect(bar._model.borderColor).toBe('rgb(0, 0, 230)');
expect(bar._model.borderWidth).toBe(2);
// Set a dataset style
chart.data.datasets[1].hoverBackgroundColor = 'rgb(128, 128, 128)';
chart.data.datasets[1].hoverBorderColor = 'rgb(0, 0, 0)';
chart.data.datasets[1].hoverBorderWidth = 5;
meta.controller.setHoverStyle(bar);
expect(bar._model.backgroundColor).toBe('rgb(128, 128, 128)');
expect(bar._model.borderColor).toBe('rgb(0, 0, 0)');
expect(bar._model.borderWidth).toBe(5);
// Should work with array styles so that we can set per bar
chart.data.datasets[1].hoverBackgroundColor = ['rgb(255, 255, 255)', 'rgb(128, 128, 128)'];
chart.data.datasets[1].hoverBorderColor = ['rgb(9, 9, 9)', 'rgb(0, 0, 0)'];
chart.data.datasets[1].hoverBorderWidth = [2.5, 5];
meta.controller.setHoverStyle(bar);
expect(bar._model.backgroundColor).toBe('rgb(255, 255, 255)');
expect(bar._model.borderColor).toBe('rgb(9, 9, 9)');
expect(bar._model.borderWidth).toBe(2.5);
// Should allow a custom style
bar.custom = {
hoverBackgroundColor: 'rgb(255, 0, 0)',
hoverBorderColor: 'rgb(0, 255, 0)',
hoverBorderWidth: 1.5
};
meta.controller.setHoverStyle(bar);
expect(bar._model.backgroundColor).toBe('rgb(255, 0, 0)');
expect(bar._model.borderColor).toBe('rgb(0, 255, 0)');
expect(bar._model.borderWidth).toBe(1.5);
});
it('should remove a hover style from a bar', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [],
}, {
data: [10, 15, 0, -4],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
elements: {
rectangle: {
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgb(0, 0, 255)',
borderWidth: 2,
}
}
}
});
var meta = chart.getDatasetMeta(1);
var bar = meta.data[0];
// Change default
chart.options.elements.rectangle.backgroundColor = 'rgb(128, 128, 128)';
chart.options.elements.rectangle.borderColor = 'rgb(15, 15, 15)';
chart.options.elements.rectangle.borderWidth = 3.14;
// Remove to defaults
meta.controller.removeHoverStyle(bar);
expect(bar._model.backgroundColor).toBe('rgb(128, 128, 128)');
expect(bar._model.borderColor).toBe('rgb(15, 15, 15)');
expect(bar._model.borderWidth).toBe(3.14);
// Should work with array styles so that we can set per bar
chart.data.datasets[1].backgroundColor = ['rgb(255, 255, 255)', 'rgb(128, 128, 128)'];
chart.data.datasets[1].borderColor = ['rgb(9, 9, 9)', 'rgb(0, 0, 0)'];
chart.data.datasets[1].borderWidth = [2.5, 5];
meta.controller.removeHoverStyle(bar);
expect(bar._model.backgroundColor).toBe('rgb(255, 255, 255)');
expect(bar._model.borderColor).toBe('rgb(9, 9, 9)');
expect(bar._model.borderWidth).toBe(2.5);
// Should allow a custom style
bar.custom = {
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgb(0, 255, 0)',
borderWidth: 1.5
};
meta.controller.removeHoverStyle(bar);
expect(bar._model.backgroundColor).toBe('rgb(255, 0, 0)');
expect(bar._model.borderColor).toBe('rgb(0, 255, 0)');
expect(bar._model.borderWidth).toBe(1.5);
});
describe('Bar width', function() {
beforeEach(function() {
// 2 datasets
this.data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
data: [10, 20, 30, 40, 50, 60, 70],
}, {
data: [10, 20, 30, 40, 50, 60, 70],
}]
};
});
afterEach(function() {
var chart = window.acquireChart(this.config);
var meta = chart.getDatasetMeta(0);
var xScale = chart.scales[meta.xAxisID];
var categoryPercentage = xScale.options.categoryPercentage;
var barPercentage = xScale.options.barPercentage;
var stacked = xScale.options.stacked;
var totalBarWidth = 0;
for (var i = 0; i < chart.data.datasets.length; i++) {
var bars = chart.getDatasetMeta(i).data;
for (var j = xScale.minIndex; j <= xScale.maxIndex; j++) {
totalBarWidth += bars[j]._model.width;
}
if (stacked) {
break;
}
}
var actualValue = totalBarWidth;
var expectedValue = xScale.width * categoryPercentage * barPercentage;
expect(actualValue).toBeCloseToPixel(expectedValue);
});
it('should correctly set bar width when min and max option is set.', function() {
this.config = {
type: 'bar',
data: this.data,
options: {
scales: {
xAxes: [{
ticks: {
min: 'March',
max: 'May',
},
}]
}
}
};
});
it('should correctly set bar width when scale are stacked with min and max options.', function() {
this.config = {
type: 'bar',
data: this.data,
options: {
scales: {
xAxes: [{
ticks: {
min: 'March',
max: 'May',
}
}],
yAxes: [{
stacked: true
}]
}
}
};
});
});
describe('Bar height (horizontalBar type)', function() {
beforeEach(function() {
// 2 datasets
this.data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
data: [10, 20, 30, 40, 50, 60, 70],
}, {
data: [10, 20, 30, 40, 50, 60, 70],
}]
};
});
afterEach(function() {
var chart = window.acquireChart(this.config);
var meta = chart.getDatasetMeta(0);
var yScale = chart.scales[meta.yAxisID];
var categoryPercentage = yScale.options.categoryPercentage;
var barPercentage = yScale.options.barPercentage;
var stacked = yScale.options.stacked;
var totalBarHeight = 0;
for (var i = 0; i < chart.data.datasets.length; i++) {
var bars = chart.getDatasetMeta(i).data;
for (var j = yScale.minIndex; j <= yScale.maxIndex; j++) {
totalBarHeight += bars[j]._model.height;
}
if (stacked) {
break;
}
}
var actualValue = totalBarHeight;
var expectedValue = yScale.height * categoryPercentage * barPercentage;
expect(actualValue).toBeCloseToPixel(expectedValue);
});
it('should correctly set bar height when min and max option is set.', function() {
this.config = {
type: 'horizontalBar',
data: this.data,
options: {
scales: {
yAxes: [{
ticks: {
min: 'March',
max: 'May',
},
}]
}
}
};
});
it('should correctly set bar height when scale are stacked with min and max options.', function() {
this.config = {
type: 'horizontalBar',
data: this.data,
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
ticks: {
min: 'March',
max: 'May',
}
}]
}
}
};
});
});
describe('Bar thickness with a category scale', function() {
[undefined, 20].forEach(function(barThickness) {
describe('When barThickness is ' + barThickness, function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [1, 2]
}, {
data: [1, 2]
}],
labels: ['label1', 'label2', 'label3']
},
options: {
scales: {
xAxes: [{
id: 'x',
type: 'category',
barThickness: barThickness
}],
yAxes: [{
type: 'linear'
}]
}
}
});
});
it('should correctly set bar width', function() {
var chart = this.chart;
var expected, i, ilen, meta;
if (barThickness) {
expected = barThickness;
} else {
var scale = chart.scales.x;
var options = chart.options.scales.xAxes[0];
var categoryPercentage = options.categoryPercentage;
var barPercentage = options.barPercentage;
var tickInterval = scale.getPixelForTick(1) - scale.getPixelForTick(0);
expected = tickInterval * categoryPercentage / 2 * barPercentage;
}
for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
meta = chart.getDatasetMeta(i);
expect(meta.data[0]._model.width).toBeCloseToPixel(expected);
expect(meta.data[1]._model.width).toBeCloseToPixel(expected);
}
});
it('should correctly set bar width if maxBarThickness is specified', function() {
var chart = this.chart;
var options = chart.options.scales.xAxes[0];
var i, ilen, meta;
options.maxBarThickness = 10;
chart.update();
for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
meta = chart.getDatasetMeta(i);
expect(meta.data[0]._model.width).toBeCloseToPixel(10);
expect(meta.data[1]._model.width).toBeCloseToPixel(10);
}
});
});
});
});
describe('Bar thickness with a time scale', function() {
['auto', 'data', 'labels'].forEach(function(source) {
['series', 'linear'].forEach(function(distribution) {
describe('When ticks.source is "' + source + '", distribution is "' + distribution + '"', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [1, 2, 3]
}, {
data: [1, 2, 3]
}],
labels: ['2017', '2018', '2020']
},
options: {
scales: {
xAxes: [{
id: 'x',
type: 'time',
time: {
unit: 'year',
parser: 'YYYY'
},
ticks: {
source: source
},
offset: true,
distribution: distribution
}],
yAxes: [{
type: 'linear'
}]
}
}
});
});
it('should correctly set bar width', function() {
var chart = this.chart;
var scale = chart.scales.x;
var options = chart.options.scales.xAxes[0];
var categoryPercentage = options.categoryPercentage;
var barPercentage = options.barPercentage;
var firstInterval = scale.getPixelForValue('2018') - scale.getPixelForValue('2017');
var firstExpected = firstInterval * categoryPercentage / 2 * barPercentage;
var lastInterval = scale.getPixelForValue('2020') - scale.getPixelForValue('2018');
var lastExpected = lastInterval * categoryPercentage / 2 * barPercentage;
var i, ilen, meta;
for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
meta = chart.getDatasetMeta(i);
expect(meta.data[0]._model.width).toBeCloseToPixel(firstExpected);
expect(meta.data[1]._model.width).toBeCloseToPixel((firstExpected + lastExpected) / 2);
expect(meta.data[2]._model.width).toBeCloseToPixel(lastExpected);
}
});
it('should correctly set bar width if maxBarThickness is specified', function() {
var chart = this.chart;
var options = chart.options.scales.xAxes[0];
var i, ilen, meta;
options.maxBarThickness = 10;
chart.update();
for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
meta = chart.getDatasetMeta(i);
expect(meta.data[0]._model.width).toBeCloseToPixel(10);
expect(meta.data[1]._model.width).toBeCloseToPixel(10);
expect(meta.data[2]._model.width).toBeCloseToPixel(10);
}
});
});
});
});
});
});
|
import json
import os
import shutil
import ssl
import subprocess
import traceback
import uuid
import zipfile
from pathlib import Path
from flask import Flask, request, jsonify, send_file, after_this_request, make_response
from werkzeug.utils import secure_filename
import yaml
import hashlib
import boto3
import botocore
app = Flask(__name__, static_url_path='', static_folder='websrc/build/')
UPLOAD_FOLDER = Path('/tmp/blobconverter')
UPLOAD_FOLDER.mkdir(parents=True, exist_ok=True)
bucket = boto3.resource('s3', aws_access_key_id=os.getenv("AWS_ACCESS"), aws_secret_access_key=os.getenv("AWS_SECRET"))\
.Bucket('blobconverter')
class EnvResolver:
def __init__(self):
self.version = request.args.get('version')
if self.version == "2021.4" or self.version is None or self.version == "":
self.base_path = Path("/opt/intel/openvino")
self.cache_path = Path("/tmp/modeldownloader/2021_4")
self.version = "2021.4"
self.converter_path = Path(__file__).parent / Path("model_compiler/openvino_2021.4/converter.py")
self.downloader_path = Path(__file__).parent / Path("model_compiler/openvino_2021.4/downloader.py")
self.venv_path = Path(__file__).parent / Path("venvs/venv2021_4")
elif self.version == "2021.3":
self.base_path = Path("/opt/intel/openvino2021_3")
self.cache_path = Path("/tmp/modeldownloader/2021_3")
self.converter_path = Path(__file__).parent / Path("model_compiler/openvino_2021.3/converter.py")
self.downloader_path = Path(__file__).parent / Path("model_compiler/openvino_2021.3/downloader.py")
self.venv_path = Path(__file__).parent / Path("venvs/venv2021_3")
elif self.version == "2021.2":
self.base_path = Path("/opt/intel/openvino2021_2")
self.cache_path = Path("/tmp/modeldownloader/2021_2")
self.converter_path = Path(__file__).parent / Path("model_compiler/openvino_2021.2/converter.py")
self.downloader_path = Path(__file__).parent / Path("model_compiler/openvino_2021.2/downloader.py")
self.venv_path = Path(__file__).parent / Path("venvs/venv2021_2")
elif self.version == "2021.1":
self.base_path = Path("/opt/intel/openvino2021_1")
self.cache_path = Path("/tmp/modeldownloader/2021_1")
self.converter_path = Path(__file__).parent / Path("model_compiler/openvino_2021.1/converter.py")
self.downloader_path = Path(__file__).parent / Path("model_compiler/openvino_2021.1/downloader.py")
self.venv_path = Path(__file__).parent / Path("venvs/venv2021_1")
elif self.version == "2020.4":
self.base_path = Path("/opt/intel/openvino2020_4")
self.cache_path = Path("/tmp/modeldownloader/2020_4")
self.converter_path = Path(__file__).parent / Path("model_compiler/openvino_2020.4/converter.py")
self.downloader_path = Path(__file__).parent / Path("model_compiler/openvino_2020.4/downloader.py")
self.venv_path = Path(__file__).parent / Path("venvs/venv2020_4")
elif self.version == "2020.3":
self.base_path = Path("/opt/intel/openvino2020_3")
self.cache_path = Path("/tmp/modeldownloader/2020_3")
self.converter_path = Path(__file__).parent / Path("model_compiler/openvino_2020.3/converter.py")
self.downloader_path = Path(__file__).parent / Path("model_compiler/openvino_2020.3/downloader.py")
self.venv_path = Path(__file__).parent / Path("venvs/venv2020_3")
elif self.version == "2020.2":
self.base_path = Path("/opt/intel/openvino2020_2")
self.cache_path = Path("/tmp/modeldownloader/2020_2")
self.converter_path = Path(__file__).parent / Path("model_compiler/openvino_2020.2/converter.py")
self.downloader_path = Path(__file__).parent / Path("model_compiler/openvino_2020.2/downloader.py")
self.venv_path = Path(__file__).parent / Path("venvs/venv2020_2")
elif self.version == "2020.1":
self.base_path = Path("/opt/intel/openvino2020_1")
self.cache_path = Path("/tmp/modeldownloader/2020_1")
self.converter_path = Path(__file__).parent / Path("model_compiler/openvino_2020.1/converter.py")
self.downloader_path = Path(__file__).parent / Path("model_compiler/openvino_2020.1/downloader.py")
self.venv_path = Path(__file__).parent / Path("venvs/venv2020_1")
elif self.version == "2019_R3.1":
self.base_path = Path("/opt/intel/openvino2019_3")
self.cache_path = Path("/tmp/modeldownloader/2019_3")
self.converter_path = Path(__file__).parent / Path("model_compiler/openvino_2019.3/converter.py")
self.downloader_path = Path(__file__).parent / Path("model_compiler/openvino_2019.3/downloader.py")
self.venv_path = Path(__file__).parent / Path("venvs/venv2019_3")
else:
raise ValueError(f'Unknown version: "{self.version}", available: "2021.4", "2021.3", "2021.2", "2021.1", "2020.4", "2020.3", "2020.2", "2020.1", "2019.R3"')
self.workdir = UPLOAD_FOLDER / Path(uuid.uuid4().hex)
self.workdir.mkdir(parents=True, exist_ok=True)
self.cache_path.mkdir(parents=True, exist_ok=True)
self.compiler_path = self.base_path / Path("deployment_tools/inference_engine/lib/intel64/myriad_compile")
self.model_zoo_type = request.values.get('zoo_type', "intel")
if self.model_zoo_type == "intel":
self.model_zoo_path = self.base_path / Path("deployment_tools/open_model_zoo/models")
elif self.model_zoo_type == "depthai":
self.model_zoo_path = Path(__file__).parent / Path("depthai-model-zoo/models")
else:
raise ValueError(f'Unknown zoo name: "{self.model_zoo_type}", available: "intel", "depthai"')
self.env = os.environ.copy()
self.env['InferenceEngine_DIR'] = str(self.base_path / Path("deployment_tools/inference_engine/share"))
self.env['INTEL_OPENVINO_DIR'] = str(self.base_path)
self.env['OpenCV_DIR'] = str(self.base_path / Path("opencv/cmake"))
self.env['LD_LIBRARY_PATH'] = f"{self.base_path}/opencv/lib:{self.base_path}/deployment_tools/ngraph/lib:/opt/intel/opencl:{self.base_path}/deployment_tools/inference_engine/external/hddl/lib:{self.base_path}/deployment_tools/inference_engine/external/gna/lib:{self.base_path}/deployment_tools/inference_engine/external/mkltiny_lnx/lib:{self.base_path}/deployment_tools/inference_engine/external/tbb/lib:{self.base_path}/deployment_tools/inference_engine/lib/intel64:"
self.env['HDDL_INSTALL_DIR'] = str(self.base_path / Path("deployment_tools/inference_engine/external/hddl"))
self.env['INTEL_CVSDK_DIR'] = str(self.base_path)
self.env['INSTALLDIR'] = str(self.base_path)
self.env['PYTHONPATH'] = f"{self.base_path}/python/python3.6:{self.base_path}/python/python3:{self.base_path}/deployment_tools/open_model_zoo/tools/accuracy_checker:{self.base_path}/deployment_tools/model_optimizer"
self.env['PATH'] = f"{self.venv_path.absolute()}/bin:{self.base_path}/deployment_tools/model_optimizer:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
self.env['VIRTUAL_ENV'] = str(self.venv_path.absolute())
@property
def executable(self):
return str((self.venv_path / "bin" / "python").absolute())
def run_command(self, command):
print("Running command: {}".format(command))
split_cmd = command.rstrip(' ').split(' ')
try:
proc = subprocess.Popen(split_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=self.env)
stdout, stderr = proc.communicate()
print("Command returned exit code: {}".format(proc.returncode))
if proc.returncode != 0:
filtered_stdout = "\n".join(filter(
lambda line: "[myriad_compile] usb_find_device_with_bcd:266\tLibrary has not been initialized when loaded" not in line,
stdout.decode().split("\n")
))
print(filtered_stdout.split("\n"))
raise CommandFailed(
message=f"Command failed with exit code {proc.returncode}, command: {command}",
payload=dict(
stderr=stderr.decode(),
stdout=filtered_stdout,
exit_code=proc.returncode
)
)
return proc, stdout, stderr
except CommandFailed:
raise
except Exception:
raise CommandFailed(
message=f"Command was unable to execute, command: {command}",
payload=dict(
stderr=traceback.format_exc(),
stdout="",
exit_code=-1
)
)
def sha256sum(filename):
h = hashlib.sha256()
b = bytearray(128*1024)
mv = memoryview(b)
with open(filename, 'rb', buffering=0) as f:
for n in iter(lambda : f.readinto(mv), 0):
h.update(mv[:n])
return h.hexdigest()
class CommandFailed(Exception):
status_code = 400
def __init__(self, message, payload=None):
Exception.__init__(self)
self.message = message
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
class BadRequest(CommandFailed):
status_code = 400
def parse_config(config_path, name, data_type, env):
with open(config_path, "r") as f:
config = yaml.safe_load(f)
if "description" not in config:
config["description"] = f"Configuration file generated for {name} model"
if "license" not in config:
config["license"] = f"Unknown"
if "files" not in config:
raise BadRequest("\"files\" property is missing in model config file")
for file in config["files"]:
if "source" not in file:
raise BadRequest("Each file needs to have \"source\" param")
if "$type" in file["source"]:
if file["source"]["$type"] == "http" and "$REQUEST" in file["source"]["url"]:
local_path = file["source"]["url"].replace("$REQUEST", str((env.workdir / name / data_type).absolute()))
file["source"]["url"] = "file://" + local_path
if "size" not in file:
if not file["source"]["url"].startswith("file://"):
raise BadRequest("You need to supply \"size\" parameter for file when using a remote source")
file["size"] = Path(local_path).stat().st_size
if "sha256" not in file:
if not file["source"]["url"].startswith("file://"):
raise BadRequest("You need to supply \"sha256\" parameter for file when using a remote source")
file["sha256"] = sha256sum(local_path)
with open(config_path, "w", encoding='utf8') as f:
yaml.dump(config, f , default_flow_style=False, allow_unicode=True)
return config
def prepare_compile_config(shaves, env):
if env.version.startswith('2021'):
config_file_content = {
'MYRIAD_NUMBER_OF_SHAVES': shaves,
'MYRIAD_NUMBER_OF_CMX_SLICES': shaves,
'MYRIAD_THROUGHPUT_STREAMS': 1
}
else:
config_file_content = {
'VPU_MYRIAD_PLATFORM': 'VPU_MYRIAD_2480',
'VPU_NUMBER_OF_SHAVES': shaves,
'VPU_NUMBER_OF_CMX_SLICES': shaves,
'VPU_MYRIAD_THROUGHPUT_STREAMS': 1
}
config_file_path = env.workdir / "myriad_compile_config.txt"
with open(config_file_path, "w") as f:
f.writelines(
[f"{key} {config_file_content[key]}\r\n" for key in config_file_content.keys()]
)
return config_file_path
def fetch_from_zoo(env, name):
return next(env.model_zoo_path.rglob(f'**/{name}/model.yml'), None)
@app.route("/compile", methods=['GET', 'POST'])
def compile():
env = EnvResolver()
name = request.values.get('name', '')
if len(name) == 0:
return "Parameter \"name\" is empty!", 400
myriad_shaves = int(request.values.get('myriad_shaves', '6'))
myriad_params_advanced = request.values.get('myriad_params_advanced', '-ip U8')
config_path = env.workdir / name / "model.yml"
config_path.parent.mkdir(parents=True, exist_ok=True)
config_file = request.files.get("config", None)
use_zoo = request.values.get('use_zoo', False)
data_type = request.values.get('data_type', "FP16")
download_ir = request.values.get('download_ir', "false").lower() == "true"
no_cache = request.args.get('no_cache', "false") == "true"
if config_file is None:
if use_zoo:
zoo_path = fetch_from_zoo(env, name)
if zoo_path is None:
return "Model {} not found in model zoo".format(name), 400
with zoo_path.open() as in_f, config_path.open("w") as out_f:
out_f.write(in_f.read())
else:
return "File named \"config\" must be present in the request form", 400
else:
config_file.save(config_path)
with open(config_path) as f:
raw_config = f.read()
file_paths = {}
for form_name, file in request.files.items():
if form_name == "config":
continue
path = env.workdir / name / data_type / secure_filename(file.filename)
path.parent.mkdir(parents=True, exist_ok=True)
file_paths[form_name] = path
file.save(path)
config = parse_config(config_path, name, data_type, env)
compile_config_path = prepare_compile_config(myriad_shaves, env)
commands = []
xml_path = env.workdir / name / data_type / (name + ".xml")
if len(file_paths) == 0:
commands.append(
f"{env.executable} {env.downloader_path} --precisions {data_type} --output_dir {env.workdir} --cache_dir {env.cache_path} --num_attempts 5 --name {name} --model_root {env.workdir}"
)
if use_zoo:
preconvert_script = next(env.model_zoo_path.rglob(f"**/{name}/pre-convert.py"), None)
if preconvert_script is not None:
commands.append(
f"{env.executable} {preconvert_script} {env.workdir / name} {env.workdir / name}"
)
if config["framework"] != "dldt":
commands.append(
f"{env.executable} {env.converter_path} --precisions {data_type} --output_dir {env.workdir} --download_dir {env.workdir} --name {name} --model_root {env.workdir}"
)
out_path = xml_path.with_suffix('.blob')
out_path.parent.mkdir(parents=True, exist_ok=True)
commands.append(f"{env.compiler_path} -m {xml_path} -o {out_path} -c {compile_config_path} {myriad_params_advanced}")
hash_obj = hashlib.sha256(json.dumps({**dict(request.args), **dict(request.values)}).encode())
if config_file is not None:
hash_obj.update(raw_config.encode())
for file_path in list(file_paths.values()):
with open(file_path, 'rb') as f:
hash_obj.update(f.read())
req_hash = hash_obj.hexdigest()
if request.args.get("dry", "false") == "true":
return jsonify(commands)
data = None
try:
if not no_cache or not download_ir:
data = bucket.Object("{}.blob".format(req_hash)).get()['Body'].read()
with out_path.open("wb") as f:
f.write(data)
except botocore.exceptions.ClientError as ex:
if ex.response['Error']['Code'] != 'NoSuchKey':
raise ex
if data is None:
for command in commands:
env.run_command(command)
major, minor = env.version.replace('_R3', '').split('.')
with open(out_path, 'rb+') as f:
f.seek(60)
f.write(int(major).to_bytes(4, byteorder="little"))
f.write(int(minor).to_bytes(4, byteorder="little"))
if not download_ir:
f.seek(0)
bucket.put_object(Body=f.read(), Key='{}.blob'.format(req_hash))
if download_ir:
zipf = zipfile.ZipFile(out_path.with_suffix('.zip'), 'w', zipfile.ZIP_DEFLATED)
zipf.write(xml_path, xml_path.name)
zipf.write(xml_path.with_suffix('.bin'), xml_path.with_suffix('.bin').name)
zipf.write(out_path, out_path.name)
zipf.close()
out_path = out_path.with_suffix('.zip')
@after_this_request
def remove_dir(response):
shutil.rmtree(env.workdir, ignore_errors=True)
return response
response = make_response(send_file(out_path, as_attachment=True, attachment_filename=out_path.name))
response.headers['X-HASH'] = req_hash
return response
@app.errorhandler(CommandFailed)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route("/zoo_models", methods=['GET'])
def get_zoo_models():
env = EnvResolver()
_, stdout, _ = env.run_command(f"{env.executable} {env.downloader_path} --model_root {env.model_zoo_path} --print_all")
return jsonify(available=stdout.decode().split())
@app.route("/update", methods=['GET'])
def update():
subprocess.check_call(["/bin/bash", "/app/docker_scheduled.sh"])
return jsonify(status="Updated")
@app.route('/')
def root():
return app.send_static_file('index.html')
|
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "equacao.h"
struct eq2grau {
double a, b, c;
double delta, x1, x2;
};
Eq2grau* criaEq() {
Eq2grau *eq = malloc(sizeof(Eq2grau));
return eq;
}
double getA(Eq2grau* eq) {
return eq->a;
}
double getB(Eq2grau* eq) {
return eq->b;
}
double getC(Eq2grau* eq) {
return eq->c;
}
double getDelta(Eq2grau* eq) {
return eq->delta;
}
double getX1(Eq2grau* eq) {
return eq->x1;
}
double getX2(Eq2grau* eq) {
return eq->x2;
}
void setA(Eq2grau* eq, double a) {
eq->a = a;
}
void setB(Eq2grau* eq, double b) {
eq->b = b;
}
void setC(Eq2grau* eq, double c) {
eq->c = c;
}
void setDelta(Eq2grau* eq, double delta) {
eq->delta = delta;
}
void setX1(Eq2grau* eq, double x1) {
eq->x1 = x1;
}
void setX2(Eq2grau* eq, double x2) {
eq->x2 = x2;
}
double calculaDelta(Eq2grau* eq) {
double a = getA(eq), b = getB(eq), c = getC(eq);
return ((b*b) - (4*a*c));
}
void calculaRaizes(Eq2grau* eq) {
double a = getA(eq), b = getB(eq), delta = getDelta(eq);
setX1(eq, (-b + sqrt(delta))/(2*a));
setX2(eq, (-b - sqrt(delta))/(2*a));
}
void freeEq2grau(Eq2grau* eq) {
free(eq);
}
|
# -*- coding: utf-8 -*-
"""
This module contains extra functions/shortcuts used to render HTML.
"""
from __future__ import unicode_literals
import json
import re
import sys
from django import template
from django.conf import settings
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.template.loader import render_to_string
def _render_error(request, errortpl="error", user_context=None):
if user_context is None:
user_context = {}
return render(
request, "common/%s.html" % errortpl, user_context
)
def render_actions(actions):
t = template.Template("""{% load lib_tags %}
{% for a in actions %}{% render_link a %}{% endfor %}
""")
return t.render(template.Context({"actions": actions}))
def getctx(status, level=1, callback=None, **kwargs):
if not callback:
callername = sys._getframe(level).f_code.co_name
else:
callername = callback
ctx = {"status": status, "callback": callername}
for kw, v in list(kwargs.items()):
ctx[kw] = v
return ctx
def ajax_response(request, status="ok", respmsg=None,
url=None, ajaxnav=False, norefresh=False,
template=None, **kwargs):
"""Ajax response shortcut
Simple shortcut that sends an JSON response. If a template is
provided, a 'content' field will be added to the response,
containing the result of this template rendering.
:param request: a Request object
:param status: the response status ('ok' or 'ko)
:param respmsg: the message that will displayed in the interface
:param url: url to display after receiving this response
:param ajaxnav:
:param norefresh: do not refresh the page after receiving this response
:param template: eventual template's path
:param kwargs: dict used for template rendering
"""
ctx = {}
for k, v in list(kwargs.items()):
ctx[k] = v
if template is not None:
content = render_to_string(template, ctx, request)
elif "content" in kwargs:
content = kwargs["content"]
else:
content = ""
jsonctx = {"status": status, "content": content}
if respmsg is not None:
jsonctx["respmsg"] = respmsg
if ajaxnav:
jsonctx["ajaxnav"] = True
if url is not None:
jsonctx["url"] = url
jsonctx["norefresh"] = norefresh
return JsonResponse(jsonctx)
def render_to_json_response(context, **response_kwargs):
"""Simple shortcut to render a JSON response.
:param dict context: response content
:return: ``HttpResponse`` object
"""
data = json.dumps(context)
response_kwargs["content_type"] = "application/json"
return HttpResponse(data, **response_kwargs)
def static_url(path):
"""Returns the correct static url for a given file
:param path: the targeted static media
"""
if path.startswith("/"):
path = path[1:]
return "%s%s" % (settings.STATIC_URL, path)
def size2integer(value):
"""Try to convert a string representing a size to an integer value
in bytes.
Supported formats:
* K|k for KB
* M|m for MB
* G|g for GB
:param value: the string to convert
:return: the corresponding integer value
"""
"""Try to convert a string representing a size to an integer value
in bytes.
Supported formats:
* K|k for KB
* M|m for MB
* G|g for GB
:param value: the string to convert
:return: the corresponding integer value
"""
m = re.match(r"(\d+)\s*(\w+)", value)
if m is None:
return 0
if re.match(r"\d+$", value) is not None:
return int(value)
if m.group(2)[0] in ["K", "k"]:
return int(m.group(1)) * 2 ** 10
if m.group(2)[0] in ["M", "m"]:
return int(m.group(1)) * 2 ** 20
if m.group(2)[0] in ["G", "g"]:
return int(m.group(1)) * 2 ** 30
return 0
class NavigationParameters(object):
"""
Just a simple object to manipulate navigation parameters.
"""
def __init__(self, request, sessionkey):
self.request = request
self.sessionkey = sessionkey
self.parameters = [("pattern", "", True),
("criteria", "from_addr", False)]
def __getitem__(self, key):
"""Retrieve an item."""
if self.sessionkey not in self.request.session:
raise KeyError
return self.request.session[self.sessionkey][key]
def __contains__(self, key):
"""Check if key is present."""
if self.sessionkey not in self.request.session:
return False
return key in self.request.session[self.sessionkey]
def __setitem__(self, key, value):
"""Set a new item."""
self.request.session[self.sessionkey][key] = value
def _store_page(self):
"""Specific method to store the current page."""
self["page"] = int(self.request.GET.get("page", 1))
def store(self):
"""Store navigation parameters into session.
"""
if self.sessionkey not in self.request.session:
self.request.session[self.sessionkey] = {}
self._store_page()
navparams = self.request.session[self.sessionkey]
navparams["order"] = self.request.GET.get("sort_order", "-date")
for param, defvalue, escape in self.parameters:
value = self.request.GET.get(param, defvalue)
if value is None:
if param in navparams:
del navparams[param]
continue
navparams[param] = re.escape(value) if escape else value
self.request.session.modified = True
def get(self, param, default_value=None):
"""Retrieve a navigation parameter.
Just a simple getter to avoid using the full key name to
access a parameter.
:param str param: parameter name
:param defaultvalue: default value if none is found
:return: parameter's value
"""
if self.sessionkey not in self.request.session:
return default_value
return self.request.session[self.sessionkey].get(param, default_value)
def remove(self, param):
"""Remove a navigation parameter from session.
:param str param: parameter name
"""
navparams = self.request.session[self.sessionkey]
if param in navparams:
del navparams[param]
|
#pragma once
namespace BLPFormat
{
#define LIBBLP_MIPMAP_COUNT 16
#define LIBBLP_PALETTE_SIZE 256
enum BLPColorEncoding : uint8_t
{
COLOR_JPEG = 0, // not supported
COLOR_PALETTE = 1,
COLOR_DXT = 2,
COLOR_ARGB8888 = 3,
COLOR_ARGB8888_dup = 4, // same decompression, likely other PIXEL_FORMAT
};
enum BLPPixelFormat : uint8_t
{
PIXEL_DXT1 = 0,
PIXEL_DXT3 = 1,
PIXEL_ARGB8888 = 2,
PIXEL_ARGB1555 = 3,
PIXEL_ARGB4444 = 4,
PIXEL_RGB565 = 5,
PIXEL_DXT5 = 7,
PIXEL_UNSPECIFIED = 8,
PIXEL_ARGB2565 = 9,
NUM_PIXEL_FORMATS = 10,
};
/* define errors. */
#define LIBBLP_SUCCESS 0 /* success. */
#define LIBBLP_ERROR_OPEN -1 /* open error on file. */
#define LIBBLP_ERROR_CLOSE -2 /* close error on file. */
#define LIBBLP_ERROR_SEEK -3 /* lseek error on file. */
#define LIBBLP_ERROR_MALLOC -6 /* memory allocation error. */
#define LIBBLP_ERROR_FORMAT -7 /* format errror. */
#define LIBBLP_ERROR_SIZE -9 /* buffer size is to small. */
struct BLPHeader
{
uint8_t magic[4];
uint32_t type;
BLPColorEncoding colorEncoding;
uint8_t alphaChannelBitDepth; // Alpha channel bit depth: 0, 1, 4 or 8
BLPPixelFormat pixelFormat; // 0, 1, 7, or 8
uint8_t has_mips; // 0 = no mips, 1 = has mips
uint32_t width;
uint32_t height;
uint32_t mipOffsets[LIBBLP_MIPMAP_COUNT];
uint32_t mipSizes[LIBBLP_MIPMAP_COUNT];
uint32_t pallete[LIBBLP_PALETTE_SIZE];
};
}
class CImageBLP
: public CImageBase
{
public:
CImageBLP(const std::string & FileName);
CImageBLP(const std::string & FileName, uint32 Width, uint32 Height, uint32 BitsPerPixel);
virtual ~CImageBLP();
protected:
bool LoadImageData(std::shared_ptr<IFile> File);
bool LoadBPL(const BLPFormat::BLPHeader& header, std::shared_ptr<IFile> f);
public: // Static
static bool IsFilenameSupported(const std::string& Filename);
static bool IsFileSupported(std::shared_ptr<IFile> File);
static std::shared_ptr<CImageBLP> CreateEmptyImage(const std::string& FileName, uint32 Width, uint32 Height, uint32 BitsPerPixel);
static std::shared_ptr<CImageBLP> CreateImage(std::shared_ptr<IFile> File);
};
|
import os
from loguru import logger
logger.add(
"spider.log",
level="DEBUG",
format="{time:YYYY-MM-DD HH:mm:ss} - {level} - {file} - {line} - {message}",
rotation="10 MB",
)
from dataclasses import dataclass, field
import time
from decimal import *
import requests
from requests.adapters import HTTPAdapter
import js2xml
from parsel import Selector
# cache
from redis import StrictRedis
from redis_cache import RedisCache
client = StrictRedis(
host=os.environ.get("REDIS_HOST", "127.0.0.1"), decode_responses=True
)
cache = RedisCache(redis_client=client)
## db
from pymongo import MongoClient
import pymongo
db = MongoClient(os.environ.get("MONGO_URI", "mongodb://localhost:27017"))["spider"][
"pools"
]
db_snapshot = MongoClient(os.environ.get("MONGO_URI", "mongodb://localhost:27017"))[
"spider"
]["snapshot"]
## requests setting
def generate_request():
s = requests.Session()
s.headers = {
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
}
s.mount("http://", HTTPAdapter(max_retries=3))
s.mount("https://", HTTPAdapter(max_retries=3))
return s
@dataclass
class poolItem:
id: str
coin: str
duration: int
issuers: str
contract_size: float
electricity_fee: float
management_fee: float
buy_url: str
upfront_fee: float
messari: float ## Messari.io
sold_percent: float
volume_availabe: str = ""
volume_total: str = ""
##TODO: messari 需要从某个网站获取
update_time: int = int(time.time())
mining_payoff: float = field(init=False)
today_income: float = field(init=False)
contract_cost: float = field(init=False)
expected_discount: float = field(init=False)
expected_breakeven_days: float = field(init=False)
present_value_of_total_cost: float = field(init=False)
present_value_of_total_electricity_fee: float = field(init=False)
daily_rate: float = field(init=False)
btc_price: float = field(init=False)
mining_payoff_btc: float = field(init=False)
honeyLemon_contract_name: str = field(init=False) # BTC 240 Days
def __post_init__(self):
if self.coin.lower() == "btc":
self.btc_price = getPrice()["BTC"]
self.mining_payoff_btc = get_global_data_BTC()
elif self.coin.lower() == "eth":
self.btc_price = getPrice()["ETH"]
self.mining_payoff_btc = get_global_data_ETH()
elif self.coin.lower() == "bch":
self.btc_price = getPrice()["BCH"]
self.mining_payoff_btc = get_global_data_BCH()
elif self.coin.lower() == "bsv":
self.btc_price = getPrice()["BSV"]
self.mining_payoff_btc = get_global_data_BSV()
elif self.coin.lower() == "etc":
self.btc_price = getPrice()["ETC"]
self.mining_payoff_btc = get_global_data_ETC()
self.mining_payoff = self.btc_price * self.mining_payoff_btc
self.today_income = self.mining_payoff * (1 - self.management_fee)
self.daily_rate = pow(1 + self.messari, 1 / 365) - 1
self.present_value_of_total_electricity_fee = (
self.electricity_fee
* ((1 - pow(1 + self.daily_rate, -self.duration)) / self.daily_rate)
* self.contract_size
)
self.present_value_of_total_cost = (
self.upfront_fee + self.present_value_of_total_electricity_fee
)
self.contract_cost = (
self.present_value_of_total_cost / self.contract_size / self.duration
)
self.expected_discount = 1 - self.contract_cost / (
self.mining_payoff * (1 - self.management_fee)
)
self.expected_breakeven_days = (
self.upfront_fee
/ self.contract_size
/ (self.mining_payoff * (1 - self.management_fee) - self.electricity_fee)
)
self.honeyLemon_contract_name = f"{self.coin.upper()} {self.duration} Days"
# btc的合约可以挖bch
# 能够同时挖BCH的平台:Genesis mining, bitdeer, Bitcoin.com, IQ Mining
# if self.coin.lower() == "btc":
# if self.issuers in ["bitdeer", "btccom", "genesis_mining", "iqmining"]:
# p1 = poolItem(
# self.id + "_bch",
# "BCH",
# self.duration,
# self.issuers,
# self.contract_size,
# self.electricity_fee,
# self.management_fee,
# self.buy_url,
# self.upfront_fee,
# self.messari,
# self.sold_percent,
# )
# p1.save2db()
# btc的合约可以挖bsv
# if self.coin.lower() == "btc":
# p1 = poolItem(
# self.id + "_bsv",
# "BSV",
# self.duration,
# self.issuers,
# self.contract_size,
# self.electricity_fee,
# self.management_fee,
# self.buy_url,
# self.upfront_fee,
# self.messari,
# self.sold_percent,
# )
# p1.save2db()
# eth的合约可以挖etc
# if self.coin.lower() == "eth":
# p1 = poolItem(
# self.id + "_etc",
# "ETC",
# self.duration,
# self.issuers,
# self.contract_size,
# self.electricity_fee,
# self.management_fee,
# self.buy_url,
# self.upfront_fee,
# self.messari,
# self.sold_percent,
# )
# p1.save2db()
def save2db(self):
db.update_one({"id": self.id}, {"$set": self.__dict__}, upsert=True)
self.snapshot()
def snapshot(self):
snapshot_data = {
"contract_cost": self.contract_cost,
"electricity_fee": self.electricity_fee,
"management_fee": self.management_fee,
"mining_payoff": self.mining_payoff,
"mining_payoff_btc": self.mining_payoff_btc,
"today_income": self.today_income,
"sold_percent": self.sold_percent,
"id": self.id,
"update_time": self.update_time,
"volume_total": self.volume_total,
"volume_availabe": self.volume_availabe,
}
db_snapshot.insert_one(snapshot_data)
db_snapshot.create_index(
[("id", pymongo.ASCENDING), ("update_time", pymongo.ASCENDING)]
)
@logger.catch
@cache.cache(ttl=300)
def getPrice():
url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest"
logger.info("从coinmarketcap爬取价格信息")
params = {"start": "1", "limit": "100", "convert": "USD"}
z = requests.get(
url,
params=params,
headers={"X-CMC_PRO_API_KEY": "fafa4240-a7ba-43ee-8954-88d8cc0eec1e"},
)
raw_data = z.json()
prices = {}
if raw_data["status"]["error_code"] == 0:
for i in raw_data["data"]:
symbol = i["symbol"]
price = i["quote"]["USD"]["price"]
prices[symbol] = price
return prices
@logger.catch
@cache.cache(ttl=300)
def get_global_data_BTC():
"""
拿到btc价格以及 每T/1天的收益
"""
##TODO:需要判断是否为btc...其他的币 需要别的获取方法...
logger.info("爬取btc价格以及每T每天的收益")
url = "https://explorer.viabtc.com/btc"
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
}
z = requests.get(url, headers=headers, timeout=60)
sel = Selector(text=z.text)
jscode = sel.xpath(
'//script[contains(.,"coin_per_t_per_day")]/text()'
).extract_first()
parse_js = js2xml.parse(jscode)
btc_price = float(
parse_js.xpath('//*[@name="usd_display_close"]/string/text()')[1].replace(
"$", ""
)
)
mining_payoff_btc = float(
parse_js.xpath('//*[@name="coin_per_t_per_day"]/string/text()')[0].strip()
)
return mining_payoff_btc
@logger.catch
@cache.cache(ttl=300)
def get_global_data_ETC():
"""
拿到etc价格以及 每T/1天的收益
"""
##TODO:需要判断是否为btc...其他的币 需要别的获取方法...
logger.info("爬取etc价格以及每T每天的收益")
url = "https://explorer.viabtc.com/etc"
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
}
z = requests.get(url, headers=headers, timeout=60)
sel = Selector(text=z.text)
jscode = sel.xpath(
'//script[contains(.,"coin_per_t_per_day")]/text()'
).extract_first()
parse_js = js2xml.parse(jscode)
btc_price = float(
parse_js.xpath('//*[@name="usd_display_close"]/string/text()')[1].replace(
"$", ""
)
)
mining_payoff_btc = float(
parse_js.xpath('//*[@name="coin_per_t_per_day"]/string/text()')[0].strip()
)
return mining_payoff_btc
@logger.catch
@cache.cache(ttl=300)
def get_global_data_BCH():
"""
拿到btc价格以及 每T/1天的收益
"""
##TODO:需要判断是否为btc...其他的币 需要别的获取方法...
logger.info("爬取bch价格以及每T每天的收益")
url = "https://explorer.viawallet.com/bch"
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
}
z = requests.get(url, headers=headers, timeout=60)
sel = Selector(text=z.text)
jscode = sel.xpath(
'//script[contains(.,"coin_per_t_per_day")]/text()'
).extract_first()
parse_js = js2xml.parse(jscode)
btc_price = float(
parse_js.xpath('//*[@name="usd_display_close"]/string/text()')[1].replace(
"$", ""
)
)
mining_payoff_btc = float(
parse_js.xpath('//*[@name="coin_per_t_per_day"]/string/text()')[0].strip()
)
return mining_payoff_btc
@logger.catch
@cache.cache(ttl=300)
def get_global_data_BSV():
"""
拿到bsv价格以及 每T/1天的收益
"""
##TODO:需要判断是否为btc...其他的币 需要别的获取方法...
logger.info("爬取bsv每T每天的收益")
url = "https://explorer.viawallet.com/bsv"
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
}
z = requests.get(url, headers=headers, timeout=60)
sel = Selector(text=z.text)
jscode = sel.xpath(
'//script[contains(.,"coin_per_t_per_day")]/text()'
).extract_first()
parse_js = js2xml.parse(jscode)
mining_payoff_btc = float(
parse_js.xpath('//*[@name="coin_per_t_per_day"]/string/text()')[0].strip()
)
return mining_payoff_btc
@logger.catch
@cache.cache(ttl=300)
def get_global_data_ETH():
logger.info("爬取eth价格以及每M每天的收益")
url = "https://www.sparkpool.com/v1/pool/stats?pool=SPARK_POOL_CN"
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
}
z = requests.get(url, headers=headers, timeout=60)
for i in z.json()["data"]:
if i["currency"] == "ETH":
return i["income"] / 100
def test_poolItem():
p = poolItem(
"oxbtctest",
"BTC",
240,
"oxbtc",
"BTC 240 Days",
10,
0.1098,
0.0,
"hhh",
77.0,
0.04,
)
assert p.__dict__ == {
"id": "oxbtctest",
"btc_price": 7316.64,
"mining_payoff_btc": 1.942e-05,
"coin": "BTC",
"duration": 240,
"issuers": "oxbtc",
"honeyLemon_contract_name": "BTC 240 Days",
"contract_size": 10,
"electricity_fee": 0.1098,
"management_fee": 0.0,
"buy_url": "hhh",
"upfront_fee": 77.0,
"messari": 0.04,
"mining_payoff": 0.1420891488,
"today_income": 0.1420891488,
"daily_rate": 0.00010745978202786333,
"present_value_of_total_electricity_fee": 260.13709201305954,
"present_value_of_total_cost": 337.13709201305954,
"contract_cost": 0.1404737883387748,
"expected_discount": 0.011368640567331001,
"expected_breakeven_days": 238.47020705606204,
}
print("公式没问题!")
if __name__ == "__main__":
test_poolItem()
|
# Copyright 2014-2021 Canonical Limited.
#
# 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 glob
import re
import subprocess
import socket
from functools import partial
from charmhelpers.fetch import apt_install, apt_update
from charmhelpers.core.hookenv import (
config,
log,
network_get_primary_address,
unit_get,
WARNING,
NoNetworkBinding,
)
from charmhelpers.core.host import (
lsb_release,
CompareHostReleases,
)
try:
import netifaces
except ImportError:
apt_update(fatal=True)
apt_install('python3-netifaces', fatal=True)
import netifaces
try:
import netaddr
except ImportError:
apt_update(fatal=True)
apt_install('python3-netaddr', fatal=True)
import netaddr
def _validate_cidr(network):
try:
netaddr.IPNetwork(network)
except (netaddr.core.AddrFormatError, ValueError):
raise ValueError("Network (%s) is not in CIDR presentation format" %
network)
def no_ip_found_error_out(network):
errmsg = ("No IP address found in network(s): %s" % network)
raise ValueError(errmsg)
def _get_ipv6_network_from_address(address):
"""Get an netaddr.IPNetwork for the given IPv6 address
:param address: a dict as returned by netifaces.ifaddresses
:returns netaddr.IPNetwork: None if the address is a link local or loopback
address
"""
if address['addr'].startswith('fe80') or address['addr'] == "::1":
return None
prefix = address['netmask'].split("/")
if len(prefix) > 1:
netmask = prefix[1]
else:
netmask = address['netmask']
return netaddr.IPNetwork("%s/%s" % (address['addr'],
netmask))
def get_address_in_network(network, fallback=None, fatal=False):
"""Get an IPv4 or IPv6 address within the network from the host.
:param network (str): CIDR presentation format. For example,
'192.168.1.0/24'. Supports multiple networks as a space-delimited list.
:param fallback (str): If no address is found, return fallback.
:param fatal (boolean): If no address is found, fallback is not
set and fatal is True then exit(1).
"""
if network is None:
if fallback is not None:
return fallback
if fatal:
no_ip_found_error_out(network)
else:
return None
networks = network.split() or [network]
for network in networks:
_validate_cidr(network)
network = netaddr.IPNetwork(network)
for iface in netifaces.interfaces():
try:
addresses = netifaces.ifaddresses(iface)
except ValueError:
# If an instance was deleted between
# netifaces.interfaces() run and now, its interfaces are gone
continue
if network.version == 4 and netifaces.AF_INET in addresses:
for addr in addresses[netifaces.AF_INET]:
cidr = netaddr.IPNetwork("%s/%s" % (addr['addr'],
addr['netmask']))
if cidr in network:
return str(cidr.ip)
if network.version == 6 and netifaces.AF_INET6 in addresses:
for addr in addresses[netifaces.AF_INET6]:
cidr = _get_ipv6_network_from_address(addr)
if cidr and cidr in network:
return str(cidr.ip)
if fallback is not None:
return fallback
if fatal:
no_ip_found_error_out(network)
return None
def is_ipv6(address):
"""Determine whether provided address is IPv6 or not."""
try:
address = netaddr.IPAddress(address)
except netaddr.AddrFormatError:
# probably a hostname - so not an address at all!
return False
return address.version == 6
def is_address_in_network(network, address):
"""
Determine whether the provided address is within a network range.
:param network (str): CIDR presentation format. For example,
'192.168.1.0/24'.
:param address: An individual IPv4 or IPv6 address without a net
mask or subnet prefix. For example, '192.168.1.1'.
:returns boolean: Flag indicating whether address is in network.
"""
try:
network = netaddr.IPNetwork(network)
except (netaddr.core.AddrFormatError, ValueError):
raise ValueError("Network (%s) is not in CIDR presentation format" %
network)
try:
address = netaddr.IPAddress(address)
except (netaddr.core.AddrFormatError, ValueError):
raise ValueError("Address (%s) is not in correct presentation format" %
address)
if address in network:
return True
else:
return False
def _get_for_address(address, key):
"""Retrieve an attribute of or the physical interface that
the IP address provided could be bound to.
:param address (str): An individual IPv4 or IPv6 address without a net
mask or subnet prefix. For example, '192.168.1.1'.
:param key: 'iface' for the physical interface name or an attribute
of the configured interface, for example 'netmask'.
:returns str: Requested attribute or None if address is not bindable.
"""
address = netaddr.IPAddress(address)
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
if address.version == 4 and netifaces.AF_INET in addresses:
addr = addresses[netifaces.AF_INET][0]['addr']
netmask = addresses[netifaces.AF_INET][0]['netmask']
network = netaddr.IPNetwork("%s/%s" % (addr, netmask))
cidr = network.cidr
if address in cidr:
if key == 'iface':
return iface
else:
return addresses[netifaces.AF_INET][0][key]
if address.version == 6 and netifaces.AF_INET6 in addresses:
for addr in addresses[netifaces.AF_INET6]:
network = _get_ipv6_network_from_address(addr)
if not network:
continue
cidr = network.cidr
if address in cidr:
if key == 'iface':
return iface
elif key == 'netmask' and cidr:
return str(cidr).split('/')[1]
else:
return addr[key]
return None
get_iface_for_address = partial(_get_for_address, key='iface')
get_netmask_for_address = partial(_get_for_address, key='netmask')
def resolve_network_cidr(ip_address):
'''
Resolves the full address cidr of an ip_address based on
configured network interfaces
'''
netmask = get_netmask_for_address(ip_address)
return str(netaddr.IPNetwork("%s/%s" % (ip_address, netmask)).cidr)
def format_ipv6_addr(address):
"""If address is IPv6, wrap it in '[]' otherwise return None.
This is required by most configuration files when specifying IPv6
addresses.
"""
if is_ipv6(address):
return "[%s]" % address
return None
def is_ipv6_disabled():
try:
result = subprocess.check_output(
['sysctl', 'net.ipv6.conf.all.disable_ipv6'],
stderr=subprocess.STDOUT,
universal_newlines=True)
except subprocess.CalledProcessError:
return True
return "net.ipv6.conf.all.disable_ipv6 = 1" in result
def get_iface_addr(iface='eth0', inet_type='AF_INET', inc_aliases=False,
fatal=True, exc_list=None):
"""Return the assigned IP address for a given interface, if any.
:param iface: network interface on which address(es) are expected to
be found.
:param inet_type: inet address family
:param inc_aliases: include alias interfaces in search
:param fatal: if True, raise exception if address not found
:param exc_list: list of addresses to ignore
:return: list of ip addresses
"""
# Extract nic if passed /dev/ethX
if '/' in iface:
iface = iface.split('/')[-1]
if not exc_list:
exc_list = []
try:
inet_num = getattr(netifaces, inet_type)
except AttributeError:
raise Exception("Unknown inet type '%s'" % str(inet_type))
interfaces = netifaces.interfaces()
if inc_aliases:
ifaces = []
for _iface in interfaces:
if iface == _iface or _iface.split(':')[0] == iface:
ifaces.append(_iface)
if fatal and not ifaces:
raise Exception("Invalid interface '%s'" % iface)
ifaces.sort()
else:
if iface not in interfaces:
if fatal:
raise Exception("Interface '%s' not found " % (iface))
else:
return []
else:
ifaces = [iface]
addresses = []
for netiface in ifaces:
net_info = netifaces.ifaddresses(netiface)
if inet_num in net_info:
for entry in net_info[inet_num]:
if 'addr' in entry and entry['addr'] not in exc_list:
addresses.append(entry['addr'])
if fatal and not addresses:
raise Exception("Interface '%s' doesn't have any %s addresses." %
(iface, inet_type))
return sorted(addresses)
get_ipv4_addr = partial(get_iface_addr, inet_type='AF_INET')
def get_iface_from_addr(addr):
"""Work out on which interface the provided address is configured."""
for iface in netifaces.interfaces():
addresses = netifaces.ifaddresses(iface)
for inet_type in addresses:
for _addr in addresses[inet_type]:
_addr = _addr['addr']
# link local
ll_key = re.compile("(.+)%.*")
raw = re.match(ll_key, _addr)
if raw:
_addr = raw.group(1)
if _addr == addr:
log("Address '%s' is configured on iface '%s'" %
(addr, iface))
return iface
msg = "Unable to infer net iface on which '%s' is configured" % (addr)
raise Exception(msg)
def sniff_iface(f):
"""Ensure decorated function is called with a value for iface.
If no iface provided, inject net iface inferred from unit private address.
"""
def iface_sniffer(*args, **kwargs):
if not kwargs.get('iface', None):
kwargs['iface'] = get_iface_from_addr(unit_get('private-address'))
return f(*args, **kwargs)
return iface_sniffer
@sniff_iface
def get_ipv6_addr(iface=None, inc_aliases=False, fatal=True, exc_list=None,
dynamic_only=True):
"""Get assigned IPv6 address for a given interface.
Returns list of addresses found. If no address found, returns empty list.
If iface is None, we infer the current primary interface by doing a reverse
lookup on the unit private-address.
We currently only support scope global IPv6 addresses i.e. non-temporary
addresses. If no global IPv6 address is found, return the first one found
in the ipv6 address list.
:param iface: network interface on which ipv6 address(es) are expected to
be found.
:param inc_aliases: include alias interfaces in search
:param fatal: if True, raise exception if address not found
:param exc_list: list of addresses to ignore
:param dynamic_only: only recognise dynamic addresses
:return: list of ipv6 addresses
"""
addresses = get_iface_addr(iface=iface, inet_type='AF_INET6',
inc_aliases=inc_aliases, fatal=fatal,
exc_list=exc_list)
if addresses:
global_addrs = []
for addr in addresses:
key_scope_link_local = re.compile("^fe80::..(.+)%(.+)")
m = re.match(key_scope_link_local, addr)
if m:
eui_64_mac = m.group(1)
iface = m.group(2)
else:
global_addrs.append(addr)
if global_addrs:
# Make sure any found global addresses are not temporary
cmd = ['ip', 'addr', 'show', iface]
out = subprocess.check_output(
cmd).decode('UTF-8', errors='replace')
if dynamic_only:
key = re.compile("inet6 (.+)/[0-9]+ scope global.* dynamic.*")
else:
key = re.compile("inet6 (.+)/[0-9]+ scope global.*")
addrs = []
for line in out.split('\n'):
line = line.strip()
m = re.match(key, line)
if m and 'temporary' not in line:
# Return the first valid address we find
for addr in global_addrs:
if m.group(1) == addr:
if not dynamic_only or \
m.group(1).endswith(eui_64_mac):
addrs.append(addr)
if addrs:
return addrs
if fatal:
raise Exception("Interface '%s' does not have a scope global "
"non-temporary ipv6 address." % iface)
return []
def get_bridges(vnic_dir='/sys/devices/virtual/net'):
"""Return a list of bridges on the system."""
b_regex = "%s/*/bridge" % vnic_dir
return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)]
def get_bridge_nics(bridge, vnic_dir='/sys/devices/virtual/net'):
"""Return a list of nics comprising a given bridge on the system."""
brif_regex = "%s/%s/brif/*" % (vnic_dir, bridge)
return [x.split('/')[-1] for x in glob.glob(brif_regex)]
def is_bridge_member(nic):
"""Check if a given nic is a member of a bridge."""
for bridge in get_bridges():
if nic in get_bridge_nics(bridge):
return True
return False
def is_ip(address):
"""
Returns True if address is a valid IP address.
"""
try:
# Test to see if already an IPv4/IPv6 address
address = netaddr.IPAddress(address)
return True
except (netaddr.AddrFormatError, ValueError):
return False
def ns_query(address):
try:
import dns.resolver
except ImportError:
apt_install('python3-dnspython', fatal=True)
import dns.resolver
if isinstance(address, dns.name.Name):
rtype = 'PTR'
elif isinstance(address, str):
rtype = 'A'
else:
return None
try:
answers = dns.resolver.query(address, rtype)
except (dns.resolver.NXDOMAIN, dns.resolver.NoNameservers):
return None
if answers:
return str(answers[0])
return None
def get_host_ip(hostname, fallback=None):
"""
Resolves the IP for a given hostname, or returns
the input if it is already an IP.
"""
if is_ip(hostname):
return hostname
ip_addr = ns_query(hostname)
if not ip_addr:
try:
ip_addr = socket.gethostbyname(hostname)
except Exception:
log("Failed to resolve hostname '%s'" % (hostname),
level=WARNING)
return fallback
return ip_addr
def get_hostname(address, fqdn=True):
"""
Resolves hostname for given IP, or returns the input
if it is already a hostname.
"""
if is_ip(address):
try:
import dns.reversename
except ImportError:
apt_install("python3-dnspython", fatal=True)
import dns.reversename
rev = dns.reversename.from_address(address)
result = ns_query(rev)
if not result:
try:
result = socket.gethostbyaddr(address)[0]
except Exception:
return None
else:
result = address
if fqdn:
# strip trailing .
if result.endswith('.'):
return result[:-1]
else:
return result
else:
return result.split('.')[0]
def port_has_listener(address, port):
"""
Returns True if the address:port is open and being listened to,
else False.
@param address: an IP address or hostname
@param port: integer port
Note calls 'zc' via a subprocess shell
"""
cmd = ['nc', '-z', address, str(port)]
result = subprocess.call(cmd)
return not(bool(result))
def assert_charm_supports_ipv6():
"""Check whether we are able to support charms ipv6."""
release = lsb_release()['DISTRIB_CODENAME'].lower()
if CompareHostReleases(release) < "trusty":
raise Exception("IPv6 is not supported in the charms for Ubuntu "
"versions less than Trusty 14.04")
def get_relation_ip(interface, cidr_network=None):
"""Return this unit's IP for the given interface.
Allow for an arbitrary interface to use with network-get to select an IP.
Handle all address selection options including passed cidr network and
IPv6.
Usage: get_relation_ip('amqp', cidr_network='10.0.0.0/8')
@param interface: string name of the relation.
@param cidr_network: string CIDR Network to select an address from.
@raises Exception if prefer-ipv6 is configured but IPv6 unsupported.
@returns IPv6 or IPv4 address
"""
# Select the interface address first
# For possible use as a fallback below with get_address_in_network
try:
# Get the interface specific IP
address = network_get_primary_address(interface)
except NotImplementedError:
# If network-get is not available
address = get_host_ip(unit_get('private-address'))
except NoNetworkBinding:
log("No network binding for {}".format(interface), WARNING)
address = get_host_ip(unit_get('private-address'))
if config('prefer-ipv6'):
# Currently IPv6 has priority, eventually we want IPv6 to just be
# another network space.
assert_charm_supports_ipv6()
return get_ipv6_addr()[0]
elif cidr_network:
# If a specific CIDR network is passed get the address from that
# network.
return get_address_in_network(cidr_network, address)
# Return the interface address
return address
|
import roslib
roslib.load_manifest('sensor_msgs')
roslib.load_manifest('dynamic_reconfigure')
import rospy
import sensor_msgs.msg
import dynamic_reconfigure.srv
import dynamic_reconfigure.encoding
import numpy as np
import time
import os.path
import queue
class CameraHandler(object):
def __init__(self,topic_prefix='',debug=False,enable_dynamic_reconfigure=False):
self.topic_prefix=topic_prefix
self.debug = debug
rospy.Subscriber( '%s/image_raw'%self.topic_prefix, sensor_msgs.msg.Image,
self.get_image_callback)
self.pipeline_max_latency = 0.2
self.last_image = None
self.im_queue = None
self.recon = None
if enable_dynamic_reconfigure:
self.recon = rospy.ServiceProxy('%s/set_parameters'%self.topic_prefix, dynamic_reconfigure.srv.Reconfigure)
self.recon_cache = {}
def reconfigure(self, **params):
if self.recon is not None:
changed = {}
for k,v in list(params.items()):
if k in self.recon_cache:
if self.recon_cache[k] != v:
changed[k] = v
else:
changed[k] = v
if changed:
msg = dynamic_reconfigure.encoding.encode_config(params)
self.recon_cache.update(changed)
self.recon(msg)
if self.im_queue is not None:
#clear the queue so we get a new image with the new settings
while True:
try:
self.im_queue.get_nowait()
except queue.Empty:
break
def set_im_queue(self,q):
self.im_queue = q
def get_image_callback(self,msg):
if self.im_queue is None:
return
try:
if self.debug:
print("%s got image: %f" % (self.topic_prefix, msg.header.stamp.to_sec()))
self.im_queue.put_nowait((self.topic_prefix,msg))
except queue.Full:
if self.debug:
print(self.topic_prefix,"full")
class _Runner(object):
def __init__(self,cam_handlers,ros_latency=0.2,queue_depth=20):
self.cam_handlers = cam_handlers
self.im_queue = queue.Queue(len(cam_handlers)*queue_depth)
for ch in self.cam_handlers:
ch.set_im_queue(self.im_queue)
self.ros_latency = ros_latency
self.max_cam_latency = max( [ch.pipeline_max_latency for ch in self.cam_handlers ])
self._result = {}
@property
def result(self):
return self._result
@property
def result_as_nparray(self):
res = {}
for cam in self._result:
nimgs = len(self._result[cam])
tmpres = [0]*nimgs
for i in range(nimgs):
msg = self._result[cam][i]
shape = (msg.height, msg.width)
imarr = np.fromstring(msg.data,dtype=np.uint8)
imarr.shape = (msg.height, msg.width)
tmpres[i] = imarr
#sad to use dstack here, IMO res[cam][:,:,i] = imarr
#should have worked.
res[cam] = np.dstack(tmpres)
return res
def cycle_duration( self, dur ):
tstart = time.time()
while (time.time() - tstart) < dur:
time.sleep(0.05) # wait 50 msec
def clear_queue(self):
q = self.im_queue
while 1:
try:
q.get_nowait()
except queue.Empty:
break
def _is_done(self,rdict,n_per_camera,verbose=False):
done=True
for topic_prefix in list(rdict.keys()):
if verbose:
rospy.loginfo(' _is_done() has %d frames for %r'%(len(rdict[topic_prefix]), topic_prefix))
if len(rdict[topic_prefix]) < n_per_camera:
done=False
return done
class SimultaneousCameraRunner(_Runner):
def __init__(self,cam_handlers,**kwargs):
_Runner.__init__(self, cam_handlers,**kwargs)
def get_images(self,n_per_camera, pre_func=None, pre_func_args=[], post_func=None, post_func_args=[], verbose=False):
self._result.clear()
for ch in self.cam_handlers:
self._result[ch.topic_prefix] = []
#clear the queue
self.clear_queue()
if pre_func: pre_func(*pre_func_args)
t_latest = time.time() + (self.ros_latency + self.max_cam_latency)*n_per_camera
#wait for the images to arrive
while not self._is_done(self._result,n_per_camera,verbose=verbose):
try:
topic_prefix, msg = self.im_queue.get(1,10.0) # block, 10 second timeout
except queue.Empty:
continue
t_image = msg.header.stamp.to_sec()
if t_image > t_latest:
rospy.logwarn("image from %s at t=%f was too slow (by %f)" % (topic_prefix, t_image, t_image - t_latest))
self._result[topic_prefix].append( msg )
if post_func: post_func(*post_func_args)
class SequentialCameraRunner(_Runner):
def __init__(self,cam_handlers,**kwargs):
_Runner.__init__(self, cam_handlers,**kwargs)
self.wait_duration = kwargs.get("wait_duration", 0.1)
self.check_earliest = False
self.check_latest = False
def get_images(self,n_per_camera,verbose=False):
self._result.clear()
for ch in self.cam_handlers:
self._result[ch.topic_prefix] = []
t_earliest = time.time()
self.clear_queue()
t_latest = t_earliest + (self.ros_latency + self.max_cam_latency)
while not self._is_done(self._result,n_per_camera,verbose=verbose):
try:
topic_prefix, msg = self.im_queue.get(1,10.0) # block, 10 second timeout
except queue.Empty:
continue
t_image = msg.header.stamp.to_sec()
if self.check_latest and t_image > t_latest:
rospy.logwarn("image from %s at t=%f was too slow (by %f)" % (topic_prefix, t_image, t_image - t_latest))
if self.check_earliest and t_image < t_earliest:
rospy.logwarn("image from %s at t=%f was too early (by %f)" % (topic_prefix, t_image, t_earliest - t_image))
continue
self._result[topic_prefix].append( msg )
|
import React from 'react';
import {
DividerHeader,
ProcessStageCircles,
StreamMethodsBox,
ButtonNextPage,
TilePdf
} from '../../../components/_index'
import { Row, Col } from 'antd';
const CoCreationProcessStage7 = props => {
const { CO_CREATION_PROCESS, MATERIALS } = props;
const { color, imgSrc, substages, name, methods, relatedMaterials } = CO_CREATION_PROCESS[6];
const prevName = CO_CREATION_PROCESS[5].name;
return (
<div className='my-resp-padding'>
<ButtonNextPage backwards to='/guidebook/co-creation-process/6' label={prevName} />
<h1 className='color-primary'>{name}</h1>
<h2 />
<ProcessStageCircles
color={color}
imgSrc={imgSrc}
substages={substages}
colSpan={3}
/>
<DividerHeader text='Introduction' />
<div>
<p>
The main objective of this stream is to establish the permanent provision of a co-created service. This covers three aspects:
</p>
<ul>
<li>legal and economic responsibility;</li>
<li>hosting of the app and back-office functions; and</li>
<li>editorial work; update and maintenance of data.</li>
</ul>
<p>
The concrete activities differ for in-house projects and external projects (see description of <a href="guidebook/co-creation-process/1" target="_blank" rel="noopener noreferrer">managing a co-creation project</a>). External projects should try to involve potential service providers from the beginning via the project board and work out a business plan. For in-house projects, it is necessary to ensure that the additional resources required for a permanent service provision are acknowledged in the organisation’s budget and that responsibilities are assigned.
</p>
</div>
<DividerHeader text='Plan for transfer' />
<div>
<p>
Plan the transfer of a prototype to a permanent service provision. Potential service providers that may take over the co-created prototype should be identified and involved right from the start. Criteria to compare alternative options may involve:
</p>
<ul>
<li>outreach to the target audience with similar and complementary services;</li>
<li>technical interoperability and required interoperability standards and interfaces;</li>
<li>intellectual property rights issues; and,</li>
<li>costs related to transfer and migration.</li>
</ul>
</div>
<DividerHeader text='Requirements for later service provision' />
<div>
<p>
In order to avoid complicated and costly adaptaion when migrating the app and integrating it into an existing portal, technical standards, data formats, map designs, search functions etc. should be checked for compatibility as early as possible and be adhered to when <a href="guidebook/co-creation-process/5" target="_blank" rel="noopener noreferrer">co-creating software</a>.
</p>
<p>
If data is transferred at the end of the co-creation process, property rights/licensing models should be clear. When data are to be collected from other sources within the project and property rights have been given for the prototype, these rights should also cover the period post-transfer.
</p>
</div>
<DividerHeader text='Business and Revenueplan' />
<div>
<p>
Data collection and data maintenance will have been financed within the project budget during the project. A later service provider will face costs for maintaining and updating the data. Therefore, a business and revenue plan should be developed that identifies possible revenue streams to cover these costs.
</p>
<p>
For an internal project within government, an organizational assignment should be found instead.
</p>
</div>
<DividerHeader text='Relation to other streams' />
<div>
<p>
This stream relates to all other streams. Maintenance and sustainability should be considered at all times (e.g. when considering the feasibility of proposed solutions or co-creating data).
</p>
</div>
<DividerHeader text='Practical recommendations' />
<ul>
<li>Disseminate your activities continuously throughout the process (newspaper, social media, etc.).</li>
<li>Make sure all necessary Intellectual Property Rights are available.</li>
<li>Get feedback from stakeholders on service concepts.</li>
<li>Publicly launch the product when finished: <ul><li>Invite involved stakeholders and the local press. </li></ul></li>
<li>Integrate/migrate the system into existing processes.</li>
<li>Explore and if possible research the benefits for the customer segments, to allow for a quantifiable estimate and measurement of project effects.</li>
<li>Gather input on what would be natural to pay for a comparable service (value) and on possible ways to distinguish between a free service and a premium service. </li>
<li>Agree on how to determine costs and benefits for the customers </li>
</ul>
<DividerHeader text='Results' />
<div>
<p>
This stream of activity results in a business plan. Agreements on who will take responsibility in legal terms, and maintain the service, are finalised.
</p>
</div>
<DividerHeader text='Methods' />
<StreamMethodsBox
methods={methods}
/>
<DividerHeader text='Materials' />
<Row gutter={48} type='flex'>
{relatedMaterials.map((m, i) =>
<Col key={i} xs={24} lg={8} className='mb-16'>
<TilePdf
header={MATERIALS[m].name}
subHeader={MATERIALS[m].text}
tags={[]}
fileId={m}
filterable={false}
/>
</Col>
)}
</Row>
</div>
)
}
export default CoCreationProcessStage7;
|
#
# Copyright 2018 the original author or 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.
#
from voltha.protos.device_pb2 import Port
import voltha.protos.device_pb2 as dev_pb2
class BBSimOltPlatform(object):
def __init__(self, log):
self.log = log
self.MAX_ONUS_PER_PON = 64
def mk_alloc_id(self, intf_id, onu_id, idx=0):
# FIXME - driver should do prefixing 1 << 10 as it is Maple specific
# return 1<<10 | onu_id<<6 | idx
return 1023 + intf_id * self.MAX_ONUS_PER_PON + onu_id # FIXME
def mk_gemport_id(self, intf_id, onu_id, idx=0):
return 1024 + (((self.MAX_ONUS_PER_PON * intf_id + onu_id - 1) * 7) + idx)
def onu_id_from_gemport_id(self, gemport_id):
return (((gemport_id - 1024) // 7) % self.MAX_ONUS_PER_PON) + 1
def mk_uni_port_num(self, intf_id, onu_id):
return intf_id << 11 | onu_id << 4
def mk_flow_id(self, intf_id, onu_id, idx):
return intf_id << 9 | onu_id << 4 | idx
def onu_id_from_port_num(self, port_num):
return (port_num >> 4) & 0x7F
def intf_id_from_uni_port_num(self, port_num):
return (port_num >> 11) & 0xF
def intf_id_from_pon_port_no(self, port_no):
return port_no & 0xF
def intf_id_to_port_no(self, intf_id, intf_type):
if intf_type is Port.ETHERNET_NNI:
return (0x1 << 16) | intf_id
elif intf_type is Port.PON_OLT:
return 0x2 << 28 | intf_id
else:
raise Exception('Invalid port type')
def intf_id_from_nni_port_num(self, port_num):
return port_num & 0xFFFF
def intf_id_to_port_type_name(self, intf_id):
if (2 << 28 ^ intf_id) < 16:
return Port.PON_OLT
elif intf_id & (0x1 << 16) == (0x1 << 16):
return Port.ETHERNET_NNI
else:
return None
def port_type_name_by_port_index(self, port_index):
try:
return dev_pb2._PORT_PORTTYPE.values_by_number[port_index].name
except Exception as err:
raise Exception(err)
def extract_access_from_flow(self, in_port, out_port):
if self.is_upstream(out_port):
return (self.intf_id_from_uni_port_num(in_port),
self.onu_id_from_port_num(in_port))
else:
return (self.intf_id_from_uni_port_num(out_port),
self.onu_id_from_port_num(out_port))
def is_upstream(self, out_port):
if out_port in [0xfffd, 0xfffffffd]:
# To Controller
return True
if (out_port & (0x1 << 16)) == (0x1 << 16):
# NNI interface
return True
return False
def max_onus_per_pon(self):
return self.MAX_ONUS_PER_PON
|
# This is an automatically generated file.
# DO NOT EDIT or your changes may be overwritten
import base64
from xdrlib import Packer, Unpacker
from ..exceptions import ValueError
from .claim_atom_type import ClaimAtomType
from .claim_liquidity_atom import ClaimLiquidityAtom
from .claim_offer_atom import ClaimOfferAtom
from .claim_offer_atom_v0 import ClaimOfferAtomV0
__all__ = ["ClaimAtom"]
class ClaimAtom:
"""
XDR Source Code
----------------------------------------------------------------
union ClaimAtom switch (ClaimAtomType type)
{
case CLAIM_ATOM_TYPE_V0:
ClaimOfferAtomV0 v0;
case CLAIM_ATOM_TYPE_ORDER_BOOK:
ClaimOfferAtom orderBook;
case CLAIM_ATOM_TYPE_LIQUIDITY_POOL:
ClaimLiquidityAtom liquidityPool;
};
----------------------------------------------------------------
"""
def __init__(
self,
type: ClaimAtomType,
v0: ClaimOfferAtomV0 = None,
order_book: ClaimOfferAtom = None,
liquidity_pool: ClaimLiquidityAtom = None,
) -> None:
self.type = type
self.v0 = v0
self.order_book = order_book
self.liquidity_pool = liquidity_pool
def pack(self, packer: Packer) -> None:
self.type.pack(packer)
if self.type == ClaimAtomType.CLAIM_ATOM_TYPE_V0:
if self.v0 is None:
raise ValueError("v0 should not be None.")
self.v0.pack(packer)
return
if self.type == ClaimAtomType.CLAIM_ATOM_TYPE_ORDER_BOOK:
if self.order_book is None:
raise ValueError("order_book should not be None.")
self.order_book.pack(packer)
return
if self.type == ClaimAtomType.CLAIM_ATOM_TYPE_LIQUIDITY_POOL:
if self.liquidity_pool is None:
raise ValueError("liquidity_pool should not be None.")
self.liquidity_pool.pack(packer)
return
@classmethod
def unpack(cls, unpacker: Unpacker) -> "ClaimAtom":
type = ClaimAtomType.unpack(unpacker)
if type == ClaimAtomType.CLAIM_ATOM_TYPE_V0:
v0 = ClaimOfferAtomV0.unpack(unpacker)
if v0 is None:
raise ValueError("v0 should not be None.")
return cls(type, v0=v0)
if type == ClaimAtomType.CLAIM_ATOM_TYPE_ORDER_BOOK:
order_book = ClaimOfferAtom.unpack(unpacker)
if order_book is None:
raise ValueError("order_book should not be None.")
return cls(type, order_book=order_book)
if type == ClaimAtomType.CLAIM_ATOM_TYPE_LIQUIDITY_POOL:
liquidity_pool = ClaimLiquidityAtom.unpack(unpacker)
if liquidity_pool is None:
raise ValueError("liquidity_pool should not be None.")
return cls(type, liquidity_pool=liquidity_pool)
return cls(type)
def to_xdr_bytes(self) -> bytes:
packer = Packer()
self.pack(packer)
return packer.get_buffer()
@classmethod
def from_xdr_bytes(cls, xdr: bytes) -> "ClaimAtom":
unpacker = Unpacker(xdr)
return cls.unpack(unpacker)
def to_xdr(self) -> str:
xdr_bytes = self.to_xdr_bytes()
return base64.b64encode(xdr_bytes).decode()
@classmethod
def from_xdr(cls, xdr: str) -> "ClaimAtom":
xdr_bytes = base64.b64decode(xdr.encode())
return cls.from_xdr_bytes(xdr_bytes)
def __eq__(self, other: object):
if not isinstance(other, self.__class__):
return NotImplemented
return (
self.type == other.type
and self.v0 == other.v0
and self.order_book == other.order_book
and self.liquidity_pool == other.liquidity_pool
)
def __str__(self):
out = []
out.append(f"type={self.type}")
out.append(f"v0={self.v0}") if self.v0 is not None else None
out.append(
f"order_book={self.order_book}"
) if self.order_book is not None else None
out.append(
f"liquidity_pool={self.liquidity_pool}"
) if self.liquidity_pool is not None else None
return f"<ClaimAtom {[', '.join(out)]}>"
|
from keras.models import Model
from keras.layers import Input, LSTM, Dense
import numpy as np
# vectorize data
input_text = []
output_text = []
input_character = set()
output_character = set()
def make_dictionary (fname):
content = []
with open(fname, 'r') as f:
content = f.readlines()
word = set()
for line in content:
for ch in line:
word.add(ch)
word = sorted(list(word))
print('Length of unique words in dictionary: ', len(word))
# make index table
char_to_int = {w: i for i, w in enumerate(word)}
int_to_char = {v: k for k, v in char_to_int.items()}
print('Lookup table 1 (map chars to integer): ', char_to_int)
print('Lookup table 2 (map integer to chars: ', int_to_char)
return char_to_int, int_to_char, content, word
input_index, input_index_rev, input_text, input_char = make_dictionary('seq_dic_nan_test.txt')
output_index, output_index_rev, output_text, output_char = make_dictionary('seq_dic_nan_test_y.txt')
encode_token = len(input_char)
decode_token = len(output_char)
max_encode_len = max([len(txt) for txt in input_text])
max_decode_len = max([len(txt) for txt in output_text])
print('Number of samples: ', len(input_text))
print('Number of unique input: ', encode_token)
print('Number of unique output: ', decode_token)
print('Max input length: ', max_encode_len)
print('Max output length: ', max_decode_len)
# 3d matrix
# input --> encode --> decode --> node --> decode
encode_input = np.zeros(
(len(input_text), max_encode_len, encode_token), dtype='float32')
decode_input = np.zeros(
(len(input_text), max_decode_len, decode_token), dtype='float32')
decode_output = np.zeros(
(len(output_text), max_decode_len, decode_token), dtype='float32')
print('Dimension(words_number * padded_word * features)')
print('encode input', encode_input.shape)
print('decode input: ', decode_input.shape)
print('decode output: ', decode_output.shape)
for i, (input_line, output_line) in enumerate(zip(input_text, output_text)):
for t, char in enumerate(input_line):
encode_input[i, t, input_index[char]] = 1
for t, char in enumerate(output_line):
decode_input[i, t, output_index[char]] = 1
if (t > 0):
decode_output[i, t - 1, output_index[char]] = 1
# define parameters that can be tuned
batch_size = 64
epochs = 100
latent_dim = 256
# input --> LSTM(encoder) -->output(input) --> LSTM(decoder) --> output
# still vector to vector
encoder_inputs = Input(shape=(None, encode_token))
encoder = LSTM(latent_dim, return_state=True)
encoder_outputs, state_h, state_c = encoder(encoder_inputs)
encoder_states = [state_h, state_c]
#set up decoder layer
decoder_inputs = Input(shape=(None, decode_token))
decoder = LSTM(latent_dim, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder(decoder_inputs, initial_state=encoder_states)
decoder_dense = Dense(decode_token, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit([encode_input, decode_input], decode_output, batch_size=batch_size, epochs=epochs,
validation_split=0.2)
model.save('example.h5')
|
/** @typedef {String} PathifiedSvgContent */
/** @typedef {String} FeatherIconsPathDefinition */
/** @typedef {{ prefix: 'fe', iconName: 'feBatteryCharging', icon: [Number|String, Number|String, import('feather-icons').FeatherAttributes, PathifiedSvgContent, FeatherIconsPathDefinition] }} FeatherBatteryChargingIconData */
/** @type {FeatherBatteryChargingIconData} */
const feBatteryCharging = {
prefix: 'fe',
iconName: 'battery-charging',
icon: [
24,
24,
'<path d="M5 18H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h3.19M15 6h2a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-3.19"></path><line x1="23" y1="13" x2="23" y2="11"></line><polyline points="11 6 7 12 13 12 9 18"></polyline>',
'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-battery-charging"><path d="M5 18H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h3.19M15 6h2a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-3.19"/><path d="M23 13 L23 11"/><path d="M11 6 L7 12 L13 12 L9 18"/></svg>',
'M5 18H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h3.19M15 6h2a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-3.19 M23 13 L23 11 M11 6 L7 12 L13 12 L9 18',
'"xmlns"="http=//www.w3.org/2000/svg" "width"="24" "height"="24" "fill"="none" "stroke"="currentColor" "stroke-width"=2 "stroke-linecap"="round" "stroke-linejoin"="round"',
{
xmlns: 'http://www.w3.org/2000/svg',
width: 24,
height: 24,
fill: 'none',
stroke: 'currentColor',
'stroke-width': 2,
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
},
],
}
export default feBatteryCharging
|
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib 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.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random-base-randu' );
var isnan = require( '@stdlib/math-base-assert-is-nan' );
var pow = require( '@stdlib/math-base-special-pow' );
var pkg = require( './../package.json' ).name;
var mskmax = require( './../lib/mskmax.js' );
// FUNCTIONS //
/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
var mask;
var x;
var i;
x = [];
mask = [];
for ( i = 0; i < len; i++ ) {
if ( randu() < 0.2 ) {
mask.push( 1 );
} else {
mask.push( 0 );
}
x.push( ( randu()*20.0 ) - 10.0 );
}
return benchmark;
function benchmark( b ) {
var v;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
v = mskmax( x.length, x, 1, mask, 1 );
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+':len='+len, f );
}
}
main();
|
'use strict';
let expect = require('chai').expect;
let Group = require('../lib/Group');
describe('Group', () => {
beforeEach(() => {
this.group = new Group('123456789012345678901234567890');
});
describe('constructor', () => {
it('should set initial properties', () => {
expect(this.group).to.have.property('properties');
});
});
describe('validateGroup', () => {
it('should throw exception on invalid value', () => {
expect(() => {
Group.validateGroup('test');
}).to.throw(Error);
});
it('should not throw exception on Group object', () => {
expect(() => {
Group.validateGroup(this.group);
}).to.not.throw(Error);
});
});
describe('get/set id', () => {
it('should set id', () => {
let id = '098765432109876543210987654321';
this.group.id = id;
expect(this.group.id).to.equal(id);
});
it('should throw error on invalid value', () => {
expect(() => {
this.group.id = 'invalid';
}).to.throw(Error);
});
});
});
|
from torch_layers import Conv2dWithSamePadding
import torch
def test_same_padding():
input_tensor_even = torch.rand(1, 3, 12, 12)
input_tensor_odd = torch.rand(1, 3, 11, 11)
assert Conv2dWithSamePadding(3, 3, 3, padding=1)(
input_tensor_even).shape == input_tensor_even.shape
assert Conv2dWithSamePadding(3, 3, 3, padding=1)(
input_tensor_odd).shape == input_tensor_odd.shape
assert Conv2dWithSamePadding(3, 3, 3, padding='same')(
input_tensor_even).shape == input_tensor_even.shape
assert Conv2dWithSamePadding(3, 3, 3, padding='same')(
input_tensor_odd).shape == input_tensor_odd.shape
|
!function(e){var n={};function t(r){if(n[r])return n[r].exports;var a=n[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,t),a.l=!0,a.exports}t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:r})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(t.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var a in e)t.d(r,a,function(n){return e[n]}.bind(null,a));return r},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},t.p="",t(t.s=15)}([function(e,n,t){"use strict";t.d(n,"a",(function(){return a}));var r=t(1);function a(){const e=Array.prototype.slice.call(arguments),n=e.shift();let t=Object(r.g)();const a=n.split(".");let o;for(let e=0;e<a.length&&(o=t[a[e]],"string"!=typeof o);e++)t=t[a[e]];for(let n=0;n<e.length;n++)o=o.replace("{}",e[n]);return o}},function(e,n,t){"use strict";t.d(n,"f",(function(){return c})),t.d(n,"g",(function(){return d})),t.d(n,"h",(function(){return m})),t.d(n,"b",(function(){return f})),t.d(n,"c",(function(){return p})),t.d(n,"d",(function(){return h})),t.d(n,"e",(function(){return g})),t.d(n,"a",(function(){return b}));const r={ja:t(5),"en-US":t(6)},a={ja:t(7),"en-US":t(8)},o={ja:new Intl.NumberFormat("ja-JP",{style:"currency",currency:"JPY",currencyDisplay:"name"}),"en-US":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",currencyDisplay:"symbol"})},i={ja:new Intl.DateTimeFormat("ja-JP",{year:"numeric",month:"long",day:"numeric"}),"en-US":new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric"})},s={ja:function(e){return e.getFullYear()+"/"+y(e.getMonth()+1)+"/"+y(e.getDate())},"en-US":function(e){return y(e.getMonth()+1)+"/"+y(e.getDate())+"/"+e.getFullYear()}},l={ja:function(e){const n=e.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/);if(!n||4!==n.length)return null;const t=parseInt(n[1],10),r=parseInt(n[2],10),a=parseInt(n[3],10);return new Date(t,r-1,a)},"en-US":function(e){const n=e.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);if(!n||4!==n.length)return null;const t=parseInt(n[3],10),r=parseInt(n[1],10),a=parseInt(n[2],10);return new Date(t,r-1,a)}},u={ja:1e3,"en-US":10};function c(){return $("html").attr("lang")}function d(e){return e=void 0!==e?e:c(),r[e]}function m(e){return e=void 0!==e?e:c(),a[e]}function f(e){return e=void 0!==e?e:c(),o[e]}function p(e){return e=void 0!==e?e:c(),i[e]}function h(e){return e=void 0!==e?e:c(),s[e]}function g(e){return e=void 0!==e?e:c(),l[e]}function b(e){return e=void 0!==e?e:c(),u[e]}function y(e){return e<10?"0"+e:""+e}},function(e,n,t){"use strict";t.d(n,"f",(function(){return a})),t.d(n,"g",(function(){return o})),t.d(n,"d",(function(){return i})),t.d(n,"h",(function(){return s})),t.d(n,"i",(function(){return l})),t.d(n,"c",(function(){return u})),t.d(n,"e",(function(){return c})),t.d(n,"b",(function(){return d})),t.d(n,"j",(function(){return m})),t.d(n,"k",(function(){return f})),t.d(n,"a",(function(){return p}));var r=t(1);function a(e){const n=Object(r.h)();let t=null;for(let r=0;r<n.length;r++)if(n[r].email===e){t=n[r];break}return t?(t.preset=!0,t):(t=localStorage.getItem(e),t?JSON.parse(t):null)}function o(e,n){const t=a(e);return t&&t.password===n}function i(){return document.cookie.replace(/(?:(?:^|.*;\s*)session\s*\=\s*([^;]*).*$)|^.*$/,"$1")}function s(e){document.cookie="session="+e+"; max-age=630720000"}function l(){document.cookie="session=; max-age=0"}function u(){return""+(Math.floor(9e9*Math.random())+1e9)}function c(){return document.cookie.replace(/(?:(?:^|.*;\s*)transaction\s*\=\s*([^;]*).*$)|^.*$/,"$1")}function d(){document.cookie="transaction=; max-age=0"}function m(){let e;e=2===location.pathname.split("/").length?location.pathname.replace(/(\/.+\.html)/,"/index.html"):location.pathname.replace(/(\/.+)(\/.+\.html)/,"$1/index.html"),location.assign(location.origin+e)}function f(){$("#signup-holder").removeClass("d-block").addClass("d-none"),$("#login-holder").removeClass("d-block").addClass("d-none"),$("#mypage-holder").removeClass("d-none").addClass("d-block"),$("#logout-holder").removeClass("d-none").addClass("d-block"),$("#logout-form").submit((function(){l()}))}function p(e,n){return!e.only||!!n&&("member"===e.only||("premium"===e.only?"premium"===n.rank:void 0))}},function(e,n,t){"use strict";t.d(n,"a",(function(){return a})),t.d(n,"c",(function(){return o})),t.d(n,"d",(function(){return i})),t.d(n,"e",(function(){return s})),t.d(n,"b",(function(){return u})),t.d(n,"f",(function(){return c}));var r=t(1);function a(e){return Object(r.b)().format(e)}function o(e){return Object(r.c)().format(e)}function i(e){return Object(r.d)()(e)}function s(e){return Object(r.e)()(e)}function l(e){return e<10?"0"+e:""+e}function u(e){return e.getFullYear()+"-"+l(e.getMonth()+1)+"-"+l(e.getDate())}function c(e){const n=e.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);if(!n||4!==n.length)return null;const t=parseInt(n[1],10),r=parseInt(n[2],10),a=parseInt(n[3],10);return new Date(t,r-1,a)}},,function(e){e.exports=JSON.parse('{"validation":{"valueMissing":"このフィールドを入力してください。","typeMismatch":{"email":"メールアドレスを入力してください。","url":"URLを入力してください。"},"badInput":"有効な値を入力してください。","patternMismatch":"指定されている形式で入力してください。","tooLong":"{}文字以内で入力してください。","tooShort":"{}文字以上で入力してください。","rangeOverflow":"{}以下の値を入力してください。","rangeUnderflow":"{}以上の値を入力してください。","stepMismatch":"有効な値を入力してください。","shoudBeNextDay":"翌日以降の日付を入力してください。","shouldBeThreeMonth":"3ヶ月以内の日付を入力してください。","mailOrAddressMismatch":"メールアドレスまたはパスワードが違います。","existsMail":"このメールアドレスはすでに登録済みです。","passwordUnmatch":"入力されたパスワードと一致しません。","underTenKb":"ファイルサイズは10KB以下にしてください。","onlyImageFile":"画像ファイルを選択してください。"},"user":{"gender":{"unregistered":"未登録","male":"男性","female":"女性","other":"その他"},"rank":{"premium":"プレミアム会員","normal":"一般会員"},"unregistered":"未登録","notification":{"true":"受け取る","false":"受け取らない"},"deleteConfirm":"退会すると全ての情報が削除されます。\\nよろしいですか?","deleteComplete":"退会処理を完了しました。ご利用ありがとうございました。"},"plans":{"premiumOnly":"❤️プレミアム会員限定❤️","memberOnly":"会員限定","oneAdult":"大人1名{}","minHeadCount":"{}名様から","reserveLink":"このプランで予約"},"reserve":{"planDescLong":"お一人様1泊{}〜、土日は25%アップ。{}名様〜{}名様、最長{}泊","planDescShort":"お一人様1泊{}〜、土日は25%アップ","roomInfo":"部屋情報","totalBill":"合計 {}(税込み)","term":"{} 〜 {} {}泊","headCount":"{}名様","breakfast":"朝食バイキング","earlyCheckIn":"昼からチェックインプラン","sightseeing":"お得な観光プラン","none":"なし","username":"{}様","contact":{"no":"希望しない","email":"メール:{}","tel":"電話:{}"}}}')},function(e){e.exports=JSON.parse('{"validation":{"valueMissing":"Please fill out this field.","typeMismatch":{"email":"Please enter a non-empty email address.","url":"Please enter a non-empty URL."},"badInput":"Please enter a valid value.","patternMismatch":"Please match the requested format.","tooLong":"Please shorten this text to {} characters or less.","tooShort":"Please lengthen this text to {} characters or more.","rangeOverflow":"Value must be less than or equal to {}.","rangeUnderflow":"Value must be greater than or equal to {}.","stepMismatch":"Please enter a valid value.","shoudBeNextDay":"Please enter a date after tomorrow.","shouldBeThreeMonth":"Please enter a date within 3 months.","mailOrAddressMismatch":"Email or password is invalid.","existsMail":"Email has already been taken.","passwordUnmatch":"Password doesn\'t match.","underTenKb":"Please select a file with a size of 10 KB or less.","onlyImageFile":"Please select an image file."},"user":{"gender":{"unregistered":"not answered","male":"male","female":"female","other":"other"},"rank":{"premium":"Premium","normal":"Normal"},"unregistered":"not answered","notification":{"true":"received","false":"not received"},"deleteConfirm":"If you cancel your membership, all information will be deleted.\\nDo you wish to proceed?","deleteComplete":"The process has been completed. Thank you for your service."},"plans":{"premiumOnly":"❤️Premium members ONLY❤️","memberOnly":"members ONLY","oneAdult":"{} per guest","minHeadCount":"at least {} person(s)","reserveLink":"Reserve room"},"reserve":{"planDescLong":"{} per night. If contains Sun or Sat, plus 25%. {} - {} persons. Max {} nights","planDescShort":"{} per night. If contains Sun or Sat, plus 25%.","roomInfo":"Room info","totalBill":"Total {} (included taxes)","term":"{} - {}. {} night(s)","headCount":"{} person(s)","breakfast":"Breakfast","earlyCheckIn":"Early check-in","sightseeing":"Sightseeing","none":"none","username":"{}","contact":{"no":"not required","email":"Email: {}","tel":"Tel: {}"}}}')},function(e){e.exports=JSON.parse('[{"email":"ichiro@example.com","password":"password","username":"山田一郎","rank":"premium","address":"東京都豊島区池袋","tel":"01234567891","gender":"1","birthday":"","notification":true},{"email":"sakura@example.com","password":"pass1234","username":"松本さくら","rank":"normal","address":"神奈川県横浜市鶴見区大黒ふ頭","tel":"","gender":"2","birthday":"2000-04-01","notification":false},{"email":"jun@example.com","password":"pa55w0rd!","username":"林潤","rank":"premium","address":"大阪府大阪市北区梅田","tel":"01212341234","gender":"9","birthday":"1988-12-17","notification":false},{"email":"yoshiki@example.com","password":"pass-pass","username":"木村良樹","rank":"normal","address":"","tel":"01298765432","gender":"0","birthday":"1992-08-31","notification":true}]')},function(e){e.exports=JSON.parse('[{"email":"clark@example.com","password":"password","username":"Clark Evans","rank":"premium","address":"Mountain View, California","tel":"01234567891","gender":"1","birthday":"","notification":true},{"email":"diana@example.com","password":"pass1234","username":"Diana Johansson","rank":"normal","address":"Redmond, Washington","tel":"","gender":"2","birthday":"2000-04-01","notification":false},{"email":"ororo@example.com","password":"pa55w0rd!","username":"Ororo Saldana","rank":"premium","address":"Cupertino, California","tel":"01212341234","gender":"9","birthday":"1988-12-17","notification":false},{"email":"miles@example.com","password":"pass-pass","username":"Miles Boseman","rank":"normal","address":"","tel":"01298765432","gender":"0","birthday":"1992-08-31","notification":true}]')},,,,,,,function(e,n,t){"use strict";t.r(n);var r=t(3),a=t(1),o=t(2),i=t(0);function s(e){let n="";return"premium"===e.only?n='<div class="card-header">'+Object(i.a)("plans.premiumOnly")+"</div>":"member"===e.only&&(n='<div class="card-header">'+Object(i.a)("plans.memberOnly")+"</div>"),'<div class="col-12 col-md-6 col-lg-4"><div class="card text-center shadow-sm mb-3">'+n+'<div class="card-body"><h5 class="card-title">'+e.name+'</h5><ul class="list-unstyled"><li>'+Object(i.a)("plans.oneAdult",Object(r.a)(e.roomBill))+"</li><li>"+Object(i.a)("plans.minHeadCount",e.minHeadCount)+"</li><li>"+e.room+'</li></ul><a href="./reserve.html?plan-id='+e.id+'" class="btn btn-primary" target="_blank">'+Object(i.a)("plans.reserveLink")+"</a></div></div></div>"}$((function(){const e=Object(o.d)();e&&Object(o.k)();const n=Object(o.f)(e),t=location.origin+"/hotel-example-site/data/"+Object(a.f)()+"/plan_data.json?"+Date.now();$.getJSON(t).done((function(e){let t="";for(let r=0;r<e.length;r++)0!==e[r].id&&Object(o.a)(e[r],n)&&(t+=s(e[r]));$("#plan-list").html(t)}))}))}]);
//# sourceMappingURL=plans.bundle.js.map
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the program */
/* GCG --- Generic Column Generation */
/* a Dantzig-Wolfe decomposition based extension */
/* of the branch-cut-and-price framework */
/* SCIP --- Solving Constraint Integer Programs */
/* */
/* Copyright (C) 2010-2019 Operations Research, RWTH Aachen University */
/* Zuse Institute Berlin (ZIB) */
/* */
/* This program is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public License */
/* as published by the Free Software Foundation; either version 3 */
/* 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 Lesser General Public License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License */
/* along with this program; if not, write to the Free Software */
/* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.*/
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**@file dec_mastersetpart.h
* @brief mastersetpart detector
* @author Martin Bergner
*/
/*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/
#ifndef DEC_MASTERSETPART_H_
#define DEC_MASTERSETPART_H_
#include "scip/scip.h"
#ifdef __cplusplus
extern "C" {
#endif
/** creates the handler for mastersetpart detector and includes it in SCIP */
extern
SCIP_RETCODE SCIPincludeDetectorMastersetpart(
SCIP* scip /**< SCIP data structure */
);
#ifdef __cplusplus
}
#endif
#endif /* DEC_MASTERSETPART_H_ */
|
#
# This file is part of m.css.
#
# Copyright © 2017, 2018, 2019, 2020 Vladimír Vondruš <mosra@centrum.cz>
# Copyright © 2020 Blair Conrad <blair@blairconrad.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
import re
from pygments.lexer import RegexLexer
from pygments.formatters import HtmlFormatter
from pygments.token import *
# Support ANSI SGR codes in input, styling the output.
# Code definitions are taken from
# http://man7.org/linux/man-pages/man4/console_codes.4.html, which
# appears in part below, in case it disappears:
#
# ECMA-48 Set Graphics Rendition
#
# The ECMA-48 SGR sequence ESC [ parameters m sets display attributes.
# Several attributes can be set in the same sequence, separated by
# semicolons. An empty parameter (between semicolons or string
# initiator or terminator) is interpreted as a zero.
# param result
# 0 reset all attributes to their defaults
# 1 set bold
# 2 set half-bright (simulated with color on a color display)
# 4 set underscore (simulated with color on a color display)
# (the colors used to simulate dim or underline are set
# using ESC ] ...)
# 5 set blink
# 7 set reverse video
# 10 reset selected mapping, display control flag, and toggle
# meta flag (ECMA-48 says "primary font").
# 11 select null mapping, set display control flag, reset
# toggle meta flag (ECMA-48 says "first alternate font").
# 12 select null mapping, set display control flag, set toggle
# meta flag (ECMA-48 says "second alternate font"). The
# toggle meta flag causes the high bit of a byte to be
# toggled before the mapping table translation is done.
# 21 set underline; before Linux 4.17, this value set normal
# intensity (as is done in many other terminals)
# 22 set normal intensity
# 24 underline off
# 25 blink off
# 27 reverse video off
# 30 set black foreground
# 31 set red foreground
# 32 set green foreground
# 33 set brown foreground
# 34 set blue foreground
# 35 set magenta foreground
# 36 set cyan foreground
# 37 set white foreground
# 38 256/24-bit foreground color follows, shoehorned into 16
# basic colors (before Linux 3.16: set underscore on, set
# default foreground color)
# 39 set default foreground color (before Linux 3.16: set
# underscore off, set default foreground color)
# 40 set black background
# 41 set red background
# 42 set green background
# 43 set brown background
# 44 set blue background
# 45 set magenta background
# 46 set cyan background
# 47 set white background
# 48 256/24-bit background color follows, shoehorned into 8
# basic colors
# 49 set default background color
# 90..97 set foreground to bright versions of 30..37
# 100..107 set background, same as 40..47 (bright not supported)
#
# Commands 38 and 48 require further arguments:
# ;5;x 256 color: values 0..15 are IBGR (black, red, green,
# ... white), 16..231 a 6x6x6 color cube, 232..255 a
# grayscale ramp
# ;2;r;g;b 24-bit color, r/g/b components are in the range 0..255
#
# For historical reasons, all "brown"s above are replaced with "yellow"
# by m.css.
#
# AnsiLexer supports commands 0, 1, 22, 30–39, 40–49, 90–97, and 100–107
# (ranges inclusive).
# All other commands will be ignored completely.
#
# Foreground colors named Bright* are not affected by the "bright" SGR
# setting—they will always appear bright, even after command 22 resets the
# normal intensity. Likewise, they will not affect the "bright" setting—a
# directive to use Red after BrightGreen will result in Red being displayed,
# not BrightRed.
#
# Palette or RGB Foreground colors from command 38 likewise do not interact
# with the "bright" setting, nor do any background colors.
class AnsiLexer(RegexLexer):
name = 'Ansi escape lexer'
_sgrs_and_text = '(?P<commands>(\x1b\\[(\\d*;)*\\d*m)+)(?P<text>[^\x1b]*)'
_sgr_split = re.compile('m\x1b\\[|;|m|\x1b\\[')
_named_colors = [
'Black',
'Red',
'Green',
'Yellow',
'Blue',
'Magenta',
'Cyan',
'White',
]
_palette_start_colors = [
'000000',
'800000',
'008000',
'808000',
'000080',
'800080',
'008080',
'c0c0c0',
'808080',
'ff0000',
'00ff00',
'ffff00',
'0000ff',
'ff00ff',
'00ffff',
'ffffff',
]
_palette_cube_steps = ['00', '5f', '87', 'af', 'd7', 'ff']
def __init__(self, **options):
RegexLexer.__init__(self, **options)
self._bright = False
self._foreground = 'Default'
self._background = 'Default'
def _callback(self, match):
commands = match.group('commands')
text = match.group('text')
# split the commands strings into their constituent parameter codes
parameters = self._sgr_split.split(commands)[1:-1]
parameters = [int(p) if p else 0 for p in parameters]
# loop over the parameters, consuming them to create commands, some
# of which will have arguments
while parameters:
command = parameters.pop(0)
if command == 0:
self._bright = False
self._foreground = 'Default'
self._background = 'Default'
elif command == 1:
self._bright = True
elif command == 22:
self._bright = False
elif command >= 30 and command <= 37:
self._foreground = self._named_colors[command - 30]
elif command == 38:
mode = parameters.pop(0)
if mode == 2:
rgb = self._read_rgb(parameters)
else:
offset = parameters.pop(0)
rgb = self._make_color_from_palette(offset)
self._foreground = 'ForegroundColor' + rgb
elif command == 39:
self._foreground = 'Default'
elif command >= 40 and command <= 47:
self._background = self._named_colors[command - 40]
elif command == 48:
mode = parameters.pop(0)
if mode == 2:
rgb = self._read_rgb(parameters)
else:
offset = parameters.pop()
rgb = self._make_color_from_palette(offset)
self._background = rgb
elif command == 49:
self._background = 'Default'
elif command >= 90 and command <= 97:
self._foreground = ('Bright' +
self._named_colors[command - 90])
elif command >= 100 and command <= 107:
self._background = ('Bright' +
self._named_colors[command - 100])
if (self._bright
and not self._foreground.startswith('Bright')
and not self._foreground.startswith('ForegroundColor')):
token = 'Generic.AnsiBright' + self._foreground
else:
token = 'Generic.Ansi' + self._foreground
if (self._background != 'Default'):
token += 'BackgroundColor' + self._background
if token == 'Generic.AnsiDefault':
yield (match.start(), Text, text)
else:
yield (match.start(), string_to_tokentype(token), text)
def _read_rgb(self, parameters):
r = parameters.pop(0)
g = parameters.pop(0)
b = parameters.pop(0)
return self._to_hex(r,g,b)
def _make_color_from_palette(self, offset):
# the palette runs from 0–255 inclusive, consisting of
# - 16 specific colors intended to give a good range
# - 216 colors laid out on a color cube, with axes for
# each of red, green, and blue
# - 24 shades of grey, from grey3 to grey93
if offset < 16:
return self._palette_start_colors[offset]
elif offset < 232:
offset = offset - 16
offset, b = divmod (offset,6)
r, g = divmod(offset, 6)
r = self._palette_cube_steps[r]
g = self._palette_cube_steps[g]
b = self._palette_cube_steps[b]
return r + g + b
else:
shade = 8 + 10 * (offset - 232)
return self._to_hex(shade, shade, shade)
def _to_hex(self, r, g, b):
return '{:02x}{:02x}{:02x}'.format(r, g, b)
tokens = {
'root': [
('[^\x1b]+', Text),
(_sgrs_and_text, _callback),
]
}
class HtmlAnsiFormatter(HtmlFormatter):
_ansi_color_re = re.compile(
r'(?P<Prefix>class="g )(?P<AnsiClass>g-Ansi\S+)(?P<Suffix>")'
)
_rgb_code_re = re.compile(r'[0-9a-f]{6}$')
def wrap(self, source, outfile):
return self._wrap_code(source)
def _wrap_code(self, source):
for i, t in source:
if i == 1: # it's a line of formatted code
t = self._ansi_color_re.sub(self._replace_ansi_class, t)
yield i, t
def _replace_ansi_class(self, match):
html_classes = ['g']
html_styles = []
foreground_color = None
background_color = None
ansi_class = match.group('AnsiClass')
i = ansi_class.find('BackgroundColor')
if i >= 0:
background_color = ansi_class[i + 15:]
ansi_class = ansi_class[:i]
if self._rgb_code_re.match(background_color):
html_styles.append('background-color: #' + background_color)
else:
html_classes.append('g-AnsiBackground' + background_color)
i = ansi_class.find('ForegroundColor')
if i >= 0:
foreground_color = ansi_class[i + 15:]
ansi_class = ansi_class[:i]
html_styles.insert(0, 'color: #' + foreground_color)
if ansi_class != 'g-Ansi':
html_classes.insert(1, ansi_class)
result = ''
if len(html_classes) > 1: # we don't want to emit just g
result = 'class="' + ' '.join(html_classes) + '"'
if html_styles:
if result:
result += ' '
result += 'style="' + '; '.join(html_styles) + '"'
return result
|
import json
import re
from typing import List, Tuple
# The token format is (token_name, token_text)
Token = Tuple[str, str]
Tokens = List[Token]
def tokenize(prerequisites: str) -> Tokens:
"""
Convert a prereq expression string to a list of tokens. The last token will
be `("END", None)`.
"""
# Remove Prerequisite Override 100
prerequisites = re.sub(r"Prerequisite Override 100 +or", "", prerequisites)
prerequisites = re.sub(r"or +Prerequisite Override 100", "", prerequisites)
# List of tokens and their regexps. Anything not matched is ignored.
TOKENS = [
# (name, regex)
("OPEN_PAREN", r"\("),
("CLOSE_PAREN", r"\)"),
("OR", r"or"),
("AND", r"and"),
("COURSE", r"[a-zA-Z]{4}(?:-| )\d{4}"),
]
# Get regex that matches a token
token_regex = "|".join(
[f"(?P<{token_name}>{regex})" for token_name, regex in TOKENS]
)
token_regex = re.compile(token_regex)
# Convert regex matches to list of tokens
tokens = token_regex.finditer(prerequisites)
tokens = map(
lambda match: next(
filter(
lambda group_text: group_text[1] is not None, match.groupdict().items()
)
),
tokens,
)
tokens = list(tokens)
tokens.append(("END", None))
return tokens
def parse_atom(tokens: Tokens, cur_tok: int):
"""Parse a course or a parenthesized sub-expression"""
if tokens[cur_tok][0] == "OPEN_PAREN":
result, cur_tok = parse_tokens(tokens, cur_tok + 1)
assert tokens[cur_tok][0] == "CLOSE_PAREN"
else:
result = {
"type": "course",
"course": tokens[cur_tok][1],
}
return (result, cur_tok + 1)
def parse_or(tokens: Tokens, cur_tok: int):
"""Parse a prereq expression with only OR"""
(left, cur_tok) = parse_atom(tokens, cur_tok)
left_list = [left]
while tokens[cur_tok][0] == "OR":
(right, cur_tok) = parse_atom(tokens, cur_tok + 1)
left_list.append(right)
if len(left_list) == 1:
result = left
else:
result = {
"type": "or",
"nested": left_list,
}
return (result, cur_tok)
def parse_tokens(tokens: Tokens, cur_tok: int = 0):
"""Parse a tokenized prereq expression"""
(left, cur_tok) = parse_or(tokens, cur_tok)
left_list = [left]
while tokens[cur_tok][0] == "AND":
(right, cur_tok) = parse_or(tokens, cur_tok + 1)
left_list.append(right)
if len(left_list) == 1:
result = left
else:
result = {
"type": "and",
"nested": left_list,
}
return (result, cur_tok)
def parse(prereqs: str):
"""Parse a prereq expression"""
tokens = tokenize(prereqs)
result, cur_tok = parse_tokens(tokens)
assert tokens[cur_tok][0] == "END"
return result
def get_prereq_string(soup):
el = soup.find(
attrs={"summary": "This layout table is used to present the seating numbers."}
)
el = el.next_sibling
section = ""
data = {}
while el:
if el.string:
if el.name == "span":
section = "_".join(el.string.lower().split())
section = "".join([i for i in section if i.isalpha() or i == "_"])
if section not in data:
data[section] = []
el = el.next_sibling
continue
if section:
if el.string.strip():
data[section].append(el.string.strip())
el = el.next_sibling
if "prerequisites" in data:
data["prerequisites"] = parse(" ".join(data["prerequisites"]))
if "corequisites" in data:
data["corequisites"] = [
"-".join(course.split()) for course in data["corequisites"]
]
if "cross_list_courses" in data:
data["cross_list_courses"] = [
"-".join(course.split()) for course in data["cross_list_courses"]
]
if "restrictions" in data:
data["restrictions_clean"] = {}
section = ""
subsection = ""
for part in data["restrictions"]:
if part.endswith("Majors:"):
section = "major"
data["restrictions_clean"][section] = {}
elif part.endswith("Levels:"):
section = "level"
data["restrictions_clean"][section] = {}
elif part.endswith("Classifications:"):
section = "classification"
data["restrictions_clean"][section] = {}
elif part.endswith("or Concentration):"):
section = "field_of_study"
data["restrictions_clean"][section] = {}
elif part.endswith("Degrees:"):
section = "degree"
data["restrictions_clean"][section] = {}
elif part.endswith("Colleges:"):
section = "college"
data["restrictions_clean"][section] = {}
elif part.endswith("Campuses:"):
section = "campus"
data["restrictions_clean"][section] = {}
if part.startswith("Must be enrolled"):
subsection = "must_be"
data["restrictions_clean"][section]["must_be"] = []
continue
elif part.startswith("May not be enrolled"):
subsection = "may_not_be"
data["restrictions_clean"][section]["may_not_be"] = []
continue
if section:
data["restrictions_clean"][section][subsection].append(part)
data["restrictions"] = data["restrictions_clean"]
del data["restrictions_clean"]
return data
|
import os
from datadog_checks.dev import get_docker_hostname
HOST = get_docker_hostname()
PORT = 9644
INSTANCE_PORT = 9644
INSTANCE_URL = "http://{}:{}/metrics".format(HOST, INSTANCE_PORT)
REDPANDA_VERSION = os.getenv('REDPANDA_VERSION')
MOCK_REDPANDA_INSTANCE = {'openmetrics_endpoint': INSTANCE_URL, 'tags': ['instance_test']}
CHECK_NAME = 'redpanda'
INSTANCE_METRIC_GROUP_MAP = {
'redpanda.application': [
'redpanda.application.uptime',
'redpanda.application.build',
],
'redpanda.alien': [
'redpanda.alien.receive_batch_queue_length',
'redpanda.alien.total_received_messages.count',
'redpanda.alien.total_sent_messages.count',
],
'redpanda.cluster': [
'redpanda.cluster.partition_committed_offset',
'redpanda.cluster.partition_end_offset',
'redpanda.cluster.partition_high_watermark',
'redpanda.cluster.partition_last_stable_offset',
'redpanda.cluster.partition_leader',
'redpanda.cluster.partition_leader_id',
'redpanda.cluster.partition_records_fetched.count',
'redpanda.cluster.partition_records_produced.count',
'redpanda.cluster.partition_under_replicated_replicas',
],
'redpanda.httpd': [
'redpanda.httpd.connections_current',
'redpanda.httpd.connections.count',
'redpanda.httpd.read_errors.count',
'redpanda.httpd.reply_errors.count',
'redpanda.httpd.requests_served.count',
],
'redpanda.internal_rpc': [
'redpanda.internal_rpc.active_connections',
'redpanda.internal_rpc.connection_close_errors.count',
'redpanda.internal_rpc.connects.count',
'redpanda.internal_rpc.consumed_mem_bytes.count',
'redpanda.internal_rpc.corrupted_headers.count',
'redpanda.internal_rpc.dispatch_handler_latency.sum',
'redpanda.internal_rpc.dispatch_handler_latency.count',
'redpanda.internal_rpc.dispatch_handler_latency.bucket',
'redpanda.internal_rpc.max_service_mem_bytes.count',
'redpanda.internal_rpc.method_not_found_errors.count',
'redpanda.internal_rpc.received_bytes.count',
'redpanda.internal_rpc.requests_blocked_memory.count',
'redpanda.internal_rpc.requests_completed.count',
'redpanda.internal_rpc.requests_pending',
'redpanda.internal_rpc.sent_bytes.count',
'redpanda.internal_rpc.service_errors.count',
],
'redpanda.io_queue': [
'redpanda.io_queue.delay',
'redpanda.io_queue.queue_length',
'redpanda.io_queue.shares',
'redpanda.io_queue.total_bytes.count',
'redpanda.io_queue.total_delay_sec.count',
'redpanda.io_queue.total_operations.count',
],
'redpanda.kafka': [
'redpanda.kafka.fetch_sessions_cache_mem_usage_bytes',
'redpanda.kafka.fetch_sessions_cache_sessions_count',
'redpanda.kafka.latency_fetch_latency_us.sum',
'redpanda.kafka.latency_fetch_latency_us.count',
'redpanda.kafka.latency_fetch_latency_us.bucket',
'redpanda.kafka.latency_produce_latency_us.sum',
'redpanda.kafka.latency_produce_latency_us.count',
'redpanda.kafka.latency_produce_latency_us.bucket',
'redpanda.kafka.rpc_active_connections',
'redpanda.kafka.rpc_connection_close_errors.count',
'redpanda.kafka.rpc_connects.count',
'redpanda.kafka.rpc_consumed_mem_bytes.count',
'redpanda.kafka.rpc_corrupted_headers.count',
'redpanda.kafka.rpc_dispatch_handler_latency.sum',
'redpanda.kafka.rpc_dispatch_handler_latency.count',
'redpanda.kafka.rpc_dispatch_handler_latency.bucket',
'redpanda.kafka.rpc_max_service_mem_bytes.count',
'redpanda.kafka.rpc_method_not_found_errors.count',
'redpanda.kafka.rpc_received_bytes.count',
'redpanda.kafka.rpc_requests_blocked_memory.count',
'redpanda.kafka.rpc_requests_completed.count',
'redpanda.kafka.rpc_requests_pending',
'redpanda.kafka.rpc_sent_bytes.count',
'redpanda.kafka.rpc_service_errors.count',
],
'redpanda.leader': [
'redpanda.leader.balancer_leader_transfer_error.count',
'redpanda.leader.balancer_leader_transfer_no_improvement.count',
'redpanda.leader.balancer_leader_transfer_succeeded.count',
'redpanda.leader.balancer_leader_transfer_timeout.count',
],
'redpanda.memory': [
'redpanda.memory.allocated_memory.count',
'redpanda.memory.cross_cpu_free_operations.count',
'redpanda.memory.free_memory.count',
'redpanda.memory.free_operations.count',
'redpanda.memory.malloc_live_objects',
'redpanda.memory.malloc_operations.count',
'redpanda.memory.reclaims_operations.count',
'redpanda.memory.total_memory.count',
],
'redpanda.pandaproxy': [
'redpanda.pandaproxy.request_latency.sum',
'redpanda.pandaproxy.request_latency.count',
'redpanda.pandaproxy.request_latency.bucket',
],
'redpanda.raft': [
'redpanda.raft.done_replicate_requests.count',
'redpanda.raft.group_count',
'redpanda.raft.heartbeat_requests_errors.count',
'redpanda.raft.leader_for',
'redpanda.raft.leadership_changes.count',
'redpanda.raft.log_flushes.count',
'redpanda.raft.log_truncations.count',
'redpanda.raft.received_append_requests.count',
'redpanda.raft.received_vote_requests.count',
'redpanda.raft.recovery_requests_errors.count',
'redpanda.raft.replicate_ack_all_requests.count',
'redpanda.raft.replicate_ack_leader_requests.count',
'redpanda.raft.replicate_ack_none_requests.count',
'redpanda.raft.replicate_request_errors.count',
'redpanda.raft.sent_vote_requests.count',
],
'redpanda.reactor': [
'redpanda.reactor.abandoned_failed_futures.count',
'redpanda.reactor.aio_bytes_read.count',
'redpanda.reactor.aio_bytes_write.count',
'redpanda.reactor.aio_errors.count',
'redpanda.reactor.aio_reads.count',
'redpanda.reactor.aio_writes.count',
'redpanda.reactor.cpp_exceptions.count',
'redpanda.reactor.cpu_busy_ms.count',
'redpanda.reactor.cpu_steal_time_ms.count',
'redpanda.reactor.fstream_read_bytes.count',
'redpanda.reactor.fstream_read_bytes_blocked.count',
'redpanda.reactor.fstream_reads.count',
'redpanda.reactor.fstream_reads_ahead_bytes_discarded.count',
'redpanda.reactor.fstream_reads_aheads_discarded.count',
'redpanda.reactor.fstream_reads_blocked.count',
'redpanda.reactor.fsyncs.count',
'redpanda.reactor.io_threaded_fallbacks.count',
'redpanda.reactor.logging_failures.count',
'redpanda.reactor.polls.count',
'redpanda.reactor.tasks_pending',
'redpanda.reactor.tasks_processed.count',
'redpanda.reactor.timers_pending.count',
'redpanda.reactor.utilization',
],
'redpanda.rpc_client': [
'redpanda.rpc_client.active_connections',
'redpanda.rpc_client.client_correlation_errors.count',
'redpanda.rpc_client.connection_errors.count',
'redpanda.rpc_client.connects.count',
'redpanda.rpc_client.corrupted_headers.count',
'redpanda.rpc_client.in_bytes.count',
'redpanda.rpc_client.out_bytes.count',
'redpanda.rpc_client.read_dispatch_errors.count',
'redpanda.rpc_client.request_errors.count',
'redpanda.rpc_client.request_timeouts.count',
'redpanda.rpc_client.requests.count',
'redpanda.rpc_client.requests_blocked_memory.count',
'redpanda.rpc_client.requests_pending',
'redpanda.rpc_client.server_correlation_errors.count',
],
'redpanda.scheduler': [
'redpanda.scheduler.queue_length',
'redpanda.scheduler.runtime_ms.count',
'redpanda.scheduler.shares',
'redpanda.scheduler.starvetime_ms.count',
'redpanda.scheduler.tasks_processed.count',
'redpanda.scheduler.time_spent_on_task_quota_violations_ms.count',
'redpanda.scheduler.waittime_ms.count',
],
'redpanda.stall': [
'redpanda.stall.detector_reported.count',
],
'redpanda.storage': [
'redpanda.storage.compaction_backlog_controller_backlog_size',
'redpanda.storage.compaction_backlog_controller_error',
'redpanda.storage.compaction_backlog_controller_shares',
'redpanda.storage.kvstore_cached_bytes.count',
'redpanda.storage.kvstore_entries_fetched.count',
'redpanda.storage.kvstore_entries_removed.count',
'redpanda.storage.kvstore_entries_written.count',
'redpanda.storage.kvstore_key_count.count',
'redpanda.storage.kvstore_segments_rolled.count',
'redpanda.storage.log_batch_parse_errors.count',
'redpanda.storage.log_batch_write_errors.count',
'redpanda.storage.log_batches_read.count',
'redpanda.storage.log_batches_written.count',
'redpanda.storage.log_cache_hits.count',
'redpanda.storage.log_cache_misses.count',
'redpanda.storage.log_cached_batches_read.count',
'redpanda.storage.log_cached_read_bytes.count',
'redpanda.storage.log_compacted_segment.count',
'redpanda.storage.log_compaction_ratio.count',
'redpanda.storage.log_corrupted_compaction_indices.count',
'redpanda.storage.log_log_segments_active.count',
'redpanda.storage.log_log_segments_created.count',
'redpanda.storage.log_log_segments_removed.count',
'redpanda.storage.log_partition_size',
'redpanda.storage.log_read_bytes.count',
'redpanda.storage.log_readers_added.count',
'redpanda.storage.log_readers_evicted.count',
'redpanda.storage.log_written_bytes.count',
],
}
# fmt: on
INSTANCE_DEFAULT_GROUPS = [
'redpanda.application',
'redpanda.cluster',
'redpanda.httpd',
'redpanda.kafka',
'redpanda.leader',
'redpanda.pandaproxy',
'redpanda.reactor',
'redpanda.storage',
]
INSTANCE_ADDITIONAL_GROUPS = [
'redpanda.alien',
'redpanda.internal_rpc',
'redpanda.io_queue',
'redpanda.memory',
'redpanda.raft',
'redpanda.rpc_client',
'redpanda.scheduler',
'redpanda.stall',
]
def get_metrics(metric_groups):
"""Given a list of metric groups, return single consolidated list"""
return sorted(m for g in metric_groups for m in INSTANCE_METRIC_GROUP_MAP[g])
INSTANCE_DEFAULT_METRICS = get_metrics(INSTANCE_DEFAULT_GROUPS)
INSTANCE_ADDITIONAL_METRICS = get_metrics(INSTANCE_ADDITIONAL_GROUPS)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------
# Written by http://www.ryanyonzon.com/
# -----------------------------------------
import argparse
import getpass
import requests
import json
def main(args):
owner = args.owner
repo = args.repo
username = args.username
output = args.write
password = None
while password is None or password == '':
password = getpass.getpass("Password for 'https://" + username + "@github.com': ")
repo_commit_url = 'https://api.github.com/repos/' + owner + '/' + repo + '/commits'
r = requests.get(repo_commit_url, auth=(username, password))
if r.status_code == 200:
json_object = json.loads(r.text)
is_write_on_file = False
if output is not None:
output_file = open(output, 'wb')
is_write_on_file = True
for commit in json_object:
commit_html_url = commit['html_url']
committer = commit['author']['login']
message = commit['commit']['message']
commit_author = commit['commit']['author']
commit_date = commit_author['date']
if is_write_on_file:
output_string = commit_date + ' - [' + committer + '] - ' + message + ' - ' + commit_html_url + "\n"
output_file.write(bytes(output_string, 'UTF-8'))
else:
print(commit_date + ' - [' + committer + '] - ' + message + ' - ' + commit_html_url)
else:
print('Error: Unable to get repository\'s commits.')
print('Make sure owner, repo, username and password are correct.')
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--owner", help="Repository owner", required=True)
parser.add_argument("-r", "--repo", help="Repository name", required=True)
parser.add_argument("-u", "--username", help="GitHub username", required=True)
parser.add_argument("-w", "--write", help="Output file name (Optional)", required=False)
args = parser.parse_args()
main(args)
|
FILE_EXT = {'.htm', '.html'}
def get_modetype():
from kaa.filetype.html.htmlmode import HTMLMode
return HTMLMode
|
const { compose } = require('react-app-rewired')
const rewireEslint = require('react-app-rewire-eslint')
const rewireReactHotLoader = require('react-app-rewire-hot-loader')
module.exports = compose(
rewireEslint,
rewireReactHotLoader
)
|
const { gql } = require('apollo-server');
module.exports = gql`
type Query {
me: Member
member(id: ID!): Member
}
type Member {
id: ID!
name: String
email: String
photoUrl: String
}
`;
|
/*
Copyright (c) 2017, The Linux Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of The Linux Foundation nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <reg.h>
#include "target_camera_common.h"
#define MIN_GAIN 1
#define MAX_ANALOG_GAIN (16)
#define MAX_DIGITAL_GAIN (1)
#define MAX_GAIN (MAX_ANALOG_GAIN * MAX_DIGITAL_GAIN)
#define REG_DIGITAL_GAIN_FRAC 0x352A
#define OV8865_MAX_DGAIN_DECIMATOR 4096
/*sensor ov8865 param*/
#define START_REG_ARRAY \
{ \
{0x0100, 0x01, 0x00}, \
}
#define STOP_REG_ARRAY \
{ \
{0x0100, 0x00, 0x00}, \
}
#define GROUPON_REG_ARRAY \
{ \
{0x3208, 0x00, 0x00}, \
}
#define GROUPOFF_REG_ARRAY \
{ \
{0x3208, 0x10, 0x00}, \
{0x3208, 0xA0, 0x00}, \
}
#define INIT0_REG_ARRAY \
{ \
{0x0103, 0x01, 0x00}, \
{0x3018, 0x32, 0x00}, \
{0x0103, 0x01, 0x00}, \
{0x0100, 0x00, 0x00}, \
{0x0100, 0x00, 0x00}, \
{0x0100, 0x00, 0x00}, \
{0x0100, 0x00, 0x00}, \
{0x3638, 0xff, 0x00}, \
{0x0302, 0x1e, 0x00}, \
{0x0303, 0x00, 0x00}, \
{0x0304, 0x03, 0x00}, \
{0x030e, 0x00, 0x00}, \
{0x030f, 0x09, 0x00}, \
{0x0312, 0x01, 0x00}, \
{0x031e, 0x0c, 0x00}, \
{0x3015, 0x01, 0x00}, \
{0x3018, 0x32, 0x00}, \
{0x3020, 0x93, 0x00}, \
{0x3022, 0x01, 0x00}, \
{0x3031, 0x0a, 0x00}, \
{0x3106, 0x01, 0x00}, \
{0x3305, 0xf1, 0x00}, \
{0x3308, 0x00, 0x00}, \
{0x3309, 0x28, 0x00}, \
{0x330a, 0x00, 0x00}, \
{0x330b, 0x20, 0x00}, \
{0x330c, 0x00, 0x00}, \
{0x330d, 0x00, 0x00}, \
{0x330e, 0x00, 0x00}, \
{0x330f, 0x40, 0x00}, \
{0x3307, 0x04, 0x00}, \
{0x3604, 0x04, 0x00}, \
{0x3602, 0x30, 0x00}, \
{0x3605, 0x00, 0x00}, \
{0x3607, 0x20, 0x00}, \
{0x3608, 0x11, 0x00}, \
{0x3609, 0x68, 0x00}, \
{0x360a, 0x40, 0x00}, \
{0x360c, 0xdd, 0x00}, \
{0x360e, 0x0c, 0x00}, \
{0x3610, 0x07, 0x00}, \
{0x3612, 0x86, 0x00}, \
{0x3613, 0x58, 0x00}, \
{0x3614, 0x28, 0x00}, \
{0x3617, 0x40, 0x00}, \
{0x3618, 0x5a, 0x00}, \
{0x3619, 0x9b, 0x00}, \
{0x361c, 0x00, 0x00}, \
{0x361d, 0x60, 0x00}, \
{0x3631, 0x60, 0x00}, \
{0x3633, 0x10, 0x00}, \
{0x3634, 0x10, 0x00}, \
{0x3635, 0x10, 0x00}, \
{0x3636, 0x10, 0x00}, \
{0x3641, 0x55, 0x00}, \
{0x3646, 0x86, 0x00}, \
{0x3647, 0x27, 0x00}, \
{0x364a, 0x1b, 0x00}, \
{0x3500, 0x00, 0x00}, \
{0x3501, 0x4c, 0x00}, \
{0x3502, 0x00, 0x00}, \
{0x3503, 0x00, 0x00}, \
{0x3508, 0x02, 0x00}, \
{0x3509, 0x00, 0x00}, \
{0x3700, 0x24, 0x00}, \
{0x3701, 0x0c, 0x00}, \
{0x3702, 0x28, 0x00}, \
{0x3703, 0x19, 0x00}, \
{0x3704, 0x14, 0x00}, \
{0x3705, 0x00, 0x00}, \
{0x3706, 0x38, 0x00}, \
{0x3707, 0x04, 0x00}, \
{0x3708, 0x24, 0x00}, \
{0x3709, 0x40, 0x00}, \
{0x370a, 0x00, 0x00}, \
{0x370b, 0xb8, 0x00}, \
{0x370c, 0x04, 0x00}, \
{0x3718, 0x12, 0x00}, \
{0x3719, 0x31, 0x00}, \
{0x3712, 0x42, 0x00}, \
{0x3714, 0x12, 0x00}, \
{0x371e, 0x19, 0x00}, \
{0x371f, 0x40, 0x00}, \
{0x3720, 0x05, 0x00}, \
{0x3721, 0x05, 0x00}, \
{0x3724, 0x02, 0x00}, \
{0x3725, 0x02, 0x00}, \
{0x3726, 0x06, 0x00}, \
{0x3728, 0x05, 0x00}, \
{0x3729, 0x02, 0x00}, \
{0x372a, 0x03, 0x00}, \
{0x372b, 0x53, 0x00}, \
{0x372c, 0xa3, 0x00}, \
{0x372d, 0x53, 0x00}, \
{0x372e, 0x06, 0x00}, \
{0x372f, 0x10, 0x00}, \
{0x3730, 0x01, 0x00}, \
{0x3731, 0x06, 0x00}, \
{0x3732, 0x14, 0x00}, \
{0x3733, 0x10, 0x00}, \
{0x3734, 0x40, 0x00}, \
{0x3736, 0x20, 0x00}, \
{0x373a, 0x02, 0x00}, \
{0x373b, 0x0c, 0x00}, \
{0x373c, 0x0a, 0x00}, \
{0x373e, 0x03, 0x00}, \
{0x3755, 0x40, 0x00}, \
{0x3758, 0x00, 0x00}, \
{0x3759, 0x4c, 0x00}, \
{0x375a, 0x06, 0x00}, \
{0x375b, 0x13, 0x00}, \
{0x375c, 0x40, 0x00}, \
{0x375d, 0x02, 0x00}, \
{0x375e, 0x00, 0x00}, \
{0x375f, 0x14, 0x00}, \
{0x3767, 0x1c, 0x00}, \
{0x3768, 0x04, 0x00}, \
{0x3769, 0x20, 0x00}, \
{0x376c, 0xc0, 0x00}, \
{0x376d, 0xc0, 0x00}, \
{0x376a, 0x08, 0x00}, \
{0x3761, 0x00, 0x00}, \
{0x3762, 0x00, 0x00}, \
{0x3763, 0x00, 0x00}, \
{0x3766, 0xff, 0x00}, \
{0x376b, 0x42, 0x00}, \
{0x3772, 0x23, 0x00}, \
{0x3773, 0x02, 0x00}, \
{0x3774, 0x16, 0x00}, \
{0x3775, 0x12, 0x00}, \
{0x3776, 0x08, 0x00}, \
{0x37a0, 0x44, 0x00}, \
{0x37a1, 0x3d, 0x00}, \
{0x37a2, 0x3d, 0x00}, \
{0x37a3, 0x01, 0x00}, \
{0x37a4, 0x00, 0x00}, \
{0x37a5, 0x08, 0x00}, \
{0x37a6, 0x00, 0x00}, \
{0x37a7, 0x44, 0x00}, \
{0x37a8, 0x58, 0x00}, \
{0x37a9, 0x58, 0x00}, \
{0x3760, 0x00, 0x00}, \
{0x376f, 0x01, 0x00}, \
{0x37aa, 0x44, 0x00}, \
{0x37ab, 0x2e, 0x00}, \
{0x37ac, 0x2e, 0x00}, \
{0x37ad, 0x33, 0x00}, \
{0x37ae, 0x0d, 0x00}, \
{0x37af, 0x0d, 0x00}, \
{0x37b0, 0x00, 0x00}, \
{0x37b1, 0x00, 0x00}, \
{0x37b2, 0x00, 0x00}, \
{0x37b3, 0x42, 0x00}, \
{0x37b4, 0x42, 0x00}, \
{0x37b5, 0x33, 0x00}, \
{0x37b6, 0x00, 0x00}, \
{0x37b7, 0x00, 0x00}, \
{0x37b8, 0x00, 0x00}, \
{0x37b9, 0xff, 0x00}, \
{0x3800, 0x00, 0x00}, \
{0x3801, 0x0c, 0x00}, \
{0x3802, 0x00, 0x00}, \
{0x3803, 0x0c, 0x00}, \
{0x3804, 0x0c, 0x00}, \
{0x3805, 0xd3, 0x00}, \
{0x3806, 0x09, 0x00}, \
{0x3807, 0xa3, 0x00}, \
{0x3808, 0x06, 0x00}, \
{0x3809, 0x60, 0x00}, \
{0x380a, 0x04, 0x00}, \
{0x380b, 0xc8, 0x00}, \
{0x380c, 0x07, 0x00}, \
{0x380d, 0x83, 0x00}, \
{0x380e, 0x04, 0x00}, \
{0x380f, 0xe8, 0x00}, /*changed from e0*/ \
{0x3810, 0x00, 0x00}, \
{0x3811, 0x04, 0x00}, \
{0x3813, 0x04, 0x00}, \
{0x3814, 0x03, 0x00}, \
{0x3815, 0x01, 0x00}, \
{0x3820, 0x00, 0x00}, \
{0x3821, 0x67, 0x00}, \
{0x382a, 0x03, 0x00}, \
{0x382b, 0x01, 0x00}, \
{0x3830, 0x08, 0x00}, \
{0x3836, 0x02, 0x00}, \
{0x3837, 0x18, 0x00}, \
{0x3841, 0xff, 0x00}, \
{0x3846, 0x88, 0x00}, \
{0x3d85, 0x06, 0x00}, \
{0x3d8c, 0x75, 0x00}, \
{0x3d8d, 0xef, 0x00}, \
{0x3f08, 0x0b, 0x00}, \
{0x4000, 0xf1, 0x00}, \
{0x4001, 0x14, 0x00}, \
{0x4005, 0x10, 0x00}, \
{0x400b, 0x0c, 0x00}, \
{0x400d, 0x10, 0x00}, \
{0x401b, 0x00, 0x00}, \
{0x401d, 0x00, 0x00}, \
{0x4020, 0x01, 0x00}, \
{0x4021, 0x20, 0x00}, \
{0x4022, 0x01, 0x00}, \
{0x4023, 0x9f, 0x00}, \
{0x4024, 0x03, 0x00}, \
{0x4025, 0xe0, 0x00}, \
{0x4026, 0x04, 0x00}, \
{0x4027, 0x5f, 0x00}, \
{0x4028, 0x00, 0x00}, \
{0x4029, 0x02, 0x00}, \
{0x402a, 0x04, 0x00}, \
{0x402b, 0x04, 0x00}, \
{0x402c, 0x02, 0x00}, \
{0x402d, 0x02, 0x00}, \
{0x402e, 0x08, 0x00}, \
{0x402f, 0x02, 0x00}, \
{0x401f, 0x00, 0x00}, \
{0x4034, 0x3f, 0x00}, \
{0x4300, 0xff, 0x00}, \
{0x4301, 0x00, 0x00}, \
{0x4302, 0x0f, 0x00}, \
{0x4500, 0x40, 0x00}, \
{0x4503, 0x10, 0x00}, \
{0x4601, 0x74, 0x00}, \
{0x481f, 0x32, 0x00}, \
{0x4837, 0x16, 0x00}, \
{0x4850, 0x10, 0x00}, \
{0x4851, 0x32, 0x00}, \
{0x4b00, 0x2a, 0x00}, \
{0x4b0d, 0x00, 0x00}, \
{0x4d00, 0x04, 0x00}, \
{0x4d01, 0x18, 0x00}, \
{0x4d02, 0xc3, 0x00}, \
{0x4d03, 0xff, 0x00}, \
{0x4d04, 0xff, 0x00}, \
{0x4d05, 0xff, 0x00}, \
{0x5000, 0x96, 0x00}, \
{0x5001, 0x01, 0x00}, \
{0x5002, 0x08, 0x00}, \
{0x5901, 0x00, 0x00}, \
{0x5e00, 0x00, 0x00}, \
{0x5e01, 0x41, 0x00}, \
{0x0100, 0x01, 0x00}, \
{0x5b00, 0x02, 0x00}, \
{0x5b01, 0xd0, 0x00}, \
{0x5b02, 0x03, 0x00}, \
{0x5b03, 0xff, 0x00}, \
{0x5b05, 0x6c, 0x00}, \
{0x5780, 0xfc, 0x00}, \
{0x5781, 0xdf, 0x00}, \
{0x5782, 0x3f, 0x00}, \
{0x5783, 0x08, 0x00}, \
{0x5784, 0x0c, 0x00}, \
{0x5786, 0x20, 0x00}, \
{0x5787, 0x40, 0x00}, \
{0x5788, 0x08, 0x00}, \
{0x5789, 0x08, 0x00}, \
{0x578a, 0x02, 0x00}, \
{0x578b, 0x01, 0x00}, \
{0x578c, 0x01, 0x00}, \
{0x578d, 0x0c, 0x00}, \
{0x578e, 0x02, 0x00}, \
{0x578f, 0x01, 0x00}, \
{0x5790, 0x01, 0x00}, \
{0x5800, 0x1d, 0x00}, \
{0x5801, 0x0e, 0x00}, \
{0x5802, 0x0c, 0x00}, \
{0x5803, 0x0c, 0x00}, \
{0x5804, 0x0f, 0x00}, \
{0x5805, 0x22, 0x00}, \
{0x5806, 0x0a, 0x00}, \
{0x5807, 0x06, 0x00}, \
{0x5808, 0x05, 0x00}, \
{0x5809, 0x05, 0x00}, \
{0x580a, 0x07, 0x00}, \
{0x580b, 0x0a, 0x00}, \
{0x580c, 0x06, 0x00}, \
{0x580d, 0x02, 0x00}, \
{0x580e, 0x00, 0x00}, \
{0x580f, 0x00, 0x00}, \
{0x5810, 0x03, 0x00}, \
{0x5811, 0x07, 0x00}, \
{0x5812, 0x06, 0x00}, \
{0x5813, 0x02, 0x00}, \
{0x5814, 0x00, 0x00}, \
{0x5815, 0x00, 0x00}, \
{0x5816, 0x03, 0x00}, \
{0x5817, 0x07, 0x00}, \
{0x5818, 0x09, 0x00}, \
{0x5819, 0x06, 0x00}, \
{0x581a, 0x04, 0x00}, \
{0x581b, 0x04, 0x00}, \
{0x581c, 0x06, 0x00}, \
{0x581d, 0x0a, 0x00}, \
{0x581e, 0x19, 0x00}, \
{0x581f, 0x0d, 0x00}, \
{0x5820, 0x0b, 0x00}, \
{0x5821, 0x0b, 0x00}, \
{0x5822, 0x0e, 0x00}, \
{0x5823, 0x22, 0x00}, \
{0x5824, 0x23, 0x00}, \
{0x5825, 0x28, 0x00}, \
{0x5826, 0x29, 0x00}, \
{0x5827, 0x27, 0x00}, \
{0x5828, 0x13, 0x00}, \
{0x5829, 0x26, 0x00}, \
{0x582a, 0x33, 0x00}, \
{0x582b, 0x32, 0x00}, \
{0x582c, 0x33, 0x00}, \
{0x582d, 0x16, 0x00}, \
{0x582e, 0x14, 0x00}, \
{0x582f, 0x30, 0x00}, \
{0x5830, 0x31, 0x00}, \
{0x5831, 0x30, 0x00}, \
{0x5832, 0x15, 0x00}, \
{0x5833, 0x26, 0x00}, \
{0x5834, 0x23, 0x00}, \
{0x5835, 0x21, 0x00}, \
{0x5836, 0x23, 0x00}, \
{0x5837, 0x05, 0x00}, \
{0x5838, 0x36, 0x00}, \
{0x5839, 0x27, 0x00}, \
{0x583a, 0x28, 0x00}, \
{0x583b, 0x26, 0x00}, \
{0x583c, 0x24, 0x00}, \
{0x583d, 0xdf, 0x00}, \
{0x0100, 0x00, 0x00}, \
}
#define RES0_REG_ARRAY \
{ \
/* 3264x2448_2lane_30fps */ \
{0x0100, 0x00, 0x00}, \
{0x0302, 0x35, 0x00}, \
{0x030f, 0x04, 0x00}, \
{0x3501, 0x98, 0x00}, \
{0x3502, 0x60, 0x00}, \
{0x3700, 0x48, 0x00}, \
{0x3701, 0x18, 0x00}, \
{0x3702, 0x50, 0x00}, \
{0x3703, 0x32, 0x00}, \
{0x3704, 0x28, 0x00}, \
{0x3706, 0x70, 0x00}, \
{0x3707, 0x08, 0x00}, \
{0x3708, 0x48, 0x00}, \
{0x3709, 0x80, 0x00}, \
{0x370a, 0x01, 0x00}, \
{0x370b, 0x70, 0x00}, \
{0x370c, 0x07, 0x00}, \
{0x3718, 0x14, 0x00}, \
{0x3712, 0x44, 0x00}, \
{0x371e, 0x31, 0x00}, \
{0x371f, 0x7f, 0x00}, \
{0x3720, 0x0a, 0x00}, \
{0x3721, 0x0a, 0x00}, \
{0x3724, 0x04, 0x00}, \
{0x3725, 0x04, 0x00}, \
{0x3726, 0x0c, 0x00}, \
{0x3728, 0x0a, 0x00}, \
{0x3729, 0x03, 0x00}, \
{0x372a, 0x06, 0x00}, \
{0x372b, 0xa6, 0x00}, \
{0x372c, 0xa6, 0x00}, \
{0x372d, 0xa6, 0x00}, \
{0x372e, 0x0c, 0x00}, \
{0x372f, 0x20, 0x00}, \
{0x3730, 0x02, 0x00}, \
{0x3731, 0x0c, 0x00}, \
{0x3732, 0x28, 0x00}, \
{0x3736, 0x30, 0x00}, \
{0x373a, 0x04, 0x00}, \
{0x373b, 0x18, 0x00}, \
{0x373c, 0x14, 0x00}, \
{0x373e, 0x06, 0x00}, \
{0x375a, 0x0c, 0x00}, \
{0x375b, 0x26, 0x00}, \
{0x375d, 0x04, 0x00}, \
{0x375f, 0x28, 0x00}, \
{0x3767, 0x1e, 0x00}, \
{0x3772, 0x46, 0x00}, \
{0x3773, 0x04, 0x00}, \
{0x3774, 0x2c, 0x00}, \
{0x3775, 0x13, 0x00}, \
{0x3776, 0x10, 0x00}, \
{0x37a0, 0x88, 0x00}, \
{0x37a1, 0x7a, 0x00}, \
{0x37a2, 0x7a, 0x00}, \
{0x37a3, 0x02, 0x00}, \
{0x37a5, 0x09, 0x00}, \
{0x37a7, 0x88, 0x00}, \
{0x37a8, 0xb0, 0x00}, \
{0x37a9, 0xb0, 0x00}, \
{0x37aa, 0x88, 0x00}, \
{0x37ab, 0x5c, 0x00}, \
{0x37ac, 0x5c, 0x00}, \
{0x37ad, 0x55, 0x00}, \
{0x37ae, 0x19, 0x00}, \
{0x37af, 0x19, 0x00}, \
{0x37b3, 0x84, 0x00}, \
{0x37b4, 0x84, 0x00}, \
{0x37b5, 0x66, 0x00}, \
{0x3808, 0x0c, 0x00}, \
{0x3809, 0xc0, 0x00}, \
{0x380a, 0x09, 0x00}, \
{0x380b, 0x90, 0x00}, \
{0x380c, 0x07, 0x00}, \
{0x380d, 0x98, 0x00}, \
{0x380e, 0x09, 0x00}, \
{0x380f, 0xb0, 0x00}, \
{0x3813, 0x02, 0x00}, \
{0x3814, 0x01, 0x00}, \
{0x3821, 0x46, 0x00}, \
{0x382a, 0x01, 0x00}, \
{0x382b, 0x01, 0x00}, \
{0x3830, 0x04, 0x00}, \
{0x3836, 0x01, 0x00}, \
{0x3846, 0x48, 0x00}, \
{0x3f08, 0x16, 0x00}, \
{0x4000, 0xf1, 0x00}, \
{0x4001, 0x14, 0x00}, \
{0x4020, 0x02, 0x00}, \
{0x4021, 0x40, 0x00}, \
{0x4022, 0x03, 0x00}, \
{0x4023, 0x3f, 0x00}, \
{0x4024, 0x07, 0x00}, \
{0x4025, 0xc0, 0x00}, \
{0x4026, 0x08, 0x00}, \
{0x4027, 0xbf, 0x00}, \
{0x402a, 0x04, 0x00}, \
{0x402b, 0x04, 0x00}, \
{0x402c, 0x02, 0x00}, \
{0x402d, 0x02, 0x00}, \
{0x402e, 0x08, 0x00}, \
{0x4500, 0x68, 0x00}, \
{0x4601, 0x10, 0x00}, \
{0x4837, 0x0c, 0x00}, \
{0x5002, 0x08, 0x00}, \
{0x5901, 0x00, 0x00}, \
}
#define START_REG_ARRAY_ON \
{ \
{0x3208,0x00,0x00},\
{0x380e,0x09,0x00},\
{0x3500,0x00,0x00},\
{0x3508,0x00,0x00},\
{0x352a,0x10,0x00},\
{0x3208,0x10,0x00},\
{0x3208,0xa0,0x00},\
}
#define TEST \
{ \
{0x5002,0x10,0x00},\
}
|
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os.path
import pytest
import spack.repo
import spack.fetch_strategy
from spack.paths import mock_packages_path
from spack.util.naming import mod_to_class
from spack.spec import Spec
from spack.util.package_hash import package_content
from spack.version import VersionChecksumError
import spack.directives
def _generate_content_strip_name(spec):
content = package_content(spec)
return content.replace(spec.package.__class__.__name__, '')
@pytest.mark.usefixtures('config', 'mock_packages')
class TestPackage(object):
def test_load_package(self):
spack.repo.get('mpich')
def test_package_name(self):
pkg = spack.repo.get('mpich')
assert pkg.name == 'mpich'
def test_package_filename(self):
repo = spack.repo.Repo(mock_packages_path)
filename = repo.filename_for_package_name('mpich')
assert filename == os.path.join(
mock_packages_path,
'packages',
'mpich',
'package.py'
)
def test_nonexisting_package_filename(self):
repo = spack.repo.Repo(mock_packages_path)
filename = repo.filename_for_package_name('some-nonexisting-package')
assert filename == os.path.join(
mock_packages_path,
'packages',
'some-nonexisting-package',
'package.py'
)
def test_package_class_names(self):
assert 'Mpich' == mod_to_class('mpich')
assert 'PmgrCollective' == mod_to_class('pmgr_collective')
assert 'PmgrCollective' == mod_to_class('pmgr-collective')
assert 'Pmgrcollective' == mod_to_class('PmgrCollective')
assert '_3db' == mod_to_class('3db')
def test_content_hash_all_same_but_patch_contents(self):
spec1 = Spec("hash-test1@1.1").concretized()
spec2 = Spec("hash-test2@1.1").concretized()
content1 = _generate_content_strip_name(spec1)
content2 = _generate_content_strip_name(spec2)
assert spec1.package.content_hash(content=content1) != \
spec2.package.content_hash(content=content2)
def test_content_hash_different_variants(self):
spec1 = Spec("hash-test1@1.2 +variantx").concretized()
spec2 = Spec("hash-test2@1.2 ~variantx").concretized()
content1 = _generate_content_strip_name(spec1)
content2 = _generate_content_strip_name(spec2)
assert spec1.package.content_hash(content=content1) == \
spec2.package.content_hash(content=content2)
def test_content_hash_cannot_get_details_from_ast(self):
"""Packages hash-test1 and hash-test3 would be considered the same
except that hash-test3 conditionally executes a phase based on
a "when" directive that Spack cannot evaluate by examining the
AST. This test ensures that Spack can compute a content hash
for hash-test3. If Spack cannot determine when a phase applies,
it adds it by default, so the test also ensures that the hashes
differ where Spack includes a phase on account of AST-examination
failure.
"""
spec3 = Spec("hash-test1@1.7").concretized()
spec4 = Spec("hash-test3@1.7").concretized()
content3 = _generate_content_strip_name(spec3)
content4 = _generate_content_strip_name(spec4)
assert(spec3.package.content_hash(content=content3) !=
spec4.package.content_hash(content=content4))
def test_all_same_but_archive_hash(self):
spec1 = Spec("hash-test1@1.3").concretized()
spec2 = Spec("hash-test2@1.3").concretized()
content1 = _generate_content_strip_name(spec1)
content2 = _generate_content_strip_name(spec2)
assert spec1.package.content_hash(content=content1) != \
spec2.package.content_hash(content=content2)
# Below tests target direct imports of spack packages from the
# spack.pkg namespace
def test_import_package(self):
import spack.pkg.builtin.mock.mpich # noqa
def test_import_package_as(self):
import spack.pkg.builtin.mock.mpich as mp # noqa
import spack.pkg.builtin.mock # noqa
import spack.pkg.builtin.mock as m # noqa
from spack.pkg.builtin import mock # noqa
def test_inheritance_of_diretives(self):
p = spack.repo.get('simple-inheritance')
# Check dictionaries that should have been filled by directives
assert len(p.dependencies) == 3
assert 'cmake' in p.dependencies
assert 'openblas' in p.dependencies
assert 'mpi' in p.dependencies
assert len(p.provided) == 2
# Check that Spec instantiation behaves as we expect
s = Spec('simple-inheritance')
s.concretize()
assert '^cmake' in s
assert '^openblas' in s
assert '+openblas' in s
assert 'mpi' in s
s = Spec('simple-inheritance~openblas')
s.concretize()
assert '^cmake' in s
assert '^openblas' not in s
assert '~openblas' in s
assert 'mpi' in s
@pytest.mark.regression('11844')
def test_inheritance_of_patches(self):
s = Spec('patch-inheritance')
# Will error if inheritor package cannot find inherited patch files
s.concretize()
def test_dependency_extensions(self):
s = Spec('extension2')
s.concretize()
deps = set(x.name for x in s.package.dependency_activations())
assert deps == set(['extension1'])
def test_import_class_from_package(self):
from spack.pkg.builtin.mock.mpich import Mpich # noqa
def test_import_module_from_package(self):
from spack.pkg.builtin.mock import mpich # noqa
def test_import_namespace_container_modules(self):
import spack.pkg # noqa
import spack.pkg as p # noqa
from spack import pkg # noqa
import spack.pkg.builtin # noqa
import spack.pkg.builtin as b # noqa
from spack.pkg import builtin # noqa
import spack.pkg.builtin.mock # noqa
import spack.pkg.builtin.mock as m # noqa
from spack.pkg.builtin import mock # noqa
@pytest.mark.regression('2737')
def test_urls_for_versions(mock_packages, config):
"""Version directive without a 'url' argument should use default url."""
for spec_str in ('url_override@0.9.0', 'url_override@1.0.0'):
s = Spec(spec_str).concretized()
url = s.package.url_for_version('0.9.0')
assert url == 'http://www.anothersite.org/uo-0.9.0.tgz'
url = s.package.url_for_version('1.0.0')
assert url == 'http://www.doesnotexist.org/url_override-1.0.0.tar.gz'
url = s.package.url_for_version('0.8.1')
assert url == 'http://www.doesnotexist.org/url_override-0.8.1.tar.gz'
def test_url_for_version_with_no_urls():
pkg = spack.repo.get('git-test')
with pytest.raises(spack.package.NoURLError):
pkg.url_for_version('1.0')
with pytest.raises(spack.package.NoURLError):
pkg.url_for_version('1.1')
def test_url_for_version_with_only_overrides(mock_packages, config):
spec = Spec('url-only-override')
spec.concretize()
pkg = spack.repo.get(spec)
# these exist and should just take the URL provided in the package
assert pkg.url_for_version('1.0.0') == 'http://a.example.com/url_override-1.0.0.tar.gz'
assert pkg.url_for_version('0.9.0') == 'http://b.example.com/url_override-0.9.0.tar.gz'
assert pkg.url_for_version('0.8.1') == 'http://c.example.com/url_override-0.8.1.tar.gz'
# these don't exist but should still work, even if there are only overrides
assert pkg.url_for_version('1.0.5') == 'http://a.example.com/url_override-1.0.5.tar.gz'
assert pkg.url_for_version('0.9.5') == 'http://b.example.com/url_override-0.9.5.tar.gz'
assert pkg.url_for_version('0.8.5') == 'http://c.example.com/url_override-0.8.5.tar.gz'
assert pkg.url_for_version('0.7.0') == 'http://c.example.com/url_override-0.7.0.tar.gz'
def test_url_for_version_with_only_overrides_with_gaps(mock_packages, config):
spec = Spec('url-only-override-with-gaps')
spec.concretize()
pkg = spack.repo.get(spec)
# same as for url-only-override -- these are specific
assert pkg.url_for_version('1.0.0') == 'http://a.example.com/url_override-1.0.0.tar.gz'
assert pkg.url_for_version('0.9.0') == 'http://b.example.com/url_override-0.9.0.tar.gz'
assert pkg.url_for_version('0.8.1') == 'http://c.example.com/url_override-0.8.1.tar.gz'
# these don't have specific URLs, but should still work by extrapolation
assert pkg.url_for_version('1.0.5') == 'http://a.example.com/url_override-1.0.5.tar.gz'
assert pkg.url_for_version('0.9.5') == 'http://b.example.com/url_override-0.9.5.tar.gz'
assert pkg.url_for_version('0.8.5') == 'http://c.example.com/url_override-0.8.5.tar.gz'
assert pkg.url_for_version('0.7.0') == 'http://c.example.com/url_override-0.7.0.tar.gz'
def test_git_top_level(mock_packages, config):
"""Ensure that top-level git attribute can be used as a default."""
pkg = spack.repo.get('git-top-level')
fetcher = spack.fetch_strategy.for_package_version(pkg, '1.0')
assert isinstance(fetcher, spack.fetch_strategy.GitFetchStrategy)
assert fetcher.url == 'https://example.com/some/git/repo'
def test_svn_top_level(mock_packages, config):
"""Ensure that top-level svn attribute can be used as a default."""
pkg = spack.repo.get('svn-top-level')
fetcher = spack.fetch_strategy.for_package_version(pkg, '1.0')
assert isinstance(fetcher, spack.fetch_strategy.SvnFetchStrategy)
assert fetcher.url == 'https://example.com/some/svn/repo'
def test_hg_top_level(mock_packages, config):
"""Ensure that top-level hg attribute can be used as a default."""
pkg = spack.repo.get('hg-top-level')
fetcher = spack.fetch_strategy.for_package_version(pkg, '1.0')
assert isinstance(fetcher, spack.fetch_strategy.HgFetchStrategy)
assert fetcher.url == 'https://example.com/some/hg/repo'
def test_no_extrapolate_without_url(mock_packages, config):
"""Verify that we can't extrapolate versions for non-URL packages."""
pkg = spack.repo.get('git-top-level')
with pytest.raises(spack.fetch_strategy.ExtrapolationError):
spack.fetch_strategy.for_package_version(pkg, '1.1')
def test_two_vcs_fetchers_top_level(mock_packages, config):
"""Verify conflict when two VCS strategies are specified together."""
pkg = spack.repo.get('git-url-svn-top-level')
with pytest.raises(spack.fetch_strategy.FetcherConflict):
spack.fetch_strategy.for_package_version(pkg, '1.0')
pkg = spack.repo.get('git-svn-top-level')
with pytest.raises(spack.fetch_strategy.FetcherConflict):
spack.fetch_strategy.for_package_version(pkg, '1.0')
def test_git_url_top_level_url_versions(mock_packages, config):
"""Test URL fetch strategy inference when url is specified with git."""
pkg = spack.repo.get('git-url-top-level')
fetcher = spack.fetch_strategy.for_package_version(pkg, '2.0')
assert isinstance(fetcher, spack.fetch_strategy.URLFetchStrategy)
assert fetcher.url == 'https://example.com/some/tarball-2.0.tar.gz'
assert fetcher.digest == 'abc20'
fetcher = spack.fetch_strategy.for_package_version(pkg, '2.1')
assert isinstance(fetcher, spack.fetch_strategy.URLFetchStrategy)
assert fetcher.url == 'https://example.com/some/tarball-2.1.tar.gz'
assert fetcher.digest == 'abc21'
fetcher = spack.fetch_strategy.for_package_version(pkg, '2.2')
assert isinstance(fetcher, spack.fetch_strategy.URLFetchStrategy)
assert fetcher.url == 'https://www.example.com/foo2.2.tar.gz'
assert fetcher.digest == 'abc22'
fetcher = spack.fetch_strategy.for_package_version(pkg, '2.3')
assert isinstance(fetcher, spack.fetch_strategy.URLFetchStrategy)
assert fetcher.url == 'https://www.example.com/foo2.3.tar.gz'
assert fetcher.digest == 'abc23'
def test_git_url_top_level_git_versions(mock_packages, config):
"""Test git fetch strategy inference when url is specified with git."""
pkg = spack.repo.get('git-url-top-level')
fetcher = spack.fetch_strategy.for_package_version(pkg, '3.0')
assert isinstance(fetcher, spack.fetch_strategy.GitFetchStrategy)
assert fetcher.url == 'https://example.com/some/git/repo'
assert fetcher.tag == 'v3.0'
assert fetcher.commit is None
assert fetcher.branch is None
fetcher = spack.fetch_strategy.for_package_version(pkg, '3.1')
assert isinstance(fetcher, spack.fetch_strategy.GitFetchStrategy)
assert fetcher.url == 'https://example.com/some/git/repo'
assert fetcher.tag == 'v3.1'
assert fetcher.commit == 'abc31'
assert fetcher.branch is None
fetcher = spack.fetch_strategy.for_package_version(pkg, '3.2')
assert isinstance(fetcher, spack.fetch_strategy.GitFetchStrategy)
assert fetcher.url == 'https://example.com/some/git/repo'
assert fetcher.tag is None
assert fetcher.commit is None
assert fetcher.branch == 'releases/v3.2'
fetcher = spack.fetch_strategy.for_package_version(pkg, '3.3')
assert isinstance(fetcher, spack.fetch_strategy.GitFetchStrategy)
assert fetcher.url == 'https://example.com/some/git/repo'
assert fetcher.tag is None
assert fetcher.commit == 'abc33'
assert fetcher.branch == 'releases/v3.3'
fetcher = spack.fetch_strategy.for_package_version(pkg, '3.4')
assert isinstance(fetcher, spack.fetch_strategy.GitFetchStrategy)
assert fetcher.url == 'https://example.com/some/git/repo'
assert fetcher.tag is None
assert fetcher.commit == 'abc34'
assert fetcher.branch is None
fetcher = spack.fetch_strategy.for_package_version(pkg, 'submodules')
assert isinstance(fetcher, spack.fetch_strategy.GitFetchStrategy)
assert fetcher.url == 'https://example.com/some/git/repo'
assert fetcher.tag is None
assert fetcher.commit is None
assert fetcher.branch is None
fetcher = spack.fetch_strategy.for_package_version(pkg, 'develop')
assert isinstance(fetcher, spack.fetch_strategy.GitFetchStrategy)
assert fetcher.url == 'https://example.com/some/git/repo'
assert fetcher.tag is None
assert fetcher.commit is None
assert fetcher.branch == 'develop'
def test_git_url_top_level_conflicts(mock_packages, config):
"""Test git fetch strategy inference when url is specified with git."""
pkg = spack.repo.get('git-url-top-level')
with pytest.raises(spack.fetch_strategy.FetcherConflict):
spack.fetch_strategy.for_package_version(pkg, '1.0')
with pytest.raises(spack.fetch_strategy.FetcherConflict):
spack.fetch_strategy.for_package_version(pkg, '1.1')
with pytest.raises(spack.fetch_strategy.FetcherConflict):
spack.fetch_strategy.for_package_version(pkg, '1.2')
with pytest.raises(spack.fetch_strategy.FetcherConflict):
spack.fetch_strategy.for_package_version(pkg, '1.3')
def test_rpath_args(mutable_database):
"""Test a package's rpath_args property."""
rec = mutable_database.get_record('mpich')
rpath_args = rec.spec.package.rpath_args
assert '-rpath' in rpath_args
assert 'mpich' in rpath_args
def test_bundle_version_checksum(mock_directive_bundle,
clear_directive_functions):
"""Test raising exception on a version checksum with a bundle package."""
with pytest.raises(VersionChecksumError, match="Checksums not allowed"):
version = spack.directives.version('1.0', checksum='1badpkg')
version(mock_directive_bundle)
def test_bundle_patch_directive(mock_directive_bundle,
clear_directive_functions):
"""Test raising exception on a patch directive with a bundle package."""
with pytest.raises(spack.directives.UnsupportedPackageDirective,
match="Patches are not allowed"):
patch = spack.directives.patch('mock/patch.txt')
patch(mock_directive_bundle)
|
#!/usr/bin/env python
#
# -----------------------------------------------------------------------------
# Copyright (c) 2017 The Regents of the University of California
#
# This file is part of kevlar (http://github.com/dib-lab/kevlar) and is
# licensed under the MIT license: see LICENSE.
# -----------------------------------------------------------------------------
import khmer
import kevlar
sketch_loader_by_filename_extension = {
'.nt': khmer.Nodetable.load,
'.ng': khmer.Nodegraph.load,
'.ct': khmer.Counttable.load,
'.cg': khmer.Countgraph.load,
'.sct': khmer.SmallCounttable.load,
'.scg': khmer.SmallCountgraph.load,
'.nodetable': khmer.Nodetable.load,
'.nodegraph': khmer.Nodegraph.load,
'.counttable': khmer.Counttable.load,
'.countgraph': khmer.Countgraph.load,
'.smallcounttable': khmer.SmallCounttable.load,
'.smallcountgraph': khmer.SmallCountgraph.load,
}
# count(?)->graph(?)->small(?)
sketch_extensions_by_trait = {
True: {
True: {
True: ('.scg', '.smallcountgraph'),
False: ('.cg', '.countgraph'),
},
False: {
True: ('.sct', '.smallcounttable'),
False: ('.ct', '.counttable'),
},
},
False: {
True: {
True: ('.ng', '.nodegraph'),
False: ('.ng', '.nodegraph'),
},
False: {
True: ('.nt', '.nodetable'),
False: ('.nt', '.nodetable'),
},
},
}
class KevlarSketchTypeError(ValueError):
pass
class KevlarUnsuitableFPRError(SystemExit):
pass
def estimate_fpr(sketch):
"""
Get a rough estimate of the false positive rate of this sketch.
Stolen shamelessly from khmer/__init__.py
"""
sizes = sketch.hashsizes()
n_ht = float(len(sizes))
occupancy = float(sketch.n_occupied())
min_size = min(sizes)
fp_one = occupancy / min_size
fp_all = fp_one ** n_ht
return fp_all
def load(filename):
"""
Convenience function for loading a sketch from the specified file.
Unfortunately, this relies on filename extensions, which are subject to
human error. But until khmer stores all relevant information in the file
itself and enables loading directly from file contents, this is the best we
can do.
"""
extensions = tuple(sketch_loader_by_filename_extension)
if not filename.endswith(extensions):
message = 'unable to determine sketch type from filename ' + filename
raise KevlarSketchTypeError(message)
ext = '.' + filename.split('.')[-1]
loadfunc = sketch_loader_by_filename_extension[ext]
return loadfunc(filename)
def get_extension(count=False, graph=False, smallcount=False):
return sketch_extensions_by_trait[count][graph][smallcount]
def allocate(ksize, target_tablesize, num_tables=4, count=False, graph=False,
smallcount=False):
"""Convenience function for allocating memory for a new sketch."""
if count and graph:
if smallcount:
createfunc = khmer.SmallCountgraph
else:
createfunc = khmer.Countgraph
elif count and not graph:
if smallcount:
createfunc = khmer.SmallCounttable
else:
createfunc = khmer.Counttable
elif not count and graph:
createfunc = khmer.Nodegraph
else:
assert not count and not graph
createfunc = khmer.Nodetable
sketch = createfunc(ksize, target_tablesize, num_tables)
return sketch
def autoload(infile, count=True, graph=False, ksize=31, table_size=1e4,
num_tables=4, num_bands=None, band=None):
"""
Use file extension to conditionally load sketch into memory.
If the file extension is one of the following, treat the file as a sketch
that has been written to disk and load it with `kevlar.sketch.load`.
Sketch attributes such as ksize, table size, and number of tables will
be set automatically.
- `.ct` or `.counttable`: `Counttable`
- `.sct` or `.smallcounttable`: `SmallCounttable`
- `.nt` or `.nodetable`: `Nodetable`
- `.cg` or `.countgraph`: `Countgraph`
- `.scg` or `.smallcountgraph`: `SmallCountgraph`
- `.ng` or `.nodegraph`: `Nodegraph`
Otherwise, a sketch will be created using the specified arguments and the
input file will be treated as a FASTA/FASTQ file to be loaded with
`.consume_seqfile` or `.consume_seqfile_banding`.
"""
try:
return load(infile)
except KevlarSketchTypeError:
sketch = allocate(ksize, table_size, num_tables, count=count,
graph=graph, smallcount=False)
if num_bands:
assert band >= 0 and band < num_bands
sketch.consume_seqfile_banding(infile, num_bands, band)
else:
sketch.consume_seqfile(infile)
return sketch
def load_sketchfiles(sketchfiles, maxfpr=0.2):
"""Load samples from pre-computed k-mer abundances."""
sketches = list()
for sketchfile in sketchfiles:
message = 'loading sketchfile "{}"...'.format(sketchfile)
kevlar.plog('[kevlar::sketch] ', message, end='')
sketch = autoload(sketchfile)
fpr = estimate_fpr(sketch)
message = 'done! estimated false positive rate is {:1.3f}'.format(fpr)
if fpr > maxfpr:
message += ' (FPR too high, bailing out!!!)'
raise KevlarUnsuitableFPRError(message)
kevlar.plog(message)
sketches.append(sketch)
return sketches
|
/* crypto/sm3/sm3.h */
/* ====================================================================
* Copyright (c) 2014 - 2015 The GmSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the GmSSL Project.
* (http://gmssl.org/)"
*
* 4. The name "GmSSL Project" must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact
* guanzhi1980@gmail.com.
*
* 5. Products derived from this software may not be called "GmSSL"
* nor may "GmSSL" appear in their names without prior written
* permission of the GmSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the GmSSL Project
* (http://gmssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
*/
#ifndef HEADER_SM3_H
#define HEADER_SM3_H
#define SM3_DIGEST_LENGTH 32
#define SM3_BLOCK_SIZE 64
//#include <sys/types.h>
//#include <stdint.h>
//#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
#define uint32_t UINT32
#define size_t UINTN
typedef struct {
uint32_t digest[8];
int nblocks;
unsigned char block[64];
int num;
} sm3_ctx_t;
int sm3_init(sm3_ctx_t *ctx);
int sm3_update(sm3_ctx_t *ctx, const unsigned char* data, size_t data_len);
int sm3_final(sm3_ctx_t *ctx, unsigned char digest[SM3_DIGEST_LENGTH]);
void sm3_compress(uint32_t digest[8], const unsigned char block[SM3_BLOCK_SIZE]);
void sm3(const unsigned char *data, size_t datalen, unsigned char digest[SM3_DIGEST_LENGTH]);
#ifdef __cplusplus
}
#endif
#endif
|
import { processCSSFactory } from '../../../../util/testHelpers';
import plugin from '..';
const { processCSS } = processCSSFactory(plugin);
function addTests(...tests) {
tests.forEach(({ message, fixture, expected }) => {
const isExpectedFunc = typeof expected === 'function';
test(
message.replace(/box/gi, 'margin'),
processCSS(
fixture.replace(/box/gi, 'margin'),
isExpectedFunc
? expected('margin')
: expected.replace(/box/gi, 'margin')
)
);
test(
message.replace(/box/gi, 'MARGIN'),
processCSS(
fixture.replace(/box/gi, 'MARGIN'),
isExpectedFunc
? expected('MARGIN')
: expected.replace(/box/gi, 'margin')
)
);
test(
message.replace(/box/gi, 'padding'),
processCSS(
fixture.replace(/box/gi, 'padding'),
isExpectedFunc
? expected('padding')
: expected.replace(/box/gi, 'padding')
)
);
test(
message.replace(/box/gi, 'PADDING'),
processCSS(
fixture.replace(/box/gi, 'PADDING'),
isExpectedFunc
? expected('PADDING')
: expected.replace(/box/gi, 'padding')
)
);
});
}
addTests(
{
message: 'should merge box values',
fixture: 'h1{box-top:10px;box-right:20px;box-bottom:30px;box-left:40px}',
expected: 'h1{box:10px 20px 30px 40px}',
},
{
message: 'should merge box values with !important',
fixture:
'h1{box-top:10px!important;box-right:20px!important;box-bottom:30px!important;box-left:40px!important}',
expected: 'h1{box:10px 20px 30px 40px!important}',
},
{
message: 'should merge & then condense box values',
fixture: 'h1{box-top:10px;box-bottom:10px;box-left:10px;box-right:10px}',
expected: 'h1{box:10px}',
},
{
message: 'should not merge box values with mixed !important',
fixture:
'h1{box-top:10px!important;box-right:20px;box-bottom:30px!important;box-left:40px}',
expected: (prop) =>
`h1{${prop}-top:10px!important;${prop}-right:20px;${prop}-bottom:30px!important;${prop}-left:40px}`,
},
{
message: 'should convert 4 values to 1 (box)',
fixture: 'h1{box:10px 10px 10px 10px}',
expected: 'h1{box:10px}',
},
{
message: 'should convert 3 values to 1 (box)',
fixture: 'h1{box:10px 10px 10px}',
expected: 'h1{box:10px}',
},
{
message: 'should convert 3 values to 2 (box)',
fixture: 'h1{box:10px 20px 10px}',
expected: 'h1{box:10px 20px}',
},
{
message: 'should convert 2 values to 1 (box)',
fixture: 'h1{box:10px 10px}',
expected: 'h1{box:10px}',
},
{
message: 'should convert 1 value to 1 (box)',
fixture: 'h1{box:10px}',
expected: 'h1{box:10px}',
},
{
message: 'should convert 4 values to 2 (box)',
fixture: 'h1{box:10px 20px 10px 20px}',
expected: 'h1{box:10px 20px}',
},
{
message: 'should convert 4 values to 3 (box)',
fixture: 'h1{box:10px 20px 30px 20px}',
expected: 'h1{box:10px 20px 30px}',
},
{
message: 'should convert 4 values to 4 (box)',
fixture: 'h1{box:10px 20px 30px 40px}',
expected: 'h1{box:10px 20px 30px 40px}',
},
{
message: 'should not mangle calc values (box)',
fixture: 'h1{box:1px 1px calc(0.5em + 1px)}',
expected: 'h1{box:1px 1px calc(0.5em + 1px)}',
},
{
message: 'should merge box-left with box',
fixture: 'h1{box:10px 20px;box-left:10px}',
expected: 'h1{box:10px 20px 10px 10px}',
},
{
message: 'should merge !important and normal box values',
fixture:
'h1{box-left:10px;box-left:20px!important;box-right:10px;box-right:20px!important;box-top:10px;box-top:20px!important;box-bottom:10px;box-bottom:20px!important}',
expected: 'h1{box:10px;box:20px!important}',
},
{
message: 'should not merge declarations with hacks (box)',
fixture: 'h1{box:4px 0;_box-top:1px}',
expected: (prop) => `h1{${prop.toLowerCase()}:4px 0;_${prop}-top:1px}`,
},
{
message: 'should not merge declarations with hacks (box) (2)',
fixture: 'h1{box:4px 0;box-top:1px\\9}',
expected: (prop) => `h1{${prop.toLowerCase()}:4px 0;${prop}-top:1px\\9}`,
},
{
message: 'should convert 2 values to 1 with an unrelated inherit (box)',
fixture: '.ui.table td{box:0.71428571em 0.71428571em;text-align:inherit}',
expected: '.ui.table td{box:0.71428571em;text-align:inherit}',
},
{
message: 'should not explode box: inherit',
fixture: 'h1{box:inherit}',
expected: (prop) => `h1{${prop}:inherit}`,
},
{
message: 'should not explode box: inherit (uppercase)',
fixture: 'h1{box:INHERIT}',
expected: (prop) => `h1{${prop}:INHERIT}`,
},
{
message: 'should not merge declarations with hacks (box) #3',
fixture: 'h1{box:4px 0 0 0;box-top:1px\\9}',
expected: (prop) => `h1{${prop.toLowerCase()}:4px 0 0;${prop}-top:1px\\9}`,
},
{
message: 'should preserve nesting level (box)',
fixture: 'section{h1{box:0 48px}}',
expected: 'section{h1{box:0 48px}}',
},
{
message: 'should override shorthand property (box)',
fixture: 'h1{box:10px;box-left:5px}',
expected: 'h1{box:10px 10px 10px 5px}',
},
{
message: 'should overwrite some box props and save fallbacks',
fixture:
'h1{box-top:10px;box-right:var(--variable);box-right:15px;box-bottom:var(--variable);box-bottom:20px;box-left:25px;box-top:var(--variable);box-left:var(--variable)}',
expected: (prop) =>
`h1{${prop.toLowerCase()}:10px 15px 20px 25px;${prop}-top:var(--variable);${prop}-left:var(--variable)}`,
},
{
message: 'should not explode box props with custom properties',
fixture: 'h1{box-bottom:var(--variable)}',
expected: (prop) => `h1{${prop}-bottom:var(--variable)}`,
},
{
message: 'should preserve case of custom properties (box)',
fixture:
'h1{box-top:10px;box-right:var(--fooBar);box-right:15px;box-bottom:var(--fooBar);box-bottom:20px;box-left:25px;box-top:var(--fooBar);box-left:var(--fooBar)}',
expected: (prop) =>
`h1{${prop.toLowerCase()}:10px 15px 20px 25px;${prop}-top:var(--fooBar);${prop}-left:var(--fooBar)}`,
},
{
message:
'should not merge incomplete box props where one has an unset property',
fixture: 'h1{box-bottom:10px;box-top:unset;box-left:20px}',
expected: (prop) =>
`h1{${prop}-bottom:10px;${prop}-top:unset;${prop}-left:20px}`,
},
{
message:
'should not merge incomplete box props where one has an unset property (uppercase)',
fixture: 'h1{box-bottom:10px;box-top:UNSET;box-left:20px}',
expected: (prop) =>
`h1{${prop}-bottom:10px;${prop}-top:UNSET;${prop}-left:20px}`,
},
{
message:
'should not merge incomplete box props where one has an initial property',
fixture: 'h1{box-bottom:10px;box-top:initial;box-left:20px}',
expected: (prop) =>
`h1{${prop}-bottom:10px;${prop}-top:initial;${prop}-left:20px}`,
},
{
message:
'should not merge incomplete box props where one has an initial property (uppercase)',
fixture: 'h1{box-bottom:10px;box-top:INITIAL;box-left:20px}',
expected: (prop) =>
`h1{${prop}-bottom:10px;${prop}-top:INITIAL;${prop}-left:20px}`,
},
{
message:
'should not merge incomplete box props where one has an inherit property',
fixture: 'h1{box-bottom:10px;box-top:inherit;box-left:20px}',
expected: (prop) =>
`h1{${prop}-bottom:10px;${prop}-top:inherit;${prop}-left:20px}`,
},
{
message:
'should not merge incomplete box props where one has an inherit property (uppercase)',
fixture: 'h1{box-bottom:10px;box-top:INHERIT;box-left:20px}',
expected: (prop) =>
`h1{${prop}-bottom:10px;${prop}-top:INHERIT;${prop}-left:20px}`,
},
{
message:
'should not merge complete box props where one has an unset property',
fixture: 'h1{box-bottom:10px;box-top:unset;box-left:20px;box-right:20px}',
expected: (prop) =>
`h1{${prop}-bottom:10px;${prop}-top:unset;${prop}-left:20px;${prop}-right:20px}`,
},
{
message:
'should not merge complete box props where one has an unset property (uppercase)',
fixture: 'h1{box-bottom:10px;box-top:UNSET;box-left:20px;box-right:20px}',
expected: (prop) =>
`h1{${prop}-bottom:10px;${prop}-top:UNSET;${prop}-left:20px;${prop}-right:20px}`,
},
{
message:
'should not merge complete box props where one has an initial property',
fixture: 'h1{box-bottom:10px;box-top:initial;box-left:20px;box-right:20px}',
expected: (prop) =>
`h1{${prop}-bottom:10px;${prop}-top:initial;${prop}-left:20px;${prop}-right:20px}`,
},
{
message:
'should not merge complete box props where one has an initial property (uppercase)',
fixture: 'h1{box-bottom:10px;box-top:INITIAL;box-left:20px;box-right:20px}',
expected: (prop) =>
`h1{${prop}-bottom:10px;${prop}-top:INITIAL;${prop}-left:20px;${prop}-right:20px}`,
},
{
message:
'should not merge complete box props where one has an inherit property',
fixture: 'h1{box-bottom:10px;box-top:inherit;box-left:20px;box-right:20px}',
expected: (prop) =>
`h1{${prop}-bottom:10px;${prop}-top:inherit;${prop}-left:20px;${prop}-right:20px}`,
},
{
message:
'should not merge complete box props where one has an inherit property (uppercase)',
fixture: 'h1{box-bottom:10px;box-top:INHERIT;box-left:20px;box-right:20px}',
expected: (prop) =>
`h1{${prop}-bottom:10px;${prop}-top:INHERIT;${prop}-left:20px;${prop}-right:20px}`,
},
{
message:
'should not merge box props where there is a mix of reserved properties',
fixture:
'h1{box-bottom:unset;box-top:initial;box-left:inherit;box-right:initial}',
expected: (prop) =>
`h1{${prop}-bottom:unset;${prop}-top:initial;${prop}-left:inherit;${prop}-right:initial}`,
},
{
message:
'should not merge box props where there is a mix of reserved properties (uppercase)',
fixture:
'h1{box-bottom:UNSET;box-top:INITIAL;box-left:INHERIT;box-right:INITIAL}',
expected: (prop) =>
`h1{${prop}-bottom:UNSET;${prop}-top:INITIAL;${prop}-left:INHERIT;${prop}-right:INITIAL}`,
},
{
message: 'should merge box props when they are all unset',
fixture:
'h1{box-bottom:unset;box-top:unset;box-left:unset;box-right:unset}',
expected: 'h1{box:unset}',
},
{
message: 'should merge box props when they are all unset (uppercase)',
fixture:
'h1{box-bottom:UNSET;box-top:UNSET;box-left:UNSET;box-right:UNSET}',
expected: 'h1{box:UNSET}',
},
{
message: 'should merge box props when they are all initial',
fixture:
'h1{box-bottom:initial;box-top:initial;box-left:initial;box-right:initial}',
expected: 'h1{box:initial}',
},
{
message: 'should merge box props when they are all initial (uppercase)',
fixture:
'h1{box-bottom:INITIAL;box-top:INITIAL;box-left:INITIAL;box-right:INITIAL}',
expected: 'h1{box:INITIAL}',
},
{
message: 'should merge box props when they are all inherit',
fixture:
'h1{box-bottom:inherit;box-top:inherit;box-left:inherit;box-right:inherit}',
expected: 'h1{box:inherit}',
},
{
message: 'should merge box props when they are all inherit (uppercase)',
fixture:
'h1{box-bottom:INHERIT;box-top:INHERIT;box-left:INHERIT;box-right:INHERIT}',
expected: 'h1{box:INHERIT}',
},
{
message: 'should not merge box props when one has a revert property',
fixture: 'h1{box:10px;box-left:revert}',
expected: (prop) => `h1{${prop.toLowerCase()}:10px;${prop}-left:revert}`,
},
{
message: 'should handle empty box properties',
fixture: 'h1{box:;}',
expected: (prop) => `h1{${prop}:;}`,
}
);
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
UserModel = getattr(settings, 'FITAPP_USER_MODEL', 'auth.User')
dependencies = [
('fitapp', '0005_upgrade_oauth1_tokens_to_oauth2'),
migrations.swappable_dependency(UserModel),
]
operations = [
migrations.AlterField(
model_name='timeseriesdata',
name='date',
field=models.DateField(help_text=b'The date the data was recorded'),
),
migrations.AlterField(
model_name='timeseriesdata',
name='resource_type',
field=models.ForeignKey(help_text=b'The type of time series data',
to='fitapp.TimeSeriesDataType',
on_delete=models.CASCADE),
),
migrations.AlterField(
model_name='timeseriesdata',
name='user',
field=models.ForeignKey(help_text=b"The data's user",
to=UserModel,
on_delete=models.CASCADE
),
),
migrations.AlterField(
model_name='timeseriesdata',
name='value',
field=models.CharField(default=None, max_length=32, null=True,
help_text=b'The value of the data. This is typically a number, though saved as a string here. The units can be inferred from the data type. For example, for step data the value might be "9783" (the units) would be "steps"'),
),
migrations.AlterField(
model_name='timeseriesdatatype',
name='category',
field=models.IntegerField(
help_text=b'The category of the time series data, one of: 0(foods), 1(activities), 2(sleep), 3(body)',
choices=[(0, b'foods'), (1, b'activities'), (2, b'sleep'), (3, b'body')]),
),
migrations.AlterField(
model_name='timeseriesdatatype',
name='resource',
field=models.CharField(
help_text=b'The specific time series resource. This is the string that will be used for the [resource-path] of the API url referred to in the Fitbit documentation',
max_length=128),
),
migrations.AlterField(
model_name='userfitbit',
name='access_token',
field=models.TextField(help_text=b'The OAuth2 access token'),
),
migrations.AlterField(
model_name='userfitbit',
name='auth_secret',
field=models.TextField(help_text=b'The OAuth2 auth secret'),
),
migrations.AlterField(
model_name='userfitbit',
name='fitbit_user',
field=models.CharField(help_text=b'The fitbit user ID', unique=True,
max_length=32),
),
migrations.AlterField(
model_name='userfitbit',
name='refresh_token',
field=models.TextField(help_text=b'The OAuth2 refresh token'),
),
migrations.AlterField(
model_name='userfitbit',
name='user',
field=models.OneToOneField(to=UserModel, help_text=b'The user',
on_delete=models.CASCADE),
),
]
|
import React from "react";
import { OverlayTrigger, Popover, Button } from "react-bootstrap";
const OptionsPopover = (props) => {
const { editCallback, deleteCallback } = props;
const popoverRight = (
<Popover id="popover-options">
<Popover.Content>
<Button variant="light" size="sm" onClick={editCallback} block="true">
Edit
</Button>
<Button
variant="danger"
size="sm"
className=""
onClick={deleteCallback}
block="true"
>
Delete
</Button>
</Popover.Content>
</Popover>
);
return (
<OverlayTrigger
trigger="click"
placement="right"
overlay={popoverRight}
rootClose
>
<Button bsPrefix="none">
<i className="material-icons">more_vert</i>
</Button>
</OverlayTrigger>
);
};
export default OptionsPopover;
|
from django.contrib import admin
from books.models import Book
admin.site.register(Book)
|
const Manager = require("./lib/Manager");
const Engineer = require("./lib/Engineer");
const Intern = require("./lib/Intern");
const q = require("./lib/questions");
const inquirer = require("inquirer");
const path = require("path");
const fs = require("fs");
const OUTPUT_DIR = path.resolve(__dirname, "output")
const outputPath = path.join(OUTPUT_DIR, "team.html");
const render = require("./lib/htmlRenderer");
const employees = [];
async function init() {
await askForEmployees();
// const employee = new Manager('Name','email','ID','RM');
// employees.push(employee)
const rendered = render(employees);
writeFile(rendered)
}
function writeFile(rendered) {
if (!fs.existsSync(OUTPUT_DIR)){
fs.mkdirSync(OUTPUT_DIR);
}
fs.writeFile(outputPath, rendered, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
}
async function askForEmployees() {
while (true) {
const anotherEmployee = await inquirer.prompt(q.anotherEmployee);
if (!anotherEmployee.anotherEmployee) {
return;
}
const emp = {}
const questions = [q.employeeTitle,q.employeeId,q.employeeEmail]
// const info = await inquirer.prompt(questions);
const name = await inquirer.prompt(q.employeeName);
emp.employeeName = name.employeeName;
const info = await inquirer.prompt(questionsWithName(questions, emp.employeeName));
emp.employeeTitle = info.employeeTitle;
emp.employeeId = info.employeeId;
emp.employeeEmail = info.employeeEmail;
const contact = await askForContact(emp)
emp.employeeContact = contact.employeeContact
employees.push(newEmployee(emp))
}
}
function questionsWithName(questions,name) {
return JSON.parse(JSON.stringify(questions).split("${employeeName}").join(name))
}
async function askForContact(info) {
const employeeContact = q.getEmployeeContact(info.employeeTitle);
const contactQuestion = JSON.parse(
JSON.stringify(q.employeeContact)
.replace('${employeeContact}', employeeContact)
.split("${employeeName}").join(info.employeeName)
);
return await inquirer.prompt(contactQuestion)
}
function newEmployee(emp) {
switch (emp.employeeTitle) {
case 'Manager':
return new Manager(emp.employeeName,emp.employeeId,emp.employeeEmail,emp.employeeContact)
case 'Engineer':
return new Engineer(emp.employeeName,emp.employeeId,emp.employeeEmail,emp.employeeContact)
case 'Intern':
return new Intern(emp.employeeName,emp.employeeId,emp.employeeEmail,emp.employeeContact)
}
}
init();
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
*
* Date: 09 September 2002
* SUMMARY: Test for TypeError on invalid default string value of object
* See ECMA reference at http://bugzilla.mozilla.org/show_bug.cgi?id=167325
*
*/
//-----------------------------------------------------------------------------
var UBound = 0;
var BUGNUMBER = 167325;
var summary = "Test for TypeError on invalid default string value of object";
var TEST_PASSED = 'TypeError';
var TEST_FAILED = 'Generated an error, but NOT a TypeError!';
var TEST_FAILED_BADLY = 'Did not generate ANY error!!!';
var status = '';
var statusitems = [];
var actual = '';
var actualvalues = [];
var expect= '';
var expectedvalues = [];
status = inSection(1);
expect = TEST_PASSED;
actual = TEST_FAILED_BADLY;
/*
* This should generate a TypeError. See ECMA reference
* at http://bugzilla.mozilla.org/show_bug.cgi?id=167325
*/
try
{
var obj = {toString: function() {return new Object();}}
obj == 'abc';
}
catch(e)
{
if (e instanceof TypeError)
actual = TEST_PASSED;
else
actual = TEST_FAILED;
}
addThis();
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function addThis()
{
statusitems[UBound] = status;
actualvalues[UBound] = actual;
expectedvalues[UBound] = expect;
UBound++;
}
function test()
{
enterFunc('test');
printBugNumber(BUGNUMBER);
printStatus(summary);
for (var i=0; i<UBound; i++)
{
reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]);
}
exitFunc ('test');
}
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#define FILE_OPEN_FAILURE (-1)
#define EXIT_IF_FAILED (1)
#define BUF_SIZE (512)
int open_file_read(const char *pathname, unsigned char do_exit);
int open_file_write(const char *pathname, unsigned char do_exit);
void copy_and_process(int read_fd, int write_fd);
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage:\n\t./part1exec filer filew\n\tmake run filer=[filer] filew=[filew]\n");
exit(1);
}
printf("System Programming. Lab 1, part 1. KP51. Maksym Honchar.\n");
printf("Out: Reading from [%s]. Writing to [%s]\n", argv[1], argv[2]);
/* Open file descriptors */
int read_fd = open_file_read(argv[1], EXIT_IF_FAILED);
printf("read_fd is %d\n", read_fd);
int write_fd = open_file_write(argv[2], EXIT_IF_FAILED);
printf("read_fd is %d\n", write_fd);
/* Perform copying and processing data from read_fd to write_fd */
copy_and_process(read_fd, write_fd);
/* Close file descriptors */
close(read_fd);
close(write_fd);
printf("End of the program.\n");
return EXIT_SUCCESS;
}
int open_file_read(const char *pathname, unsigned char do_exit) {
const int flags = O_RDONLY;
int file;
file = open(pathname, flags);
if (FILE_OPEN_FAILURE == file) {
fprintf(stderr, "Out: Cannot open file to read: [%s]. Errno:[%d]. Str:[%s]\n", pathname, errno, strerror(errno));
if (do_exit) {
exit(EXIT_FAILURE);
}
}
return file;
}
int open_file_write(const char *pathname, unsigned char do_exit) {
const int flags = O_WRONLY | O_CREAT | O_EXCL;
const mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; // 0644 mode_t
int file;
file = open(pathname, flags, mode);
if (FILE_OPEN_FAILURE == file) {
fprintf(stderr, "Out: Cannot open/create file to write: [%s]. Errno:[%d]. Str:[%s]\n", pathname, errno, strerror(errno));
if (do_exit) {
exit(EXIT_FAILURE);
}
}
return file;
}
void copy_and_process(int read_fd, int write_fd) {
char read_buffer[BUF_SIZE] = {0}, total_amount_info_buffer[BUF_SIZE] = {0};
ssize_t cur_read_bytes, cur_written_bytes;
ssize_t total_read_bytes = 0, total_written_bytes = 0;
do {
// Read bytes from read_fd file.
cur_read_bytes = read(read_fd, &read_buffer, (size_t)BUF_SIZE);
if (cur_read_bytes < 0) {
fprintf(stderr, "Out: error occured while reading file descriptor [%d]. Errno:[%d]. Str:[%s]\n", read_fd, errno, strerror(errno));
return;
}
if (cur_read_bytes == 0) {
break;
}
// Lower buffer content.
for (ssize_t i = 0; i < cur_read_bytes; i++) {
read_buffer[i] = tolower(read_buffer[i]);
}
// Write content to write_fd file.
cur_written_bytes = write(write_fd, &read_buffer, (size_t)cur_read_bytes);
if (cur_written_bytes < 0) {
fprintf(stderr, "Out: failed to write data to file description [%d]. Errno:[%d]. Str:[%s]\n", write_fd, errno, strerror(errno));
return;
}
if (cur_written_bytes != cur_read_bytes) {
fprintf(stderr, "Out: bytes read and bytes written missmatch.");
return;
}
// Sum total amount of bytes read and written.
total_read_bytes += cur_read_bytes;
total_written_bytes += cur_written_bytes;
} while(cur_read_bytes > 0);
// Write total amount of written/read data. In the end it has to be equal.
sprintf(total_amount_info_buffer, "Bytes written:[%ld]. Bytes read:[%ld].", total_written_bytes, total_read_bytes);
cur_written_bytes = write(write_fd, &total_amount_info_buffer, strlen(total_amount_info_buffer));
if (cur_written_bytes < 0) {
fprintf(stderr, "Out: failed to write data about total amount of written/read data. Errno:[%d]. Str:[%s]\n", errno, strerror(errno));
}
printf("Out: Written data about bytes written/read: %s", total_amount_info_buffer);
}
|
var settings = require('./settings.json'),
connect = require('gulp-connect');
module.exports = {
configuration: settings,
connect: connect
};
|
/***********************************************************************
filename: CEGUISequentialLayoutContainer.h
created: 02/8/2010
author: Martin Preisler
purpose: Defines abstract base class for layout containers
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
*
* 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#ifndef _CEGUISequentialLayoutContainer_h_
#define _CEGUISequentialLayoutContainer_h_
#include "CEGUILayoutContainer.h"
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4251)
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
/*!
\brief
An abstract base class providing common functionality and specifying the
required interface for derived classes.
Sequential Layout Container provide means for automatic positioning of
windows in sequence
*/
class CEGUIEXPORT SequentialLayoutContainer : public LayoutContainer
{
public:
/*************************************************************************
Event name constants
*************************************************************************/
//! Namespace for global events
static const String EventNamespace;
//! fired when child windows get rearranged
static const String EventChildWindowOrderChanged;
/*!
\brief
Constructor for Window base class
\param type
String object holding Window type (usually provided by WindowFactory).
\param name
String object holding unique name for the Window.
*/
SequentialLayoutContainer(const String& type, const String& name);
/*!
\brief
Destructor for Window base class
*/
virtual ~SequentialLayoutContainer(void);
/*!
\brief
Gets the position of given child window
*/
size_t getPositionOfChildWindow(Window* wnd) const;
/*!
\brief
Gets the position of given child window
*/
size_t getPositionOfChildWindow(const String& wnd) const;
/*!
\brief
Gets the child window that currently is at given position
*/
Window* getChildWindowAtPosition(size_t position) const;
/*!
\brief
Swaps windows at given positions
*/
virtual void swapChildWindowPositions(size_t wnd1, size_t wnd2);
/*!
\brief
Swaps positions of given windows
*/
void swapChildWindows(Window* wnd1, Window* wnd2);
/*!
\brief
Swaps positions of given windows
*/
void swapChildWindows(const String& wnd1, Window* wnd2);
/*!
\brief
Swaps positions of given windows
*/
void swapChildWindows(Window* wnd1, const String& wnd2);
/*!
\brief
Swaps positions of given windows
*/
void swapChildWindows(const String& wnd1, const String& wnd2);
/*!
\brief
Moves a window that is alrady child of thi layout container
to given position (if the window is currently in a position
that is smaller than given position, given position is
automatically decremented
*/
virtual void moveChildWindowToPosition(Window* wnd, size_t position);
/*!
\brief
Moves a window that is alrady child of thi layout container
to given position (if the window is currently in a position
that is smaller than given position, given position is
automatically decremented
*/
void moveChildWindowToPosition(const String& wnd, size_t position);
/*!
\brief
Moves a window forward or backward, depending on delta
(-1 moves it backward one step, 1 moves it forward one step)
\param delta
The amount of steps the window will be moved
(old position + delta = new position)
*/
void moveChildWindow(Window* window, int delta = 1);
/*!
\brief
Adds a window to given position
*/
void addChildWindowToPosition(Window* window, size_t position);
/*!
\brief
Adds a window to given position
*/
void addChildWindowToPosition(const String& window, size_t position);
/*!
\brief
Removes a window from given position
*/
void removeChildWindowFromPosition(size_t position);
protected:
/*!
\brief
Handler called when children of this window gets rearranged in any way
\param e
WindowEventArgs object whose 'window' field is set this layout
container.
*/
virtual void onChildWindowOrderChanged(WindowEventArgs& e);
//! @copydoc Window::testClassName_impl
virtual bool testClassName_impl(const String& class_name) const
{
if (class_name == "SequentialLayoutContainer") return true;
return LayoutContainer::testClassName_impl(class_name);
}
};
} // End of CEGUI namespace section
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif // end of guard _CEGUISequentialLayoutContainer_h_
|
/*
* Copyright (C) 2019 Intel Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*/
#ifndef _AOT_RELOC_H_
#define _AOT_RELOC_H_
#include "aot_runtime.h"
#include "aot_intrinsic.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
const char *symbol_name;
void *symbol_addr;
} SymbolMap;
/* clang-format off */
#define REG_SYM(symbol) { #symbol, (void *)symbol }
#if WASM_ENABLE_BULK_MEMORY != 0
#define REG_BULK_MEMORY_SYM() \
REG_SYM(aot_memory_init), \
REG_SYM(aot_data_drop),
#else
#define REG_BULK_MEMORY_SYM()
#endif
#if WASM_ENABLE_SHARED_MEMORY != 0
#include "wasm_shared_memory.h"
#define REG_ATOMIC_WAIT_SYM() \
REG_SYM(wasm_runtime_atomic_wait), \
REG_SYM(wasm_runtime_atomic_notify),
#else
#define REG_ATOMIC_WAIT_SYM()
#endif
#if WASM_ENABLE_REF_TYPES != 0
#define REG_REF_TYPES_SYM() \
REG_SYM(aot_drop_table_seg), \
REG_SYM(aot_table_init), \
REG_SYM(aot_table_copy), \
REG_SYM(aot_table_fill), \
REG_SYM(aot_table_grow),
#else
#define REG_REF_TYPES_SYM()
#endif
#if (WASM_ENABLE_PERF_PROFILING != 0) || (WASM_ENABLE_DUMP_CALL_STACK != 0)
#define REG_AOT_TRACE_SYM() \
REG_SYM(aot_alloc_frame), \
REG_SYM(aot_free_frame),
#else
#define REG_AOT_TRACE_SYM()
#endif
#define REG_INTRINSIC_SYM() \
REG_SYM(aot_intrinsic_fabs_f32), \
REG_SYM(aot_intrinsic_fabs_f64), \
REG_SYM(aot_intrinsic_floor_f32), \
REG_SYM(aot_intrinsic_floor_f64), \
REG_SYM(aot_intrinsic_ceil_f32), \
REG_SYM(aot_intrinsic_ceil_f64), \
REG_SYM(aot_intrinsic_trunc_f32), \
REG_SYM(aot_intrinsic_trunc_f64), \
REG_SYM(aot_intrinsic_rint_f32), \
REG_SYM(aot_intrinsic_rint_f64), \
REG_SYM(aot_intrinsic_sqrt_f32), \
REG_SYM(aot_intrinsic_sqrt_f64), \
REG_SYM(aot_intrinsic_copysign_f32), \
REG_SYM(aot_intrinsic_copysign_f64), \
REG_SYM(aot_intrinsic_fadd_f32), \
REG_SYM(aot_intrinsic_fadd_f64), \
REG_SYM(aot_intrinsic_fsub_f32), \
REG_SYM(aot_intrinsic_fsub_f64), \
REG_SYM(aot_intrinsic_fmul_f32), \
REG_SYM(aot_intrinsic_fmul_f64), \
REG_SYM(aot_intrinsic_fdiv_f32), \
REG_SYM(aot_intrinsic_fdiv_f64), \
REG_SYM(aot_intrinsic_fmin_f32), \
REG_SYM(aot_intrinsic_fmin_f64), \
REG_SYM(aot_intrinsic_fmax_f32), \
REG_SYM(aot_intrinsic_fmax_f64), \
REG_SYM(aot_intrinsic_clz_i32), \
REG_SYM(aot_intrinsic_clz_i64), \
REG_SYM(aot_intrinsic_ctz_i32), \
REG_SYM(aot_intrinsic_ctz_i64), \
REG_SYM(aot_intrinsic_popcnt_i32), \
REG_SYM(aot_intrinsic_popcnt_i64), \
REG_SYM(aot_intrinsic_i32_to_f32), \
REG_SYM(aot_intrinsic_u32_to_f32), \
REG_SYM(aot_intrinsic_i32_to_f64), \
REG_SYM(aot_intrinsic_u32_to_f64), \
REG_SYM(aot_intrinsic_i64_to_f32), \
REG_SYM(aot_intrinsic_u64_to_f32), \
REG_SYM(aot_intrinsic_i64_to_f64), \
REG_SYM(aot_intrinsic_u64_to_f64), \
REG_SYM(aot_intrinsic_f64_to_f32), \
REG_SYM(aot_intrinsic_f64_to_i32), \
REG_SYM(aot_intrinsic_f64_to_u32), \
REG_SYM(aot_intrinsic_f32_to_f64), \
REG_SYM(aot_intrinsic_f32_cmp), \
REG_SYM(aot_intrinsic_f64_cmp), \
#define REG_COMMON_SYMBOLS \
REG_SYM(aot_set_exception_with_id), \
REG_SYM(aot_invoke_native), \
REG_SYM(aot_call_indirect), \
REG_SYM(aot_enlarge_memory), \
REG_SYM(aot_set_exception), \
{ "memset", (void*)aot_memset }, \
{ "memmove", (void*)aot_memmove }, \
{ "memcpy", (void*)aot_memmove }, \
REG_SYM(fmin), \
REG_SYM(fminf), \
REG_SYM(fmax), \
REG_SYM(fmaxf), \
REG_SYM(ceil), \
REG_SYM(ceilf), \
REG_SYM(floor), \
REG_SYM(floorf), \
REG_SYM(trunc), \
REG_SYM(truncf), \
REG_SYM(rint), \
REG_SYM(rintf), \
REG_BULK_MEMORY_SYM() \
REG_ATOMIC_WAIT_SYM() \
REG_REF_TYPES_SYM() \
REG_AOT_TRACE_SYM() \
REG_INTRINSIC_SYM() \
#define CHECK_RELOC_OFFSET(data_size) do { \
if (!check_reloc_offset(target_section_size, \
reloc_offset, data_size, \
error_buf, error_buf_size)) \
return false; \
} while (0)
SymbolMap *
get_target_symbol_map(uint32 *sym_num);
uint32
get_plt_table_size();
void
init_plt_table(uint8 *plt);
void
get_current_target(char *target_buf, uint32 target_buf_size);
bool
apply_relocation(AOTModule *module,
uint8 *target_section_addr, uint32 target_section_size,
uint64 reloc_offset, int64 reloc_addend,
uint32 reloc_type, void *symbol_addr, int32 symbol_index,
char *error_buf, uint32 error_buf_size);
/* clang-format off */
#ifdef __cplusplus
}
#endif
#endif /* end of _AOT_RELOC_H_ */
|
// Doc: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CodeCommit.html
const { error: { catchErrors, wrapErrors } } = require('puffy')
let _codeCommit
const getCodeCommit = () => {
if (!_codeCommit) {
const AWS = require('aws-sdk')
if (process.env.REGION)
AWS.config.update({region:process.env.REGION})
_codeCommit = new AWS.CodeCommit({apiVersion: '2015-04-13'})
}
return _codeCommit
}
const _promisify = fn => (...args) => catchErrors(new Promise((next,fail) => {
const codeCommit = getCodeCommit()
codeCommit[fn](...args, (err,data) => {
if (err)
fail(err)
else
next(data)
})
}))
/**
* Pushes a file to a repo. If the subfolder does not exist, it is created.
*
* @param {String} content
* @param {String} repo
* @param {String} branch Default: 'master'
* @param {String} filePath
* @param {String} email
* @param {String} commitMessage
* @param {String} committer
* @param {String} parentCommitId Required if this is not the first commit in this repo.
*
* @return {[Error]} resp[0].errors
* @return {String} resp[1].commitId
* @return {String} resp[1].blobId
* @return {String} resp[1].treeId
*/
const pushFile = ({ content='', repo, branch='master', filePath, email, commitMessage, committer, parentCommitId }) => catchErrors((async () => {
const errMsg = `Fail to push file ${filePath} to ${repo}:${branch}`
const [errors, resp] = await _promisify('putFile')({
branchName: branch,
fileContent: content,
filePath,
repositoryName: repo,
commitMessage,
email,
name: committer,
parentCommitId
})
if (errors)
throw wrapErrors(errMsg, errors)
return resp
})())
/**
* Lists all repositories in the current account.
*
* @param {String} order Valid values: 'asc' (default), 'desc'
* @param {String} sortBy Valid values: 'name' (default), 'creation_date'
* @param {String} nextToken
*
* @return {[Error]} resp[0].errors
* @return {String} resp[1].count
* @return {String} resp[1].data[].id
* @return {String} resp[1].data[].name
*/
const listRepositories = query => catchErrors((async () => {
const { order, sortBy, nextToken } = query||{}
const errMsg = 'Fail to list repositories'
const [errors, resp] = await _promisify('listRepositories')({
order: order ? order == 'asc' ? 'ascending' : 'descending' : 'ascending',
sortBy,
nextToken
})
if (errors)
throw wrapErrors(errMsg, errors)
if (!resp || !resp.repositories || !resp.repositories.length)
return {
count: 0,
data:[]
}
else
return {
count: resp.repositories.length,
data: resp.repositories.map(r => ({
id: r.repositoryId,
name: r.repositoryName
}))
}
})())
/**
* Gets a repository from the current account.
*
* @param {String} order Valid values: 'asc' (default), 'desc'
* @param {String} sortBy Valid values: 'name' (default), 'creation_date'
* @param {String} nextToken
*
* @return {[Error]} resp[0].errors
* @return {String} resp[1].id
* @return {String} resp[1].name
* @return {String} resp[1].defaultBranch
* @return {String} resp[1].accountId
* @return {String} resp[1].lastModifiedDate
* @return {String} resp[1].creationDate
* @return {String} resp[1].cloneUrlHttp
* @return {String} resp[1].cloneUrlSsh
* @return {String} resp[1].Arn
*/
const getRepository = name => catchErrors((async () => {
if (!name)
return null
const errMsg = `Fail to get repository ${name}`
const [errors, resp] = await _promisify('getRepository')({
repositoryName: name
})
if (errors)
throw wrapErrors(errMsg, errors)
if (!resp || !resp.repositoryMetadata)
return null
else
return {
id: resp.repositoryMetadata.repositoryId,
name: resp.repositoryMetadata.repositoryName,
defaultBranch: resp.repositoryMetadata.defaultBranch,
accountId: resp.repositoryMetadata.accountId,
lastModifiedDate: resp.repositoryMetadata.lastModifiedDate ? new Date(resp.repositoryMetadata.lastModifiedDate) : null,
creationDate: resp.repositoryMetadata.creationDate ? new Date(resp.repositoryMetadata.creationDate) : null,
cloneUrlHttp: resp.repositoryMetadata.cloneUrlHttp,
cloneUrlSsh: resp.repositoryMetadata.cloneUrlSsh,
Arn: resp.repositoryMetadata.Arn
}
})())
module.exports = {
pushFile,
listRepositories,
getRepository
}
|
/**
* @author v.lugovksy
* created on 16.12.2015
*/
(function () {
'use strict';
angular.module('BlurAdmin.pages.dashboard')
.directive('trafficChart', trafficChart);
/** @ngInject */
function trafficChart() {
return {
restrict: 'E',
controller: 'TrafficChartCtrl',
templateUrl: 'app/pages/dashboard/stats/trafficChart/trafficChart.html'
};
}
})();
|
# Check whether an rle pattern contains a self-forcing patch
from pattern_basics import degollify, mat_to_pattern, print_pattern
from gol_agars import find_self_forcing
# Glider; replace by another pattern to check it
rle = """
x = 3, y = 3, rule = B3/S23
3o$o$bo!
"""
# We find and print the largest subpattern that forces itself in all nth preimages, shifted by -shift.
# "No pattern" means the input is an (nth generation) orphan.
# "Empty pattern" means the pattern contains no self-forcing patch with these parameters.
# Note: even though there is no self-forcing patch with n and shift,
# there might be one with k*n and k*shift for some k >= 2.
# Number of iterations n
temp = 1
# Spatial shift
shift = (0,0)
# SAT instance construction method
instance = "sort_network"
#instance = "bisector"
pat = mat_to_pattern(degollify(rle))
print("Input pattern")
print_pattern(pat)
print("Finding maximal self-forcing patch")
print_pattern(find_self_forcing(pat, temp, shift, instance=instance))
|
import * as types from './types';
export function setActiveTab(activeTab = 'Home') {
return {
type: types.SET_ACTIVE_TAB,
activeTab
}
}
|
from .common_voice import CommonVoiceRaw, CommonVoiceRawDataset, \
CommonVoiceEntry, CommonVoiceDataset, load_audio
|
!function(e){function t(i){if(n[i])return n[i].exports;var o=n[i]={exports:{},id:i,loaded:!1};return e[i].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){n(1),n(2),window.jQuery=n(4),n(3),n(5)},function(e,t){},function(e,t){},function(e,t){function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}!function(e){"use strict";function t(e){if(void 0===Function.prototype.name){var t=/function\s([^(]{1,})\(/,n=t.exec(e.toString());return n&&n.length>1?n[1].trim():""}return void 0===e.prototype?e.constructor.name:e.prototype.constructor.name}function n(e){return!!/true/.test(e)||!/false/.test(e)&&(isNaN(1*e)?e:parseFloat(e))}function i(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}var o="6.2.3",r={version:o,_plugins:{},_uuids:[],rtl:function(){return"rtl"===e("html").attr("dir")},plugin:function(e,n){var o=n||t(e),r=i(o);this._plugins[r]=this[o]=e},registerPlugin:function(e,n){var o=n?i(n):t(e.constructor).toLowerCase();e.uuid=this.GetYoDigits(6,o),e.$element.attr("data-"+o)||e.$element.attr("data-"+o,e.uuid),e.$element.data("zfPlugin")||e.$element.data("zfPlugin",e),e.$element.trigger("init.zf."+o),this._uuids.push(e.uuid)},unregisterPlugin:function(e){var n=i(t(e.$element.data("zfPlugin").constructor));this._uuids.splice(this._uuids.indexOf(e.uuid),1),e.$element.removeAttr("data-"+n).removeData("zfPlugin").trigger("destroyed.zf."+n);for(var o in e)e[o]=null},reInit:function(t){var n=t instanceof e;try{if(n)t.each(function(){e(this).data("zfPlugin")._init()});else{var o=typeof t,r=this,s={object:function(t){t.forEach(function(t){t=i(t),e("[data-"+t+"]").foundation("_init")})},string:function(){t=i(t),e("[data-"+t+"]").foundation("_init")},undefined:function(){this.object(Object.keys(r._plugins))}};s[o](t)}}catch(a){console.error(a)}finally{return t}},GetYoDigits:function(e,t){return e=e||6,Math.round(Math.pow(36,e+1)-Math.random()*Math.pow(36,e)).toString(36).slice(1)+(t?"-"+t:"")},reflow:function(t,i){"undefined"==typeof i?i=Object.keys(this._plugins):"string"==typeof i&&(i=[i]);var o=this;e.each(i,function(i,r){var s=o._plugins[r],a=e(t).find("[data-"+r+"]").addBack("[data-"+r+"]");a.each(function(){var t=e(this),i={};if(t.data("zfPlugin"))return void console.warn("Tried to initialize "+r+" on an element that already has a Foundation plugin.");t.attr("data-options")&&t.attr("data-options").split(";").forEach(function(e,t){var o=e.split(":").map(function(e){return e.trim()});o[0]&&(i[o[0]]=n(o[1]))});try{t.data("zfPlugin",new s(e(this),i))}catch(o){console.error(o)}finally{return}})})},getFnName:t,transitionend:function(e){var t,n={transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"otransitionend"},i=document.createElement("div");for(var o in n)"undefined"!=typeof i.style[o]&&(t=n[o]);return t?t:(t=setTimeout(function(){e.triggerHandler("transitionend",[e])},1),"transitionend")}};r.util={throttle:function(e,t){var n=null;return function(){var i=this,o=arguments;null===n&&(n=setTimeout(function(){e.apply(i,o),n=null},t))}}};var s=function(n){var i=typeof n,o=e("meta.foundation-mq"),s=e(".no-js");if(o.length||e('<meta class="foundation-mq">').appendTo(document.head),s.length&&s.removeClass("no-js"),"undefined"===i)r.MediaQuery._init(),r.reflow(this);else{if("string"!==i)throw new TypeError("We're sorry, "+i+" is not a valid parameter. You must use a string representing the method you wish to invoke.");var a=Array.prototype.slice.call(arguments,1),l=this.data("zfPlugin");if(void 0===l||void 0===l[n])throw new ReferenceError("We're sorry, '"+n+"' is not an available method for "+(l?t(l):"this element")+".");1===this.length?l[n].apply(l,a):this.each(function(t,i){l[n].apply(e(i).data("zfPlugin"),a)})}return this};window.Foundation=r,e.fn.foundation=s,function(){Date.now&&window.Date.now||(window.Date.now=Date.now=function(){return(new Date).getTime()});for(var e=["webkit","moz"],t=0;t<e.length&&!window.requestAnimationFrame;++t){var n=e[t];window.requestAnimationFrame=window[n+"RequestAnimationFrame"],window.cancelAnimationFrame=window[n+"CancelAnimationFrame"]||window[n+"CancelRequestAnimationFrame"]}if(/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent)||!window.requestAnimationFrame||!window.cancelAnimationFrame){var i=0;window.requestAnimationFrame=function(e){var t=Date.now(),n=Math.max(i+16,t);return setTimeout(function(){e(i=n)},n-t)},window.cancelAnimationFrame=clearTimeout}window.performance&&window.performance.now||(window.performance={start:Date.now(),now:function(){return Date.now()-this.start}})}(),Function.prototype.bind||(Function.prototype.bind=function(e){if("function"!=typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var t=Array.prototype.slice.call(arguments,1),n=this,i=function(){},o=function(){return n.apply(this instanceof i?this:e,t.concat(Array.prototype.slice.call(arguments)))};return this.prototype&&(i.prototype=this.prototype),o.prototype=new i,o})}(jQuery),!function(e){function t(e,t,i,o){var r,s,a,l,u=n(e);if(t){var c=n(t);s=u.offset.top+u.height<=c.height+c.offset.top,r=u.offset.top>=c.offset.top,a=u.offset.left>=c.offset.left,l=u.offset.left+u.width<=c.width+c.offset.left}else s=u.offset.top+u.height<=u.windowDims.height+u.windowDims.offset.top,r=u.offset.top>=u.windowDims.offset.top,a=u.offset.left>=u.windowDims.offset.left,l=u.offset.left+u.width<=u.windowDims.width;var d=[s,r,a,l];return i?a===l==1:o?r===s==1:-1===d.indexOf(!1)}function n(e,t){if(e=e.length?e[0]:e,e===window||e===document)throw new Error("I'm sorry, Dave. I'm afraid I can't do that.");var n=e.getBoundingClientRect(),i=e.parentNode.getBoundingClientRect(),o=document.body.getBoundingClientRect(),r=window.pageYOffset,s=window.pageXOffset;return{width:n.width,height:n.height,offset:{top:n.top+r,left:n.left+s},parentDims:{width:i.width,height:i.height,offset:{top:i.top+r,left:i.left+s}},windowDims:{width:o.width,height:o.height,offset:{top:r,left:s}}}}function i(e,t,i,o,r,s){var a=n(e),l=t?n(t):null;switch(i){case"top":return{left:Foundation.rtl()?l.offset.left-a.width+l.width:l.offset.left,top:l.offset.top-(a.height+o)};case"left":return{left:l.offset.left-(a.width+r),top:l.offset.top};case"right":return{left:l.offset.left+l.width+r,top:l.offset.top};case"center top":return{left:l.offset.left+l.width/2-a.width/2,top:l.offset.top-(a.height+o)};case"center bottom":return{left:s?r:l.offset.left+l.width/2-a.width/2,top:l.offset.top+l.height+o};case"center left":return{left:l.offset.left-(a.width+r),top:l.offset.top+l.height/2-a.height/2};case"center right":return{left:l.offset.left+l.width+r+1,top:l.offset.top+l.height/2-a.height/2};case"center":return{left:a.windowDims.offset.left+a.windowDims.width/2-a.width/2,top:a.windowDims.offset.top+a.windowDims.height/2-a.height/2};case"reveal":return{left:(a.windowDims.width-a.width)/2,top:a.windowDims.offset.top+o};case"reveal full":return{left:a.windowDims.offset.left,top:a.windowDims.offset.top};case"left bottom":return{left:l.offset.left-(a.width+r),top:l.offset.top+l.height};case"right bottom":return{left:l.offset.left+l.width+r-a.width,top:l.offset.top+l.height};default:return{left:Foundation.rtl()?l.offset.left-a.width+l.width:l.offset.left,top:l.offset.top+l.height+o}}}Foundation.Box={ImNotTouchingYou:t,GetDimensions:n,GetOffsets:i}}(jQuery),!function(e){function t(e){var t={};for(var n in e)t[e[n]]=e[n];return t}var n={9:"TAB",13:"ENTER",27:"ESCAPE",32:"SPACE",37:"ARROW_LEFT",38:"ARROW_UP",39:"ARROW_RIGHT",40:"ARROW_DOWN"},i={},o={keys:t(n),parseKey:function(e){var t=n[e.which||e.keyCode]||String.fromCharCode(e.which).toUpperCase();return e.shiftKey&&(t="SHIFT_"+t),e.ctrlKey&&(t="CTRL_"+t),e.altKey&&(t="ALT_"+t),t},handleKey:function(t,n,o){var r,s,a,l=i[n],u=this.parseKey(t);if(!l)return console.warn("Component not defined!");if(r="undefined"==typeof l.ltr?l:Foundation.rtl()?e.extend({},l.ltr,l.rtl):e.extend({},l.rtl,l.ltr),s=r[u],a=o[s],a&&"function"==typeof a){var c=a.apply();(o.handled||"function"==typeof o.handled)&&o.handled(c)}else(o.unhandled||"function"==typeof o.unhandled)&&o.unhandled()},findFocusable:function(t){return t.find("a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]").filter(function(){return e(this).is(":visible")&&!(e(this).attr("tabindex")<0)})},register:function(e,t){i[e]=t}};Foundation.Keyboard=o}(jQuery),!function(e){function t(e){var t={};return"string"!=typeof e?t:(e=e.trim().slice(1,-1))?t=e.split("&").reduce(function(e,t){var n=t.replace(/\+/g," ").split("="),i=n[0],o=n[1];return i=decodeURIComponent(i),o=void 0===o?null:decodeURIComponent(o),e.hasOwnProperty(i)?Array.isArray(e[i])?e[i].push(o):e[i]=[e[i],o]:e[i]=o,e},{}):t}var n={queries:[],current:"",_init:function(){var n,i=this,o=e(".foundation-mq").css("font-family");n=t(o);for(var r in n)n.hasOwnProperty(r)&&i.queries.push({name:r,value:"only screen and (min-width: "+n[r]+")"});this.current=this._getCurrentSize(),this._watcher()},atLeast:function(e){var t=this.get(e);return!!t&&window.matchMedia(t).matches},get:function(e){for(var t in this.queries)if(this.queries.hasOwnProperty(t)){var n=this.queries[t];if(e===n.name)return n.value}return null},_getCurrentSize:function(){for(var e,t=0;t<this.queries.length;t++){var n=this.queries[t];window.matchMedia(n.value).matches&&(e=n)}return"object"==typeof e?e.name:e},_watcher:function(){var t=this;e(window).on("resize.zf.mediaquery",function(){var n=t._getCurrentSize(),i=t.current;n!==i&&(t.current=n,e(window).trigger("changed.zf.mediaquery",[n,i]))})}};Foundation.MediaQuery=n,window.matchMedia||(window.matchMedia=function(){"use strict";var e=window.styleMedia||window.media;if(!e){var t=document.createElement("style"),n=document.getElementsByTagName("script")[0],i=null;t.type="text/css",t.id="matchmediajs-test",n.parentNode.insertBefore(t,n),i="getComputedStyle"in window&&window.getComputedStyle(t,null)||t.currentStyle,e={matchMedium:function(e){var n="@media "+e+"{ #matchmediajs-test { width: 1px; } }";return t.styleSheet?t.styleSheet.cssText=n:t.textContent=n,"1px"===i.width}}}return function(t){return{matches:e.matchMedium(t||"all"),media:t||"all"}}}()),Foundation.MediaQuery=n}(jQuery),!function(e){function t(e,t,n){function i(a){s||(s=window.performance.now()),r=a-s,n.apply(t),e>r?o=window.requestAnimationFrame(i,t):(window.cancelAnimationFrame(o),t.trigger("finished.zf.animate",[t]).triggerHandler("finished.zf.animate",[t]))}var o,r,s=null;o=window.requestAnimationFrame(i)}function n(t,n,r,s){function a(){t||n.hide(),l(),s&&s.apply(n)}function l(){n[0].style.transitionDuration=0,n.removeClass(u+" "+c+" "+r)}if(n=e(n).eq(0),n.length){var u=t?i[0]:i[1],c=t?o[0]:o[1];l(),n.addClass(r).css("transition","none"),requestAnimationFrame(function(){n.addClass(u),t&&n.show()}),requestAnimationFrame(function(){n[0].offsetWidth,n.css("transition","").addClass(c)}),n.one(Foundation.transitionend(n),a)}}var i=["mui-enter","mui-leave"],o=["mui-enter-active","mui-leave-active"],r={animateIn:function(e,t,i){n(!0,e,t,i)},animateOut:function(e,t,i){n(!1,e,t,i)}};Foundation.Move=t,Foundation.Motion=r}(jQuery),!function(e){var t={Feather:function(t){var n=arguments.length<=1||void 0===arguments[1]?"zf":arguments[1];t.attr("role","menubar");var i=t.find("li").attr({role:"menuitem"}),o="is-"+n+"-submenu",r=o+"-item",s="is-"+n+"-submenu-parent";t.find("a:first").attr("tabindex",0),i.each(function(){var t=e(this),n=t.children("ul");n.length&&(t.addClass(s).attr({"aria-haspopup":!0,"aria-expanded":!1,"aria-label":t.children("a:first").text()}),n.addClass("submenu "+o).attr({"data-submenu":"","aria-hidden":!0,role:"menu"})),t.parent("[data-submenu]").length&&t.addClass("is-submenu-item "+r)})},Burn:function(e,t){var n=(e.find("li").removeAttr("tabindex"),"is-"+t+"-submenu"),i=n+"-item",o="is-"+t+"-submenu-parent";e.find("*").removeClass(n+" "+i+" "+o+" is-submenu-item submenu is-active").removeAttr("data-submenu").css("display","")}};Foundation.Nest=t}(jQuery),!function(e){function t(e,t,n){var i,o,r=this,s=t.duration,a=Object.keys(e.data())[0]||"timer",l=-1;this.isPaused=!1,this.restart=function(){l=-1,clearTimeout(o),this.start()},this.start=function(){this.isPaused=!1,clearTimeout(o),l=0>=l?s:l,e.data("paused",!1),i=Date.now(),o=setTimeout(function(){t.infinite&&r.restart(),n()},l),e.trigger("timerstart.zf."+a)},this.pause=function(){this.isPaused=!0,clearTimeout(o),e.data("paused",!0);var t=Date.now();l-=t-i,e.trigger("timerpaused.zf."+a)}}function n(t,n){function i(){o--,0===o&&n()}var o=t.length;0===o&&n(),t.each(function(){this.complete?i():"undefined"!=typeof this.naturalWidth&&this.naturalWidth>0?i():e(this).one("load",function(){i()})})}Foundation.Timer=t,Foundation.onImagesLoaded=n}(jQuery),function(e){function t(){this.removeEventListener("touchmove",n),this.removeEventListener("touchend",t),u=!1}function n(n){if(e.spotSwipe.preventDefault&&n.preventDefault(),u){var i,o=n.touches[0].pageX,s=(n.touches[0].pageY,r-o);l=(new Date).getTime()-a,Math.abs(s)>=e.spotSwipe.moveThreshold&&l<=e.spotSwipe.timeThreshold&&(i=s>0?"left":"right"),i&&(n.preventDefault(),t.call(this),e(this).trigger("swipe",i).trigger("swipe"+i))}}function i(e){1==e.touches.length&&(r=e.touches[0].pageX,s=e.touches[0].pageY,u=!0,a=(new Date).getTime(),this.addEventListener("touchmove",n,!1),this.addEventListener("touchend",t,!1))}function o(){this.addEventListener&&this.addEventListener("touchstart",i,!1)}e.spotSwipe={version:"1.0.0",enabled:"ontouchstart"in document.documentElement,preventDefault:!1,moveThreshold:75,timeThreshold:200};var r,s,a,l,u=!1;e.event.special.swipe={setup:o},e.each(["left","up","down","right"],function(){e.event.special["swipe"+this]={setup:function(){e(this).on("swipe",e.noop)}}})}(jQuery),!function(e){e.fn.addTouch=function(){this.each(function(n,i){e(i).bind("touchstart touchmove touchend touchcancel",function(){t(event)})});var t=function(e){var t,n=e.changedTouches,i=n[0],o={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup"},r=o[e.type];"MouseEvent"in window&&"function"==typeof window.MouseEvent?t=new window.MouseEvent(r,{bubbles:!0,cancelable:!0,screenX:i.screenX,screenY:i.screenY,clientX:i.clientX,clientY:i.clientY}):(t=document.createEvent("MouseEvent"),t.initMouseEvent(r,!0,!0,window,1,i.screenX,i.screenY,i.clientX,i.clientY,!1,!1,!1,!1,0,null)),i.target.dispatchEvent(t)}}}(jQuery),!function(e){function t(){r(),i(),o(),n()}function n(t){var n=e("[data-yeti-box]"),i=["dropdown","tooltip","reveal"];if(t&&("string"==typeof t?i.push(t):"object"==typeof t&&"string"==typeof t[0]?i.concat(t):console.error("Plugin names must be strings")),n.length){var o=i.map(function(e){return"closeme.zf."+e}).join(" ");e(window).off(o).on(o,function(t,n){var i=t.namespace.split(".")[0],o=e("[data-"+i+"]").not('[data-yeti-box="'+n+'"]');o.each(function(){var t=e(this);t.triggerHandler("close.zf.trigger",[t])})})}}function i(t){var n=void 0,i=e("[data-resize]");i.length&&e(window).off("resize.zf.trigger").on("resize.zf.trigger",function(o){n&&clearTimeout(n),n=setTimeout(function(){s||i.each(function(){e(this).triggerHandler("resizeme.zf.trigger")}),i.attr("data-events","resize")},t||10)})}function o(t){var n=void 0,i=e("[data-scroll]");i.length&&e(window).off("scroll.zf.trigger").on("scroll.zf.trigger",function(o){n&&clearTimeout(n),n=setTimeout(function(){s||i.each(function(){e(this).triggerHandler("scrollme.zf.trigger")}),i.attr("data-events","scroll")},t||10)})}function r(){if(!s)return!1;var t=document.querySelectorAll("[data-resize], [data-scroll], [data-mutate]"),n=function(t){var n=e(t[0].target);switch(n.attr("data-events")){case"resize":n.triggerHandler("resizeme.zf.trigger",[n]);break;case"scroll":n.triggerHandler("scrollme.zf.trigger",[n,window.pageYOffset]);break;default:return!1}};if(t.length)for(var i=0;i<=t.length-1;i++){var o=new s(n);o.observe(t[i],{attributes:!0,childList:!1,characterData:!1,subtree:!1,attributeFilter:["data-events"]})}}var s=function(){for(var e=["WebKit","Moz","O","Ms",""],t=0;t<e.length;t++)if(e[t]+"MutationObserver"in window)return window[e[t]+"MutationObserver"];return!1}(),a=function(t,n){t.data(n).split(" ").forEach(function(i){e("#"+i)["close"===n?"trigger":"triggerHandler"](n+".zf.trigger",[t])})};e(document).on("click.zf.trigger","[data-open]",function(){a(e(this),"open")}),e(document).on("click.zf.trigger","[data-close]",function(){var t=e(this).data("close");t?a(e(this),"close"):e(this).trigger("close.zf.trigger")}),e(document).on("click.zf.trigger","[data-toggle]",function(){a(e(this),"toggle")}),e(document).on("close.zf.trigger","[data-closable]",function(t){t.stopPropagation();var n=e(this).data("closable");""!==n?Foundation.Motion.animateOut(e(this),n,function(){e(this).trigger("closed.zf")}):e(this).fadeOut().trigger("closed.zf")}),e(document).on("focus.zf.trigger blur.zf.trigger","[data-toggle-focus]",function(){var t=e(this).data("toggle-focus");e("#"+t).triggerHandler("toggle.zf.trigger",[e(this)])}),e(window).load(function(){t()}),Foundation.IHearYou=t}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i){var o=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];n(this,t),this.$element=i,this.options=e.extend({},t.defaults,this.$element.data(),o),this._init(),Foundation.registerPlugin(this,"Abide")}return i(t,[{key:"_init",value:function(){this.$inputs=this.$element.find("input, textarea, select"),this._events()}},{key:"_events",value:function(){var t=this;this.$element.off(".abide").on("reset.zf.abide",function(){t.resetForm()}).on("submit.zf.abide",function(){return t.validateForm()}),"fieldChange"===this.options.validateOn&&this.$inputs.off("change.zf.abide").on("change.zf.abide",function(n){t.validateInput(e(n.target))}),this.options.liveValidate&&this.$inputs.off("input.zf.abide").on("input.zf.abide",function(n){t.validateInput(e(n.target))})}},{key:"_reflow",value:function(){this._init()}},{key:"requiredCheck",value:function(e){if(!e.attr("required"))return!0;var t=!0;switch(e[0].type){case"checkbox":t=e[0].checked;break;case"select":case"select-one":case"select-multiple":var n=e.find("option:selected");n.length&&n.val()||(t=!1);break;default:e.val()&&e.val().length||(t=!1)}return t}},{key:"findFormError",value:function(e){var t=e.siblings(this.options.formErrorSelector);return t.length||(t=e.parent().find(this.options.formErrorSelector)),t}},{key:"findLabel",value:function(e){var t=e[0].id,n=this.$element.find('label[for="'+t+'"]');return n.length?n:e.closest("label")}},{key:"findRadioLabels",value:function(t){var n=this,i=t.map(function(t,i){var o=i.id,r=n.$element.find('label[for="'+o+'"]');return r.length||(r=e(i).closest("label")),r[0]});return e(i)}},{key:"addErrorClasses",value:function(e){var t=this.findLabel(e),n=this.findFormError(e);t.length&&t.addClass(this.options.labelErrorClass),n.length&&n.addClass(this.options.formErrorClass),e.addClass(this.options.inputErrorClass).attr("data-invalid","")}},{key:"removeRadioErrorClasses",value:function(e){var t=this.$element.find(':radio[name="'+e+'"]'),n=this.findRadioLabels(t),i=this.findFormError(t);n.length&&n.removeClass(this.options.labelErrorClass),i.length&&i.removeClass(this.options.formErrorClass),t.removeClass(this.options.inputErrorClass).removeAttr("data-invalid")}},{key:"removeErrorClasses",value:function(e){if("radio"==e[0].type)return this.removeRadioErrorClasses(e.attr("name"));var t=this.findLabel(e),n=this.findFormError(e);t.length&&t.removeClass(this.options.labelErrorClass),n.length&&n.removeClass(this.options.formErrorClass),e.removeClass(this.options.inputErrorClass).removeAttr("data-invalid")}},{key:"validateInput",value:function(e){var t=this.requiredCheck(e),n=!1,i=!0,o=e.attr("data-validator"),r=!0;if(e.is("[data-abide-ignore]")||e.is('[type="hidden"]'))return!0;switch(e[0].type){case"radio":n=this.validateRadio(e.attr("name"));break;case"checkbox":n=t;break;case"select":case"select-one":case"select-multiple":n=t;break;default:n=this.validateText(e)}o&&(i=this.matchValidation(e,o,e.attr("required"))),e.attr("data-equalto")&&(r=this.options.validators.equalTo(e));var s=-1===[t,n,i,r].indexOf(!1),a=(s?"valid":"invalid")+".zf.abide";return this[s?"removeErrorClasses":"addErrorClasses"](e),e.trigger(a,[e]),s}},{key:"validateForm",value:function(){var t=[],n=this;this.$inputs.each(function(){t.push(n.validateInput(e(this)))});var i=-1===t.indexOf(!1);return this.$element.find("[data-abide-error]").css("display",i?"none":"block"),this.$element.trigger((i?"formvalid":"forminvalid")+".zf.abide",[this.$element]),i}},{key:"validateText",value:function(e,t){t=t||e.attr("pattern")||e.attr("type");var n=e.val(),i=!1;return n.length?i=this.options.patterns.hasOwnProperty(t)?this.options.patterns[t].test(n):t===e.attr("type")||new RegExp(t).test(n):e.prop("required")||(i=!0),i}},{key:"validateRadio",value:function(t){var n=this.$element.find(':radio[name="'+t+'"]'),i=!1,o=!1;return n.each(function(t,n){e(n).attr("required")&&(o=!0)}),o||(i=!0),i||n.each(function(t,n){e(n).prop("checked")&&(i=!0)}),i}},{key:"matchValidation",value:function(e,t,n){var i=this;n=!!n;var o=t.split(" ").map(function(t){return i.options.validators[t](e,n,e.parent())});return-1===o.indexOf(!1)}},{key:"resetForm",value:function(){var t=this.$element,n=this.options;e("."+n.labelErrorClass,t).not("small").removeClass(n.labelErrorClass),e("."+n.inputErrorClass,t).not("small").removeClass(n.inputErrorClass),e(n.formErrorSelector+"."+n.formErrorClass).removeClass(n.formErrorClass),t.find("[data-abide-error]").css("display","none"),e(":input",t).not(":button, :submit, :reset, :hidden, :radio, :checkbox, [data-abide-ignore]").val("").removeAttr("data-invalid"),e(":input:radio",t).not("[data-abide-ignore]").prop("checked",!1).removeAttr("data-invalid"),e(":input:checkbox",t).not("[data-abide-ignore]").prop("checked",!1).removeAttr("data-invalid"),t.trigger("formreset.zf.abide",[t])}},{key:"destroy",value:function(){var t=this;this.$element.off(".abide").find("[data-abide-error]").css("display","none"),this.$inputs.off(".abide").each(function(){t.removeErrorClasses(e(this))}),Foundation.unregisterPlugin(this)}}]),t}();t.defaults={validateOn:"fieldChange",labelErrorClass:"is-invalid-label",inputErrorClass:"is-invalid-input",formErrorSelector:".form-error",formErrorClass:"is-visible",liveValidate:!1,patterns:{alpha:/^[a-zA-Z]+$/,alpha_numeric:/^[a-zA-Z0-9]+$/,integer:/^[-+]?\d+$/,number:/^[-+]?\d*(?:[\.\,]\d+)?$/,card:/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/,cvv:/^([0-9]){3,4}$/,email:/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/,url:/^(https?|ftp|file|ssh):\/\/(((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/,domain:/^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,8}$/,datetime:/^([0-2][0-9]{3})\-([0-1][0-9])\-([0-3][0-9])T([0-5][0-9])\:([0-5][0-9])\:([0-5][0-9])(Z|([\-\+]([0-1][0-9])\:00))$/,date:/(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))$/,time:/^(0[0-9]|1[0-9]|2[0-3])(:[0-5][0-9]){2}$/,dateISO:/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/,month_day_year:/^(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.]\d{4}$/,day_month_year:/^(0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.]\d{4}$/,color:/^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/},validators:{equalTo:function(t,n,i){return e("#"+t.attr("data-equalto")).val()===t.val()}}},Foundation.plugin(t,"Abide")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i,o){n(this,t),this.$element=i,this.options=e.extend({},t.defaults,this.$element.data(),o),this._init(),Foundation.registerPlugin(this,"Accordion"),Foundation.Keyboard.register("Accordion",{ENTER:"toggle",SPACE:"toggle",ARROW_DOWN:"next",ARROW_UP:"previous"})}return i(t,[{key:"_init",value:function(){this.$element.attr("role","tablist"),this.$tabs=this.$element.children("li, [data-accordion-item]"),this.$tabs.each(function(t,n){var i=e(n),o=i.children("[data-tab-content]"),r=o[0].id||Foundation.GetYoDigits(6,"accordion"),s=n.id||r+"-label";i.find("a:first").attr({"aria-controls":r,role:"tab",id:s,"aria-expanded":!1,"aria-selected":!1}),o.attr({role:"tabpanel","aria-labelledby":s,"aria-hidden":!0,id:r})});var t=this.$element.find(".is-active").children("[data-tab-content]");t.length&&this.down(t,!0),this._events()}},{key:"_events",value:function(){var t=this;this.$tabs.each(function(){var n=e(this),i=n.children("[data-tab-content]");i.length&&n.children("a").off("click.zf.accordion keydown.zf.accordion").on("click.zf.accordion",function(e){e.preventDefault(),n.hasClass("is-active")?(t.options.allowAllClosed||n.siblings().hasClass("is-active"))&&t.up(i):t.down(i)}).on("keydown.zf.accordion",function(e){Foundation.Keyboard.handleKey(e,"Accordion",{toggle:function(){t.toggle(i)},next:function(){var e=n.next().find("a").focus();t.options.multiExpand||e.trigger("click.zf.accordion")},previous:function(){var e=n.prev().find("a").focus();t.options.multiExpand||e.trigger("click.zf.accordion")},handled:function(){e.preventDefault(),e.stopPropagation()}})})})}},{key:"toggle",value:function(e){if(e.parent().hasClass("is-active")){if(!this.options.allowAllClosed&&!e.parent().siblings().hasClass("is-active"))return;this.up(e)}else this.down(e)}},{key:"down",value:function(t,n){var i=this;if(!this.options.multiExpand&&!n){var o=this.$element.children(".is-active").children("[data-tab-content]");o.length&&this.up(o)}t.attr("aria-hidden",!1).parent("[data-tab-content]").addBack().parent().addClass("is-active"),t.slideDown(this.options.slideSpeed,function(){i.$element.trigger("down.zf.accordion",[t])}),e("#"+t.attr("aria-labelledby")).attr({"aria-expanded":!0,"aria-selected":!0})}},{key:"up",value:function(t){var n=t.parent().siblings(),i=this,o=this.options.multiExpand?n.hasClass("is-active"):t.parent().hasClass("is-active");(this.options.allowAllClosed||o)&&(t.slideUp(i.options.slideSpeed,function(){i.$element.trigger("up.zf.accordion",[t])}),t.attr("aria-hidden",!0).parent().removeClass("is-active"),e("#"+t.attr("aria-labelledby")).attr({"aria-expanded":!1,"aria-selected":!1}))}},{key:"destroy",value:function(){this.$element.find("[data-tab-content]").stop(!0).slideUp(0).css("display",""),this.$element.find("a").off(".zf.accordion"),Foundation.unregisterPlugin(this)}}]),t}();t.defaults={slideSpeed:250,multiExpand:!1,allowAllClosed:!1},Foundation.plugin(t,"Accordion")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i,o){n(this,t),this.$element=i,this.options=e.extend({},t.defaults,this.$element.data(),o),Foundation.Nest.Feather(this.$element,"accordion"),this._init(),Foundation.registerPlugin(this,"AccordionMenu"),Foundation.Keyboard.register("AccordionMenu",{ENTER:"toggle",SPACE:"toggle",ARROW_RIGHT:"open",ARROW_UP:"up",ARROW_DOWN:"down",ARROW_LEFT:"close",ESCAPE:"closeAll",TAB:"down",SHIFT_TAB:"up"})}return i(t,[{key:"_init",value:function(){this.$element.find("[data-submenu]").not(".is-active").slideUp(0),this.$element.attr({role:"tablist","aria-multiselectable":this.options.multiOpen}),this.$menuLinks=this.$element.find(".is-accordion-submenu-parent"),this.$menuLinks.each(function(){var t=this.id||Foundation.GetYoDigits(6,"acc-menu-link"),n=e(this),i=n.children("[data-submenu]"),o=i[0].id||Foundation.GetYoDigits(6,"acc-menu"),r=i.hasClass("is-active");n.attr({"aria-controls":o,"aria-expanded":r,role:"tab",id:t}),i.attr({"aria-labelledby":t,"aria-hidden":!r,role:"tabpanel",id:o})});var t=this.$element.find(".is-active");if(t.length){var n=this;t.each(function(){n.down(e(this))})}this._events()}},{key:"_events",value:function(){var t=this;this.$element.find("li").each(function(){var n=e(this).children("[data-submenu]");n.length&&e(this).children("a").off("click.zf.accordionMenu").on("click.zf.accordionMenu",function(e){e.preventDefault(),t.toggle(n)})}).on("keydown.zf.accordionmenu",function(n){var i,o,r=e(this),s=r.parent("ul").children("li"),a=r.children("[data-submenu]");s.each(function(t){return e(this).is(r)?(i=s.eq(Math.max(0,t-1)).find("a").first(),o=s.eq(Math.min(t+1,s.length-1)).find("a").first(),
e(this).children("[data-submenu]:visible").length&&(o=r.find("li:first-child").find("a").first()),e(this).is(":first-child")?i=r.parents("li").first().find("a").first():i.children("[data-submenu]:visible").length&&(i=i.find("li:last-child").find("a").first()),void(e(this).is(":last-child")&&(o=r.parents("li").first().next("li").find("a").first()))):void 0}),Foundation.Keyboard.handleKey(n,"AccordionMenu",{open:function(){a.is(":hidden")&&(t.down(a),a.find("li").first().find("a").first().focus())},close:function(){a.length&&!a.is(":hidden")?t.up(a):r.parent("[data-submenu]").length&&(t.up(r.parent("[data-submenu]")),r.parents("li").first().find("a").first().focus())},up:function(){return i.attr("tabindex",-1).focus(),!0},down:function(){return o.attr("tabindex",-1).focus(),!0},toggle:function(){r.children("[data-submenu]").length&&t.toggle(r.children("[data-submenu]"))},closeAll:function(){t.hideAll()},handled:function(e){e&&n.preventDefault(),n.stopImmediatePropagation()}})})}},{key:"hideAll",value:function(){this.$element.find("[data-submenu]").slideUp(this.options.slideSpeed)}},{key:"toggle",value:function(e){e.is(":animated")||(e.is(":hidden")?this.down(e):this.up(e))}},{key:"down",value:function(e){var t=this;this.options.multiOpen||this.up(this.$element.find(".is-active").not(e.parentsUntil(this.$element).add(e))),e.addClass("is-active").attr({"aria-hidden":!1}).parent(".is-accordion-submenu-parent").attr({"aria-expanded":!0}),e.slideDown(t.options.slideSpeed,function(){t.$element.trigger("down.zf.accordionMenu",[e])})}},{key:"up",value:function(e){var t=this;e.slideUp(t.options.slideSpeed,function(){t.$element.trigger("up.zf.accordionMenu",[e])});var n=e.find("[data-submenu]").slideUp(0).addBack().attr("aria-hidden",!0);n.parent(".is-accordion-submenu-parent").attr("aria-expanded",!1)}},{key:"destroy",value:function(){this.$element.find("[data-submenu]").slideDown(0).css("display",""),this.$element.find("a").off("click.zf.accordionMenu"),Foundation.Nest.Burn(this.$element,"accordion"),Foundation.unregisterPlugin(this)}}]),t}();t.defaults={slideSpeed:250,multiOpen:!0},Foundation.plugin(t,"AccordionMenu")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i,o){n(this,t),this.$element=i,this.options=e.extend({},t.defaults,this.$element.data(),o),Foundation.Nest.Feather(this.$element,"drilldown"),this._init(),Foundation.registerPlugin(this,"Drilldown"),Foundation.Keyboard.register("Drilldown",{ENTER:"open",SPACE:"open",ARROW_RIGHT:"next",ARROW_UP:"up",ARROW_DOWN:"down",ARROW_LEFT:"previous",ESCAPE:"close",TAB:"down",SHIFT_TAB:"up"})}return i(t,[{key:"_init",value:function(){this.$submenuAnchors=this.$element.find("li.is-drilldown-submenu-parent").children("a"),this.$submenus=this.$submenuAnchors.parent("li").children("[data-submenu]"),this.$menuItems=this.$element.find("li").not(".js-drilldown-back").attr("role","menuitem").find("a"),this._prepareMenu(),this._keyboardEvents()}},{key:"_prepareMenu",value:function(){var t=this;this.$submenuAnchors.each(function(){var n=e(this),i=n.parent();t.options.parentLink&&n.clone().prependTo(i.children("[data-submenu]")).wrap('<li class="is-submenu-parent-item is-submenu-item is-drilldown-submenu-item" role="menu-item"></li>'),n.data("savedHref",n.attr("href")).removeAttr("href"),n.children("[data-submenu]").attr({"aria-hidden":!0,tabindex:0,role:"menu"}),t._events(n)}),this.$submenus.each(function(){var n=e(this),i=n.find(".js-drilldown-back");i.length||n.prepend(t.options.backButton),t._back(n)}),this.$element.parent().hasClass("is-drilldown")||(this.$wrapper=e(this.options.wrapper).addClass("is-drilldown"),this.$wrapper=this.$element.wrap(this.$wrapper).parent().css(this._getMaxDims()))}},{key:"_events",value:function(t){var n=this;t.off("click.zf.drilldown").on("click.zf.drilldown",function(i){if(e(i.target).parentsUntil("ul","li").hasClass("is-drilldown-submenu-parent")&&(i.stopImmediatePropagation(),i.preventDefault()),n._show(t.parent("li")),n.options.closeOnClick){var o=e("body");o.off(".zf.drilldown").on("click.zf.drilldown",function(t){t.target===n.$element[0]||e.contains(n.$element[0],t.target)||(t.preventDefault(),n._hideAll(),o.off(".zf.drilldown"))})}})}},{key:"_keyboardEvents",value:function(){var t=this;this.$menuItems.add(this.$element.find(".js-drilldown-back > a")).on("keydown.zf.drilldown",function(n){var i,o,r=e(this),s=r.parent("li").parent("ul").children("li").children("a");s.each(function(t){return e(this).is(r)?(i=s.eq(Math.max(0,t-1)),void(o=s.eq(Math.min(t+1,s.length-1)))):void 0}),Foundation.Keyboard.handleKey(n,"Drilldown",{next:function(){return r.is(t.$submenuAnchors)?(t._show(r.parent("li")),r.parent("li").one(Foundation.transitionend(r),function(){r.parent("li").find("ul li a").filter(t.$menuItems).first().focus()}),!0):void 0},previous:function(){return t._hide(r.parent("li").parent("ul")),r.parent("li").parent("ul").one(Foundation.transitionend(r),function(){setTimeout(function(){r.parent("li").parent("ul").parent("li").children("a").first().focus()},1)}),!0},up:function(){return i.focus(),!0},down:function(){return o.focus(),!0},close:function(){t._back()},open:function(){return r.is(t.$menuItems)?r.is(t.$submenuAnchors)&&(t._show(r.parent("li")),r.parent("li").one(Foundation.transitionend(r),function(){r.parent("li").find("ul li a").filter(t.$menuItems).first().focus()})):(t._hide(r.parent("li").parent("ul")),r.parent("li").parent("ul").one(Foundation.transitionend(r),function(){setTimeout(function(){r.parent("li").parent("ul").parent("li").children("a").first().focus()},1)})),!0},handled:function(e){e&&n.preventDefault(),n.stopImmediatePropagation()}})})}},{key:"_hideAll",value:function(){var e=this.$element.find(".is-drilldown-submenu.is-active").addClass("is-closing");e.one(Foundation.transitionend(e),function(t){e.removeClass("is-active is-closing")}),this.$element.trigger("closed.zf.drilldown")}},{key:"_back",value:function(e){var t=this;e.off("click.zf.drilldown"),e.children(".js-drilldown-back").on("click.zf.drilldown",function(n){n.stopImmediatePropagation(),t._hide(e)})}},{key:"_menuLinkEvents",value:function(){var e=this;this.$menuItems.not(".is-drilldown-submenu-parent").off("click.zf.drilldown").on("click.zf.drilldown",function(t){setTimeout(function(){e._hideAll()},0)})}},{key:"_show",value:function(e){e.children("[data-submenu]").addClass("is-active"),this.$element.trigger("open.zf.drilldown",[e])}},{key:"_hide",value:function(e){e.addClass("is-closing").one(Foundation.transitionend(e),function(){e.removeClass("is-active is-closing"),e.blur()}),e.trigger("hide.zf.drilldown",[e])}},{key:"_getMaxDims",value:function(){var t=0,n={};return this.$submenus.add(this.$element).each(function(){var n=e(this).children("li").length;t=n>t?n:t}),n["min-height"]=t*this.$menuItems[0].getBoundingClientRect().height+"px",n["max-width"]=this.$element[0].getBoundingClientRect().width+"px",n}},{key:"destroy",value:function(){this._hideAll(),Foundation.Nest.Burn(this.$element,"drilldown"),this.$element.unwrap().find(".js-drilldown-back, .is-submenu-parent-item").remove().end().find(".is-active, .is-closing, .is-drilldown-submenu").removeClass("is-active is-closing is-drilldown-submenu").end().find("[data-submenu]").removeAttr("aria-hidden tabindex role"),this.$submenuAnchors.each(function(){e(this).off(".zf.drilldown")}),this.$element.find("a").each(function(){var t=e(this);t.data("savedHref")&&t.attr("href",t.data("savedHref")).removeData("savedHref")}),Foundation.unregisterPlugin(this)}}]),t}();t.defaults={backButton:'<li class="js-drilldown-back"><a tabindex="0">Back</a></li>',wrapper:"<div></div>",parentLink:!1,closeOnClick:!1},Foundation.plugin(t,"Drilldown")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i,o){n(this,t),this.$element=i,this.options=e.extend({},t.defaults,this.$element.data(),o),this._init(),Foundation.registerPlugin(this,"Dropdown"),Foundation.Keyboard.register("Dropdown",{ENTER:"open",SPACE:"open",ESCAPE:"close",TAB:"tab_forward",SHIFT_TAB:"tab_backward"})}return i(t,[{key:"_init",value:function(){var t=this.$element.attr("id");this.$anchor=e('[data-toggle="'+t+'"]')||e('[data-open="'+t+'"]'),this.$anchor.attr({"aria-controls":t,"data-is-focus":!1,"data-yeti-box":t,"aria-haspopup":!0,"aria-expanded":!1}),this.options.positionClass=this.getPositionClass(),this.counter=4,this.usedPositions=[],this.$element.attr({"aria-hidden":"true","data-yeti-box":t,"data-resize":t,"aria-labelledby":this.$anchor[0].id||Foundation.GetYoDigits(6,"dd-anchor")}),this._events()}},{key:"getPositionClass",value:function(){var e=this.$element[0].className.match(/(top|left|right|bottom)/g);e=e?e[0]:"";var t=/float-(\S+)\s/.exec(this.$anchor[0].className);t=t?t[1]:"";var n=t?t+" "+e:e;return n}},{key:"_reposition",value:function(e){this.usedPositions.push(e?e:"bottom"),!e&&this.usedPositions.indexOf("top")<0?this.$element.addClass("top"):"top"===e&&this.usedPositions.indexOf("bottom")<0?this.$element.removeClass(e):"left"===e&&this.usedPositions.indexOf("right")<0?this.$element.removeClass(e).addClass("right"):"right"===e&&this.usedPositions.indexOf("left")<0?this.$element.removeClass(e).addClass("left"):!e&&this.usedPositions.indexOf("top")>-1&&this.usedPositions.indexOf("left")<0?this.$element.addClass("left"):"top"===e&&this.usedPositions.indexOf("bottom")>-1&&this.usedPositions.indexOf("left")<0?this.$element.removeClass(e).addClass("left"):"left"===e&&this.usedPositions.indexOf("right")>-1&&this.usedPositions.indexOf("bottom")<0?this.$element.removeClass(e):"right"===e&&this.usedPositions.indexOf("left")>-1&&this.usedPositions.indexOf("bottom")<0?this.$element.removeClass(e):this.$element.removeClass(e),this.classChanged=!0,this.counter--}},{key:"_setPosition",value:function(){if("false"===this.$anchor.attr("aria-expanded"))return!1;var e=this.getPositionClass(),t=Foundation.Box.GetDimensions(this.$element),n=(Foundation.Box.GetDimensions(this.$anchor),"left"===e?"left":"right"===e?"left":"top"),i="top"===n?"height":"width";if("height"===i?this.options.vOffset:this.options.hOffset,t.width>=t.windowDims.width||!this.counter&&!Foundation.Box.ImNotTouchingYou(this.$element))return this.$element.offset(Foundation.Box.GetOffsets(this.$element,this.$anchor,"center bottom",this.options.vOffset,this.options.hOffset,!0)).css({width:t.windowDims.width-2*this.options.hOffset,height:"auto"}),this.classChanged=!0,!1;for(this.$element.offset(Foundation.Box.GetOffsets(this.$element,this.$anchor,e,this.options.vOffset,this.options.hOffset));!Foundation.Box.ImNotTouchingYou(this.$element,!1,!0)&&this.counter;)this._reposition(e),this._setPosition()}},{key:"_events",value:function(){var t=this;this.$element.on({"open.zf.trigger":this.open.bind(this),"close.zf.trigger":this.close.bind(this),"toggle.zf.trigger":this.toggle.bind(this),"resizeme.zf.trigger":this._setPosition.bind(this)}),this.options.hover&&(this.$anchor.off("mouseenter.zf.dropdown mouseleave.zf.dropdown").on("mouseenter.zf.dropdown",function(){clearTimeout(t.timeout),t.timeout=setTimeout(function(){t.open(),t.$anchor.data("hover",!0)},t.options.hoverDelay)}).on("mouseleave.zf.dropdown",function(){clearTimeout(t.timeout),t.timeout=setTimeout(function(){t.close(),t.$anchor.data("hover",!1)},t.options.hoverDelay)}),this.options.hoverPane&&this.$element.off("mouseenter.zf.dropdown mouseleave.zf.dropdown").on("mouseenter.zf.dropdown",function(){clearTimeout(t.timeout)}).on("mouseleave.zf.dropdown",function(){clearTimeout(t.timeout),t.timeout=setTimeout(function(){t.close(),t.$anchor.data("hover",!1)},t.options.hoverDelay)})),this.$anchor.add(this.$element).on("keydown.zf.dropdown",function(n){var i=e(this),o=Foundation.Keyboard.findFocusable(t.$element);Foundation.Keyboard.handleKey(n,"Dropdown",{tab_forward:function(){t.$element.find(":focus").is(o.eq(-1))&&(t.options.trapFocus?(o.eq(0).focus(),n.preventDefault()):t.close())},tab_backward:function(){(t.$element.find(":focus").is(o.eq(0))||t.$element.is(":focus"))&&(t.options.trapFocus?(o.eq(-1).focus(),n.preventDefault()):t.close())},open:function(){i.is(t.$anchor)&&(t.open(),t.$element.attr("tabindex",-1).focus(),n.preventDefault())},close:function(){t.close(),t.$anchor.focus()}})})}},{key:"_addBodyHandler",value:function(){var t=e(document.body).not(this.$element),n=this;t.off("click.zf.dropdown").on("click.zf.dropdown",function(e){n.$anchor.is(e.target)||n.$anchor.find(e.target).length||n.$element.find(e.target).length||(n.close(),t.off("click.zf.dropdown"))})}},{key:"open",value:function(){if(this.$element.trigger("closeme.zf.dropdown",this.$element.attr("id")),this.$anchor.addClass("hover").attr({"aria-expanded":!0}),this._setPosition(),this.$element.addClass("is-open").attr({"aria-hidden":!1}),this.options.autoFocus){var e=Foundation.Keyboard.findFocusable(this.$element);e.length&&e.eq(0).focus()}this.options.closeOnClick&&this._addBodyHandler(),this.$element.trigger("show.zf.dropdown",[this.$element])}},{key:"close",value:function(){if(!this.$element.hasClass("is-open"))return!1;if(this.$element.removeClass("is-open").attr({"aria-hidden":!0}),this.$anchor.removeClass("hover").attr("aria-expanded",!1),this.classChanged){var e=this.getPositionClass();e&&this.$element.removeClass(e),this.$element.addClass(this.options.positionClass).css({height:"",width:""}),this.classChanged=!1,this.counter=4,this.usedPositions.length=0}this.$element.trigger("hide.zf.dropdown",[this.$element])}},{key:"toggle",value:function(){if(this.$element.hasClass("is-open")){if(this.$anchor.data("hover"))return;this.close()}else this.open()}},{key:"destroy",value:function(){this.$element.off(".zf.trigger").hide(),this.$anchor.off(".zf.dropdown"),Foundation.unregisterPlugin(this)}}]),t}();t.defaults={hoverDelay:250,hover:!1,hoverPane:!1,vOffset:1,hOffset:1,positionClass:"",trapFocus:!1,autoFocus:!1,closeOnClick:!1},Foundation.plugin(t,"Dropdown")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i,o){n(this,t),this.$element=i,this.options=e.extend({},t.defaults,this.$element.data(),o),Foundation.Nest.Feather(this.$element,"dropdown"),this._init(),Foundation.registerPlugin(this,"DropdownMenu"),Foundation.Keyboard.register("DropdownMenu",{ENTER:"open",SPACE:"open",ARROW_RIGHT:"next",ARROW_UP:"up",ARROW_DOWN:"down",ARROW_LEFT:"previous",ESCAPE:"close"})}return i(t,[{key:"_init",value:function(){var e=this.$element.find("li.is-dropdown-submenu-parent");this.$element.children(".is-dropdown-submenu-parent").children(".is-dropdown-submenu").addClass("first-sub"),this.$menuItems=this.$element.find('[role="menuitem"]'),this.$tabs=this.$element.children('[role="menuitem"]'),this.$tabs.find("ul.is-dropdown-submenu").addClass(this.options.verticalClass),this.$element.hasClass(this.options.rightClass)||"right"===this.options.alignment||Foundation.rtl()||this.$element.parents(".top-bar-right").is("*")?(this.options.alignment="right",e.addClass("opens-left")):e.addClass("opens-right"),this.changed=!1,this._events()}},{key:"_events",value:function(){var t=this,n="ontouchstart"in window||"undefined"!=typeof window.ontouchstart,i="is-dropdown-submenu-parent",o=function(o){var r=e(o.target).parentsUntil("ul","."+i),s=r.hasClass(i),a="true"===r.attr("data-is-click");if(r.children(".is-dropdown-submenu"),s)if(a){if(!t.options.closeOnClick||!t.options.clickOpen&&!n||t.options.forceFollow&&n)return;o.stopImmediatePropagation(),o.preventDefault(),t._hide(r)}else o.preventDefault(),o.stopImmediatePropagation(),t._show(r.children(".is-dropdown-submenu")),r.add(r.parentsUntil(t.$element,"."+i)).attr("data-is-click",!0)};(this.options.clickOpen||n)&&this.$menuItems.on("click.zf.dropdownmenu touchstart.zf.dropdownmenu",o),this.options.disableHover||this.$menuItems.on("mouseenter.zf.dropdownmenu",function(n){var o=e(this),r=o.hasClass(i);r&&(clearTimeout(t.delay),t.delay=setTimeout(function(){t._show(o.children(".is-dropdown-submenu"))},t.options.hoverDelay))}).on("mouseleave.zf.dropdownmenu",function(n){var o=e(this),r=o.hasClass(i);if(r&&t.options.autoclose){if("true"===o.attr("data-is-click")&&t.options.clickOpen)return!1;clearTimeout(t.delay),t.delay=setTimeout(function(){t._hide(o)},t.options.closingTime)}}),this.$menuItems.on("keydown.zf.dropdownmenu",function(n){var i,o,r=e(n.target).parentsUntil("ul",'[role="menuitem"]'),s=t.$tabs.index(r)>-1,a=s?t.$tabs:r.siblings("li").add(r);a.each(function(t){return e(this).is(r)?(i=a.eq(t-1),void(o=a.eq(t+1))):void 0});var l=function(){r.is(":last-child")||(o.children("a:first").focus(),n.preventDefault())},u=function(){i.children("a:first").focus(),n.preventDefault()},c=function(){var e=r.children("ul.is-dropdown-submenu");e.length&&(t._show(e),r.find("li > a:first").focus(),n.preventDefault())},d=function(){var e=r.parent("ul").parent("li");e.children("a:first").focus(),t._hide(e),n.preventDefault()},f={open:c,close:function(){t._hide(t.$element),t.$menuItems.find("a:first").focus(),n.preventDefault()},handled:function(){n.stopImmediatePropagation()}};s?t.$element.hasClass(t.options.verticalClass)?"left"===t.options.alignment?e.extend(f,{down:l,up:u,next:c,previous:d}):e.extend(f,{down:l,up:u,next:d,previous:c}):e.extend(f,{next:l,previous:u,down:c,up:d}):"left"===t.options.alignment?e.extend(f,{next:c,previous:d,down:l,up:u}):e.extend(f,{next:d,previous:c,down:l,up:u}),Foundation.Keyboard.handleKey(n,"DropdownMenu",f)})}},{key:"_addBodyHandler",value:function(){var t=e(document.body),n=this;t.off("mouseup.zf.dropdownmenu touchend.zf.dropdownmenu").on("mouseup.zf.dropdownmenu touchend.zf.dropdownmenu",function(e){var i=n.$element.find(e.target);i.length||(n._hide(),t.off("mouseup.zf.dropdownmenu touchend.zf.dropdownmenu"))})}},{key:"_show",value:function(t){var n=this.$tabs.index(this.$tabs.filter(function(n,i){return e(i).find(t).length>0})),i=t.parent("li.is-dropdown-submenu-parent").siblings("li.is-dropdown-submenu-parent");this._hide(i,n),t.css("visibility","hidden").addClass("js-dropdown-active").attr({"aria-hidden":!1}).parent("li.is-dropdown-submenu-parent").addClass("is-active").attr({"aria-expanded":!0});var o=Foundation.Box.ImNotTouchingYou(t,null,!0);if(!o){var r="left"===this.options.alignment?"-right":"-left",s=t.parent(".is-dropdown-submenu-parent");s.removeClass("opens"+r).addClass("opens-"+this.options.alignment),o=Foundation.Box.ImNotTouchingYou(t,null,!0),o||s.removeClass("opens-"+this.options.alignment).addClass("opens-inner"),this.changed=!0}t.css("visibility",""),this.options.closeOnClick&&this._addBodyHandler(),this.$element.trigger("show.zf.dropdownmenu",[t])}},{key:"_hide",value:function(e,t){var n;n=e&&e.length?e:void 0!==t?this.$tabs.not(function(e,n){return e===t}):this.$element;var i=n.hasClass("is-active")||n.find(".is-active").length>0;if(i){if(n.find("li.is-active").add(n).attr({"aria-expanded":!1,"data-is-click":!1}).removeClass("is-active"),n.find("ul.js-dropdown-active").attr({"aria-hidden":!0}).removeClass("js-dropdown-active"),this.changed||n.find("opens-inner").length){var o="left"===this.options.alignment?"right":"left";n.find("li.is-dropdown-submenu-parent").add(n).removeClass("opens-inner opens-"+this.options.alignment).addClass("opens-"+o),this.changed=!1}this.$element.trigger("hide.zf.dropdownmenu",[n])}}},{key:"destroy",value:function(){this.$menuItems.off(".zf.dropdownmenu").removeAttr("data-is-click").removeClass("is-right-arrow is-left-arrow is-down-arrow opens-right opens-left opens-inner"),e(document.body).off(".zf.dropdownmenu"),Foundation.Nest.Burn(this.$element,"dropdown"),Foundation.unregisterPlugin(this)}}]),t}();t.defaults={disableHover:!1,autoclose:!0,hoverDelay:50,clickOpen:!1,closingTime:500,alignment:"left",closeOnClick:!0,verticalClass:"vertical",rightClass:"align-right",forceFollow:!0},Foundation.plugin(t,"DropdownMenu")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i,o){n(this,t),this.$element=i,this.options=e.extend({},t.defaults,this.$element.data(),o),this._init(),Foundation.registerPlugin(this,"Equalizer")}return i(t,[{key:"_init",value:function(){var t=this.$element.attr("data-equalizer")||"",n=this.$element.find('[data-equalizer-watch="'+t+'"]');this.$watched=n.length?n:this.$element.find("[data-equalizer-watch]"),this.$element.attr("data-resize",t||Foundation.GetYoDigits(6,"eq")),this.hasNested=this.$element.find("[data-equalizer]").length>0,this.isNested=this.$element.parentsUntil(document.body,"[data-equalizer]").length>0,this.isOn=!1,this._bindHandler={onResizeMeBound:this._onResizeMe.bind(this),onPostEqualizedBound:this._onPostEqualized.bind(this)};var i,o=this.$element.find("img");this.options.equalizeOn?(i=this._checkMQ(),e(window).on("changed.zf.mediaquery",this._checkMQ.bind(this))):this._events(),(void 0!==i&&i===!1||void 0===i)&&(o.length?Foundation.onImagesLoaded(o,this._reflow.bind(this)):this._reflow())}},{key:"_pauseEvents",value:function(){this.isOn=!1,this.$element.off({".zf.equalizer":this._bindHandler.onPostEqualizedBound,"resizeme.zf.trigger":this._bindHandler.onResizeMeBound})}},{key:"_onResizeMe",value:function(e){this._reflow()}},{key:"_onPostEqualized",value:function(e){e.target!==this.$element[0]&&this._reflow()}},{key:"_events",value:function(){this._pauseEvents(),this.hasNested?this.$element.on("postequalized.zf.equalizer",this._bindHandler.onPostEqualizedBound):this.$element.on("resizeme.zf.trigger",this._bindHandler.onResizeMeBound),this.isOn=!0}},{key:"_checkMQ",value:function(){var e=!Foundation.MediaQuery.atLeast(this.options.equalizeOn);return e?this.isOn&&(this._pauseEvents(),this.$watched.css("height","auto")):this.isOn||this._events(),e}},{key:"_killswitch",value:function(){}},{key:"_reflow",value:function(){return!this.options.equalizeOnStack&&this._isStacked()?(this.$watched.css("height","auto"),!1):void(this.options.equalizeByRow?this.getHeightsByRow(this.applyHeightByRow.bind(this)):this.getHeights(this.applyHeight.bind(this)))}},{key:"_isStacked",value:function(){return this.$watched[0].getBoundingClientRect().top!==this.$watched[1].getBoundingClientRect().top}},{key:"getHeights",value:function(e){for(var t=[],n=0,i=this.$watched.length;i>n;n++)this.$watched[n].style.height="auto",t.push(this.$watched[n].offsetHeight);e(t)}},{key:"getHeightsByRow",value:function(t){var n=this.$watched.length?this.$watched.first().offset().top:0,i=[],o=0;i[o]=[];for(var r=0,s=this.$watched.length;s>r;r++){this.$watched[r].style.height="auto";var a=e(this.$watched[r]).offset().top;a!=n&&(o++,i[o]=[],n=a),i[o].push([this.$watched[r],this.$watched[r].offsetHeight])}for(var l=0,u=i.length;u>l;l++){var c=e(i[l]).map(function(){return this[1]}).get(),d=Math.max.apply(null,c);i[l].push(d)}t(i)}},{key:"applyHeight",value:function(e){var t=Math.max.apply(null,e);this.$element.trigger("preequalized.zf.equalizer"),this.$watched.css("height",t),this.$element.trigger("postequalized.zf.equalizer")}},{key:"applyHeightByRow",value:function(t){this.$element.trigger("preequalized.zf.equalizer");for(var n=0,i=t.length;i>n;n++){var o=t[n].length,r=t[n][o-1];if(2>=o)e(t[n][0][0]).css({height:"auto"});else{this.$element.trigger("preequalizedrow.zf.equalizer");for(var s=0,a=o-1;a>s;s++)e(t[n][s][0]).css({height:r});this.$element.trigger("postequalizedrow.zf.equalizer")}}this.$element.trigger("postequalized.zf.equalizer")}},{key:"destroy",value:function(){this._pauseEvents(),this.$watched.css("height","auto"),Foundation.unregisterPlugin(this)}}]),t}();t.defaults={equalizeOnStack:!0,equalizeByRow:!1,equalizeOn:""},Foundation.plugin(t,"Equalizer")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i,o){n(this,t),this.$element=i,this.options=e.extend({},t.defaults,o),this.rules=[],this.currentPath="",this._init(),this._events(),Foundation.registerPlugin(this,"Interchange")}return i(t,[{key:"_init",value:function(){this._addBreakpoints(),this._generateRules(),this._reflow()}},{key:"_events",value:function(){e(window).on("resize.zf.interchange",Foundation.util.throttle(this._reflow.bind(this),50))}},{key:"_reflow",value:function(){var e;for(var t in this.rules)if(this.rules.hasOwnProperty(t)){var n=this.rules[t];window.matchMedia(n.query).matches&&(e=n)}e&&this.replace(e.path)}},{key:"_addBreakpoints",value:function(){for(var e in Foundation.MediaQuery.queries)if(Foundation.MediaQuery.queries.hasOwnProperty(e)){var n=Foundation.MediaQuery.queries[e];t.SPECIAL_QUERIES[n.name]=n.value}}},{key:"_generateRules",value:function(e){var n,i=[];n=this.options.rules?this.options.rules:this.$element.data("interchange").match(/\[.*?\]/g);for(var o in n)if(n.hasOwnProperty(o)){var r=n[o].slice(1,-1).split(", "),s=r.slice(0,-1).join(""),a=r[r.length-1];t.SPECIAL_QUERIES[a]&&(a=t.SPECIAL_QUERIES[a]),i.push({path:s,query:a})}this.rules=i}},{key:"replace",value:function(t){if(this.currentPath!==t){var n=this,i="replaced.zf.interchange";"IMG"===this.$element[0].nodeName?this.$element.attr("src",t).load(function(){n.currentPath=t}).trigger(i):t.match(/\.(gif|jpg|jpeg|png|svg|tiff)([?#].*)?/i)?this.$element.css({"background-image":"url("+t+")"}).trigger(i):e.get(t,function(o){n.$element.html(o).trigger(i),e(o).foundation(),n.currentPath=t})}}},{key:"destroy",value:function(){}}]),t}();t.defaults={rules:null},t.SPECIAL_QUERIES={landscape:"screen and (orientation: landscape)",portrait:"screen and (orientation: portrait)",retina:"only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dpi), only screen and (min-resolution: 2dppx)"},Foundation.plugin(t,"Interchange")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i,o){n(this,t),this.$element=i,this.options=e.extend({},t.defaults,this.$element.data(),o),this._init(),Foundation.registerPlugin(this,"Magellan")}return i(t,[{key:"_init",value:function(){var t=this.$element[0].id||Foundation.GetYoDigits(6,"magellan");this.$targets=e("[data-magellan-target]"),this.$links=this.$element.find("a"),this.$element.attr({"data-resize":t,"data-scroll":t,id:t}),this.$active=e(),this.scrollPos=parseInt(window.pageYOffset,10),this._events()}},{key:"calcPoints",value:function(){var t=this,n=document.body,i=document.documentElement;this.points=[],this.winHeight=Math.round(Math.max(window.innerHeight,i.clientHeight)),this.docHeight=Math.round(Math.max(n.scrollHeight,n.offsetHeight,i.clientHeight,i.scrollHeight,i.offsetHeight)),this.$targets.each(function(){var n=e(this),i=Math.round(n.offset().top-t.options.threshold);n.targetPoint=i,t.points.push(i)})}},{key:"_events",value:function(){var t=this;e("html, body"),{duration:t.options.animationDuration,easing:t.options.animationEasing},e(window).one("load",function(){t.options.deepLinking&&location.hash&&t.scrollToLoc(location.hash),t.calcPoints(),t._updateActive()}),this.$element.on({"resizeme.zf.trigger":this.reflow.bind(this),"scrollme.zf.trigger":this._updateActive.bind(this)}).on("click.zf.magellan",'a[href^="#"]',function(e){e.preventDefault();var n=this.getAttribute("href");t.scrollToLoc(n)})}},{key:"scrollToLoc",value:function(t){var n=Math.round(e(t).offset().top-this.options.threshold/2-this.options.barOffset);e("html, body").stop(!0).animate({scrollTop:n},this.options.animationDuration,this.options.animationEasing)}},{key:"reflow",value:function(){this.calcPoints(),this._updateActive()}},{key:"_updateActive",value:function(){var e,t=parseInt(window.pageYOffset,10);if(t+this.winHeight===this.docHeight)e=this.points.length-1;else if(t<this.points[0])e=0;else{var n=this.scrollPos<t,i=this,o=this.points.filter(function(e,o){return n?e-i.options.barOffset<=t:e-i.options.barOffset-i.options.threshold<=t});e=o.length?o.length-1:0}if(this.$active.removeClass(this.options.activeClass),this.$active=this.$links.eq(e).addClass(this.options.activeClass),this.options.deepLinking){var r=this.$active[0].getAttribute("href");window.history.pushState?window.history.pushState(null,null,r):window.location.hash=r}this.scrollPos=t,this.$element.trigger("update.zf.magellan",[this.$active])}},{key:"destroy",value:function(){if(this.$element.off(".zf.trigger .zf.magellan").find("."+this.options.activeClass).removeClass(this.options.activeClass),this.options.deepLinking){var e=this.$active[0].getAttribute("href");window.location.hash.replace(e,"")}Foundation.unregisterPlugin(this)}}]),t}();t.defaults={animationDuration:500,animationEasing:"linear",threshold:50,activeClass:"active",deepLinking:!1,barOffset:0},Foundation.plugin(t,"Magellan")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i,o){n(this,t),this.$element=i,this.options=e.extend({},t.defaults,this.$element.data(),o),this.$lastTrigger=e(),this.$triggers=e(),this._init(),this._events(),Foundation.registerPlugin(this,"OffCanvas")}return i(t,[{key:"_init",value:function(){var t=this.$element.attr("id");if(this.$element.attr("aria-hidden","true"),this.$triggers=e(document).find('[data-open="'+t+'"], [data-close="'+t+'"], [data-toggle="'+t+'"]').attr("aria-expanded","false").attr("aria-controls",t),this.options.closeOnClick)if(e(".js-off-canvas-exit").length)this.$exiter=e(".js-off-canvas-exit");else{var n=document.createElement("div");n.setAttribute("class","js-off-canvas-exit"),e("[data-off-canvas-content]").append(n),this.$exiter=e(n)}this.options.isRevealed=this.options.isRevealed||new RegExp(this.options.revealClass,"g").test(this.$element[0].className),this.options.isRevealed&&(this.options.revealOn=this.options.revealOn||this.$element[0].className.match(/(reveal-for-medium|reveal-for-large)/g)[0].split("-")[2],this._setMQChecker()),this.options.transitionTime||(this.options.transitionTime=1e3*parseFloat(window.getComputedStyle(e("[data-off-canvas-wrapper]")[0]).transitionDuration))}},{key:"_events",value:function(){this.$element.off(".zf.trigger .zf.offcanvas").on({"open.zf.trigger":this.open.bind(this),"close.zf.trigger":this.close.bind(this),"toggle.zf.trigger":this.toggle.bind(this),"keydown.zf.offcanvas":this._handleKeyboard.bind(this)}),this.options.closeOnClick&&this.$exiter.length&&this.$exiter.on({"click.zf.offcanvas":this.close.bind(this)})}},{key:"_setMQChecker",value:function(){var t=this;e(window).on("changed.zf.mediaquery",function(){Foundation.MediaQuery.atLeast(t.options.revealOn)?t.reveal(!0):t.reveal(!1)}).one("load.zf.offcanvas",function(){Foundation.MediaQuery.atLeast(t.options.revealOn)&&t.reveal(!0);
})}},{key:"reveal",value:function(e){var t=this.$element.find("[data-close]");e?(this.close(),this.isRevealed=!0,this.$element.off("open.zf.trigger toggle.zf.trigger"),t.length&&t.hide()):(this.isRevealed=!1,this.$element.on({"open.zf.trigger":this.open.bind(this),"toggle.zf.trigger":this.toggle.bind(this)}),t.length&&t.show())}},{key:"open",value:function(t,n){if(!this.$element.hasClass("is-open")&&!this.isRevealed){var i=this;e(document.body),this.options.forceTop&&e("body").scrollTop(0),Foundation.Move(this.options.transitionTime,this.$element,function(){e("[data-off-canvas-wrapper]").addClass("is-off-canvas-open is-open-"+i.options.position),i.$element.addClass("is-open")}),this.$triggers.attr("aria-expanded","true"),this.$element.attr("aria-hidden","false").trigger("opened.zf.offcanvas"),this.options.closeOnClick&&this.$exiter.addClass("is-visible"),n&&(this.$lastTrigger=n),this.options.autoFocus&&this.$element.one(Foundation.transitionend(this.$element),function(){i.$element.find("a, button").eq(0).focus()}),this.options.trapFocus&&(e("[data-off-canvas-content]").attr("tabindex","-1"),this._trapFocus())}}},{key:"_trapFocus",value:function(){var e=Foundation.Keyboard.findFocusable(this.$element),t=e.eq(0),n=e.eq(-1);e.off(".zf.offcanvas").on("keydown.zf.offcanvas",function(e){9!==e.which&&9!==e.keycode||(e.target!==n[0]||e.shiftKey||(e.preventDefault(),t.focus()),e.target===t[0]&&e.shiftKey&&(e.preventDefault(),n.focus()))})}},{key:"close",value:function(t){if(this.$element.hasClass("is-open")&&!this.isRevealed){var n=this;e("[data-off-canvas-wrapper]").removeClass("is-off-canvas-open is-open-"+n.options.position),n.$element.removeClass("is-open"),this.$element.attr("aria-hidden","true").trigger("closed.zf.offcanvas"),this.options.closeOnClick&&this.$exiter.removeClass("is-visible"),this.$triggers.attr("aria-expanded","false"),this.options.trapFocus&&e("[data-off-canvas-content]").removeAttr("tabindex")}}},{key:"toggle",value:function(e,t){this.$element.hasClass("is-open")?this.close(e,t):this.open(e,t)}},{key:"_handleKeyboard",value:function(e){27===e.which&&(e.stopPropagation(),e.preventDefault(),this.close(),this.$lastTrigger.focus())}},{key:"destroy",value:function(){this.close(),this.$element.off(".zf.trigger .zf.offcanvas"),this.$exiter.off(".zf.offcanvas"),Foundation.unregisterPlugin(this)}}]),t}();t.defaults={closeOnClick:!0,transitionTime:0,position:"left",forceTop:!0,isRevealed:!1,revealOn:null,autoFocus:!0,revealClass:"reveal-for-",trapFocus:!1},Foundation.plugin(t,"OffCanvas")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i,o){n(this,t),this.$element=i,this.options=e.extend({},t.defaults,this.$element.data(),o),this._init(),Foundation.registerPlugin(this,"Orbit"),Foundation.Keyboard.register("Orbit",{ltr:{ARROW_RIGHT:"next",ARROW_LEFT:"previous"},rtl:{ARROW_LEFT:"next",ARROW_RIGHT:"previous"}})}return i(t,[{key:"_init",value:function(){this.$wrapper=this.$element.find("."+this.options.containerClass),this.$slides=this.$element.find("."+this.options.slideClass);var e=this.$element.find("img"),t=this.$slides.filter(".is-active");t.length||this.$slides.eq(0).addClass("is-active"),this.options.useMUI||this.$slides.addClass("no-motionui"),e.length?Foundation.onImagesLoaded(e,this._prepareForOrbit.bind(this)):this._prepareForOrbit(),this.options.bullets&&this._loadBullets(),this._events(),this.options.autoPlay&&this.$slides.length>1&&this.geoSync(),this.options.accessible&&this.$wrapper.attr("tabindex",0)}},{key:"_loadBullets",value:function(){this.$bullets=this.$element.find("."+this.options.boxOfBullets).find("button")}},{key:"geoSync",value:function(){var e=this;this.timer=new Foundation.Timer(this.$element,{duration:this.options.timerDelay,infinite:!1},function(){e.changeSlide(!0)}),this.timer.start()}},{key:"_prepareForOrbit",value:function(){var e=this;this._setWrapperHeight(function(t){e._setSlideHeight(t)})}},{key:"_setWrapperHeight",value:function(t){var n,i=0,o=0;this.$slides.each(function(){n=this.getBoundingClientRect().height,e(this).attr("data-slide",o),o&&e(this).css({position:"relative",display:"none"}),i=n>i?n:i,o++}),o===this.$slides.length&&(this.$wrapper.css({height:i}),t(i))}},{key:"_setSlideHeight",value:function(t){this.$slides.each(function(){e(this).css("max-height",t)})}},{key:"_events",value:function(){var t=this;if(this.$slides.length>1){if(this.options.swipe&&this.$slides.off("swipeleft.zf.orbit swiperight.zf.orbit").on("swipeleft.zf.orbit",function(e){e.preventDefault(),t.changeSlide(!0)}).on("swiperight.zf.orbit",function(e){e.preventDefault(),t.changeSlide(!1)}),this.options.autoPlay&&(this.$slides.on("click.zf.orbit",function(){t.$element.data("clickedOn",!t.$element.data("clickedOn")),t.timer[t.$element.data("clickedOn")?"pause":"start"]()}),this.options.pauseOnHover&&this.$element.on("mouseenter.zf.orbit",function(){t.timer.pause()}).on("mouseleave.zf.orbit",function(){t.$element.data("clickedOn")||t.timer.start()})),this.options.navButtons){var n=this.$element.find("."+this.options.nextClass+", ."+this.options.prevClass);n.attr("tabindex",0).on("click.zf.orbit touchend.zf.orbit",function(n){n.preventDefault(),t.changeSlide(e(this).hasClass(t.options.nextClass))})}this.options.bullets&&this.$bullets.on("click.zf.orbit touchend.zf.orbit",function(){if(/is-active/g.test(this.className))return!1;var n=e(this).data("slide"),i=n>t.$slides.filter(".is-active").data("slide"),o=t.$slides.eq(n);t.changeSlide(i,o,n)}),this.$wrapper.add(this.$bullets).on("keydown.zf.orbit",function(n){Foundation.Keyboard.handleKey(n,"Orbit",{next:function(){t.changeSlide(!0)},previous:function(){t.changeSlide(!1)},handled:function(){e(n.target).is(t.$bullets)&&t.$bullets.filter(".is-active").focus()}})})}}},{key:"changeSlide",value:function(e,t,n){var i=this.$slides.filter(".is-active").eq(0);if(/mui/g.test(i[0].className))return!1;var o,r=this.$slides.first(),s=this.$slides.last(),a=e?"Right":"Left",l=e?"Left":"Right",u=this;o=t?t:e?this.options.infiniteWrap?i.next("."+this.options.slideClass).length?i.next("."+this.options.slideClass):r:i.next("."+this.options.slideClass):this.options.infiniteWrap?i.prev("."+this.options.slideClass).length?i.prev("."+this.options.slideClass):s:i.prev("."+this.options.slideClass),o.length&&(this.options.bullets&&(n=n||this.$slides.index(o),this._updateBullets(n)),this.options.useMUI?(Foundation.Motion.animateIn(o.addClass("is-active").css({position:"absolute",top:0}),this.options["animInFrom"+a],function(){o.css({position:"relative",display:"block"}).attr("aria-live","polite")}),Foundation.Motion.animateOut(i.removeClass("is-active"),this.options["animOutTo"+l],function(){i.removeAttr("aria-live"),u.options.autoPlay&&!u.timer.isPaused&&u.timer.restart()})):(i.removeClass("is-active is-in").removeAttr("aria-live").hide(),o.addClass("is-active is-in").attr("aria-live","polite").show(),this.options.autoPlay&&!this.timer.isPaused&&this.timer.restart()),this.$element.trigger("slidechange.zf.orbit",[o]))}},{key:"_updateBullets",value:function(e){var t=this.$element.find("."+this.options.boxOfBullets).find(".is-active").removeClass("is-active").blur(),n=t.find("span:last").detach();this.$bullets.eq(e).addClass("is-active").append(n)}},{key:"destroy",value:function(){this.$element.off(".zf.orbit").find("*").off(".zf.orbit").end().hide(),Foundation.unregisterPlugin(this)}}]),t}();t.defaults={bullets:!0,navButtons:!0,animInFromRight:"slide-in-right",animOutToRight:"slide-out-right",animInFromLeft:"slide-in-left",animOutToLeft:"slide-out-left",autoPlay:!0,timerDelay:5e3,infiniteWrap:!0,swipe:!0,pauseOnHover:!0,accessible:!0,containerClass:"orbit-container",slideClass:"orbit-slide",boxOfBullets:"orbit-bullets",nextClass:"orbit-next",prevClass:"orbit-previous",useMUI:!0},Foundation.plugin(t,"Orbit")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i,o){n(this,t),this.$element=e(i),this.rules=this.$element.data("responsive-menu"),this.currentMq=null,this.currentPlugin=null,this._init(),this._events(),Foundation.registerPlugin(this,"ResponsiveMenu")}return i(t,[{key:"_init",value:function(){if("string"==typeof this.rules){for(var t={},n=this.rules.split(" "),i=0;i<n.length;i++){var r=n[i].split("-"),s=r.length>1?r[0]:"small",a=r.length>1?r[1]:r[0];null!==o[a]&&(t[s]=o[a])}this.rules=t}e.isEmptyObject(this.rules)||this._checkMediaQueries()}},{key:"_events",value:function(){var t=this;e(window).on("changed.zf.mediaquery",function(){t._checkMediaQueries()})}},{key:"_checkMediaQueries",value:function(){var t,n=this;e.each(this.rules,function(e){Foundation.MediaQuery.atLeast(e)&&(t=e)}),t&&(this.currentPlugin instanceof this.rules[t].plugin||(e.each(o,function(e,t){n.$element.removeClass(t.cssClass)}),this.$element.addClass(this.rules[t].cssClass),this.currentPlugin&&this.currentPlugin.destroy(),this.currentPlugin=new this.rules[t].plugin(this.$element,{})))}},{key:"destroy",value:function(){this.currentPlugin.destroy(),e(window).off(".zf.ResponsiveMenu"),Foundation.unregisterPlugin(this)}}]),t}();t.defaults={};var o={dropdown:{cssClass:"dropdown",plugin:Foundation._plugins["dropdown-menu"]||null},drilldown:{cssClass:"drilldown",plugin:Foundation._plugins.drilldown||null},accordion:{cssClass:"accordion-menu",plugin:Foundation._plugins["accordion-menu"]||null}};Foundation.plugin(t,"ResponsiveMenu")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i,o){n(this,t),this.$element=e(i),this.options=e.extend({},t.defaults,this.$element.data(),o),this._init(),this._events(),Foundation.registerPlugin(this,"ResponsiveToggle")}return i(t,[{key:"_init",value:function(){var t=this.$element.data("responsive-toggle");t||console.error("Your tab bar needs an ID of a Menu as the value of data-tab-bar."),this.$targetMenu=e("#"+t),this.$toggler=this.$element.find("[data-toggle]"),this._update()}},{key:"_events",value:function(){this._updateMqHandler=this._update.bind(this),e(window).on("changed.zf.mediaquery",this._updateMqHandler),this.$toggler.on("click.zf.responsiveToggle",this.toggleMenu.bind(this))}},{key:"_update",value:function(){Foundation.MediaQuery.atLeast(this.options.hideFor)?(this.$element.hide(),this.$targetMenu.show()):(this.$element.show(),this.$targetMenu.hide())}},{key:"toggleMenu",value:function(){Foundation.MediaQuery.atLeast(this.options.hideFor)||(this.$targetMenu.toggle(0),this.$element.trigger("toggled.zf.responsiveToggle"))}},{key:"destroy",value:function(){this.$element.off(".zf.responsiveToggle"),this.$toggler.off(".zf.responsiveToggle"),e(window).off("changed.zf.mediaquery",this._updateMqHandler),Foundation.unregisterPlugin(this)}}]),t}();t.defaults={hideFor:"medium"},Foundation.plugin(t,"ResponsiveToggle")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){function t(){return/iP(ad|hone|od).*OS/.test(window.navigator.userAgent)}function o(){return/Android/.test(window.navigator.userAgent)}function r(){return t()||o()}var s=function(){function t(i,o){n(this,t),this.$element=i,this.options=e.extend({},t.defaults,this.$element.data(),o),this._init(),Foundation.registerPlugin(this,"Reveal"),Foundation.Keyboard.register("Reveal",{ENTER:"open",SPACE:"open",ESCAPE:"close",TAB:"tab_forward",SHIFT_TAB:"tab_backward"})}return i(t,[{key:"_init",value:function(){this.id=this.$element.attr("id"),this.isActive=!1,this.cached={mq:Foundation.MediaQuery.current},this.isMobile=r(),this.$anchor=e(e('[data-open="'+this.id+'"]').length?'[data-open="'+this.id+'"]':'[data-toggle="'+this.id+'"]'),this.$anchor.attr({"aria-controls":this.id,"aria-haspopup":!0,tabindex:0}),(this.options.fullScreen||this.$element.hasClass("full"))&&(this.options.fullScreen=!0,this.options.overlay=!1),this.options.overlay&&!this.$overlay&&(this.$overlay=this._makeOverlay(this.id)),this.$element.attr({role:"dialog","aria-hidden":!0,"data-yeti-box":this.id,"data-resize":this.id}),this.$overlay?this.$element.detach().appendTo(this.$overlay):(this.$element.detach().appendTo(e("body")),this.$element.addClass("without-overlay")),this._events(),this.options.deepLink&&window.location.hash==="#"+this.id&&e(window).one("load.zf.reveal",this.open.bind(this))}},{key:"_makeOverlay",value:function(t){var n=e("<div></div>").addClass("reveal-overlay").appendTo("body");return n}},{key:"_updatePosition",value:function(){var t,n,i=this.$element.outerWidth(),o=e(window).width(),r=this.$element.outerHeight(),s=e(window).height();t="auto"===this.options.hOffset?parseInt((o-i)/2,10):parseInt(this.options.hOffset,10),n="auto"===this.options.vOffset?r>s?parseInt(Math.min(100,s/10),10):parseInt((s-r)/4,10):parseInt(this.options.vOffset,10),this.$element.css({top:n+"px"}),this.$overlay&&"auto"===this.options.hOffset||(this.$element.css({left:t+"px"}),this.$element.css({margin:"0px"}))}},{key:"_events",value:function(){var t=this,n=this;this.$element.on({"open.zf.trigger":this.open.bind(this),"close.zf.trigger":function(i,o){return i.target===n.$element[0]||e(i.target).parents("[data-closable]")[0]===o?t.close.apply(t):void 0},"toggle.zf.trigger":this.toggle.bind(this),"resizeme.zf.trigger":function(){n._updatePosition()}}),this.$anchor.length&&this.$anchor.on("keydown.zf.reveal",function(e){13!==e.which&&32!==e.which||(e.stopPropagation(),e.preventDefault(),n.open())}),this.options.closeOnClick&&this.options.overlay&&this.$overlay.off(".zf.reveal").on("click.zf.reveal",function(t){t.target===n.$element[0]||e.contains(n.$element[0],t.target)||n.close()}),this.options.deepLink&&e(window).on("popstate.zf.reveal:"+this.id,this._handleState.bind(this))}},{key:"_handleState",value:function(e){window.location.hash!=="#"+this.id||this.isActive?this.close():this.open()}},{key:"open",value:function(){var t=this;if(this.options.deepLink){var n="#"+this.id;window.history.pushState?window.history.pushState(null,null,n):window.location.hash=n}if(this.isActive=!0,this.$element.css({visibility:"hidden"}).show().scrollTop(0),this.options.overlay&&this.$overlay.css({visibility:"hidden"}).show(),this._updatePosition(),this.$element.hide().css({visibility:""}),this.$overlay&&(this.$overlay.css({visibility:""}).hide(),this.$element.hasClass("fast")?this.$overlay.addClass("fast"):this.$element.hasClass("slow")&&this.$overlay.addClass("slow")),this.options.multipleOpened||this.$element.trigger("closeme.zf.reveal",this.id),this.options.animationIn){var i;!function(){var e=function(){i.$element.attr({"aria-hidden":!1,tabindex:-1}).focus(),console.log("focus")};i=t,t.options.overlay&&Foundation.Motion.animateIn(t.$overlay,"fade-in"),Foundation.Motion.animateIn(t.$element,t.options.animationIn,function(){t.focusableElements=Foundation.Keyboard.findFocusable(t.$element),e()})}()}else this.options.overlay&&this.$overlay.show(0),this.$element.show(this.options.showDelay);this.$element.attr({"aria-hidden":!1,tabindex:-1}).focus(),this.$element.trigger("open.zf.reveal"),this.isMobile?(this.originalScrollPos=window.pageYOffset,e("html, body").addClass("is-reveal-open")):e("body").addClass("is-reveal-open"),setTimeout(function(){t._extraHandlers()},0)}},{key:"_extraHandlers",value:function(){var t=this;this.focusableElements=Foundation.Keyboard.findFocusable(this.$element),this.options.overlay||!this.options.closeOnClick||this.options.fullScreen||e("body").on("click.zf.reveal",function(n){n.target===t.$element[0]||e.contains(t.$element[0],n.target)||t.close()}),this.options.closeOnEsc&&e(window).on("keydown.zf.reveal",function(e){Foundation.Keyboard.handleKey(e,"Reveal",{close:function(){t.options.closeOnEsc&&(t.close(),t.$anchor.focus())}})}),this.$element.on("keydown.zf.reveal",function(n){var i=e(this);Foundation.Keyboard.handleKey(n,"Reveal",{tab_forward:function(){return t.$element.find(":focus").is(t.focusableElements.eq(-1))?(t.focusableElements.eq(0).focus(),!0):0===t.focusableElements.length||void 0},tab_backward:function(){return t.$element.find(":focus").is(t.focusableElements.eq(0))||t.$element.is(":focus")?(t.focusableElements.eq(-1).focus(),!0):0===t.focusableElements.length||void 0},open:function(){t.$element.find(":focus").is(t.$element.find("[data-close]"))?setTimeout(function(){t.$anchor.focus()},1):i.is(t.focusableElements)&&t.open()},close:function(){t.options.closeOnEsc&&(t.close(),t.$anchor.focus())},handled:function(e){e&&n.preventDefault()}})})}},{key:"close",value:function(){function t(){n.isMobile?(e("html, body").removeClass("is-reveal-open"),n.originalScrollPos&&(e("body").scrollTop(n.originalScrollPos),n.originalScrollPos=null)):e("body").removeClass("is-reveal-open"),n.$element.attr("aria-hidden",!0),n.$element.trigger("closed.zf.reveal")}if(!this.isActive||!this.$element.is(":visible"))return!1;var n=this;this.options.animationOut?(this.options.overlay?Foundation.Motion.animateOut(this.$overlay,"fade-out",t):t(),Foundation.Motion.animateOut(this.$element,this.options.animationOut)):(this.options.overlay?this.$overlay.hide(0,t):t(),this.$element.hide(this.options.hideDelay)),this.options.closeOnEsc&&e(window).off("keydown.zf.reveal"),!this.options.overlay&&this.options.closeOnClick&&e("body").off("click.zf.reveal"),this.$element.off("keydown.zf.reveal"),this.options.resetOnClose&&this.$element.html(this.$element.html()),this.isActive=!1,n.options.deepLink&&(window.history.replaceState?window.history.replaceState("",document.title,window.location.pathname):window.location.hash="")}},{key:"toggle",value:function(){this.isActive?this.close():this.open()}},{key:"destroy",value:function(){this.options.overlay&&(this.$element.appendTo(e("body")),this.$overlay.hide().off().remove()),this.$element.hide().off(),this.$anchor.off(".zf"),e(window).off(".zf.reveal:"+this.id),Foundation.unregisterPlugin(this)}}]),t}();s.defaults={animationIn:"",animationOut:"",showDelay:0,hideDelay:0,closeOnClick:!0,closeOnEsc:!0,multipleOpened:!1,vOffset:"auto",hOffset:"auto",fullScreen:!1,btmOffsetPct:10,overlay:!0,resetOnClose:!1,deepLink:!1},Foundation.plugin(s,"Reveal")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){function t(e,t){return e/t}function o(e,t,n,i){return Math.abs(e.position()[t]+e[i]()/2-n)}var r=function(){function r(t,i){n(this,r),this.$element=t,this.options=e.extend({},r.defaults,this.$element.data(),i),this._init(),Foundation.registerPlugin(this,"Slider"),Foundation.Keyboard.register("Slider",{ltr:{ARROW_RIGHT:"increase",ARROW_UP:"increase",ARROW_DOWN:"decrease",ARROW_LEFT:"decrease",SHIFT_ARROW_RIGHT:"increase_fast",SHIFT_ARROW_UP:"increase_fast",SHIFT_ARROW_DOWN:"decrease_fast",SHIFT_ARROW_LEFT:"decrease_fast"},rtl:{ARROW_LEFT:"increase",ARROW_RIGHT:"decrease",SHIFT_ARROW_LEFT:"increase_fast",SHIFT_ARROW_RIGHT:"decrease_fast"}})}return i(r,[{key:"_init",value:function(){this.inputs=this.$element.find("input"),this.handles=this.$element.find("[data-slider-handle]"),this.$handle=this.handles.eq(0),this.$input=this.inputs.length?this.inputs.eq(0):e("#"+this.$handle.attr("aria-controls")),this.$fill=this.$element.find("[data-slider-fill]").css(this.options.vertical?"height":"width",0);var t=!1,n=this;(this.options.disabled||this.$element.hasClass(this.options.disabledClass))&&(this.options.disabled=!0,this.$element.addClass(this.options.disabledClass)),this.inputs.length||(this.inputs=e().add(this.$input),this.options.binding=!0),this._setInitAttr(0),this._events(this.$handle),this.handles[1]&&(this.options.doubleSided=!0,this.$handle2=this.handles.eq(1),this.$input2=this.inputs.length>1?this.inputs.eq(1):e("#"+this.$handle2.attr("aria-controls")),this.inputs[1]||(this.inputs=this.inputs.add(this.$input2)),t=!0,this._setHandlePos(this.$handle,this.options.initialStart,!0,function(){n._setHandlePos(n.$handle2,n.options.initialEnd,!0)}),this._setInitAttr(1),this._events(this.$handle2)),t||this._setHandlePos(this.$handle,this.options.initialStart,!0)}},{key:"_setHandlePos",value:function(e,n,i,o){if(!this.$element.hasClass(this.options.disabledClass)){n=parseFloat(n),n<this.options.start?n=this.options.start:n>this.options.end&&(n=this.options.end);var r=this.options.doubleSided;if(r)if(0===this.handles.index(e)){var s=parseFloat(this.$handle2.attr("aria-valuenow"));n=n>=s?s-this.options.step:n}else{var a=parseFloat(this.$handle.attr("aria-valuenow"));n=a>=n?a+this.options.step:n}this.options.vertical&&!i&&(n=this.options.end-n);var l=this,u=this.options.vertical,c=u?"height":"width",d=u?"top":"left",f=e[0].getBoundingClientRect()[c],h=this.$element[0].getBoundingClientRect()[c],p=t(n-this.options.start,this.options.end-this.options.start).toFixed(2),g=(h-f)*p,m=(100*t(g,h)).toFixed(this.options.decimal);n=parseFloat(n.toFixed(this.options.decimal));var v={};if(this._setValues(e,n),r){var y,b=0===this.handles.index(e),w=~~(100*t(f,h));if(b)v[d]=m+"%",y=parseFloat(this.$handle2[0].style[d])-m+w,o&&"function"==typeof o&&o();else{var x=parseFloat(this.$handle[0].style[d]);y=m-(isNaN(x)?this.options.initialStart/((this.options.end-this.options.start)/100):x)+w}v["min-"+c]=y+"%"}this.$element.one("finished.zf.animate",function(){l.$element.trigger("moved.zf.slider",[e])});var C=this.$element.data("dragging")?1e3/60:this.options.moveTime;Foundation.Move(C,e,function(){e.css(d,m+"%"),l.options.doubleSided?l.$fill.css(v):l.$fill.css(c,100*p+"%")}),clearTimeout(l.timeout),l.timeout=setTimeout(function(){l.$element.trigger("changed.zf.slider",[e])},l.options.changedDelay)}}},{key:"_setInitAttr",value:function(e){var t=this.inputs.eq(e).attr("id")||Foundation.GetYoDigits(6,"slider");this.inputs.eq(e).attr({id:t,max:this.options.end,min:this.options.start,step:this.options.step}),this.handles.eq(e).attr({role:"slider","aria-controls":t,"aria-valuemax":this.options.end,"aria-valuemin":this.options.start,"aria-valuenow":0===e?this.options.initialStart:this.options.initialEnd,"aria-orientation":this.options.vertical?"vertical":"horizontal",tabindex:0})}},{key:"_setValues",value:function(e,t){var n=this.options.doubleSided?this.handles.index(e):0;this.inputs.eq(n).val(t),e.attr("aria-valuenow",t)}},{key:"_handleEvent",value:function(n,i,r){var s,a;if(r)s=this._adjustValue(null,r),a=!0;else{n.preventDefault();var l=this,u=this.options.vertical,c=u?"height":"width",d=u?"top":"left",f=u?n.pageY:n.pageX,h=(this.$handle[0].getBoundingClientRect()[c]/2,this.$element[0].getBoundingClientRect()[c]),p=u?e(window).scrollTop():e(window).scrollLeft(),g=this.$element.offset()[d];n.clientY===n.pageY&&(f+=p);var m,v=f-g;if(m=0>v?0:v>h?h:v,offsetPct=t(m,h),s=(this.options.end-this.options.start)*offsetPct+this.options.start,Foundation.rtl()&&!this.options.vertical&&(s=this.options.end-s),s=l._adjustValue(null,s),a=!1,!i){var y=o(this.$handle,d,m,c),b=o(this.$handle2,d,m,c);i=b>=y?this.$handle:this.$handle2}}this._setHandlePos(i,s,a)}},{key:"_adjustValue",value:function(e,t){var n,i,o,r,s=this.options.step,a=parseFloat(s/2);return n=e?parseFloat(e.attr("aria-valuenow")):t,i=n%s,o=n-i,r=o+s,0===i?n:n=n>=o+a?r:o}},{key:"_events",value:function(t){var n,i=this;if(this.inputs.off("change.zf.slider").on("change.zf.slider",function(t){var n=i.inputs.index(e(this));i._handleEvent(t,i.handles.eq(n),e(this).val())}),this.options.clickSelect&&this.$element.off("click.zf.slider").on("click.zf.slider",function(t){return!i.$element.data("dragging")&&void(e(t.target).is("[data-slider-handle]")||(i.options.doubleSided?i._handleEvent(t):i._handleEvent(t,i.$handle)))}),this.options.draggable){this.handles.addTouch();var o=e("body");t.off("mousedown.zf.slider").on("mousedown.zf.slider",function(r){t.addClass("is-dragging"),i.$fill.addClass("is-dragging"),i.$element.data("dragging",!0),n=e(r.currentTarget),o.on("mousemove.zf.slider",function(e){e.preventDefault(),i._handleEvent(e,n)}).on("mouseup.zf.slider",function(e){i._handleEvent(e,n),t.removeClass("is-dragging"),i.$fill.removeClass("is-dragging"),i.$element.data("dragging",!1),o.off("mousemove.zf.slider mouseup.zf.slider")})}).on("selectstart.zf.slider touchmove.zf.slider",function(e){e.preventDefault()})}t.off("keydown.zf.slider").on("keydown.zf.slider",function(t){var n,o=e(this),r=i.options.doubleSided?i.handles.index(o):0,s=parseFloat(i.inputs.eq(r).val());Foundation.Keyboard.handleKey(t,"Slider",{decrease:function(){n=s-i.options.step},increase:function(){n=s+i.options.step},decrease_fast:function(){n=s-10*i.options.step},increase_fast:function(){n=s+10*i.options.step},handled:function(){t.preventDefault(),i._setHandlePos(o,n,!0)}})})}},{key:"destroy",value:function(){this.handles.off(".zf.slider"),this.inputs.off(".zf.slider"),this.$element.off(".zf.slider"),Foundation.unregisterPlugin(this)}}]),r}();r.defaults={start:0,end:100,step:1,initialStart:0,initialEnd:100,binding:!1,clickSelect:!0,vertical:!1,draggable:!0,disabled:!1,doubleSided:!1,decimal:2,moveTime:200,disabledClass:"disabled",invertVertical:!1,changedDelay:500},Foundation.plugin(r,"Slider")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){function t(e){return parseInt(window.getComputedStyle(document.body,null).fontSize,10)*e}var o=function(){function o(t,i){n(this,o),this.$element=t,this.options=e.extend({},o.defaults,this.$element.data(),i),this._init(),Foundation.registerPlugin(this,"Sticky")}return i(o,[{key:"_init",value:function(){var t=this.$element.parent("[data-sticky-container]"),n=this.$element[0].id||Foundation.GetYoDigits(6,"sticky"),i=this;t.length||(this.wasWrapped=!0),this.$container=t.length?t:e(this.options.container).wrapInner(this.$element),this.$container.addClass(this.options.containerClass),this.$element.addClass(this.options.stickyClass).attr({"data-resize":n}),this.scrollCount=this.options.checkEvery,this.isStuck=!1,e(window).one("load.zf.sticky",function(){""!==i.options.anchor?i.$anchor=e("#"+i.options.anchor):i._parsePoints(),i._setSizes(function(){i._calc(!1)}),i._events(n.split("-").reverse().join("-"))})}},{key:"_parsePoints",value:function(){for(var t=""==this.options.topAnchor?1:this.options.topAnchor,n=""==this.options.btmAnchor?document.documentElement.scrollHeight:this.options.btmAnchor,i=[t,n],o={},r=0,s=i.length;s>r&&i[r];r++){var a;if("number"==typeof i[r])a=i[r];else{var l=i[r].split(":"),u=e("#"+l[0]);a=u.offset().top,l[1]&&"bottom"===l[1].toLowerCase()&&(a+=u[0].getBoundingClientRect().height)}o[r]=a}this.points=o}},{key:"_events",value:function(t){var n=this,i=this.scrollListener="scroll.zf."+t;this.isOn||(this.canStick&&(this.isOn=!0,e(window).off(i).on(i,function(e){0===n.scrollCount?(n.scrollCount=n.options.checkEvery,n._setSizes(function(){n._calc(!1,window.pageYOffset)})):(n.scrollCount--,n._calc(!1,window.pageYOffset))})),this.$element.off("resizeme.zf.trigger").on("resizeme.zf.trigger",function(e,o){n._setSizes(function(){n._calc(!1),n.canStick?n.isOn||n._events(t):n.isOn&&n._pauseListeners(i)})}))}},{key:"_pauseListeners",value:function(t){this.isOn=!1,e(window).off(t),this.$element.trigger("pause.zf.sticky")}},{key:"_calc",value:function(e,t){return e&&this._setSizes(),this.canStick?(t||(t=window.pageYOffset),void(t>=this.topPoint?t<=this.bottomPoint?this.isStuck||this._setSticky():this.isStuck&&this._removeSticky(!1):this.isStuck&&this._removeSticky(!0))):(this.isStuck&&this._removeSticky(!0),!1)}},{key:"_setSticky",value:function(){var e=this,t=this.options.stickTo,n="top"===t?"marginTop":"marginBottom",i="top"===t?"bottom":"top",o={};o[n]=this.options[n]+"em",o[t]=0,o[i]="auto",o.left=this.$container.offset().left+parseInt(window.getComputedStyle(this.$container[0])["padding-left"],10),this.isStuck=!0,this.$element.removeClass("is-anchored is-at-"+i).addClass("is-stuck is-at-"+t).css(o).trigger("sticky.zf.stuckto:"+t),this.$element.on("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd",function(){e._setSizes()})}},{key:"_removeSticky",value:function(e){var t=this.options.stickTo,n="top"===t,i={},o=(this.points?this.points[1]-this.points[0]:this.anchorHeight)-this.elemHeight,r=n?"marginTop":"marginBottom",s=e?"top":"bottom";i[r]=0,i.bottom="auto",e?i.top=0:i.top=o,i.left="",this.isStuck=!1,this.$element.removeClass("is-stuck is-at-"+t).addClass("is-anchored is-at-"+s).css(i).trigger("sticky.zf.unstuckfrom:"+s)}},{key:"_setSizes",value:function(e){this.canStick=Foundation.MediaQuery.atLeast(this.options.stickyOn),this.canStick||e();var t=this.$container[0].getBoundingClientRect().width,n=window.getComputedStyle(this.$container[0]),i=parseInt(n["padding-right"],10);this.$anchor&&this.$anchor.length?this.anchorHeight=this.$anchor[0].getBoundingClientRect().height:this._parsePoints(),this.$element.css({"max-width":t-i+"px"});var o=this.$element[0].getBoundingClientRect().height||this.containerHeight;"none"==this.$element.css("display")&&(o=0),this.containerHeight=o,this.$container.css({height:o}),this.elemHeight=o,this.isStuck&&this.$element.css({left:this.$container.offset().left+parseInt(n["padding-left"],10)}),this._setBreakPoints(o,function(){e&&e()})}},{key:"_setBreakPoints",value:function(e,n){if(!this.canStick){if(!n)return!1;n()}var i=t(this.options.marginTop),o=t(this.options.marginBottom),r=this.points?this.points[0]:this.$anchor.offset().top,s=this.points?this.points[1]:r+this.anchorHeight,a=window.innerHeight;"top"===this.options.stickTo?(r-=i,s-=e+i):"bottom"===this.options.stickTo&&(r-=a-(e+o),s-=a-o),this.topPoint=r,this.bottomPoint=s,n&&n()}},{key:"destroy",value:function(){this._removeSticky(!0),this.$element.removeClass(this.options.stickyClass+" is-anchored is-at-top").css({height:"",top:"",bottom:"","max-width":""}).off("resizeme.zf.trigger"),this.$anchor&&this.$anchor.length&&this.$anchor.off("change.zf.sticky"),e(window).off(this.scrollListener),this.wasWrapped?this.$element.unwrap():this.$container.removeClass(this.options.containerClass).css({height:""}),Foundation.unregisterPlugin(this)}}]),o}();o.defaults={container:"<div data-sticky-container></div>",stickTo:"top",anchor:"",topAnchor:"",btmAnchor:"",marginTop:1,marginBottom:1,stickyOn:"medium",stickyClass:"sticky",containerClass:"sticky-container",checkEvery:-1},Foundation.plugin(o,"Sticky")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i,o){n(this,t),this.$element=i,this.options=e.extend({},t.defaults,this.$element.data(),o),this._init(),Foundation.registerPlugin(this,"Tabs"),Foundation.Keyboard.register("Tabs",{ENTER:"open",SPACE:"open",ARROW_RIGHT:"next",ARROW_UP:"previous",ARROW_DOWN:"next",ARROW_LEFT:"previous"})}return i(t,[{key:"_init",value:function(){var t=this;if(this.$tabTitles=this.$element.find("."+this.options.linkClass),this.$tabContent=e('[data-tabs-content="'+this.$element[0].id+'"]'),
this.$tabTitles.each(function(){var n=e(this),i=n.find("a"),o=n.hasClass("is-active"),r=i[0].hash.slice(1),s=i[0].id?i[0].id:r+"-label",a=e("#"+r);n.attr({role:"presentation"}),i.attr({role:"tab","aria-controls":r,"aria-selected":o,id:s}),a.attr({role:"tabpanel","aria-hidden":!o,"aria-labelledby":s}),o&&t.options.autoFocus&&i.focus()}),this.options.matchHeight){var n=this.$tabContent.find("img");n.length?Foundation.onImagesLoaded(n,this._setHeight.bind(this)):this._setHeight()}this._events()}},{key:"_events",value:function(){this._addKeyHandler(),this._addClickHandler(),this._setHeightMqHandler=null,this.options.matchHeight&&(this._setHeightMqHandler=this._setHeight.bind(this),e(window).on("changed.zf.mediaquery",this._setHeightMqHandler))}},{key:"_addClickHandler",value:function(){var t=this;this.$element.off("click.zf.tabs").on("click.zf.tabs","."+this.options.linkClass,function(n){n.preventDefault(),n.stopPropagation(),e(this).hasClass("is-active")||t._handleTabChange(e(this))})}},{key:"_addKeyHandler",value:function(){var t=this;t.$element.find("li:first-of-type"),t.$element.find("li:last-of-type"),this.$tabTitles.off("keydown.zf.tabs").on("keydown.zf.tabs",function(n){if(9!==n.which){var i,o,r=e(this),s=r.parent("ul").children("li");s.each(function(n){return e(this).is(r)?void(t.options.wrapOnKeys?(i=0===n?s.last():s.eq(n-1),o=n===s.length-1?s.first():s.eq(n+1)):(i=s.eq(Math.max(0,n-1)),o=s.eq(Math.min(n+1,s.length-1)))):void 0}),Foundation.Keyboard.handleKey(n,"Tabs",{open:function(){r.find('[role="tab"]').focus(),t._handleTabChange(r)},previous:function(){i.find('[role="tab"]').focus(),t._handleTabChange(i)},next:function(){o.find('[role="tab"]').focus(),t._handleTabChange(o)},handled:function(){n.stopPropagation(),n.preventDefault()}})}})}},{key:"_handleTabChange",value:function(t){var n=t.find('[role="tab"]'),i=n[0].hash,o=this.$tabContent.find(i),r=this.$element.find("."+this.options.linkClass+".is-active").removeClass("is-active").find('[role="tab"]').attr({"aria-selected":"false"});e("#"+r.attr("aria-controls")).removeClass("is-active").attr({"aria-hidden":"true"}),t.addClass("is-active"),n.attr({"aria-selected":"true"}),o.addClass("is-active").attr({"aria-hidden":"false"}),this.$element.trigger("change.zf.tabs",[t])}},{key:"selectTab",value:function(e){var t;t="object"==typeof e?e[0].id:e,t.indexOf("#")<0&&(t="#"+t);var n=this.$tabTitles.find('[href="'+t+'"]').parent("."+this.options.linkClass);this._handleTabChange(n)}},{key:"_setHeight",value:function(){var t=0;this.$tabContent.find("."+this.options.panelClass).css("height","").each(function(){var n=e(this),i=n.hasClass("is-active");i||n.css({visibility:"hidden",display:"block"});var o=this.getBoundingClientRect().height;i||n.css({visibility:"",display:""}),t=o>t?o:t}).css("height",t+"px")}},{key:"destroy",value:function(){this.$element.find("."+this.options.linkClass).off(".zf.tabs").hide().end().find("."+this.options.panelClass).hide(),this.options.matchHeight&&null!=this._setHeightMqHandler&&e(window).off("changed.zf.mediaquery",this._setHeightMqHandler),Foundation.unregisterPlugin(this)}}]),t}();t.defaults={autoFocus:!1,wrapOnKeys:!0,matchHeight:!1,linkClass:"tabs-title",panelClass:"tabs-panel"},Foundation.plugin(t,"Tabs")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i,o){n(this,t),this.$element=i,this.options=e.extend({},t.defaults,i.data(),o),this.className="",this._init(),this._events(),Foundation.registerPlugin(this,"Toggler")}return i(t,[{key:"_init",value:function(){var t;this.options.animate?(t=this.options.animate.split(" "),this.animationIn=t[0],this.animationOut=t[1]||null):(t=this.$element.data("toggler"),this.className="."===t[0]?t.slice(1):t);var n=this.$element[0].id;e('[data-open="'+n+'"], [data-close="'+n+'"], [data-toggle="'+n+'"]').attr("aria-controls",n),this.$element.attr("aria-expanded",!this.$element.is(":hidden"))}},{key:"_events",value:function(){this.$element.off("toggle.zf.trigger").on("toggle.zf.trigger",this.toggle.bind(this))}},{key:"toggle",value:function(){this[this.options.animate?"_toggleAnimate":"_toggleClass"]()}},{key:"_toggleClass",value:function(){this.$element.toggleClass(this.className);var e=this.$element.hasClass(this.className);e?this.$element.trigger("on.zf.toggler"):this.$element.trigger("off.zf.toggler"),this._updateARIA(e)}},{key:"_toggleAnimate",value:function(){var e=this;this.$element.is(":hidden")?Foundation.Motion.animateIn(this.$element,this.animationIn,function(){e._updateARIA(!0),this.trigger("on.zf.toggler")}):Foundation.Motion.animateOut(this.$element,this.animationOut,function(){e._updateARIA(!1),this.trigger("off.zf.toggler")})}},{key:"_updateARIA",value:function(e){this.$element.attr("aria-expanded",!!e)}},{key:"destroy",value:function(){this.$element.off(".zf.toggler"),Foundation.unregisterPlugin(this)}}]),t}();t.defaults={animate:!1},Foundation.plugin(t,"Toggler")}(jQuery);var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(e){var t=function(){function t(i,o){n(this,t),this.$element=i,this.options=e.extend({},t.defaults,this.$element.data(),o),this.isActive=!1,this.isClick=!1,this._init(),Foundation.registerPlugin(this,"Tooltip")}return i(t,[{key:"_init",value:function(){var t=this.$element.attr("aria-describedby")||Foundation.GetYoDigits(6,"tooltip");this.options.positionClass=this.options.positionClass||this._getPositionClass(this.$element),this.options.tipText=this.options.tipText||this.$element.attr("title"),this.template=this.options.template?e(this.options.template):this._buildTemplate(t),this.template.appendTo(document.body).text(this.options.tipText).hide(),this.$element.attr({title:"","aria-describedby":t,"data-yeti-box":t,"data-toggle":t,"data-resize":t}).addClass(this.triggerClass),this.usedPositions=[],this.counter=4,this.classChanged=!1,this._events()}},{key:"_getPositionClass",value:function(e){if(!e)return"";var t=e[0].className.match(/\b(top|left|right)\b/g);return t=t?t[0]:""}},{key:"_buildTemplate",value:function(t){var n=(this.options.tooltipClass+" "+this.options.positionClass+" "+this.options.templateClasses).trim(),i=e("<div></div>").addClass(n).attr({role:"tooltip","aria-hidden":!0,"data-is-active":!1,"data-is-focus":!1,id:t});return i}},{key:"_reposition",value:function(e){this.usedPositions.push(e?e:"bottom"),!e&&this.usedPositions.indexOf("top")<0?this.template.addClass("top"):"top"===e&&this.usedPositions.indexOf("bottom")<0?this.template.removeClass(e):"left"===e&&this.usedPositions.indexOf("right")<0?this.template.removeClass(e).addClass("right"):"right"===e&&this.usedPositions.indexOf("left")<0?this.template.removeClass(e).addClass("left"):!e&&this.usedPositions.indexOf("top")>-1&&this.usedPositions.indexOf("left")<0?this.template.addClass("left"):"top"===e&&this.usedPositions.indexOf("bottom")>-1&&this.usedPositions.indexOf("left")<0?this.template.removeClass(e).addClass("left"):"left"===e&&this.usedPositions.indexOf("right")>-1&&this.usedPositions.indexOf("bottom")<0?this.template.removeClass(e):"right"===e&&this.usedPositions.indexOf("left")>-1&&this.usedPositions.indexOf("bottom")<0?this.template.removeClass(e):this.template.removeClass(e),this.classChanged=!0,this.counter--}},{key:"_setPosition",value:function(){var e=this._getPositionClass(this.template),t=Foundation.Box.GetDimensions(this.template),n=Foundation.Box.GetDimensions(this.$element),i="left"===e?"left":"right"===e?"left":"top",o="top"===i?"height":"width";if("height"===o?this.options.vOffset:this.options.hOffset,t.width>=t.windowDims.width||!this.counter&&!Foundation.Box.ImNotTouchingYou(this.template))return this.template.offset(Foundation.Box.GetOffsets(this.template,this.$element,"center bottom",this.options.vOffset,this.options.hOffset,!0)).css({width:n.windowDims.width-2*this.options.hOffset,height:"auto"}),!1;for(this.template.offset(Foundation.Box.GetOffsets(this.template,this.$element,"center "+(e||"bottom"),this.options.vOffset,this.options.hOffset));!Foundation.Box.ImNotTouchingYou(this.template)&&this.counter;)this._reposition(e),this._setPosition()}},{key:"show",value:function(){if("all"!==this.options.showOn&&!Foundation.MediaQuery.atLeast(this.options.showOn))return!1;var e=this;this.template.css("visibility","hidden").show(),this._setPosition(),this.$element.trigger("closeme.zf.tooltip",this.template.attr("id")),this.template.attr({"data-is-active":!0,"aria-hidden":!1}),e.isActive=!0,this.template.stop().hide().css("visibility","").fadeIn(this.options.fadeInDuration,function(){}),this.$element.trigger("show.zf.tooltip")}},{key:"hide",value:function(){var e=this;this.template.stop().attr({"aria-hidden":!0,"data-is-active":!1}).fadeOut(this.options.fadeOutDuration,function(){e.isActive=!1,e.isClick=!1,e.classChanged&&(e.template.removeClass(e._getPositionClass(e.template)).addClass(e.options.positionClass),e.usedPositions=[],e.counter=4,e.classChanged=!1)}),this.$element.trigger("hide.zf.tooltip")}},{key:"_events",value:function(){var e=this,t=(this.template,!1);this.options.disableHover||this.$element.on("mouseenter.zf.tooltip",function(t){e.isActive||(e.timeout=setTimeout(function(){e.show()},e.options.hoverDelay))}).on("mouseleave.zf.tooltip",function(n){clearTimeout(e.timeout),(!t||e.isClick&&!e.options.clickOpen)&&e.hide()}),this.options.clickOpen?this.$element.on("mousedown.zf.tooltip",function(t){t.stopImmediatePropagation(),e.isClick||(e.isClick=!0,!e.options.disableHover&&e.$element.attr("tabindex")||e.isActive||e.show())}):this.$element.on("mousedown.zf.tooltip",function(t){t.stopImmediatePropagation(),e.isClick=!0}),this.options.disableForTouch||this.$element.on("tap.zf.tooltip touchend.zf.tooltip",function(t){e.isActive?e.hide():e.show()}),this.$element.on({"close.zf.trigger":this.hide.bind(this)}),this.$element.on("focus.zf.tooltip",function(n){return t=!0,e.isClick?(e.options.clickOpen||(t=!1),!1):void e.show()}).on("focusout.zf.tooltip",function(n){t=!1,e.isClick=!1,e.hide()}).on("resizeme.zf.trigger",function(){e.isActive&&e._setPosition()})}},{key:"toggle",value:function(){this.isActive?this.hide():this.show()}},{key:"destroy",value:function(){this.$element.attr("title",this.template.text()).off(".zf.trigger .zf.tootip").removeAttr("aria-describedby").removeAttr("data-yeti-box").removeAttr("data-toggle").removeAttr("data-resize"),this.template.remove(),Foundation.unregisterPlugin(this)}}]),t}();t.defaults={disableForTouch:!1,hoverDelay:200,fadeInDuration:150,fadeOutDuration:150,disableHover:!1,templateClasses:"",tooltipClass:"tooltip",triggerClass:"has-tip",showOn:"small",template:"",tipText:"",touchCloseText:"Tap to close.",clickOpen:!0,positionClass:"",vOffset:10,hOffset:12},Foundation.plugin(t,"Tooltip")}(jQuery)},function(e,t,n){var i,o;/*! jQuery v2.2.4 | (c) jQuery Foundation | jquery.org/license */
!function(t,n){"object"==typeof e&&"object"==typeof e.exports?e.exports=t.document?n(t,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return n(e)}:n(t)}("undefined"!=typeof window?window:this,function(r,s){function a(e){var t=!!e&&"length"in e&&e.length,n=ce.type(e);return"function"!==n&&!ce.isWindow(e)&&("array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e)}function l(e,t,n){if(ce.isFunction(t))return ce.grep(e,function(e,i){return!!t.call(e,i,e)!==n});if(t.nodeType)return ce.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(we.test(t))return ce.filter(t,e,n);t=ce.filter(t,e)}return ce.grep(e,function(e){return oe.call(t,e)>-1!==n})}function u(e,t){for(;(e=e[t])&&1!==e.nodeType;);return e}function c(e){var t={};return ce.each(e.match(Fe)||[],function(e,n){t[n]=!0}),t}function d(){ee.removeEventListener("DOMContentLoaded",d),r.removeEventListener("load",d),ce.ready()}function f(){this.expando=ce.expando+f.uid++}function h(e,t,n){var i;if(void 0===n&&1===e.nodeType)if(i="data-"+t.replace(ze,"-$&").toLowerCase(),n=e.getAttribute(i),"string"==typeof n){try{n="true"===n||"false"!==n&&("null"===n?null:+n+""===n?+n:Oe.test(n)?ce.parseJSON(n):n)}catch(o){}De.set(e,t,n)}else n=void 0;return n}function p(e,t,n,i){var o,r=1,s=20,a=i?function(){return i.cur()}:function(){return ce.css(e,t,"")},l=a(),u=n&&n[3]||(ce.cssNumber[t]?"":"px"),c=(ce.cssNumber[t]||"px"!==u&&+l)&&qe.exec(ce.css(e,t));if(c&&c[3]!==u){u=u||c[3],n=n||[],c=+l||1;do r=r||".5",c/=r,ce.style(e,t,c+u);while(r!==(r=a()/l)&&1!==r&&--s)}return n&&(c=+c||+l||0,o=n[1]?c+(n[1]+1)*n[2]:+n[2],i&&(i.unit=u,i.start=c,i.end=o)),o}function g(e,t){var n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[];return void 0===t||t&&ce.nodeName(e,t)?ce.merge([e],n):n}function m(e,t){for(var n=0,i=e.length;i>n;n++)Se.set(e[n],"globalEval",!t||Se.get(t[n],"globalEval"))}function v(e,t,n,i,o){for(var r,s,a,l,u,c,d=t.createDocumentFragment(),f=[],h=0,p=e.length;p>h;h++)if(r=e[h],r||0===r)if("object"===ce.type(r))ce.merge(f,r.nodeType?[r]:r);else if(Ie.test(r)){for(s=s||d.appendChild(t.createElement("div")),a=(Re.exec(r)||["",""])[1].toLowerCase(),l=Me[a]||Me._default,s.innerHTML=l[1]+ce.htmlPrefilter(r)+l[2],c=l[0];c--;)s=s.lastChild;ce.merge(f,s.childNodes),s=d.firstChild,s.textContent=""}else f.push(t.createTextNode(r));for(d.textContent="",h=0;r=f[h++];)if(i&&ce.inArray(r,i)>-1)o&&o.push(r);else if(u=ce.contains(r.ownerDocument,r),s=g(d.appendChild(r),"script"),u&&m(s),n)for(c=0;r=s[c++];)Le.test(r.type||"")&&n.push(r);return d}function y(){return!0}function b(){return!1}function w(){try{return ee.activeElement}catch(e){}}function x(e,t,n,i,o,r){var s,a;if("object"==typeof t){"string"!=typeof n&&(i=i||n,n=void 0);for(a in t)x(e,a,n,i,t[a],r);return e}if(null==i&&null==o?(o=n,i=n=void 0):null==o&&("string"==typeof n?(o=i,i=void 0):(o=i,i=n,n=void 0)),o===!1)o=b;else if(!o)return e;return 1===r&&(s=o,o=function(e){return ce().off(e),s.apply(this,arguments)},o.guid=s.guid||(s.guid=ce.guid++)),e.each(function(){ce.event.add(this,t,o,i,n)})}function C(e,t){return ce.nodeName(e,"table")&&ce.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function k(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function $(e){var t=Ke.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function T(e,t){var n,i,o,r,s,a,l,u;if(1===t.nodeType){if(Se.hasData(e)&&(r=Se.access(e),s=Se.set(t,r),u=r.events)){delete s.handle,s.events={};for(o in u)for(n=0,i=u[o].length;i>n;n++)ce.event.add(t,o,u[o][n])}De.hasData(e)&&(a=De.access(e),l=ce.extend({},a),De.set(t,l))}}function F(e,t){var n=t.nodeName.toLowerCase();"input"===n&&He.test(e.type)?t.checked=e.checked:"input"!==n&&"textarea"!==n||(t.defaultValue=e.defaultValue)}function E(e,t,n,i){t=ne.apply([],t);var o,r,s,a,l,u,c=0,d=e.length,f=d-1,h=t[0],p=ce.isFunction(h);if(p||d>1&&"string"==typeof h&&!le.checkClone&&Xe.test(h))return e.each(function(o){var r=e.eq(o);p&&(t[0]=h.call(this,o,r.html())),E(r,t,n,i)});if(d&&(o=v(t,e[0].ownerDocument,!1,e,i),r=o.firstChild,1===o.childNodes.length&&(o=r),r||i)){for(s=ce.map(g(o,"script"),k),a=s.length;d>c;c++)l=o,c!==f&&(l=ce.clone(l,!0,!0),a&&ce.merge(s,g(l,"script"))),n.call(e[c],l,c);if(a)for(u=s[s.length-1].ownerDocument,ce.map(s,$),c=0;a>c;c++)l=s[c],Le.test(l.type||"")&&!Se.access(l,"globalEval")&&ce.contains(u,l)&&(l.src?ce._evalUrl&&ce._evalUrl(l.src):ce.globalEval(l.textContent.replace(Ge,"")))}return e}function A(e,t,n){for(var i,o=t?ce.filter(t,e):e,r=0;null!=(i=o[r]);r++)n||1!==i.nodeType||ce.cleanData(g(i)),i.parentNode&&(n&&ce.contains(i.ownerDocument,i)&&m(g(i,"script")),i.parentNode.removeChild(i));return e}function _(e,t){var n=ce(t.createElement(e)).appendTo(t.body),i=ce.css(n[0],"display");return n.detach(),i}function S(e){var t=ee,n=Ze[e];return n||(n=_(e,t),"none"!==n&&n||(Ve=(Ve||ce("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=Ve[0].contentDocument,t.write(),t.close(),n=_(e,t),Ve.detach()),Ze[e]=n),n}function D(e,t,n){var i,o,r,s,a=e.style;return n=n||tt(e),s=n?n.getPropertyValue(t)||n[t]:void 0,""!==s&&void 0!==s||ce.contains(e.ownerDocument,e)||(s=ce.style(e,t)),n&&!le.pixelMarginRight()&&et.test(s)&&Je.test(t)&&(i=a.width,o=a.minWidth,r=a.maxWidth,a.minWidth=a.maxWidth=a.width=s,s=n.width,a.width=i,a.minWidth=o,a.maxWidth=r),void 0!==s?s+"":s}function O(e,t){return{get:function(){return e()?void delete this.get:(this.get=t).apply(this,arguments)}}}function z(e){if(e in lt)return e;for(var t=e[0].toUpperCase()+e.slice(1),n=at.length;n--;)if(e=at[n]+t,e in lt)return e}function P(e,t,n){var i=qe.exec(t);return i?Math.max(0,i[2]-(n||0))+(i[3]||"px"):t}function q(e,t,n,i,o){for(var r=n===(i?"border":"content")?4:"width"===t?1:0,s=0;4>r;r+=2)"margin"===n&&(s+=ce.css(e,n+Ne[r],!0,o)),i?("content"===n&&(s-=ce.css(e,"padding"+Ne[r],!0,o)),"margin"!==n&&(s-=ce.css(e,"border"+Ne[r]+"Width",!0,o))):(s+=ce.css(e,"padding"+Ne[r],!0,o),"padding"!==n&&(s+=ce.css(e,"border"+Ne[r]+"Width",!0,o)));return s}function N(e,t,n){var i=!0,o="width"===t?e.offsetWidth:e.offsetHeight,r=tt(e),s="border-box"===ce.css(e,"boxSizing",!1,r);if(0>=o||null==o){if(o=D(e,t,r),(0>o||null==o)&&(o=e.style[t]),et.test(o))return o;i=s&&(le.boxSizingReliable()||o===e.style[t]),o=parseFloat(o)||0}return o+q(e,t,n||(s?"border":"content"),i,r)+"px"}function j(e,t){for(var n,i,o,r=[],s=0,a=e.length;a>s;s++)i=e[s],i.style&&(r[s]=Se.get(i,"olddisplay"),n=i.style.display,t?(r[s]||"none"!==n||(i.style.display=""),""===i.style.display&&je(i)&&(r[s]=Se.access(i,"olddisplay",S(i.nodeName)))):(o=je(i),"none"===n&&o||Se.set(i,"olddisplay",o?n:ce.css(i,"display"))));for(s=0;a>s;s++)i=e[s],i.style&&(t&&"none"!==i.style.display&&""!==i.style.display||(i.style.display=t?r[s]||"":"none"));return e}function H(e,t,n,i,o){return new H.prototype.init(e,t,n,i,o)}function R(){return r.setTimeout(function(){ut=void 0}),ut=ce.now()}function L(e,t){var n,i=0,o={height:e};for(t=t?1:0;4>i;i+=2-t)n=Ne[i],o["margin"+n]=o["padding"+n]=e;return t&&(o.opacity=o.width=e),o}function M(e,t,n){for(var i,o=(W.tweeners[t]||[]).concat(W.tweeners["*"]),r=0,s=o.length;s>r;r++)if(i=o[r].call(n,t,e))return i}function I(e,t,n){var i,o,r,s,a,l,u,c,d=this,f={},h=e.style,p=e.nodeType&&je(e),g=Se.get(e,"fxshow");n.queue||(a=ce._queueHooks(e,"fx"),null==a.unqueued&&(a.unqueued=0,l=a.empty.fire,a.empty.fire=function(){a.unqueued||l()}),a.unqueued++,d.always(function(){d.always(function(){a.unqueued--,ce.queue(e,"fx").length||a.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],u=ce.css(e,"display"),c="none"===u?Se.get(e,"olddisplay")||S(e.nodeName):u,"inline"===c&&"none"===ce.css(e,"float")&&(h.display="inline-block")),n.overflow&&(h.overflow="hidden",d.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]}));for(i in t)if(o=t[i],dt.exec(o)){if(delete t[i],r=r||"toggle"===o,o===(p?"hide":"show")){if("show"!==o||!g||void 0===g[i])continue;p=!0}f[i]=g&&g[i]||ce.style(e,i)}else u=void 0;if(ce.isEmptyObject(f))"inline"===("none"===u?S(e.nodeName):u)&&(h.display=u);else{g?"hidden"in g&&(p=g.hidden):g=Se.access(e,"fxshow",{}),r&&(g.hidden=!p),p?ce(e).show():d.done(function(){ce(e).hide()}),d.done(function(){var t;Se.remove(e,"fxshow");for(t in f)ce.style(e,t,f[t])});for(i in f)s=M(p?g[i]:0,i,d),i in g||(g[i]=s.start,p&&(s.end=s.start,s.start="width"===i||"height"===i?1:0))}}function B(e,t){var n,i,o,r,s;for(n in e)if(i=ce.camelCase(n),o=t[i],r=e[n],ce.isArray(r)&&(o=r[1],r=e[n]=r[0]),n!==i&&(e[i]=r,delete e[n]),s=ce.cssHooks[i],s&&"expand"in s){r=s.expand(r),delete e[i];for(n in r)n in e||(e[n]=r[n],t[n]=o)}else t[i]=o}function W(e,t,n){var i,o,r=0,s=W.prefilters.length,a=ce.Deferred().always(function(){delete l.elem}),l=function(){if(o)return!1;for(var t=ut||R(),n=Math.max(0,u.startTime+u.duration-t),i=n/u.duration||0,r=1-i,s=0,l=u.tweens.length;l>s;s++)u.tweens[s].run(r);return a.notifyWith(e,[u,r,n]),1>r&&l?n:(a.resolveWith(e,[u]),!1)},u=a.promise({elem:e,props:ce.extend({},t),opts:ce.extend(!0,{specialEasing:{},easing:ce.easing._default},n),originalProperties:t,originalOptions:n,startTime:ut||R(),duration:n.duration,tweens:[],createTween:function(t,n){var i=ce.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(i),i},stop:function(t){var n=0,i=t?u.tweens.length:0;if(o)return this;for(o=!0;i>n;n++)u.tweens[n].run(1);return t?(a.notifyWith(e,[u,1,0]),a.resolveWith(e,[u,t])):a.rejectWith(e,[u,t]),this}}),c=u.props;for(B(c,u.opts.specialEasing);s>r;r++)if(i=W.prefilters[r].call(u,e,c,u.opts))return ce.isFunction(i.stop)&&(ce._queueHooks(u.elem,u.opts.queue).stop=ce.proxy(i.stop,i)),i;return ce.map(c,M,u),ce.isFunction(u.opts.start)&&u.opts.start.call(e,u),ce.fx.timer(ce.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function Q(e){return e.getAttribute&&e.getAttribute("class")||""}function U(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var i,o=0,r=t.toLowerCase().match(Fe)||[];if(ce.isFunction(n))for(;i=r[o++];)"+"===i[0]?(i=i.slice(1)||"*",(e[i]=e[i]||[]).unshift(n)):(e[i]=e[i]||[]).push(n)}}function Y(e,t,n,i){function o(a){var l;return r[a]=!0,ce.each(e[a]||[],function(e,a){var u=a(t,n,i);return"string"!=typeof u||s||r[u]?s?!(l=u):void 0:(t.dataTypes.unshift(u),o(u),!1)}),l}var r={},s=e===Dt;return o(t.dataTypes[0])||!r["*"]&&o("*")}function X(e,t){var n,i,o=ce.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((o[n]?e:i||(i={}))[n]=t[n]);return i&&ce.extend(!0,e,i),e}function K(e,t,n){for(var i,o,r,s,a=e.contents,l=e.dataTypes;"*"===l[0];)l.shift(),void 0===i&&(i=e.mimeType||t.getResponseHeader("Content-Type"));if(i)for(o in a)if(a[o]&&a[o].test(i)){l.unshift(o);break}if(l[0]in n)r=l[0];else{for(o in n){if(!l[0]||e.converters[o+" "+l[0]]){r=o;break}s||(s=o)}r=r||s}return r?(r!==l[0]&&l.unshift(r),n[r]):void 0}function G(e,t,n,i){var o,r,s,a,l,u={},c=e.dataTypes.slice();if(c[1])for(s in e.converters)u[s.toLowerCase()]=e.converters[s];for(r=c.shift();r;)if(e.responseFields[r]&&(n[e.responseFields[r]]=t),!l&&i&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=r,r=c.shift())if("*"===r)r=l;else if("*"!==l&&l!==r){if(s=u[l+" "+r]||u["* "+r],!s)for(o in u)if(a=o.split(" "),a[1]===r&&(s=u[l+" "+a[0]]||u["* "+a[0]])){s===!0?s=u[o]:u[o]!==!0&&(r=a[0],c.unshift(a[1]));break}if(s!==!0)if(s&&e["throws"])t=s(t);else try{t=s(t)}catch(d){return{state:"parsererror",error:s?d:"No conversion from "+l+" to "+r}}}return{state:"success",data:t}}function V(e,t,n,i){var o;if(ce.isArray(t))ce.each(t,function(t,o){n||qt.test(e)?i(e,o):V(e+"["+("object"==typeof o&&null!=o?t:"")+"]",o,n,i)});else if(n||"object"!==ce.type(t))i(e,t);else for(o in t)V(e+"["+o+"]",t[o],n,i)}function Z(e){return ce.isWindow(e)?e:9===e.nodeType&&e.defaultView}var J=[],ee=r.document,te=J.slice,ne=J.concat,ie=J.push,oe=J.indexOf,re={},se=re.toString,ae=re.hasOwnProperty,le={},ue="2.2.4",ce=function(e,t){return new ce.fn.init(e,t)},de=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,fe=/^-ms-/,he=/-([\da-z])/gi,pe=function(e,t){return t.toUpperCase()};ce.fn=ce.prototype={jquery:ue,constructor:ce,selector:"",length:0,toArray:function(){return te.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:te.call(this)},pushStack:function(e){var t=ce.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e){return ce.each(this,e)},map:function(e){return this.pushStack(ce.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(te.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:ie,sort:J.sort,splice:J.splice},ce.extend=ce.fn.extend=function(){var e,t,n,i,o,r,s=arguments[0]||{},a=1,l=arguments.length,u=!1;for("boolean"==typeof s&&(u=s,s=arguments[a]||{},a++),"object"==typeof s||ce.isFunction(s)||(s={}),a===l&&(s=this,a--);l>a;a++)if(null!=(e=arguments[a]))for(t in e)n=s[t],i=e[t],s!==i&&(u&&i&&(ce.isPlainObject(i)||(o=ce.isArray(i)))?(o?(o=!1,r=n&&ce.isArray(n)?n:[]):r=n&&ce.isPlainObject(n)?n:{},s[t]=ce.extend(u,r,i)):void 0!==i&&(s[t]=i));return s},ce.extend({expando:"jQuery"+(ue+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===ce.type(e)},isArray:Array.isArray,isWindow:function(e){return null!=e&&e===e.window},isNumeric:function(e){var t=e&&e.toString();return!ce.isArray(e)&&t-parseFloat(t)+1>=0},isPlainObject:function(e){var t;if("object"!==ce.type(e)||e.nodeType||ce.isWindow(e))return!1;if(e.constructor&&!ae.call(e,"constructor")&&!ae.call(e.constructor.prototype||{},"isPrototypeOf"))return!1;for(t in e);return void 0===t||ae.call(e,t)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?re[se.call(e)]||"object":typeof e},globalEval:function(e){var t,n=eval;e=ce.trim(e),e&&(1===e.indexOf("use strict")?(t=ee.createElement("script"),t.text=e,ee.head.appendChild(t).parentNode.removeChild(t)):n(e))},camelCase:function(e){return e.replace(fe,"ms-").replace(he,pe)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t){var n,i=0;if(a(e))for(n=e.length;n>i&&t.call(e[i],i,e[i])!==!1;i++);else for(i in e)if(t.call(e[i],i,e[i])===!1)break;return e},trim:function(e){return null==e?"":(e+"").replace(de,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(a(Object(e))?ce.merge(n,"string"==typeof e?[e]:e):ie.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:oe.call(t,e,n)},merge:function(e,t){for(var n=+t.length,i=0,o=e.length;n>i;i++)e[o++]=t[i];return e.length=o,e},grep:function(e,t,n){for(var i,o=[],r=0,s=e.length,a=!n;s>r;r++)i=!t(e[r],r),i!==a&&o.push(e[r]);return o},map:function(e,t,n){var i,o,r=0,s=[];if(a(e))for(i=e.length;i>r;r++)o=t(e[r],r,n),null!=o&&s.push(o);else for(r in e)o=t(e[r],r,n),null!=o&&s.push(o);return ne.apply([],s)},guid:1,proxy:function(e,t){var n,i,o;return"string"==typeof t&&(n=e[t],t=e,e=n),ce.isFunction(e)?(i=te.call(arguments,2),o=function(){return e.apply(t||this,i.concat(te.call(arguments)))},o.guid=e.guid=e.guid||ce.guid++,o):void 0},now:Date.now,support:le}),"function"==typeof Symbol&&(ce.fn[Symbol.iterator]=J[Symbol.iterator]),ce.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){re["[object "+t+"]"]=t.toLowerCase()});var ge=function(e){function t(e,t,n,i){var o,r,s,a,l,u,d,h,p=t&&t.ownerDocument,g=t?t.nodeType:9;if(n=n||[],"string"!=typeof e||!e||1!==g&&9!==g&&11!==g)return n;if(!i&&((t?t.ownerDocument||t:L)!==O&&D(t),t=t||O,P)){if(11!==g&&(u=ve.exec(e)))if(o=u[1]){if(9===g){if(!(s=t.getElementById(o)))return n;if(s.id===o)return n.push(s),n}else if(p&&(s=p.getElementById(o))&&H(t,s)&&s.id===o)return n.push(s),n}else{if(u[2])return Z.apply(n,t.getElementsByTagName(e)),n;if((o=u[3])&&x.getElementsByClassName&&t.getElementsByClassName)return Z.apply(n,t.getElementsByClassName(o)),n}if(x.qsa&&!Q[e+" "]&&(!q||!q.test(e))){if(1!==g)p=t,h=e;else if("object"!==t.nodeName.toLowerCase()){for((a=t.getAttribute("id"))?a=a.replace(be,"\\$&"):t.setAttribute("id",a=R),d=T(e),r=d.length,l=fe.test(a)?"#"+a:"[id='"+a+"']";r--;)d[r]=l+" "+f(d[r]);h=d.join(","),p=ye.test(e)&&c(t.parentNode)||t}if(h)try{return Z.apply(n,p.querySelectorAll(h)),n}catch(m){}finally{a===R&&t.removeAttribute("id")}}}return E(e.replace(ae,"$1"),t,n,i)}function n(){function e(n,i){return t.push(n+" ")>C.cacheLength&&delete e[t.shift()],e[n+" "]=i}var t=[];return e}function i(e){return e[R]=!0,e}function o(e){var t=O.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function r(e,t){for(var n=e.split("|"),i=n.length;i--;)C.attrHandle[n[i]]=t}function s(e,t){var n=t&&e,i=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||Y)-(~e.sourceIndex||Y);if(i)return i;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function a(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function l(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function u(e){return i(function(t){return t=+t,i(function(n,i){for(var o,r=e([],n.length,t),s=r.length;s--;)n[o=r[s]]&&(n[o]=!(i[o]=n[o]))})})}function c(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function d(){}function f(e){for(var t=0,n=e.length,i="";n>t;t++)i+=e[t].value;return i}function h(e,t,n){var i=t.dir,o=n&&"parentNode"===i,r=I++;return t.first?function(t,n,r){for(;t=t[i];)if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var a,l,u,c=[M,r];if(s){for(;t=t[i];)if((1===t.nodeType||o)&&e(t,n,s))return!0}else for(;t=t[i];)if(1===t.nodeType||o){if(u=t[R]||(t[R]={}),l=u[t.uniqueID]||(u[t.uniqueID]={}),(a=l[i])&&a[0]===M&&a[1]===r)return c[2]=a[2];if(l[i]=c,c[2]=e(t,n,s))return!0}}}function p(e){return e.length>1?function(t,n,i){for(var o=e.length;o--;)if(!e[o](t,n,i))return!1;return!0}:e[0]}function g(e,n,i){for(var o=0,r=n.length;r>o;o++)t(e,n[o],i);return i}function m(e,t,n,i,o){for(var r,s=[],a=0,l=e.length,u=null!=t;l>a;a++)(r=e[a])&&(n&&!n(r,i,o)||(s.push(r),u&&t.push(a)));return s}function v(e,t,n,o,r,s){return o&&!o[R]&&(o=v(o)),r&&!r[R]&&(r=v(r,s)),i(function(i,s,a,l){var u,c,d,f=[],h=[],p=s.length,v=i||g(t||"*",a.nodeType?[a]:a,[]),y=!e||!i&&t?v:m(v,f,e,a,l),b=n?r||(i?e:p||o)?[]:s:y;if(n&&n(y,b,a,l),o)for(u=m(b,h),o(u,[],a,l),c=u.length;c--;)(d=u[c])&&(b[h[c]]=!(y[h[c]]=d));if(i){if(r||e){if(r){for(u=[],c=b.length;c--;)(d=b[c])&&u.push(y[c]=d);r(null,b=[],u,l)}for(c=b.length;c--;)(d=b[c])&&(u=r?ee(i,d):f[c])>-1&&(i[u]=!(s[u]=d))}}else b=m(b===s?b.splice(p,b.length):b),r?r(null,s,b,l):Z.apply(s,b)})}function y(e){for(var t,n,i,o=e.length,r=C.relative[e[0].type],s=r||C.relative[" "],a=r?1:0,l=h(function(e){return e===t},s,!0),u=h(function(e){return ee(t,e)>-1},s,!0),c=[function(e,n,i){var o=!r&&(i||n!==A)||((t=n).nodeType?l(e,n,i):u(e,n,i));return t=null,o}];o>a;a++)if(n=C.relative[e[a].type])c=[h(p(c),n)];else{if(n=C.filter[e[a].type].apply(null,e[a].matches),n[R]){for(i=++a;o>i&&!C.relative[e[i].type];i++);return v(a>1&&p(c),a>1&&f(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(ae,"$1"),n,i>a&&y(e.slice(a,i)),o>i&&y(e=e.slice(i)),o>i&&f(e))}c.push(n)}return p(c)}function b(e,n){var o=n.length>0,r=e.length>0,s=function(i,s,a,l,u){var c,d,f,h=0,p="0",g=i&&[],v=[],y=A,b=i||r&&C.find.TAG("*",u),w=M+=null==y?1:Math.random()||.1,x=b.length;for(u&&(A=s===O||s||u);p!==x&&null!=(c=b[p]);p++){if(r&&c){for(d=0,s||c.ownerDocument===O||(D(c),a=!P);f=e[d++];)if(f(c,s||O,a)){l.push(c);break}u&&(M=w)}o&&((c=!f&&c)&&h--,i&&g.push(c))}if(h+=p,o&&p!==h){for(d=0;f=n[d++];)f(g,v,s,a);if(i){if(h>0)for(;p--;)g[p]||v[p]||(v[p]=G.call(l));v=m(v)}Z.apply(l,v),u&&!i&&v.length>0&&h+n.length>1&&t.uniqueSort(l)}return u&&(M=w,A=y),g};return o?i(s):s}var w,x,C,k,$,T,F,E,A,_,S,D,O,z,P,q,N,j,H,R="sizzle"+1*new Date,L=e.document,M=0,I=0,B=n(),W=n(),Q=n(),U=function(e,t){return e===t&&(S=!0),0},Y=1<<31,X={}.hasOwnProperty,K=[],G=K.pop,V=K.push,Z=K.push,J=K.slice,ee=function(e,t){for(var n=0,i=e.length;i>n;n++)if(e[n]===t)return n;return-1},te="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",ne="[\\x20\\t\\r\\n\\f]",ie="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",oe="\\["+ne+"*("+ie+")(?:"+ne+"*([*^$|!~]?=)"+ne+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+ie+"))|)"+ne+"*\\]",re=":("+ie+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+oe+")*)|.*)\\)|)",se=new RegExp(ne+"+","g"),ae=new RegExp("^"+ne+"+|((?:^|[^\\\\])(?:\\\\.)*)"+ne+"+$","g"),le=new RegExp("^"+ne+"*,"+ne+"*"),ue=new RegExp("^"+ne+"*([>+~]|"+ne+")"+ne+"*"),ce=new RegExp("="+ne+"*([^\\]'\"]*?)"+ne+"*\\]","g"),de=new RegExp(re),fe=new RegExp("^"+ie+"$"),he={ID:new RegExp("^#("+ie+")"),CLASS:new RegExp("^\\.("+ie+")"),TAG:new RegExp("^("+ie+"|[*])"),ATTR:new RegExp("^"+oe),PSEUDO:new RegExp("^"+re),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ne+"*(even|odd|(([+-]|)(\\d*)n|)"+ne+"*(?:([+-]|)"+ne+"*(\\d+)|))"+ne+"*\\)|)","i"),bool:new RegExp("^(?:"+te+")$","i"),needsContext:new RegExp("^"+ne+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ne+"*((?:-\\d)?\\d*)"+ne+"*\\)|)(?=[^-]|$)","i")},pe=/^(?:input|select|textarea|button)$/i,ge=/^h\d$/i,me=/^[^{]+\{\s*\[native \w/,ve=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ye=/[+~]/,be=/'|\\/g,we=new RegExp("\\\\([\\da-f]{1,6}"+ne+"?|("+ne+")|.)","ig"),xe=function(e,t,n){var i="0x"+t-65536;return i!==i||n?t:0>i?String.fromCharCode(i+65536):String.fromCharCode(i>>10|55296,1023&i|56320)},Ce=function(){D()};try{Z.apply(K=J.call(L.childNodes),L.childNodes),K[L.childNodes.length].nodeType}catch(ke){Z={apply:K.length?function(e,t){V.apply(e,J.call(t))}:function(e,t){for(var n=e.length,i=0;e[n++]=t[i++];);e.length=n-1}}}x=t.support={},$=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},D=t.setDocument=function(e){var t,n,i=e?e.ownerDocument||e:L;return i!==O&&9===i.nodeType&&i.documentElement?(O=i,z=O.documentElement,P=!$(O),(n=O.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",Ce,!1):n.attachEvent&&n.attachEvent("onunload",Ce)),x.attributes=o(function(e){return e.className="i",!e.getAttribute("className")}),x.getElementsByTagName=o(function(e){return e.appendChild(O.createComment("")),!e.getElementsByTagName("*").length}),x.getElementsByClassName=me.test(O.getElementsByClassName),x.getById=o(function(e){return z.appendChild(e).id=R,!O.getElementsByName||!O.getElementsByName(R).length}),x.getById?(C.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&P){var n=t.getElementById(e);return n?[n]:[]}},C.filter.ID=function(e){var t=e.replace(we,xe);return function(e){return e.getAttribute("id")===t}}):(delete C.find.ID,C.filter.ID=function(e){var t=e.replace(we,xe);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}}),C.find.TAG=x.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):x.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,i=[],o=0,r=t.getElementsByTagName(e);if("*"===e){for(;n=r[o++];)1===n.nodeType&&i.push(n);return i}return r},C.find.CLASS=x.getElementsByClassName&&function(e,t){return"undefined"!=typeof t.getElementsByClassName&&P?t.getElementsByClassName(e):void 0},N=[],q=[],(x.qsa=me.test(O.querySelectorAll))&&(o(function(e){z.appendChild(e).innerHTML="<a id='"+R+"'></a><select id='"+R+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+ne+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||q.push("\\["+ne+"*(?:value|"+te+")"),e.querySelectorAll("[id~="+R+"-]").length||q.push("~="),e.querySelectorAll(":checked").length||q.push(":checked"),e.querySelectorAll("a#"+R+"+*").length||q.push(".#.+[+~]")}),o(function(e){var t=O.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&q.push("name"+ne+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),q.push(",.*:")})),(x.matchesSelector=me.test(j=z.matches||z.webkitMatchesSelector||z.mozMatchesSelector||z.oMatchesSelector||z.msMatchesSelector))&&o(function(e){x.disconnectedMatch=j.call(e,"div"),j.call(e,"[s!='']:x"),N.push("!=",re)}),q=q.length&&new RegExp(q.join("|")),N=N.length&&new RegExp(N.join("|")),t=me.test(z.compareDocumentPosition),H=t||me.test(z.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,i=t&&t.parentNode;return e===i||!(!i||1!==i.nodeType||!(n.contains?n.contains(i):e.compareDocumentPosition&&16&e.compareDocumentPosition(i)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},U=t?function(e,t){if(e===t)return S=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n?n:(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&n||!x.sortDetached&&t.compareDocumentPosition(e)===n?e===O||e.ownerDocument===L&&H(L,e)?-1:t===O||t.ownerDocument===L&&H(L,t)?1:_?ee(_,e)-ee(_,t):0:4&n?-1:1)}:function(e,t){if(e===t)return S=!0,0;var n,i=0,o=e.parentNode,r=t.parentNode,a=[e],l=[t];if(!o||!r)return e===O?-1:t===O?1:o?-1:r?1:_?ee(_,e)-ee(_,t):0;if(o===r)return s(e,t);for(n=e;n=n.parentNode;)a.unshift(n);for(n=t;n=n.parentNode;)l.unshift(n);for(;a[i]===l[i];)i++;return i?s(a[i],l[i]):a[i]===L?-1:l[i]===L?1:0},O):O},t.matches=function(e,n){return t(e,null,null,n)},t.matchesSelector=function(e,n){if((e.ownerDocument||e)!==O&&D(e),n=n.replace(ce,"='$1']"),x.matchesSelector&&P&&!Q[n+" "]&&(!N||!N.test(n))&&(!q||!q.test(n)))try{var i=j.call(e,n);if(i||x.disconnectedMatch||e.document&&11!==e.document.nodeType)return i}catch(o){}return t(n,O,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==O&&D(e),H(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==O&&D(e);var n=C.attrHandle[t.toLowerCase()],i=n&&X.call(C.attrHandle,t.toLowerCase())?n(e,t,!P):void 0;return void 0!==i?i:x.attributes||!P?e.getAttribute(t):(i=e.getAttributeNode(t))&&i.specified?i.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!x.detectDuplicates,_=!x.sortStable&&e.slice(0),e.sort(U),S){for(;t=e[o++];)t===e[o]&&(i=n.push(o));for(;i--;)e.splice(n[i],1)}return _=null,e},k=t.getText=function(e){var t,n="",i=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=k(e)}else if(3===o||4===o)return e.nodeValue}else for(;t=e[i++];)n+=k(t);return n},C=t.selectors={cacheLength:50,createPseudo:i,match:he,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(we,xe),e[3]=(e[3]||e[4]||e[5]||"").replace(we,xe),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||t.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&t.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return he.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&de.test(n)&&(t=T(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(we,xe).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=B[e+" "];return t||(t=new RegExp("(^|"+ne+")"+e+"("+ne+"|$)"))&&B(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,n,i){return function(o){var r=t.attr(o,e);return null==r?"!="===n:!n||(r+="","="===n?r===i:"!="===n?r!==i:"^="===n?i&&0===r.indexOf(i):"*="===n?i&&r.indexOf(i)>-1:"$="===n?i&&r.slice(-i.length)===i:"~="===n?(" "+r.replace(se," ")+" ").indexOf(i)>-1:"|="===n&&(r===i||r.slice(0,i.length+1)===i+"-"))}},CHILD:function(e,t,n,i,o){var r="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===i&&0===o?function(e){return!!e.parentNode}:function(t,n,l){var u,c,d,f,h,p,g=r!==s?"nextSibling":"previousSibling",m=t.parentNode,v=a&&t.nodeName.toLowerCase(),y=!l&&!a,b=!1;if(m){if(r){for(;g;){for(f=t;f=f[g];)if(a?f.nodeName.toLowerCase()===v:1===f.nodeType)return!1;p=g="only"===e&&!p&&"nextSibling"}return!0}if(p=[s?m.firstChild:m.lastChild],s&&y){for(f=m,d=f[R]||(f[R]={}),c=d[f.uniqueID]||(d[f.uniqueID]={}),u=c[e]||[],h=u[0]===M&&u[1],b=h&&u[2],f=h&&m.childNodes[h];f=++h&&f&&f[g]||(b=h=0)||p.pop();)if(1===f.nodeType&&++b&&f===t){c[e]=[M,h,b];break}}else if(y&&(f=t,d=f[R]||(f[R]={}),c=d[f.uniqueID]||(d[f.uniqueID]={}),u=c[e]||[],h=u[0]===M&&u[1],b=h),b===!1)for(;(f=++h&&f&&f[g]||(b=h=0)||p.pop())&&((a?f.nodeName.toLowerCase()!==v:1!==f.nodeType)||!++b||(y&&(d=f[R]||(f[R]={}),c=d[f.uniqueID]||(d[f.uniqueID]={}),c[e]=[M,b]),f!==t)););return b-=o,b===i||b%i===0&&b/i>=0}}},PSEUDO:function(e,n){var o,r=C.pseudos[e]||C.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return r[R]?r(n):r.length>1?(o=[e,e,"",n],C.setFilters.hasOwnProperty(e.toLowerCase())?i(function(e,t){for(var i,o=r(e,n),s=o.length;s--;)i=ee(e,o[s]),e[i]=!(t[i]=o[s])}):function(e){return r(e,0,o)}):r}},pseudos:{not:i(function(e){var t=[],n=[],o=F(e.replace(ae,"$1"));return o[R]?i(function(e,t,n,i){for(var r,s=o(e,null,i,[]),a=e.length;a--;)(r=s[a])&&(e[a]=!(t[a]=r))}):function(e,i,r){return t[0]=e,o(t,null,r,n),t[0]=null,!n.pop()}}),has:i(function(e){return function(n){return t(e,n).length>0}}),contains:i(function(e){return e=e.replace(we,xe),function(t){return(t.textContent||t.innerText||k(t)).indexOf(e)>-1}}),lang:i(function(e){return fe.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(we,xe).toLowerCase(),function(t){var n;do if(n=P?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===z},focus:function(e){return e===O.activeElement&&(!O.hasFocus||O.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!C.pseudos.empty(e)},header:function(e){return ge.test(e.nodeName)},input:function(e){return pe.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,n){return[0>n?n+t:n]}),even:u(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:u(function(e,t){
for(var n=1;t>n;n+=2)e.push(n);return e}),lt:u(function(e,t,n){for(var i=0>n?n+t:n;--i>=0;)e.push(i);return e}),gt:u(function(e,t,n){for(var i=0>n?n+t:n;++i<t;)e.push(i);return e})}},C.pseudos.nth=C.pseudos.eq;for(w in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})C.pseudos[w]=a(w);for(w in{submit:!0,reset:!0})C.pseudos[w]=l(w);return d.prototype=C.filters=C.pseudos,C.setFilters=new d,T=t.tokenize=function(e,n){var i,o,r,s,a,l,u,c=W[e+" "];if(c)return n?0:c.slice(0);for(a=e,l=[],u=C.preFilter;a;){i&&!(o=le.exec(a))||(o&&(a=a.slice(o[0].length)||a),l.push(r=[])),i=!1,(o=ue.exec(a))&&(i=o.shift(),r.push({value:i,type:o[0].replace(ae," ")}),a=a.slice(i.length));for(s in C.filter)!(o=he[s].exec(a))||u[s]&&!(o=u[s](o))||(i=o.shift(),r.push({value:i,type:s,matches:o}),a=a.slice(i.length));if(!i)break}return n?a.length:a?t.error(e):W(e,l).slice(0)},F=t.compile=function(e,t){var n,i=[],o=[],r=Q[e+" "];if(!r){for(t||(t=T(e)),n=t.length;n--;)r=y(t[n]),r[R]?i.push(r):o.push(r);r=Q(e,b(o,i)),r.selector=e}return r},E=t.select=function(e,t,n,i){var o,r,s,a,l,u="function"==typeof e&&e,d=!i&&T(e=u.selector||e);if(n=n||[],1===d.length){if(r=d[0]=d[0].slice(0),r.length>2&&"ID"===(s=r[0]).type&&x.getById&&9===t.nodeType&&P&&C.relative[r[1].type]){if(t=(C.find.ID(s.matches[0].replace(we,xe),t)||[])[0],!t)return n;u&&(t=t.parentNode),e=e.slice(r.shift().value.length)}for(o=he.needsContext.test(e)?0:r.length;o--&&(s=r[o],!C.relative[a=s.type]);)if((l=C.find[a])&&(i=l(s.matches[0].replace(we,xe),ye.test(r[0].type)&&c(t.parentNode)||t))){if(r.splice(o,1),e=i.length&&f(r),!e)return Z.apply(n,i),n;break}}return(u||F(e,d))(i,t,!P,n,!t||ye.test(e)&&c(t.parentNode)||t),n},x.sortStable=R.split("").sort(U).join("")===R,x.detectDuplicates=!!S,D(),x.sortDetached=o(function(e){return 1&e.compareDocumentPosition(O.createElement("div"))}),o(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||r("type|href|height|width",function(e,t,n){return n?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),x.attributes&&o(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||r("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),o(function(e){return null==e.getAttribute("disabled")})||r(te,function(e,t,n){var i;return n?void 0:e[t]===!0?t.toLowerCase():(i=e.getAttributeNode(t))&&i.specified?i.value:null}),t}(r);ce.find=ge,ce.expr=ge.selectors,ce.expr[":"]=ce.expr.pseudos,ce.uniqueSort=ce.unique=ge.uniqueSort,ce.text=ge.getText,ce.isXMLDoc=ge.isXML,ce.contains=ge.contains;var me=function(e,t,n){for(var i=[],o=void 0!==n;(e=e[t])&&9!==e.nodeType;)if(1===e.nodeType){if(o&&ce(e).is(n))break;i.push(e)}return i},ve=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},ye=ce.expr.match.needsContext,be=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,we=/^.[^:#\[\.,]*$/;ce.filter=function(e,t,n){var i=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===i.nodeType?ce.find.matchesSelector(i,e)?[i]:[]:ce.find.matches(e,ce.grep(t,function(e){return 1===e.nodeType}))},ce.fn.extend({find:function(e){var t,n=this.length,i=[],o=this;if("string"!=typeof e)return this.pushStack(ce(e).filter(function(){for(t=0;n>t;t++)if(ce.contains(o[t],this))return!0}));for(t=0;n>t;t++)ce.find(e,o[t],i);return i=this.pushStack(n>1?ce.unique(i):i),i.selector=this.selector?this.selector+" "+e:e,i},filter:function(e){return this.pushStack(l(this,e||[],!1))},not:function(e){return this.pushStack(l(this,e||[],!0))},is:function(e){return!!l(this,"string"==typeof e&&ye.test(e)?ce(e):e||[],!1).length}});var xe,Ce=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,ke=ce.fn.init=function(e,t,n){var i,o;if(!e)return this;if(n=n||xe,"string"==typeof e){if(i="<"===e[0]&&">"===e[e.length-1]&&e.length>=3?[null,e,null]:Ce.exec(e),!i||!i[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof ce?t[0]:t,ce.merge(this,ce.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:ee,!0)),be.test(i[1])&&ce.isPlainObject(t))for(i in t)ce.isFunction(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}return o=ee.getElementById(i[2]),o&&o.parentNode&&(this.length=1,this[0]=o),this.context=ee,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):ce.isFunction(e)?void 0!==n.ready?n.ready(e):e(ce):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),ce.makeArray(e,this))};ke.prototype=ce.fn,xe=ce(ee);var $e=/^(?:parents|prev(?:Until|All))/,Te={children:!0,contents:!0,next:!0,prev:!0};ce.fn.extend({has:function(e){var t=ce(e,this),n=t.length;return this.filter(function(){for(var e=0;n>e;e++)if(ce.contains(this,t[e]))return!0})},closest:function(e,t){for(var n,i=0,o=this.length,r=[],s=ye.test(e)||"string"!=typeof e?ce(e,t||this.context):0;o>i;i++)for(n=this[i];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(s?s.index(n)>-1:1===n.nodeType&&ce.find.matchesSelector(n,e))){r.push(n);break}return this.pushStack(r.length>1?ce.uniqueSort(r):r)},index:function(e){return e?"string"==typeof e?oe.call(ce(e),this[0]):oe.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(ce.uniqueSort(ce.merge(this.get(),ce(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),ce.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return me(e,"parentNode")},parentsUntil:function(e,t,n){return me(e,"parentNode",n)},next:function(e){return u(e,"nextSibling")},prev:function(e){return u(e,"previousSibling")},nextAll:function(e){return me(e,"nextSibling")},prevAll:function(e){return me(e,"previousSibling")},nextUntil:function(e,t,n){return me(e,"nextSibling",n)},prevUntil:function(e,t,n){return me(e,"previousSibling",n)},siblings:function(e){return ve((e.parentNode||{}).firstChild,e)},children:function(e){return ve(e.firstChild)},contents:function(e){return e.contentDocument||ce.merge([],e.childNodes)}},function(e,t){ce.fn[e]=function(n,i){var o=ce.map(this,t,n);return"Until"!==e.slice(-5)&&(i=n),i&&"string"==typeof i&&(o=ce.filter(i,o)),this.length>1&&(Te[e]||ce.uniqueSort(o),$e.test(e)&&o.reverse()),this.pushStack(o)}});var Fe=/\S+/g;ce.Callbacks=function(e){e="string"==typeof e?c(e):ce.extend({},e);var t,n,i,o,r=[],s=[],a=-1,l=function(){for(o=e.once,i=t=!0;s.length;a=-1)for(n=s.shift();++a<r.length;)r[a].apply(n[0],n[1])===!1&&e.stopOnFalse&&(a=r.length,n=!1);e.memory||(n=!1),t=!1,o&&(r=n?[]:"")},u={add:function(){return r&&(n&&!t&&(a=r.length-1,s.push(n)),function i(t){ce.each(t,function(t,n){ce.isFunction(n)?e.unique&&u.has(n)||r.push(n):n&&n.length&&"string"!==ce.type(n)&&i(n)})}(arguments),n&&!t&&l()),this},remove:function(){return ce.each(arguments,function(e,t){for(var n;(n=ce.inArray(t,r,n))>-1;)r.splice(n,1),a>=n&&a--}),this},has:function(e){return e?ce.inArray(e,r)>-1:r.length>0},empty:function(){return r&&(r=[]),this},disable:function(){return o=s=[],r=n="",this},disabled:function(){return!r},lock:function(){return o=s=[],n||(r=n=""),this},locked:function(){return!!o},fireWith:function(e,n){return o||(n=n||[],n=[e,n.slice?n.slice():n],s.push(n),t||l()),this},fire:function(){return u.fireWith(this,arguments),this},fired:function(){return!!i}};return u},ce.extend({Deferred:function(e){var t=[["resolve","done",ce.Callbacks("once memory"),"resolved"],["reject","fail",ce.Callbacks("once memory"),"rejected"],["notify","progress",ce.Callbacks("memory")]],n="pending",i={state:function(){return n},always:function(){return o.done(arguments).fail(arguments),this},then:function(){var e=arguments;return ce.Deferred(function(n){ce.each(t,function(t,r){var s=ce.isFunction(e[t])&&e[t];o[r[1]](function(){var e=s&&s.apply(this,arguments);e&&ce.isFunction(e.promise)?e.promise().progress(n.notify).done(n.resolve).fail(n.reject):n[r[0]+"With"](this===i?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?ce.extend(e,i):i}},o={};return i.pipe=i.then,ce.each(t,function(e,r){var s=r[2],a=r[3];i[r[1]]=s.add,a&&s.add(function(){n=a},t[1^e][2].disable,t[2][2].lock),o[r[0]]=function(){return o[r[0]+"With"](this===o?i:this,arguments),this},o[r[0]+"With"]=s.fireWith}),i.promise(o),e&&e.call(o,o),o},when:function(e){var t,n,i,o=0,r=te.call(arguments),s=r.length,a=1!==s||e&&ce.isFunction(e.promise)?s:0,l=1===a?e:ce.Deferred(),u=function(e,n,i){return function(o){n[e]=this,i[e]=arguments.length>1?te.call(arguments):o,i===t?l.notifyWith(n,i):--a||l.resolveWith(n,i)}};if(s>1)for(t=new Array(s),n=new Array(s),i=new Array(s);s>o;o++)r[o]&&ce.isFunction(r[o].promise)?r[o].promise().progress(u(o,n,t)).done(u(o,i,r)).fail(l.reject):--a;return a||l.resolveWith(i,r),l.promise()}});var Ee;ce.fn.ready=function(e){return ce.ready.promise().done(e),this},ce.extend({isReady:!1,readyWait:1,holdReady:function(e){e?ce.readyWait++:ce.ready(!0)},ready:function(e){(e===!0?--ce.readyWait:ce.isReady)||(ce.isReady=!0,e!==!0&&--ce.readyWait>0||(Ee.resolveWith(ee,[ce]),ce.fn.triggerHandler&&(ce(ee).triggerHandler("ready"),ce(ee).off("ready"))))}}),ce.ready.promise=function(e){return Ee||(Ee=ce.Deferred(),"complete"===ee.readyState||"loading"!==ee.readyState&&!ee.documentElement.doScroll?r.setTimeout(ce.ready):(ee.addEventListener("DOMContentLoaded",d),r.addEventListener("load",d))),Ee.promise(e)},ce.ready.promise();var Ae=function(e,t,n,i,o,r,s){var a=0,l=e.length,u=null==n;if("object"===ce.type(n)){o=!0;for(a in n)Ae(e,t,a,n[a],!0,r,s)}else if(void 0!==i&&(o=!0,ce.isFunction(i)||(s=!0),u&&(s?(t.call(e,i),t=null):(u=t,t=function(e,t,n){return u.call(ce(e),n)})),t))for(;l>a;a++)t(e[a],n,s?i:i.call(e[a],a,t(e[a],n)));return o?e:u?t.call(e):l?t(e[0],n):r},_e=function(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType};f.uid=1,f.prototype={register:function(e,t){var n=t||{};return e.nodeType?e[this.expando]=n:Object.defineProperty(e,this.expando,{value:n,writable:!0,configurable:!0}),e[this.expando]},cache:function(e){if(!_e(e))return{};var t=e[this.expando];return t||(t={},_e(e)&&(e.nodeType?e[this.expando]=t:Object.defineProperty(e,this.expando,{value:t,configurable:!0}))),t},set:function(e,t,n){var i,o=this.cache(e);if("string"==typeof t)o[t]=n;else for(i in t)o[i]=t[i];return o},get:function(e,t){return void 0===t?this.cache(e):e[this.expando]&&e[this.expando][t]},access:function(e,t,n){var i;return void 0===t||t&&"string"==typeof t&&void 0===n?(i=this.get(e,t),void 0!==i?i:this.get(e,ce.camelCase(t))):(this.set(e,t,n),void 0!==n?n:t)},remove:function(e,t){var n,i,o,r=e[this.expando];if(void 0!==r){if(void 0===t)this.register(e);else{ce.isArray(t)?i=t.concat(t.map(ce.camelCase)):(o=ce.camelCase(t),t in r?i=[t,o]:(i=o,i=i in r?[i]:i.match(Fe)||[])),n=i.length;for(;n--;)delete r[i[n]]}(void 0===t||ce.isEmptyObject(r))&&(e.nodeType?e[this.expando]=void 0:delete e[this.expando])}},hasData:function(e){var t=e[this.expando];return void 0!==t&&!ce.isEmptyObject(t)}};var Se=new f,De=new f,Oe=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,ze=/[A-Z]/g;ce.extend({hasData:function(e){return De.hasData(e)||Se.hasData(e)},data:function(e,t,n){return De.access(e,t,n)},removeData:function(e,t){De.remove(e,t)},_data:function(e,t,n){return Se.access(e,t,n)},_removeData:function(e,t){Se.remove(e,t)}}),ce.fn.extend({data:function(e,t){var n,i,o,r=this[0],s=r&&r.attributes;if(void 0===e){if(this.length&&(o=De.get(r),1===r.nodeType&&!Se.get(r,"hasDataAttrs"))){for(n=s.length;n--;)s[n]&&(i=s[n].name,0===i.indexOf("data-")&&(i=ce.camelCase(i.slice(5)),h(r,i,o[i])));Se.set(r,"hasDataAttrs",!0)}return o}return"object"==typeof e?this.each(function(){De.set(this,e)}):Ae(this,function(t){var n,i;if(r&&void 0===t){if(n=De.get(r,e)||De.get(r,e.replace(ze,"-$&").toLowerCase()),void 0!==n)return n;if(i=ce.camelCase(e),n=De.get(r,i),void 0!==n)return n;if(n=h(r,i,void 0),void 0!==n)return n}else i=ce.camelCase(e),this.each(function(){var n=De.get(this,i);De.set(this,i,t),e.indexOf("-")>-1&&void 0!==n&&De.set(this,e,t)})},null,t,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){De.remove(this,e)})}}),ce.extend({queue:function(e,t,n){var i;return e?(t=(t||"fx")+"queue",i=Se.get(e,t),n&&(!i||ce.isArray(n)?i=Se.access(e,t,ce.makeArray(n)):i.push(n)),i||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=ce.queue(e,t),i=n.length,o=n.shift(),r=ce._queueHooks(e,t),s=function(){ce.dequeue(e,t)};"inprogress"===o&&(o=n.shift(),i--),o&&("fx"===t&&n.unshift("inprogress"),delete r.stop,o.call(e,s,r)),!i&&r&&r.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return Se.get(e,n)||Se.access(e,n,{empty:ce.Callbacks("once memory").add(function(){Se.remove(e,[t+"queue",n])})})}}),ce.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?ce.queue(this[0],e):void 0===t?this:this.each(function(){var n=ce.queue(this,e,t);ce._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&ce.dequeue(this,e)})},dequeue:function(e){return this.each(function(){ce.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,i=1,o=ce.Deferred(),r=this,s=this.length,a=function(){--i||o.resolveWith(r,[r])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";s--;)n=Se.get(r[s],e+"queueHooks"),n&&n.empty&&(i++,n.empty.add(a));return a(),o.promise(t)}});var Pe=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,qe=new RegExp("^(?:([+-])=|)("+Pe+")([a-z%]*)$","i"),Ne=["Top","Right","Bottom","Left"],je=function(e,t){return e=t||e,"none"===ce.css(e,"display")||!ce.contains(e.ownerDocument,e)},He=/^(?:checkbox|radio)$/i,Re=/<([\w:-]+)/,Le=/^$|\/(?:java|ecma)script/i,Me={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};Me.optgroup=Me.option,Me.tbody=Me.tfoot=Me.colgroup=Me.caption=Me.thead,Me.th=Me.td;var Ie=/<|&#?\w+;/;!function(){var e=ee.createDocumentFragment(),t=e.appendChild(ee.createElement("div")),n=ee.createElement("input");n.setAttribute("type","radio"),n.setAttribute("checked","checked"),n.setAttribute("name","t"),t.appendChild(n),le.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,t.innerHTML="<textarea>x</textarea>",le.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue}();var Be=/^key/,We=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Qe=/^([^.]*)(?:\.(.+)|)/;ce.event={global:{},add:function(e,t,n,i,o){var r,s,a,l,u,c,d,f,h,p,g,m=Se.get(e);if(m)for(n.handler&&(r=n,n=r.handler,o=r.selector),n.guid||(n.guid=ce.guid++),(l=m.events)||(l=m.events={}),(s=m.handle)||(s=m.handle=function(t){return"undefined"!=typeof ce&&ce.event.triggered!==t.type?ce.event.dispatch.apply(e,arguments):void 0}),t=(t||"").match(Fe)||[""],u=t.length;u--;)a=Qe.exec(t[u])||[],h=g=a[1],p=(a[2]||"").split(".").sort(),h&&(d=ce.event.special[h]||{},h=(o?d.delegateType:d.bindType)||h,d=ce.event.special[h]||{},c=ce.extend({type:h,origType:g,data:i,handler:n,guid:n.guid,selector:o,needsContext:o&&ce.expr.match.needsContext.test(o),namespace:p.join(".")},r),(f=l[h])||(f=l[h]=[],f.delegateCount=0,d.setup&&d.setup.call(e,i,p,s)!==!1||e.addEventListener&&e.addEventListener(h,s)),d.add&&(d.add.call(e,c),c.handler.guid||(c.handler.guid=n.guid)),o?f.splice(f.delegateCount++,0,c):f.push(c),ce.event.global[h]=!0)},remove:function(e,t,n,i,o){var r,s,a,l,u,c,d,f,h,p,g,m=Se.hasData(e)&&Se.get(e);if(m&&(l=m.events)){for(t=(t||"").match(Fe)||[""],u=t.length;u--;)if(a=Qe.exec(t[u])||[],h=g=a[1],p=(a[2]||"").split(".").sort(),h){for(d=ce.event.special[h]||{},h=(i?d.delegateType:d.bindType)||h,f=l[h]||[],a=a[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),s=r=f.length;r--;)c=f[r],!o&&g!==c.origType||n&&n.guid!==c.guid||a&&!a.test(c.namespace)||i&&i!==c.selector&&("**"!==i||!c.selector)||(f.splice(r,1),c.selector&&f.delegateCount--,d.remove&&d.remove.call(e,c));s&&!f.length&&(d.teardown&&d.teardown.call(e,p,m.handle)!==!1||ce.removeEvent(e,h,m.handle),delete l[h])}else for(h in l)ce.event.remove(e,h+t[u],n,i,!0);ce.isEmptyObject(l)&&Se.remove(e,"handle events")}},dispatch:function(e){e=ce.event.fix(e);var t,n,i,o,r,s=[],a=te.call(arguments),l=(Se.get(this,"events")||{})[e.type]||[],u=ce.event.special[e.type]||{};if(a[0]=e,e.delegateTarget=this,!u.preDispatch||u.preDispatch.call(this,e)!==!1){for(s=ce.event.handlers.call(this,e,l),t=0;(o=s[t++])&&!e.isPropagationStopped();)for(e.currentTarget=o.elem,n=0;(r=o.handlers[n++])&&!e.isImmediatePropagationStopped();)e.rnamespace&&!e.rnamespace.test(r.namespace)||(e.handleObj=r,e.data=r.data,i=((ce.event.special[r.origType]||{}).handle||r.handler).apply(o.elem,a),void 0!==i&&(e.result=i)===!1&&(e.preventDefault(),e.stopPropagation()));return u.postDispatch&&u.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,i,o,r,s=[],a=t.delegateCount,l=e.target;if(a&&l.nodeType&&("click"!==e.type||isNaN(e.button)||e.button<1))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(i=[],n=0;a>n;n++)r=t[n],o=r.selector+" ",void 0===i[o]&&(i[o]=r.needsContext?ce(o,this).index(l)>-1:ce.find(o,this,null,[l]).length),i[o]&&i.push(r);i.length&&s.push({elem:l,handlers:i})}return a<t.length&&s.push({elem:this,handlers:t.slice(a)}),s},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,i,o,r=t.button;return null==e.pageX&&null!=t.clientX&&(n=e.target.ownerDocument||ee,i=n.documentElement,o=n.body,e.pageX=t.clientX+(i&&i.scrollLeft||o&&o.scrollLeft||0)-(i&&i.clientLeft||o&&o.clientLeft||0),e.pageY=t.clientY+(i&&i.scrollTop||o&&o.scrollTop||0)-(i&&i.clientTop||o&&o.clientTop||0)),e.which||void 0===r||(e.which=1&r?1:2&r?3:4&r?2:0),e}},fix:function(e){if(e[ce.expando])return e;var t,n,i,o=e.type,r=e,s=this.fixHooks[o];for(s||(this.fixHooks[o]=s=We.test(o)?this.mouseHooks:Be.test(o)?this.keyHooks:{}),i=s.props?this.props.concat(s.props):this.props,e=new ce.Event(r),t=i.length;t--;)n=i[t],e[n]=r[n];return e.target||(e.target=ee),3===e.target.nodeType&&(e.target=e.target.parentNode),s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==w()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===w()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&ce.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(e){return ce.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}}},ce.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)},ce.Event=function(e,t){return this instanceof ce.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?y:b):this.type=e,t&&ce.extend(this,t),this.timeStamp=e&&e.timeStamp||ce.now(),void(this[ce.expando]=!0)):new ce.Event(e,t)},ce.Event.prototype={constructor:ce.Event,isDefaultPrevented:b,isPropagationStopped:b,isImmediatePropagationStopped:b,isSimulated:!1,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=y,e&&!this.isSimulated&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=y,e&&!this.isSimulated&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=y,e&&!this.isSimulated&&e.stopImmediatePropagation(),this.stopPropagation()}},ce.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){ce.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,i=this,o=e.relatedTarget,r=e.handleObj;return o&&(o===i||ce.contains(i,o))||(e.type=r.origType,n=r.handler.apply(this,arguments),e.type=t),n}}}),ce.fn.extend({on:function(e,t,n,i){return x(this,e,t,n,i)},one:function(e,t,n,i){return x(this,e,t,n,i,1)},off:function(e,t,n){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,ce(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,t,e[o]);return this}return t!==!1&&"function"!=typeof t||(n=t,t=void 0),n===!1&&(n=b),this.each(function(){ce.event.remove(this,e,n,t)})}});var Ue=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,Ye=/<script|<style|<link/i,Xe=/checked\s*(?:[^=]|=\s*.checked.)/i,Ke=/^true\/(.*)/,Ge=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;ce.extend({htmlPrefilter:function(e){return e.replace(Ue,"<$1></$2>")},clone:function(e,t,n){var i,o,r,s,a=e.cloneNode(!0),l=ce.contains(e.ownerDocument,e);if(!(le.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ce.isXMLDoc(e)))for(s=g(a),r=g(e),i=0,o=r.length;o>i;i++)F(r[i],s[i]);if(t)if(n)for(r=r||g(e),s=s||g(a),i=0,o=r.length;o>i;i++)T(r[i],s[i]);else T(e,a);return s=g(a,"script"),s.length>0&&m(s,!l&&g(e,"script")),a},cleanData:function(e){for(var t,n,i,o=ce.event.special,r=0;void 0!==(n=e[r]);r++)if(_e(n)){if(t=n[Se.expando]){if(t.events)for(i in t.events)o[i]?ce.event.remove(n,i):ce.removeEvent(n,i,t.handle);n[Se.expando]=void 0}n[De.expando]&&(n[De.expando]=void 0)}}}),ce.fn.extend({domManip:E,detach:function(e){return A(this,e,!0)},remove:function(e){return A(this,e)},text:function(e){return Ae(this,function(e){return void 0===e?ce.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return E(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=C(this,e);t.appendChild(e)}})},prepend:function(){return E(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=C(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return E(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return E(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(ce.cleanData(g(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return ce.clone(this,e,t)})},html:function(e){return Ae(this,function(e){var t=this[0]||{},n=0,i=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Ye.test(e)&&!Me[(Re.exec(e)||["",""])[1].toLowerCase()]){e=ce.htmlPrefilter(e);try{for(;i>n;n++)t=this[n]||{},1===t.nodeType&&(ce.cleanData(g(t,!1)),t.innerHTML=e);t=0}catch(o){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=[];return E(this,arguments,function(t){var n=this.parentNode;ce.inArray(this,e)<0&&(ce.cleanData(g(this)),n&&n.replaceChild(t,this))},e)}}),ce.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){ce.fn[e]=function(e){for(var n,i=[],o=ce(e),r=o.length-1,s=0;r>=s;s++)n=s===r?this:this.clone(!0),ce(o[s])[t](n),ie.apply(i,n.get());return this.pushStack(i)}});var Ve,Ze={HTML:"block",BODY:"block"},Je=/^margin/,et=new RegExp("^("+Pe+")(?!px)[a-z%]+$","i"),tt=function(e){var t=e.ownerDocument.defaultView;return t&&t.opener||(t=r),t.getComputedStyle(e)},nt=function(e,t,n,i){var o,r,s={};for(r in t)s[r]=e.style[r],e.style[r]=t[r];o=n.apply(e,i||[]);for(r in t)e.style[r]=s[r];return o},it=ee.documentElement;!function(){function e(){a.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",a.innerHTML="",it.appendChild(s);var e=r.getComputedStyle(a);t="1%"!==e.top,o="2px"===e.marginLeft,n="4px"===e.width,a.style.marginRight="50%",i="4px"===e.marginRight,it.removeChild(s)}var t,n,i,o,s=ee.createElement("div"),a=ee.createElement("div");a.style&&(a.style.backgroundClip="content-box",a.cloneNode(!0).style.backgroundClip="",le.clearCloneStyle="content-box"===a.style.backgroundClip,s.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",s.appendChild(a),ce.extend(le,{pixelPosition:function(){return e(),t},boxSizingReliable:function(){return null==n&&e(),n},pixelMarginRight:function(){return null==n&&e(),i},reliableMarginLeft:function(){return null==n&&e(),o},reliableMarginRight:function(){var e,t=a.appendChild(ee.createElement("div"));return t.style.cssText=a.style.cssText="-webkit-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",t.style.marginRight=t.style.width="0",a.style.width="1px",it.appendChild(s),e=!parseFloat(r.getComputedStyle(t).marginRight),it.removeChild(s),a.removeChild(t),e}}))}();var ot=/^(none|table(?!-c[ea]).+)/,rt={position:"absolute",visibility:"hidden",display:"block"},st={letterSpacing:"0",fontWeight:"400"},at=["Webkit","O","Moz","ms"],lt=ee.createElement("div").style;ce.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=D(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(e,t,n,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,r,s,a=ce.camelCase(t),l=e.style;return t=ce.cssProps[a]||(ce.cssProps[a]=z(a)||a),s=ce.cssHooks[t]||ce.cssHooks[a],void 0===n?s&&"get"in s&&void 0!==(o=s.get(e,!1,i))?o:l[t]:(r=typeof n,"string"===r&&(o=qe.exec(n))&&o[1]&&(n=p(e,t,o),r="number"),void(null!=n&&n===n&&("number"===r&&(n+=o&&o[3]||(ce.cssNumber[a]?"":"px")),le.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),s&&"set"in s&&void 0===(n=s.set(e,n,i))||(l[t]=n))))}},css:function(e,t,n,i){var o,r,s,a=ce.camelCase(t);return t=ce.cssProps[a]||(ce.cssProps[a]=z(a)||a),s=ce.cssHooks[t]||ce.cssHooks[a],s&&"get"in s&&(o=s.get(e,!0,n)),void 0===o&&(o=D(e,t,i)),"normal"===o&&t in st&&(o=st[t]),""===n||n?(r=parseFloat(o),n===!0||isFinite(r)?r||0:o):o}}),ce.each(["height","width"],function(e,t){ce.cssHooks[t]={get:function(e,n,i){return n?ot.test(ce.css(e,"display"))&&0===e.offsetWidth?nt(e,rt,function(){return N(e,t,i)}):N(e,t,i):void 0},set:function(e,n,i){var o,r=i&&tt(e),s=i&&q(e,t,i,"border-box"===ce.css(e,"boxSizing",!1,r),r);return s&&(o=qe.exec(n))&&"px"!==(o[3]||"px")&&(e.style[t]=n,n=ce.css(e,t)),P(e,n,s)}}}),ce.cssHooks.marginLeft=O(le.reliableMarginLeft,function(e,t){return t?(parseFloat(D(e,"marginLeft"))||e.getBoundingClientRect().left-nt(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px":void 0}),ce.cssHooks.marginRight=O(le.reliableMarginRight,function(e,t){return t?nt(e,{display:"inline-block"},D,[e,"marginRight"]):void 0}),ce.each({margin:"",padding:"",border:"Width"},function(e,t){ce.cssHooks[e+t]={expand:function(n){for(var i=0,o={},r="string"==typeof n?n.split(" "):[n];4>i;i++)o[e+Ne[i]+t]=r[i]||r[i-2]||r[0];return o}},Je.test(e)||(ce.cssHooks[e+t].set=P)}),ce.fn.extend({css:function(e,t){return Ae(this,function(e,t,n){var i,o,r={},s=0;if(ce.isArray(t)){for(i=tt(e),o=t.length;o>s;s++)r[t[s]]=ce.css(e,t[s],!1,i);return r}return void 0!==n?ce.style(e,t,n):ce.css(e,t)},e,t,arguments.length>1)},show:function(){return j(this,!0)},hide:function(){return j(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){je(this)?ce(this).show():ce(this).hide()})}}),ce.Tween=H,H.prototype={constructor:H,init:function(e,t,n,i,o,r){this.elem=e,this.prop=n,this.easing=o||ce.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=i,this.unit=r||(ce.cssNumber[n]?"":"px")},cur:function(){var e=H.propHooks[this.prop];return e&&e.get?e.get(this):H.propHooks._default.get(this)},run:function(e){var t,n=H.propHooks[this.prop];return this.options.duration?this.pos=t=ce.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):H.propHooks._default.set(this),this}},H.prototype.init.prototype=H.prototype,H.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=ce.css(e.elem,e.prop,""),t&&"auto"!==t?t:0)},set:function(e){ce.fx.step[e.prop]?ce.fx.step[e.prop](e):1!==e.elem.nodeType||null==e.elem.style[ce.cssProps[e.prop]]&&!ce.cssHooks[e.prop]?e.elem[e.prop]=e.now:ce.style(e.elem,e.prop,e.now+e.unit)}}},H.propHooks.scrollTop=H.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},ce.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},ce.fx=H.prototype.init,ce.fx.step={};var ut,ct,dt=/^(?:toggle|show|hide)$/,ft=/queueHooks$/;ce.Animation=ce.extend(W,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return p(n.elem,e,qe.exec(t),n),n}]},tweener:function(e,t){ce.isFunction(e)?(t=e,e=["*"]):e=e.match(Fe);for(var n,i=0,o=e.length;o>i;i++)n=e[i],W.tweeners[n]=W.tweeners[n]||[],W.tweeners[n].unshift(t)},prefilters:[I],prefilter:function(e,t){t?W.prefilters.unshift(e):W.prefilters.push(e)}}),ce.speed=function(e,t,n){var i=e&&"object"==typeof e?ce.extend({},e):{complete:n||!n&&t||ce.isFunction(e)&&e,duration:e,easing:n&&t||t&&!ce.isFunction(t)&&t};return i.duration=ce.fx.off?0:"number"==typeof i.duration?i.duration:i.duration in ce.fx.speeds?ce.fx.speeds[i.duration]:ce.fx.speeds._default,null!=i.queue&&i.queue!==!0||(i.queue="fx"),i.old=i.complete,i.complete=function(){ce.isFunction(i.old)&&i.old.call(this),i.queue&&ce.dequeue(this,i.queue)},i},ce.fn.extend({fadeTo:function(e,t,n,i){return this.filter(je).css("opacity",0).show().end().animate({opacity:t},e,n,i)},animate:function(e,t,n,i){var o=ce.isEmptyObject(e),r=ce.speed(t,n,i),s=function(){var t=W(this,ce.extend({},e),r);(o||Se.get(this,"finish"))&&t.stop(!0)};return s.finish=s,o||r.queue===!1?this.each(s):this.queue(r.queue,s)},stop:function(e,t,n){var i=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,o=null!=e&&e+"queueHooks",r=ce.timers,s=Se.get(this);if(o)s[o]&&s[o].stop&&i(s[o]);else for(o in s)s[o]&&s[o].stop&&ft.test(o)&&i(s[o]);for(o=r.length;o--;)r[o].elem!==this||null!=e&&r[o].queue!==e||(r[o].anim.stop(n),t=!1,r.splice(o,1));!t&&n||ce.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=Se.get(this),i=n[e+"queue"],o=n[e+"queueHooks"],r=ce.timers,s=i?i.length:0;for(n.finish=!0,ce.queue(this,e,[]),o&&o.stop&&o.stop.call(this,!0),t=r.length;t--;)r[t].elem===this&&r[t].queue===e&&(r[t].anim.stop(!0),r.splice(t,1));for(t=0;s>t;t++)i[t]&&i[t].finish&&i[t].finish.call(this);delete n.finish})}}),ce.each(["toggle","show","hide"],function(e,t){var n=ce.fn[t];ce.fn[t]=function(e,i,o){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(L(t,!0),e,i,o)}}),ce.each({slideDown:L("show"),slideUp:L("hide"),slideToggle:L("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){ce.fn[e]=function(e,n,i){return this.animate(t,e,n,i)}}),ce.timers=[],ce.fx.tick=function(){var e,t=0,n=ce.timers;for(ut=ce.now();t<n.length;t++)e=n[t],
e()||n[t]!==e||n.splice(t--,1);n.length||ce.fx.stop(),ut=void 0},ce.fx.timer=function(e){ce.timers.push(e),e()?ce.fx.start():ce.timers.pop()},ce.fx.interval=13,ce.fx.start=function(){ct||(ct=r.setInterval(ce.fx.tick,ce.fx.interval))},ce.fx.stop=function(){r.clearInterval(ct),ct=null},ce.fx.speeds={slow:600,fast:200,_default:400},ce.fn.delay=function(e,t){return e=ce.fx?ce.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var i=r.setTimeout(t,e);n.stop=function(){r.clearTimeout(i)}})},function(){var e=ee.createElement("input"),t=ee.createElement("select"),n=t.appendChild(ee.createElement("option"));e.type="checkbox",le.checkOn=""!==e.value,le.optSelected=n.selected,t.disabled=!0,le.optDisabled=!n.disabled,e=ee.createElement("input"),e.value="t",e.type="radio",le.radioValue="t"===e.value}();var ht,pt=ce.expr.attrHandle;ce.fn.extend({attr:function(e,t){return Ae(this,ce.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){ce.removeAttr(this,e)})}}),ce.extend({attr:function(e,t,n){var i,o,r=e.nodeType;if(3!==r&&8!==r&&2!==r)return"undefined"==typeof e.getAttribute?ce.prop(e,t,n):(1===r&&ce.isXMLDoc(e)||(t=t.toLowerCase(),o=ce.attrHooks[t]||(ce.expr.match.bool.test(t)?ht:void 0)),void 0!==n?null===n?void ce.removeAttr(e,t):o&&"set"in o&&void 0!==(i=o.set(e,n,t))?i:(e.setAttribute(t,n+""),n):o&&"get"in o&&null!==(i=o.get(e,t))?i:(i=ce.find.attr(e,t),null==i?void 0:i))},attrHooks:{type:{set:function(e,t){if(!le.radioValue&&"radio"===t&&ce.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,i,o=0,r=t&&t.match(Fe);if(r&&1===e.nodeType)for(;n=r[o++];)i=ce.propFix[n]||n,ce.expr.match.bool.test(n)&&(e[i]=!1),e.removeAttribute(n)}}),ht={set:function(e,t,n){return t===!1?ce.removeAttr(e,n):e.setAttribute(n,n),n}},ce.each(ce.expr.match.bool.source.match(/\w+/g),function(e,t){var n=pt[t]||ce.find.attr;pt[t]=function(e,t,i){var o,r;return i||(r=pt[t],pt[t]=o,o=null!=n(e,t,i)?t.toLowerCase():null,pt[t]=r),o}});var gt=/^(?:input|select|textarea|button)$/i,mt=/^(?:a|area)$/i;ce.fn.extend({prop:function(e,t){return Ae(this,ce.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[ce.propFix[e]||e]})}}),ce.extend({prop:function(e,t,n){var i,o,r=e.nodeType;if(3!==r&&8!==r&&2!==r)return 1===r&&ce.isXMLDoc(e)||(t=ce.propFix[t]||t,o=ce.propHooks[t]),void 0!==n?o&&"set"in o&&void 0!==(i=o.set(e,n,t))?i:e[t]=n:o&&"get"in o&&null!==(i=o.get(e,t))?i:e[t]},propHooks:{tabIndex:{get:function(e){var t=ce.find.attr(e,"tabindex");return t?parseInt(t,10):gt.test(e.nodeName)||mt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),le.optSelected||(ce.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),ce.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ce.propFix[this.toLowerCase()]=this});var vt=/[\t\r\n\f]/g;ce.fn.extend({addClass:function(e){var t,n,i,o,r,s,a,l=0;if(ce.isFunction(e))return this.each(function(t){ce(this).addClass(e.call(this,t,Q(this)))});if("string"==typeof e&&e)for(t=e.match(Fe)||[];n=this[l++];)if(o=Q(n),i=1===n.nodeType&&(" "+o+" ").replace(vt," ")){for(s=0;r=t[s++];)i.indexOf(" "+r+" ")<0&&(i+=r+" ");a=ce.trim(i),o!==a&&n.setAttribute("class",a)}return this},removeClass:function(e){var t,n,i,o,r,s,a,l=0;if(ce.isFunction(e))return this.each(function(t){ce(this).removeClass(e.call(this,t,Q(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof e&&e)for(t=e.match(Fe)||[];n=this[l++];)if(o=Q(n),i=1===n.nodeType&&(" "+o+" ").replace(vt," ")){for(s=0;r=t[s++];)for(;i.indexOf(" "+r+" ")>-1;)i=i.replace(" "+r+" "," ");a=ce.trim(i),o!==a&&n.setAttribute("class",a)}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):ce.isFunction(e)?this.each(function(n){ce(this).toggleClass(e.call(this,n,Q(this),t),t)}):this.each(function(){var t,i,o,r;if("string"===n)for(i=0,o=ce(this),r=e.match(Fe)||[];t=r[i++];)o.hasClass(t)?o.removeClass(t):o.addClass(t);else void 0!==e&&"boolean"!==n||(t=Q(this),t&&Se.set(this,"__className__",t),this.setAttribute&&this.setAttribute("class",t||e===!1?"":Se.get(this,"__className__")||""))})},hasClass:function(e){var t,n,i=0;for(t=" "+e+" ";n=this[i++];)if(1===n.nodeType&&(" "+Q(n)+" ").replace(vt," ").indexOf(t)>-1)return!0;return!1}});var yt=/\r/g,bt=/[\x20\t\r\n\f]+/g;ce.fn.extend({val:function(e){var t,n,i,o=this[0];return arguments.length?(i=ce.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,ce(this).val()):e,null==o?o="":"number"==typeof o?o+="":ce.isArray(o)&&(o=ce.map(o,function(e){return null==e?"":e+""})),t=ce.valHooks[this.type]||ce.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,o,"value")||(this.value=o))})):o?(t=ce.valHooks[o.type]||ce.valHooks[o.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(o,"value"))?n:(n=o.value,"string"==typeof n?n.replace(yt,""):null==n?"":n)):void 0}}),ce.extend({valHooks:{option:{get:function(e){var t=ce.find.attr(e,"value");return null!=t?t:ce.trim(ce.text(e)).replace(bt," ")}},select:{get:function(e){for(var t,n,i=e.options,o=e.selectedIndex,r="select-one"===e.type||0>o,s=r?null:[],a=r?o+1:i.length,l=0>o?a:r?o:0;a>l;l++)if(n=i[l],(n.selected||l===o)&&(le.optDisabled?!n.disabled:null===n.getAttribute("disabled"))&&(!n.parentNode.disabled||!ce.nodeName(n.parentNode,"optgroup"))){if(t=ce(n).val(),r)return t;s.push(t)}return s},set:function(e,t){for(var n,i,o=e.options,r=ce.makeArray(t),s=o.length;s--;)i=o[s],(i.selected=ce.inArray(ce.valHooks.option.get(i),r)>-1)&&(n=!0);return n||(e.selectedIndex=-1),r}}}}),ce.each(["radio","checkbox"],function(){ce.valHooks[this]={set:function(e,t){return ce.isArray(t)?e.checked=ce.inArray(ce(e).val(),t)>-1:void 0}},le.checkOn||(ce.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var wt=/^(?:focusinfocus|focusoutblur)$/;ce.extend(ce.event,{trigger:function(e,t,n,i){var o,s,a,l,u,c,d,f=[n||ee],h=ae.call(e,"type")?e.type:e,p=ae.call(e,"namespace")?e.namespace.split("."):[];if(s=a=n=n||ee,3!==n.nodeType&&8!==n.nodeType&&!wt.test(h+ce.event.triggered)&&(h.indexOf(".")>-1&&(p=h.split("."),h=p.shift(),p.sort()),u=h.indexOf(":")<0&&"on"+h,e=e[ce.expando]?e:new ce.Event(h,"object"==typeof e&&e),e.isTrigger=i?2:3,e.namespace=p.join("."),e.rnamespace=e.namespace?new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=n),t=null==t?[e]:ce.makeArray(t,[e]),d=ce.event.special[h]||{},i||!d.trigger||d.trigger.apply(n,t)!==!1)){if(!i&&!d.noBubble&&!ce.isWindow(n)){for(l=d.delegateType||h,wt.test(l+h)||(s=s.parentNode);s;s=s.parentNode)f.push(s),a=s;a===(n.ownerDocument||ee)&&f.push(a.defaultView||a.parentWindow||r)}for(o=0;(s=f[o++])&&!e.isPropagationStopped();)e.type=o>1?l:d.bindType||h,c=(Se.get(s,"events")||{})[e.type]&&Se.get(s,"handle"),c&&c.apply(s,t),c=u&&s[u],c&&c.apply&&_e(s)&&(e.result=c.apply(s,t),e.result===!1&&e.preventDefault());return e.type=h,i||e.isDefaultPrevented()||d._default&&d._default.apply(f.pop(),t)!==!1||!_e(n)||u&&ce.isFunction(n[h])&&!ce.isWindow(n)&&(a=n[u],a&&(n[u]=null),ce.event.triggered=h,n[h](),ce.event.triggered=void 0,a&&(n[u]=a)),e.result}},simulate:function(e,t,n){var i=ce.extend(new ce.Event,n,{type:e,isSimulated:!0});ce.event.trigger(i,null,t)}}),ce.fn.extend({trigger:function(e,t){return this.each(function(){ce.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?ce.event.trigger(e,t,n,!0):void 0}}),ce.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){ce.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),ce.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),le.focusin="onfocusin"in r,le.focusin||ce.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){ce.event.simulate(t,e.target,ce.event.fix(e))};ce.event.special[t]={setup:function(){var i=this.ownerDocument||this,o=Se.access(i,t);o||i.addEventListener(e,n,!0),Se.access(i,t,(o||0)+1)},teardown:function(){var i=this.ownerDocument||this,o=Se.access(i,t)-1;o?Se.access(i,t,o):(i.removeEventListener(e,n,!0),Se.remove(i,t))}}});var xt=r.location,Ct=ce.now(),kt=/\?/;ce.parseJSON=function(e){return JSON.parse(e+"")},ce.parseXML=function(e){var t;if(!e||"string"!=typeof e)return null;try{t=(new r.DOMParser).parseFromString(e,"text/xml")}catch(n){t=void 0}return t&&!t.getElementsByTagName("parsererror").length||ce.error("Invalid XML: "+e),t};var $t=/#.*$/,Tt=/([?&])_=[^&]*/,Ft=/^(.*?):[ \t]*([^\r\n]*)$/gm,Et=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,At=/^(?:GET|HEAD)$/,_t=/^\/\//,St={},Dt={},Ot="*/".concat("*"),zt=ee.createElement("a");zt.href=xt.href,ce.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:xt.href,type:"GET",isLocal:Et.test(xt.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Ot,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":ce.parseJSON,"text xml":ce.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?X(X(e,ce.ajaxSettings),t):X(ce.ajaxSettings,e)},ajaxPrefilter:U(St),ajaxTransport:U(Dt),ajax:function(e,t){function n(e,t,n,a){var u,d,y,b,x,k=t;2!==w&&(w=2,l&&r.clearTimeout(l),i=void 0,s=a||"",C.readyState=e>0?4:0,u=e>=200&&300>e||304===e,n&&(b=K(f,C,n)),b=G(f,b,C,u),u?(f.ifModified&&(x=C.getResponseHeader("Last-Modified"),x&&(ce.lastModified[o]=x),x=C.getResponseHeader("etag"),x&&(ce.etag[o]=x)),204===e||"HEAD"===f.type?k="nocontent":304===e?k="notmodified":(k=b.state,d=b.data,y=b.error,u=!y)):(y=k,!e&&k||(k="error",0>e&&(e=0))),C.status=e,C.statusText=(t||k)+"",u?g.resolveWith(h,[d,k,C]):g.rejectWith(h,[C,k,y]),C.statusCode(v),v=void 0,c&&p.trigger(u?"ajaxSuccess":"ajaxError",[C,f,u?d:y]),m.fireWith(h,[C,k]),c&&(p.trigger("ajaxComplete",[C,f]),--ce.active||ce.event.trigger("ajaxStop")))}"object"==typeof e&&(t=e,e=void 0),t=t||{};var i,o,s,a,l,u,c,d,f=ce.ajaxSetup({},t),h=f.context||f,p=f.context&&(h.nodeType||h.jquery)?ce(h):ce.event,g=ce.Deferred(),m=ce.Callbacks("once memory"),v=f.statusCode||{},y={},b={},w=0,x="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===w){if(!a)for(a={};t=Ft.exec(s);)a[t[1].toLowerCase()]=t[2];t=a[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===w?s:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return w||(e=b[n]=b[n]||e,y[e]=t),this},overrideMimeType:function(e){return w||(f.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>w)for(t in e)v[t]=[v[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||x;return i&&i.abort(t),n(0,t),this}};if(g.promise(C).complete=m.add,C.success=C.done,C.error=C.fail,f.url=((e||f.url||xt.href)+"").replace($t,"").replace(_t,xt.protocol+"//"),f.type=t.method||t.type||f.method||f.type,f.dataTypes=ce.trim(f.dataType||"*").toLowerCase().match(Fe)||[""],null==f.crossDomain){u=ee.createElement("a");try{u.href=f.url,u.href=u.href,f.crossDomain=zt.protocol+"//"+zt.host!=u.protocol+"//"+u.host}catch(k){f.crossDomain=!0}}if(f.data&&f.processData&&"string"!=typeof f.data&&(f.data=ce.param(f.data,f.traditional)),Y(St,f,t,C),2===w)return C;c=ce.event&&f.global,c&&0===ce.active++&&ce.event.trigger("ajaxStart"),f.type=f.type.toUpperCase(),f.hasContent=!At.test(f.type),o=f.url,f.hasContent||(f.data&&(o=f.url+=(kt.test(o)?"&":"?")+f.data,delete f.data),f.cache===!1&&(f.url=Tt.test(o)?o.replace(Tt,"$1_="+Ct++):o+(kt.test(o)?"&":"?")+"_="+Ct++)),f.ifModified&&(ce.lastModified[o]&&C.setRequestHeader("If-Modified-Since",ce.lastModified[o]),ce.etag[o]&&C.setRequestHeader("If-None-Match",ce.etag[o])),(f.data&&f.hasContent&&f.contentType!==!1||t.contentType)&&C.setRequestHeader("Content-Type",f.contentType),C.setRequestHeader("Accept",f.dataTypes[0]&&f.accepts[f.dataTypes[0]]?f.accepts[f.dataTypes[0]]+("*"!==f.dataTypes[0]?", "+Ot+"; q=0.01":""):f.accepts["*"]);for(d in f.headers)C.setRequestHeader(d,f.headers[d]);if(f.beforeSend&&(f.beforeSend.call(h,C,f)===!1||2===w))return C.abort();x="abort";for(d in{success:1,error:1,complete:1})C[d](f[d]);if(i=Y(Dt,f,t,C)){if(C.readyState=1,c&&p.trigger("ajaxSend",[C,f]),2===w)return C;f.async&&f.timeout>0&&(l=r.setTimeout(function(){C.abort("timeout")},f.timeout));try{w=1,i.send(y,n)}catch(k){if(!(2>w))throw k;n(-1,k)}}else n(-1,"No Transport");return C},getJSON:function(e,t,n){return ce.get(e,t,n,"json")},getScript:function(e,t){return ce.get(e,void 0,t,"script")}}),ce.each(["get","post"],function(e,t){ce[t]=function(e,n,i,o){return ce.isFunction(n)&&(o=o||i,i=n,n=void 0),ce.ajax(ce.extend({url:e,type:t,dataType:o,data:n,success:i},ce.isPlainObject(e)&&e))}}),ce._evalUrl=function(e){return ce.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},ce.fn.extend({wrapAll:function(e){var t;return ce.isFunction(e)?this.each(function(t){ce(this).wrapAll(e.call(this,t))}):(this[0]&&(t=ce(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstElementChild;)e=e.firstElementChild;return e}).append(this)),this)},wrapInner:function(e){return ce.isFunction(e)?this.each(function(t){ce(this).wrapInner(e.call(this,t))}):this.each(function(){var t=ce(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=ce.isFunction(e);return this.each(function(n){ce(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){ce.nodeName(this,"body")||ce(this).replaceWith(this.childNodes)}).end()}}),ce.expr.filters.hidden=function(e){return!ce.expr.filters.visible(e)},ce.expr.filters.visible=function(e){return e.offsetWidth>0||e.offsetHeight>0||e.getClientRects().length>0};var Pt=/%20/g,qt=/\[\]$/,Nt=/\r?\n/g,jt=/^(?:submit|button|image|reset|file)$/i,Ht=/^(?:input|select|textarea|keygen)/i;ce.param=function(e,t){var n,i=[],o=function(e,t){t=ce.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=ce.ajaxSettings&&ce.ajaxSettings.traditional),ce.isArray(e)||e.jquery&&!ce.isPlainObject(e))ce.each(e,function(){o(this.name,this.value)});else for(n in e)V(n,e[n],t,o);return i.join("&").replace(Pt,"+")},ce.fn.extend({serialize:function(){return ce.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=ce.prop(this,"elements");return e?ce.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!ce(this).is(":disabled")&&Ht.test(this.nodeName)&&!jt.test(e)&&(this.checked||!He.test(e))}).map(function(e,t){var n=ce(this).val();return null==n?null:ce.isArray(n)?ce.map(n,function(e){return{name:t.name,value:e.replace(Nt,"\r\n")}}):{name:t.name,value:n.replace(Nt,"\r\n")}}).get()}}),ce.ajaxSettings.xhr=function(){try{return new r.XMLHttpRequest}catch(e){}};var Rt={0:200,1223:204},Lt=ce.ajaxSettings.xhr();le.cors=!!Lt&&"withCredentials"in Lt,le.ajax=Lt=!!Lt,ce.ajaxTransport(function(e){var t,n;return le.cors||Lt&&!e.crossDomain?{send:function(i,o){var s,a=e.xhr();if(a.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(s in e.xhrFields)a[s]=e.xhrFields[s];e.mimeType&&a.overrideMimeType&&a.overrideMimeType(e.mimeType),e.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(s in i)a.setRequestHeader(s,i[s]);t=function(e){return function(){t&&(t=n=a.onload=a.onerror=a.onabort=a.onreadystatechange=null,"abort"===e?a.abort():"error"===e?"number"!=typeof a.status?o(0,"error"):o(a.status,a.statusText):o(Rt[a.status]||a.status,a.statusText,"text"!==(a.responseType||"text")||"string"!=typeof a.responseText?{binary:a.response}:{text:a.responseText},a.getAllResponseHeaders()))}},a.onload=t(),n=a.onerror=t("error"),void 0!==a.onabort?a.onabort=n:a.onreadystatechange=function(){4===a.readyState&&r.setTimeout(function(){t&&n()})},t=t("abort");try{a.send(e.hasContent&&e.data||null)}catch(l){if(t)throw l}},abort:function(){t&&t()}}:void 0}),ce.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return ce.globalEval(e),e}}}),ce.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),ce.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(i,o){t=ce("<script>").prop({charset:e.scriptCharset,src:e.url}).on("load error",n=function(e){t.remove(),n=null,e&&o("error"===e.type?404:200,e.type)}),ee.head.appendChild(t[0])},abort:function(){n&&n()}}}});var Mt=[],It=/(=)\?(?=&|$)|\?\?/;ce.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mt.pop()||ce.expando+"_"+Ct++;return this[e]=!0,e}}),ce.ajaxPrefilter("json jsonp",function(e,t,n){var i,o,s,a=e.jsonp!==!1&&(It.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&It.test(e.data)&&"data");return a||"jsonp"===e.dataTypes[0]?(i=e.jsonpCallback=ce.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(It,"$1"+i):e.jsonp!==!1&&(e.url+=(kt.test(e.url)?"&":"?")+e.jsonp+"="+i),e.converters["script json"]=function(){return s||ce.error(i+" was not called"),s[0]},e.dataTypes[0]="json",o=r[i],r[i]=function(){s=arguments},n.always(function(){void 0===o?ce(r).removeProp(i):r[i]=o,e[i]&&(e.jsonpCallback=t.jsonpCallback,Mt.push(i)),s&&ce.isFunction(o)&&o(s[0]),s=o=void 0}),"script"):void 0}),ce.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||ee;var i=be.exec(e),o=!n&&[];return i?[t.createElement(i[1])]:(i=v([e],t,o),o&&o.length&&ce(o).remove(),ce.merge([],i.childNodes))};var Bt=ce.fn.load;ce.fn.load=function(e,t,n){if("string"!=typeof e&&Bt)return Bt.apply(this,arguments);var i,o,r,s=this,a=e.indexOf(" ");return a>-1&&(i=ce.trim(e.slice(a)),e=e.slice(0,a)),ce.isFunction(t)?(n=t,t=void 0):t&&"object"==typeof t&&(o="POST"),s.length>0&&ce.ajax({url:e,type:o||"GET",dataType:"html",data:t}).done(function(e){r=arguments,s.html(i?ce("<div>").append(ce.parseHTML(e)).find(i):e)}).always(n&&function(e,t){s.each(function(){n.apply(this,r||[e.responseText,t,e])})}),this},ce.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ce.fn[t]=function(e){return this.on(t,e)}}),ce.expr.filters.animated=function(e){return ce.grep(ce.timers,function(t){return e===t.elem}).length},ce.offset={setOffset:function(e,t,n){var i,o,r,s,a,l,u,c=ce.css(e,"position"),d=ce(e),f={};"static"===c&&(e.style.position="relative"),a=d.offset(),r=ce.css(e,"top"),l=ce.css(e,"left"),u=("absolute"===c||"fixed"===c)&&(r+l).indexOf("auto")>-1,u?(i=d.position(),s=i.top,o=i.left):(s=parseFloat(r)||0,o=parseFloat(l)||0),ce.isFunction(t)&&(t=t.call(e,n,ce.extend({},a))),null!=t.top&&(f.top=t.top-a.top+s),null!=t.left&&(f.left=t.left-a.left+o),"using"in t?t.using.call(e,f):d.css(f)}},ce.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){ce.offset.setOffset(this,e,t)});var t,n,i=this[0],o={top:0,left:0},r=i&&i.ownerDocument;return r?(t=r.documentElement,ce.contains(t,i)?(o=i.getBoundingClientRect(),n=Z(r),{top:o.top+n.pageYOffset-t.clientTop,left:o.left+n.pageXOffset-t.clientLeft}):o):void 0},position:function(){if(this[0]){var e,t,n=this[0],i={top:0,left:0};return"fixed"===ce.css(n,"position")?t=n.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),ce.nodeName(e[0],"html")||(i=e.offset()),i.top+=ce.css(e[0],"borderTopWidth",!0),i.left+=ce.css(e[0],"borderLeftWidth",!0)),{top:t.top-i.top-ce.css(n,"marginTop",!0),left:t.left-i.left-ce.css(n,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent;e&&"static"===ce.css(e,"position");)e=e.offsetParent;return e||it})}}),ce.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n="pageYOffset"===t;ce.fn[e]=function(i){return Ae(this,function(e,i,o){var r=Z(e);return void 0===o?r?r[t]:e[i]:void(r?r.scrollTo(n?r.pageXOffset:o,n?o:r.pageYOffset):e[i]=o)},e,i,arguments.length)}}),ce.each(["top","left"],function(e,t){ce.cssHooks[t]=O(le.pixelPosition,function(e,n){return n?(n=D(e,t),et.test(n)?ce(e).position()[t]+"px":n):void 0})}),ce.each({Height:"height",Width:"width"},function(e,t){ce.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,i){ce.fn[i]=function(i,o){var r=arguments.length&&(n||"boolean"!=typeof i),s=n||(i===!0||o===!0?"margin":"border");return Ae(this,function(t,n,i){var o;return ce.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(o=t.documentElement,Math.max(t.body["scroll"+e],o["scroll"+e],t.body["offset"+e],o["offset"+e],o["client"+e])):void 0===i?ce.css(t,n,s):ce.style(t,n,i,s)},t,r?i:void 0,r,null)}})}),ce.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,i){return this.on(t,e,n,i)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},size:function(){return this.length}}),ce.fn.andSelf=ce.fn.addBack,n(7)&&(i=[],o=function(){return ce}.apply(t,i),!(void 0!==o&&(e.exports=o)));var Wt=r.jQuery,Qt=r.$;return ce.noConflict=function(e){return r.$===ce&&(r.$=Qt),e&&r.jQuery===ce&&(r.jQuery=Wt),ce},s||(r.jQuery=r.$=ce),ce})},function(e,t,n){var i,o,r;!function(s,a){o=[n(6)],i=a,r="function"==typeof i?i.apply(t,o):i,!(void 0!==r&&(e.exports=r))}(this,function(e){"use strict";function t(t,r,s,a){function l(){t||r.hide(),u(),a&&a.apply(r)}function u(){r[0].style.transitionDuration=0,r.removeClass(c+" "+d+" "+s)}if(r=e(r).eq(0),r.length){if(null===o)return t?r.show():r.hide(),void a();var c=t?n[0]:n[1],d=t?i[0]:i[1];u(),r.addClass(s),r.css("transition","none"),requestAnimationFrame(function(){r.addClass(c),t&&r.show()}),requestAnimationFrame(function(){r[0].offsetWidth,r.css("transition",""),r.addClass(d)}),r.one("transitionend",l)}}!function(){Date.now||(Date.now=function(){return(new Date).getTime()});for(var e=["webkit","moz"],t=0;t<e.length&&!window.requestAnimationFrame;++t){var n=e[t];window.requestAnimationFrame=window[n+"RequestAnimationFrame"],window.cancelAnimationFrame=window[n+"CancelAnimationFrame"]||window[n+"CancelRequestAnimationFrame"]}if(/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent)||!window.requestAnimationFrame||!window.cancelAnimationFrame){var i=0;window.requestAnimationFrame=function(e){var t=Date.now(),n=Math.max(i+16,t);return setTimeout(function(){e(i=n)},n-t)},window.cancelAnimationFrame=clearTimeout}}();var n=["mui-enter","mui-leave"],i=["mui-enter-active","mui-leave-active"],o=function(){var e={transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"otransitionend"},t=window.document.createElement("div");for(var n in e)if("undefined"!=typeof t.style[n])return e[n];return null}(),r={animateIn:function(e,n,i){t(!0,e,n,i)},animateOut:function(e,n,i){t(!1,e,n,i)}};return r})},function(e,t,n){var i,o;/*!
* jQuery JavaScript Library v2.2.4
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-05-20T17:23Z
*/
!function(t,n){"object"==typeof e&&"object"==typeof e.exports?e.exports=t.document?n(t,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return n(e)}:n(t)}("undefined"!=typeof window?window:this,function(n,r){function s(e){var t=!!e&&"length"in e&&e.length,n=ue.type(e);return"function"!==n&&!ue.isWindow(e)&&("array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e)}function a(e,t,n){if(ue.isFunction(t))return ue.grep(e,function(e,i){return!!t.call(e,i,e)!==n});if(t.nodeType)return ue.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(be.test(t))return ue.filter(t,e,n);t=ue.filter(t,e)}return ue.grep(e,function(e){return ie.call(t,e)>-1!==n})}function l(e,t){for(;(e=e[t])&&1!==e.nodeType;);return e}function u(e){var t={};return ue.each(e.match(Te)||[],function(e,n){t[n]=!0}),t}function c(){J.removeEventListener("DOMContentLoaded",c),n.removeEventListener("load",c),ue.ready()}function d(){this.expando=ue.expando+d.uid++}function f(e,t,n){var i;if(void 0===n&&1===e.nodeType)if(i="data-"+t.replace(Oe,"-$&").toLowerCase(),n=e.getAttribute(i),"string"==typeof n){try{n="true"===n||"false"!==n&&("null"===n?null:+n+""===n?+n:De.test(n)?ue.parseJSON(n):n)}catch(o){}Se.set(e,t,n)}else n=void 0;return n}function h(e,t,n,i){var o,r=1,s=20,a=i?function(){return i.cur()}:function(){return ue.css(e,t,"")},l=a(),u=n&&n[3]||(ue.cssNumber[t]?"":"px"),c=(ue.cssNumber[t]||"px"!==u&&+l)&&Pe.exec(ue.css(e,t));if(c&&c[3]!==u){u=u||c[3],n=n||[],c=+l||1;do r=r||".5",c/=r,ue.style(e,t,c+u);while(r!==(r=a()/l)&&1!==r&&--s)}return n&&(c=+c||+l||0,o=n[1]?c+(n[1]+1)*n[2]:+n[2],i&&(i.unit=u,i.start=c,i.end=o)),o}function p(e,t){var n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[];return void 0===t||t&&ue.nodeName(e,t)?ue.merge([e],n):n}function g(e,t){for(var n=0,i=e.length;n<i;n++)_e.set(e[n],"globalEval",!t||_e.get(t[n],"globalEval"))}function m(e,t,n,i,o){for(var r,s,a,l,u,c,d=t.createDocumentFragment(),f=[],h=0,m=e.length;h<m;h++)if(r=e[h],r||0===r)if("object"===ue.type(r))ue.merge(f,r.nodeType?[r]:r);else if(Me.test(r)){for(s=s||d.appendChild(t.createElement("div")),a=(He.exec(r)||["",""])[1].toLowerCase(),l=Le[a]||Le._default,s.innerHTML=l[1]+ue.htmlPrefilter(r)+l[2],c=l[0];c--;)s=s.lastChild;ue.merge(f,s.childNodes),s=d.firstChild,s.textContent=""}else f.push(t.createTextNode(r));for(d.textContent="",h=0;r=f[h++];)if(i&&ue.inArray(r,i)>-1)o&&o.push(r);else if(u=ue.contains(r.ownerDocument,r),s=p(d.appendChild(r),"script"),u&&g(s),n)for(c=0;r=s[c++];)Re.test(r.type||"")&&n.push(r);return d}function v(){return!0}function y(){return!1}function b(){try{return J.activeElement}catch(e){}}function w(e,t,n,i,o,r){var s,a;if("object"==typeof t){"string"!=typeof n&&(i=i||n,n=void 0);for(a in t)w(e,a,n,i,t[a],r);return e}if(null==i&&null==o?(o=n,i=n=void 0):null==o&&("string"==typeof n?(o=i,i=void 0):(o=i,i=n,n=void 0)),o===!1)o=y;else if(!o)return e;return 1===r&&(s=o,o=function(e){return ue().off(e),s.apply(this,arguments)},o.guid=s.guid||(s.guid=ue.guid++)),e.each(function(){ue.event.add(this,t,o,i,n)})}function x(e,t){return ue.nodeName(e,"table")&&ue.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function C(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function k(e){var t=Xe.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function $(e,t){var n,i,o,r,s,a,l,u;if(1===t.nodeType){if(_e.hasData(e)&&(r=_e.access(e),s=_e.set(t,r),u=r.events)){delete s.handle,s.events={};for(o in u)for(n=0,i=u[o].length;n<i;n++)ue.event.add(t,o,u[o][n])}Se.hasData(e)&&(a=Se.access(e),l=ue.extend({},a),Se.set(t,l))}}function T(e,t){var n=t.nodeName.toLowerCase();"input"===n&&je.test(e.type)?t.checked=e.checked:"input"!==n&&"textarea"!==n||(t.defaultValue=e.defaultValue)}function F(e,t,n,i){t=te.apply([],t);var o,r,s,a,l,u,c=0,d=e.length,f=d-1,h=t[0],g=ue.isFunction(h);if(g||d>1&&"string"==typeof h&&!ae.checkClone&&Ye.test(h))return e.each(function(o){var r=e.eq(o);g&&(t[0]=h.call(this,o,r.html())),F(r,t,n,i)});if(d&&(o=m(t,e[0].ownerDocument,!1,e,i),r=o.firstChild,1===o.childNodes.length&&(o=r),r||i)){for(s=ue.map(p(o,"script"),C),a=s.length;c<d;c++)l=o,c!==f&&(l=ue.clone(l,!0,!0),a&&ue.merge(s,p(l,"script"))),n.call(e[c],l,c);if(a)for(u=s[s.length-1].ownerDocument,ue.map(s,k),c=0;c<a;c++)l=s[c],Re.test(l.type||"")&&!_e.access(l,"globalEval")&&ue.contains(u,l)&&(l.src?ue._evalUrl&&ue._evalUrl(l.src):ue.globalEval(l.textContent.replace(Ke,"")))}return e}function E(e,t,n){for(var i,o=t?ue.filter(t,e):e,r=0;null!=(i=o[r]);r++)n||1!==i.nodeType||ue.cleanData(p(i)),i.parentNode&&(n&&ue.contains(i.ownerDocument,i)&&g(p(i,"script")),i.parentNode.removeChild(i));return e}function A(e,t){var n=ue(t.createElement(e)).appendTo(t.body),i=ue.css(n[0],"display");return n.detach(),i}function _(e){var t=J,n=Ve[e];return n||(n=A(e,t),"none"!==n&&n||(Ge=(Ge||ue("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=Ge[0].contentDocument,t.write(),t.close(),n=A(e,t),Ge.detach()),Ve[e]=n),n}function S(e,t,n){var i,o,r,s,a=e.style;return n=n||et(e),s=n?n.getPropertyValue(t)||n[t]:void 0,""!==s&&void 0!==s||ue.contains(e.ownerDocument,e)||(s=ue.style(e,t)),n&&!ae.pixelMarginRight()&&Je.test(s)&&Ze.test(t)&&(i=a.width,o=a.minWidth,r=a.maxWidth,a.minWidth=a.maxWidth=a.width=s,s=n.width,a.width=i,a.minWidth=o,a.maxWidth=r),void 0!==s?s+"":s}function D(e,t){return{get:function(){return e()?void delete this.get:(this.get=t).apply(this,arguments)}}}function O(e){if(e in at)return e;for(var t=e[0].toUpperCase()+e.slice(1),n=st.length;n--;)if(e=st[n]+t,e in at)return e}function z(e,t,n){var i=Pe.exec(t);return i?Math.max(0,i[2]-(n||0))+(i[3]||"px"):t}function P(e,t,n,i,o){for(var r=n===(i?"border":"content")?4:"width"===t?1:0,s=0;r<4;r+=2)"margin"===n&&(s+=ue.css(e,n+qe[r],!0,o)),i?("content"===n&&(s-=ue.css(e,"padding"+qe[r],!0,o)),"margin"!==n&&(s-=ue.css(e,"border"+qe[r]+"Width",!0,o))):(s+=ue.css(e,"padding"+qe[r],!0,o),"padding"!==n&&(s+=ue.css(e,"border"+qe[r]+"Width",!0,o)));return s}function q(e,t,n){var i=!0,o="width"===t?e.offsetWidth:e.offsetHeight,r=et(e),s="border-box"===ue.css(e,"boxSizing",!1,r);if(o<=0||null==o){if(o=S(e,t,r),(o<0||null==o)&&(o=e.style[t]),Je.test(o))return o;i=s&&(ae.boxSizingReliable()||o===e.style[t]),o=parseFloat(o)||0}return o+P(e,t,n||(s?"border":"content"),i,r)+"px"}function N(e,t){for(var n,i,o,r=[],s=0,a=e.length;s<a;s++)i=e[s],i.style&&(r[s]=_e.get(i,"olddisplay"),n=i.style.display,t?(r[s]||"none"!==n||(i.style.display=""),""===i.style.display&&Ne(i)&&(r[s]=_e.access(i,"olddisplay",_(i.nodeName)))):(o=Ne(i),"none"===n&&o||_e.set(i,"olddisplay",o?n:ue.css(i,"display"))));for(s=0;s<a;s++)i=e[s],i.style&&(t&&"none"!==i.style.display&&""!==i.style.display||(i.style.display=t?r[s]||"":"none"));return e}function j(e,t,n,i,o){return new j.prototype.init(e,t,n,i,o)}function H(){return n.setTimeout(function(){lt=void 0}),lt=ue.now()}function R(e,t){var n,i=0,o={height:e};for(t=t?1:0;i<4;i+=2-t)n=qe[i],o["margin"+n]=o["padding"+n]=e;return t&&(o.opacity=o.width=e),o}function L(e,t,n){for(var i,o=(B.tweeners[t]||[]).concat(B.tweeners["*"]),r=0,s=o.length;r<s;r++)if(i=o[r].call(n,t,e))return i}function M(e,t,n){var i,o,r,s,a,l,u,c,d=this,f={},h=e.style,p=e.nodeType&&Ne(e),g=_e.get(e,"fxshow");n.queue||(a=ue._queueHooks(e,"fx"),null==a.unqueued&&(a.unqueued=0,l=a.empty.fire,a.empty.fire=function(){a.unqueued||l()}),a.unqueued++,d.always(function(){d.always(function(){a.unqueued--,ue.queue(e,"fx").length||a.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],u=ue.css(e,"display"),c="none"===u?_e.get(e,"olddisplay")||_(e.nodeName):u,"inline"===c&&"none"===ue.css(e,"float")&&(h.display="inline-block")),n.overflow&&(h.overflow="hidden",d.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]}));for(i in t)if(o=t[i],ct.exec(o)){if(delete t[i],r=r||"toggle"===o,o===(p?"hide":"show")){if("show"!==o||!g||void 0===g[i])continue;p=!0}f[i]=g&&g[i]||ue.style(e,i)}else u=void 0;if(ue.isEmptyObject(f))"inline"===("none"===u?_(e.nodeName):u)&&(h.display=u);else{g?"hidden"in g&&(p=g.hidden):g=_e.access(e,"fxshow",{}),r&&(g.hidden=!p),p?ue(e).show():d.done(function(){ue(e).hide()}),d.done(function(){var t;_e.remove(e,"fxshow");for(t in f)ue.style(e,t,f[t])});for(i in f)s=L(p?g[i]:0,i,d),i in g||(g[i]=s.start,p&&(s.end=s.start,s.start="width"===i||"height"===i?1:0))}}function I(e,t){var n,i,o,r,s;for(n in e)if(i=ue.camelCase(n),o=t[i],r=e[n],ue.isArray(r)&&(o=r[1],r=e[n]=r[0]),n!==i&&(e[i]=r,delete e[n]),s=ue.cssHooks[i],s&&"expand"in s){r=s.expand(r),delete e[i];for(n in r)n in e||(e[n]=r[n],t[n]=o)}else t[i]=o}function B(e,t,n){var i,o,r=0,s=B.prefilters.length,a=ue.Deferred().always(function(){delete l.elem}),l=function(){if(o)return!1;for(var t=lt||H(),n=Math.max(0,u.startTime+u.duration-t),i=n/u.duration||0,r=1-i,s=0,l=u.tweens.length;s<l;s++)u.tweens[s].run(r);return a.notifyWith(e,[u,r,n]),r<1&&l?n:(a.resolveWith(e,[u]),!1)},u=a.promise({elem:e,props:ue.extend({},t),opts:ue.extend(!0,{specialEasing:{},easing:ue.easing._default},n),originalProperties:t,originalOptions:n,startTime:lt||H(),duration:n.duration,tweens:[],createTween:function(t,n){var i=ue.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(i),i},stop:function(t){var n=0,i=t?u.tweens.length:0;if(o)return this;for(o=!0;n<i;n++)u.tweens[n].run(1);return t?(a.notifyWith(e,[u,1,0]),a.resolveWith(e,[u,t])):a.rejectWith(e,[u,t]),this}}),c=u.props;for(I(c,u.opts.specialEasing);r<s;r++)if(i=B.prefilters[r].call(u,e,c,u.opts))return ue.isFunction(i.stop)&&(ue._queueHooks(u.elem,u.opts.queue).stop=ue.proxy(i.stop,i)),i;return ue.map(c,L,u),ue.isFunction(u.opts.start)&&u.opts.start.call(e,u),ue.fx.timer(ue.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function W(e){return e.getAttribute&&e.getAttribute("class")||""}function Q(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var i,o=0,r=t.toLowerCase().match(Te)||[];if(ue.isFunction(n))for(;i=r[o++];)"+"===i[0]?(i=i.slice(1)||"*",(e[i]=e[i]||[]).unshift(n)):(e[i]=e[i]||[]).push(n)}}function U(e,t,n,i){function o(a){var l;return r[a]=!0,ue.each(e[a]||[],function(e,a){var u=a(t,n,i);return"string"!=typeof u||s||r[u]?s?!(l=u):void 0:(t.dataTypes.unshift(u),o(u),!1)}),l}var r={},s=e===St;return o(t.dataTypes[0])||!r["*"]&&o("*")}function Y(e,t){var n,i,o=ue.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((o[n]?e:i||(i={}))[n]=t[n]);return i&&ue.extend(!0,e,i),e}function X(e,t,n){for(var i,o,r,s,a=e.contents,l=e.dataTypes;"*"===l[0];)l.shift(),void 0===i&&(i=e.mimeType||t.getResponseHeader("Content-Type"));if(i)for(o in a)if(a[o]&&a[o].test(i)){l.unshift(o);break}if(l[0]in n)r=l[0];else{for(o in n){if(!l[0]||e.converters[o+" "+l[0]]){r=o;break}s||(s=o)}r=r||s}if(r)return r!==l[0]&&l.unshift(r),n[r]}function K(e,t,n,i){var o,r,s,a,l,u={},c=e.dataTypes.slice();if(c[1])for(s in e.converters)u[s.toLowerCase()]=e.converters[s];for(r=c.shift();r;)if(e.responseFields[r]&&(n[e.responseFields[r]]=t),!l&&i&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=r,r=c.shift())if("*"===r)r=l;else if("*"!==l&&l!==r){if(s=u[l+" "+r]||u["* "+r],!s)for(o in u)if(a=o.split(" "),a[1]===r&&(s=u[l+" "+a[0]]||u["* "+a[0]])){s===!0?s=u[o]:u[o]!==!0&&(r=a[0],c.unshift(a[1]));break}if(s!==!0)if(s&&e["throws"])t=s(t);else try{t=s(t)}catch(d){return{state:"parsererror",error:s?d:"No conversion from "+l+" to "+r}}}return{state:"success",data:t}}function G(e,t,n,i){var o;if(ue.isArray(t))ue.each(t,function(t,o){n||Pt.test(e)?i(e,o):G(e+"["+("object"==typeof o&&null!=o?t:"")+"]",o,n,i)});else if(n||"object"!==ue.type(t))i(e,t);else for(o in t)G(e+"["+o+"]",t[o],n,i)}function V(e){return ue.isWindow(e)?e:9===e.nodeType&&e.defaultView}var Z=[],J=n.document,ee=Z.slice,te=Z.concat,ne=Z.push,ie=Z.indexOf,oe={},re=oe.toString,se=oe.hasOwnProperty,ae={},le="2.2.4",ue=function(e,t){return new ue.fn.init(e,t)},ce=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,de=/^-ms-/,fe=/-([\da-z])/gi,he=function(e,t){return t.toUpperCase()};ue.fn=ue.prototype={jquery:le,constructor:ue,selector:"",length:0,toArray:function(){return ee.call(this)},get:function(e){return null!=e?e<0?this[e+this.length]:this[e]:ee.call(this)},pushStack:function(e){var t=ue.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e){return ue.each(this,e)},map:function(e){return this.pushStack(ue.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(ee.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:ne,sort:Z.sort,splice:Z.splice},ue.extend=ue.fn.extend=function(){var e,t,n,i,o,r,s=arguments[0]||{},a=1,l=arguments.length,u=!1;for("boolean"==typeof s&&(u=s,s=arguments[a]||{},a++),"object"==typeof s||ue.isFunction(s)||(s={}),a===l&&(s=this,a--);a<l;a++)if(null!=(e=arguments[a]))for(t in e)n=s[t],i=e[t],s!==i&&(u&&i&&(ue.isPlainObject(i)||(o=ue.isArray(i)))?(o?(o=!1,r=n&&ue.isArray(n)?n:[]):r=n&&ue.isPlainObject(n)?n:{},s[t]=ue.extend(u,r,i)):void 0!==i&&(s[t]=i));return s},ue.extend({expando:"jQuery"+(le+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===ue.type(e)},isArray:Array.isArray,isWindow:function(e){return null!=e&&e===e.window},isNumeric:function(e){var t=e&&e.toString();return!ue.isArray(e)&&t-parseFloat(t)+1>=0},isPlainObject:function(e){var t;if("object"!==ue.type(e)||e.nodeType||ue.isWindow(e))return!1;if(e.constructor&&!se.call(e,"constructor")&&!se.call(e.constructor.prototype||{},"isPrototypeOf"))return!1;for(t in e);return void 0===t||se.call(e,t)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?oe[re.call(e)]||"object":typeof e},globalEval:function(e){var t,n=eval;e=ue.trim(e),e&&(1===e.indexOf("use strict")?(t=J.createElement("script"),t.text=e,J.head.appendChild(t).parentNode.removeChild(t)):n(e))},camelCase:function(e){return e.replace(de,"ms-").replace(fe,he)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t){var n,i=0;if(s(e))for(n=e.length;i<n&&t.call(e[i],i,e[i])!==!1;i++);else for(i in e)if(t.call(e[i],i,e[i])===!1)break;return e},trim:function(e){return null==e?"":(e+"").replace(ce,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(s(Object(e))?ue.merge(n,"string"==typeof e?[e]:e):ne.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:ie.call(t,e,n)},merge:function(e,t){for(var n=+t.length,i=0,o=e.length;i<n;i++)e[o++]=t[i];return e.length=o,e},grep:function(e,t,n){for(var i,o=[],r=0,s=e.length,a=!n;r<s;r++)i=!t(e[r],r),i!==a&&o.push(e[r]);return o},map:function(e,t,n){var i,o,r=0,a=[];if(s(e))for(i=e.length;r<i;r++)o=t(e[r],r,n),null!=o&&a.push(o);else for(r in e)o=t(e[r],r,n),null!=o&&a.push(o);return te.apply([],a)},guid:1,proxy:function(e,t){var n,i,o;if("string"==typeof t&&(n=e[t],t=e,e=n),ue.isFunction(e))return i=ee.call(arguments,2),o=function(){return e.apply(t||this,i.concat(ee.call(arguments)))},o.guid=e.guid=e.guid||ue.guid++,o},now:Date.now,support:ae}),"function"==typeof Symbol&&(ue.fn[Symbol.iterator]=Z[Symbol.iterator]),ue.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){oe["[object "+t+"]"]=t.toLowerCase()});var pe=/*!
* Sizzle CSS Selector Engine v2.2.1
* http://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2015-10-17
*/
function(e){function t(e,t,n,i){var o,r,s,a,l,u,d,h,p=t&&t.ownerDocument,g=t?t.nodeType:9;if(n=n||[],"string"!=typeof e||!e||1!==g&&9!==g&&11!==g)return n;if(!i&&((t?t.ownerDocument||t:L)!==O&&D(t),t=t||O,P)){if(11!==g&&(u=ve.exec(e)))if(o=u[1]){if(9===g){if(!(s=t.getElementById(o)))return n;if(s.id===o)return n.push(s),n}else if(p&&(s=p.getElementById(o))&&H(t,s)&&s.id===o)return n.push(s),n}else{if(u[2])return Z.apply(n,t.getElementsByTagName(e)),n;if((o=u[3])&&x.getElementsByClassName&&t.getElementsByClassName)return Z.apply(n,t.getElementsByClassName(o)),n}if(x.qsa&&!Q[e+" "]&&(!q||!q.test(e))){if(1!==g)p=t,h=e;else if("object"!==t.nodeName.toLowerCase()){for((a=t.getAttribute("id"))?a=a.replace(be,"\\$&"):t.setAttribute("id",a=R),d=T(e),r=d.length,l=fe.test(a)?"#"+a:"[id='"+a+"']";r--;)d[r]=l+" "+f(d[r]);h=d.join(","),p=ye.test(e)&&c(t.parentNode)||t}if(h)try{return Z.apply(n,p.querySelectorAll(h)),n}catch(m){}finally{a===R&&t.removeAttribute("id")}}}return E(e.replace(ae,"$1"),t,n,i)}function n(){function e(n,i){return t.push(n+" ")>C.cacheLength&&delete e[t.shift()],e[n+" "]=i}var t=[];return e}function i(e){return e[R]=!0,e}function o(e){var t=O.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function r(e,t){for(var n=e.split("|"),i=n.length;i--;)C.attrHandle[n[i]]=t}function s(e,t){var n=t&&e,i=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||Y)-(~e.sourceIndex||Y);if(i)return i;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function a(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function l(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function u(e){return i(function(t){return t=+t,i(function(n,i){for(var o,r=e([],n.length,t),s=r.length;s--;)n[o=r[s]]&&(n[o]=!(i[o]=n[o]))})})}function c(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function d(){}function f(e){for(var t=0,n=e.length,i="";t<n;t++)i+=e[t].value;return i}function h(e,t,n){var i=t.dir,o=n&&"parentNode"===i,r=I++;return t.first?function(t,n,r){for(;t=t[i];)if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var a,l,u,c=[M,r];if(s){for(;t=t[i];)if((1===t.nodeType||o)&&e(t,n,s))return!0}else for(;t=t[i];)if(1===t.nodeType||o){if(u=t[R]||(t[R]={}),l=u[t.uniqueID]||(u[t.uniqueID]={}),(a=l[i])&&a[0]===M&&a[1]===r)return c[2]=a[2];if(l[i]=c,c[2]=e(t,n,s))return!0}}}function p(e){return e.length>1?function(t,n,i){for(var o=e.length;o--;)if(!e[o](t,n,i))return!1;return!0}:e[0]}function g(e,n,i){for(var o=0,r=n.length;o<r;o++)t(e,n[o],i);return i}function m(e,t,n,i,o){for(var r,s=[],a=0,l=e.length,u=null!=t;a<l;a++)(r=e[a])&&(n&&!n(r,i,o)||(s.push(r),u&&t.push(a)));return s}function v(e,t,n,o,r,s){return o&&!o[R]&&(o=v(o)),r&&!r[R]&&(r=v(r,s)),i(function(i,s,a,l){var u,c,d,f=[],h=[],p=s.length,v=i||g(t||"*",a.nodeType?[a]:a,[]),y=!e||!i&&t?v:m(v,f,e,a,l),b=n?r||(i?e:p||o)?[]:s:y;if(n&&n(y,b,a,l),o)for(u=m(b,h),o(u,[],a,l),c=u.length;c--;)(d=u[c])&&(b[h[c]]=!(y[h[c]]=d));if(i){if(r||e){if(r){for(u=[],c=b.length;c--;)(d=b[c])&&u.push(y[c]=d);r(null,b=[],u,l)}for(c=b.length;c--;)(d=b[c])&&(u=r?ee(i,d):f[c])>-1&&(i[u]=!(s[u]=d))}}else b=m(b===s?b.splice(p,b.length):b),r?r(null,s,b,l):Z.apply(s,b)})}function y(e){for(var t,n,i,o=e.length,r=C.relative[e[0].type],s=r||C.relative[" "],a=r?1:0,l=h(function(e){return e===t},s,!0),u=h(function(e){return ee(t,e)>-1},s,!0),c=[function(e,n,i){var o=!r&&(i||n!==A)||((t=n).nodeType?l(e,n,i):u(e,n,i));return t=null,o}];a<o;a++)if(n=C.relative[e[a].type])c=[h(p(c),n)];else{if(n=C.filter[e[a].type].apply(null,e[a].matches),n[R]){for(i=++a;i<o&&!C.relative[e[i].type];i++);return v(a>1&&p(c),a>1&&f(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(ae,"$1"),n,a<i&&y(e.slice(a,i)),i<o&&y(e=e.slice(i)),i<o&&f(e))}c.push(n)}return p(c)}function b(e,n){var o=n.length>0,r=e.length>0,s=function(i,s,a,l,u){var c,d,f,h=0,p="0",g=i&&[],v=[],y=A,b=i||r&&C.find.TAG("*",u),w=M+=null==y?1:Math.random()||.1,x=b.length;for(u&&(A=s===O||s||u);p!==x&&null!=(c=b[p]);p++){if(r&&c){for(d=0,s||c.ownerDocument===O||(D(c),a=!P);f=e[d++];)if(f(c,s||O,a)){l.push(c);break}u&&(M=w)}o&&((c=!f&&c)&&h--,i&&g.push(c))}if(h+=p,o&&p!==h){for(d=0;f=n[d++];)f(g,v,s,a);if(i){if(h>0)for(;p--;)g[p]||v[p]||(v[p]=G.call(l));v=m(v)}Z.apply(l,v),u&&!i&&v.length>0&&h+n.length>1&&t.uniqueSort(l)}return u&&(M=w,A=y),g};return o?i(s):s}var w,x,C,k,$,T,F,E,A,_,S,D,O,z,P,q,N,j,H,R="sizzle"+1*new Date,L=e.document,M=0,I=0,B=n(),W=n(),Q=n(),U=function(e,t){return e===t&&(S=!0),0},Y=1<<31,X={}.hasOwnProperty,K=[],G=K.pop,V=K.push,Z=K.push,J=K.slice,ee=function(e,t){for(var n=0,i=e.length;n<i;n++)if(e[n]===t)return n;return-1},te="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",ne="[\\x20\\t\\r\\n\\f]",ie="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",oe="\\["+ne+"*("+ie+")(?:"+ne+"*([*^$|!~]?=)"+ne+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+ie+"))|)"+ne+"*\\]",re=":("+ie+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+oe+")*)|.*)\\)|)",se=new RegExp(ne+"+","g"),ae=new RegExp("^"+ne+"+|((?:^|[^\\\\])(?:\\\\.)*)"+ne+"+$","g"),le=new RegExp("^"+ne+"*,"+ne+"*"),ue=new RegExp("^"+ne+"*([>+~]|"+ne+")"+ne+"*"),ce=new RegExp("="+ne+"*([^\\]'\"]*?)"+ne+"*\\]","g"),de=new RegExp(re),fe=new RegExp("^"+ie+"$"),he={ID:new RegExp("^#("+ie+")"),CLASS:new RegExp("^\\.("+ie+")"),TAG:new RegExp("^("+ie+"|[*])"),ATTR:new RegExp("^"+oe),PSEUDO:new RegExp("^"+re),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ne+"*(even|odd|(([+-]|)(\\d*)n|)"+ne+"*(?:([+-]|)"+ne+"*(\\d+)|))"+ne+"*\\)|)","i"),bool:new RegExp("^(?:"+te+")$","i"),needsContext:new RegExp("^"+ne+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ne+"*((?:-\\d)?\\d*)"+ne+"*\\)|)(?=[^-]|$)","i")},pe=/^(?:input|select|textarea|button)$/i,ge=/^h\d$/i,me=/^[^{]+\{\s*\[native \w/,ve=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ye=/[+~]/,be=/'|\\/g,we=new RegExp("\\\\([\\da-f]{1,6}"+ne+"?|("+ne+")|.)","ig"),xe=function(e,t,n){var i="0x"+t-65536;return i!==i||n?t:i<0?String.fromCharCode(i+65536):String.fromCharCode(i>>10|55296,1023&i|56320)},Ce=function(){D()};try{Z.apply(K=J.call(L.childNodes),L.childNodes),K[L.childNodes.length].nodeType}catch(ke){Z={apply:K.length?function(e,t){V.apply(e,J.call(t))}:function(e,t){for(var n=e.length,i=0;e[n++]=t[i++];);e.length=n-1}}}x=t.support={},$=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},D=t.setDocument=function(e){var t,n,i=e?e.ownerDocument||e:L;return i!==O&&9===i.nodeType&&i.documentElement?(O=i,z=O.documentElement,P=!$(O),(n=O.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",Ce,!1):n.attachEvent&&n.attachEvent("onunload",Ce)),x.attributes=o(function(e){return e.className="i",!e.getAttribute("className")}),x.getElementsByTagName=o(function(e){return e.appendChild(O.createComment("")),!e.getElementsByTagName("*").length}),x.getElementsByClassName=me.test(O.getElementsByClassName),x.getById=o(function(e){return z.appendChild(e).id=R,!O.getElementsByName||!O.getElementsByName(R).length}),x.getById?(C.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&P){var n=t.getElementById(e);return n?[n]:[]}},C.filter.ID=function(e){var t=e.replace(we,xe);return function(e){return e.getAttribute("id")===t}}):(delete C.find.ID,C.filter.ID=function(e){var t=e.replace(we,xe);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}}),C.find.TAG=x.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):x.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,i=[],o=0,r=t.getElementsByTagName(e);if("*"===e){for(;n=r[o++];)1===n.nodeType&&i.push(n);return i}return r},C.find.CLASS=x.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&P)return t.getElementsByClassName(e)},N=[],q=[],(x.qsa=me.test(O.querySelectorAll))&&(o(function(e){z.appendChild(e).innerHTML="<a id='"+R+"'></a><select id='"+R+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+ne+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||q.push("\\["+ne+"*(?:value|"+te+")"),e.querySelectorAll("[id~="+R+"-]").length||q.push("~="),e.querySelectorAll(":checked").length||q.push(":checked"),e.querySelectorAll("a#"+R+"+*").length||q.push(".#.+[+~]")}),o(function(e){var t=O.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&q.push("name"+ne+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),q.push(",.*:")})),(x.matchesSelector=me.test(j=z.matches||z.webkitMatchesSelector||z.mozMatchesSelector||z.oMatchesSelector||z.msMatchesSelector))&&o(function(e){x.disconnectedMatch=j.call(e,"div"),j.call(e,"[s!='']:x"),N.push("!=",re)}),q=q.length&&new RegExp(q.join("|")),N=N.length&&new RegExp(N.join("|")),t=me.test(z.compareDocumentPosition),H=t||me.test(z.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,i=t&&t.parentNode;return e===i||!(!i||1!==i.nodeType||!(n.contains?n.contains(i):e.compareDocumentPosition&&16&e.compareDocumentPosition(i)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},U=t?function(e,t){if(e===t)return S=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n?n:(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&n||!x.sortDetached&&t.compareDocumentPosition(e)===n?e===O||e.ownerDocument===L&&H(L,e)?-1:t===O||t.ownerDocument===L&&H(L,t)?1:_?ee(_,e)-ee(_,t):0:4&n?-1:1)}:function(e,t){if(e===t)return S=!0,0;var n,i=0,o=e.parentNode,r=t.parentNode,a=[e],l=[t];if(!o||!r)return e===O?-1:t===O?1:o?-1:r?1:_?ee(_,e)-ee(_,t):0;if(o===r)return s(e,t);for(n=e;n=n.parentNode;)a.unshift(n);for(n=t;n=n.parentNode;)l.unshift(n);for(;a[i]===l[i];)i++;return i?s(a[i],l[i]):a[i]===L?-1:l[i]===L?1:0},O):O},t.matches=function(e,n){return t(e,null,null,n)},t.matchesSelector=function(e,n){if((e.ownerDocument||e)!==O&&D(e),n=n.replace(ce,"='$1']"),x.matchesSelector&&P&&!Q[n+" "]&&(!N||!N.test(n))&&(!q||!q.test(n)))try{var i=j.call(e,n);if(i||x.disconnectedMatch||e.document&&11!==e.document.nodeType)return i}catch(o){}return t(n,O,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==O&&D(e),H(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==O&&D(e);var n=C.attrHandle[t.toLowerCase()],i=n&&X.call(C.attrHandle,t.toLowerCase())?n(e,t,!P):void 0;return void 0!==i?i:x.attributes||!P?e.getAttribute(t):(i=e.getAttributeNode(t))&&i.specified?i.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!x.detectDuplicates,_=!x.sortStable&&e.slice(0),e.sort(U),S){for(;t=e[o++];)t===e[o]&&(i=n.push(o));for(;i--;)e.splice(n[i],1)}return _=null,e},k=t.getText=function(e){var t,n="",i=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=k(e)}else if(3===o||4===o)return e.nodeValue}else for(;t=e[i++];)n+=k(t);return n},C=t.selectors={cacheLength:50,createPseudo:i,match:he,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(we,xe),e[3]=(e[3]||e[4]||e[5]||"").replace(we,xe),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||t.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&t.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return he.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&de.test(n)&&(t=T(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(we,xe).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=B[e+" "];return t||(t=new RegExp("(^|"+ne+")"+e+"("+ne+"|$)"))&&B(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,n,i){return function(o){var r=t.attr(o,e);return null==r?"!="===n:!n||(r+="","="===n?r===i:"!="===n?r!==i:"^="===n?i&&0===r.indexOf(i):"*="===n?i&&r.indexOf(i)>-1:"$="===n?i&&r.slice(-i.length)===i:"~="===n?(" "+r.replace(se," ")+" ").indexOf(i)>-1:"|="===n&&(r===i||r.slice(0,i.length+1)===i+"-"))}},CHILD:function(e,t,n,i,o){var r="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===i&&0===o?function(e){return!!e.parentNode}:function(t,n,l){var u,c,d,f,h,p,g=r!==s?"nextSibling":"previousSibling",m=t.parentNode,v=a&&t.nodeName.toLowerCase(),y=!l&&!a,b=!1;if(m){if(r){for(;g;){for(f=t;f=f[g];)if(a?f.nodeName.toLowerCase()===v:1===f.nodeType)return!1;p=g="only"===e&&!p&&"nextSibling"}return!0}if(p=[s?m.firstChild:m.lastChild],s&&y){for(f=m,d=f[R]||(f[R]={}),c=d[f.uniqueID]||(d[f.uniqueID]={}),u=c[e]||[],h=u[0]===M&&u[1],b=h&&u[2],f=h&&m.childNodes[h];f=++h&&f&&f[g]||(b=h=0)||p.pop();)if(1===f.nodeType&&++b&&f===t){c[e]=[M,h,b];break}}else if(y&&(f=t,d=f[R]||(f[R]={}),c=d[f.uniqueID]||(d[f.uniqueID]={}),u=c[e]||[],h=u[0]===M&&u[1],b=h),b===!1)for(;(f=++h&&f&&f[g]||(b=h=0)||p.pop())&&((a?f.nodeName.toLowerCase()!==v:1!==f.nodeType)||!++b||(y&&(d=f[R]||(f[R]={}),c=d[f.uniqueID]||(d[f.uniqueID]={}),c[e]=[M,b]),f!==t)););return b-=o,b===i||b%i===0&&b/i>=0}}},PSEUDO:function(e,n){var o,r=C.pseudos[e]||C.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return r[R]?r(n):r.length>1?(o=[e,e,"",n],C.setFilters.hasOwnProperty(e.toLowerCase())?i(function(e,t){for(var i,o=r(e,n),s=o.length;s--;)i=ee(e,o[s]),e[i]=!(t[i]=o[s])}):function(e){return r(e,0,o)}):r}},pseudos:{not:i(function(e){var t=[],n=[],o=F(e.replace(ae,"$1"));return o[R]?i(function(e,t,n,i){for(var r,s=o(e,null,i,[]),a=e.length;a--;)(r=s[a])&&(e[a]=!(t[a]=r))}):function(e,i,r){return t[0]=e,o(t,null,r,n),t[0]=null,!n.pop()}}),has:i(function(e){return function(n){return t(e,n).length>0}}),contains:i(function(e){return e=e.replace(we,xe),function(t){return(t.textContent||t.innerText||k(t)).indexOf(e)>-1}}),lang:i(function(e){return fe.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(we,xe).toLowerCase(),function(t){var n;do if(n=P?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===z},focus:function(e){return e===O.activeElement&&(!O.hasFocus||O.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!C.pseudos.empty(e)},header:function(e){return ge.test(e.nodeName)},input:function(e){return pe.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,n){return[n<0?n+t:n]}),even:u(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:u(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:u(function(e,t,n){for(var i=n<0?n+t:n;--i>=0;)e.push(i);return e}),gt:u(function(e,t,n){for(var i=n<0?n+t:n;++i<t;)e.push(i);return e})}},C.pseudos.nth=C.pseudos.eq;for(w in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})C.pseudos[w]=a(w);for(w in{submit:!0,reset:!0})C.pseudos[w]=l(w);return d.prototype=C.filters=C.pseudos,C.setFilters=new d,T=t.tokenize=function(e,n){var i,o,r,s,a,l,u,c=W[e+" "];if(c)return n?0:c.slice(0);for(a=e,l=[],u=C.preFilter;a;){i&&!(o=le.exec(a))||(o&&(a=a.slice(o[0].length)||a),l.push(r=[])),i=!1,(o=ue.exec(a))&&(i=o.shift(),r.push({value:i,type:o[0].replace(ae," ")}),a=a.slice(i.length));for(s in C.filter)!(o=he[s].exec(a))||u[s]&&!(o=u[s](o))||(i=o.shift(),r.push({value:i,type:s,matches:o}),a=a.slice(i.length));if(!i)break}return n?a.length:a?t.error(e):W(e,l).slice(0)},F=t.compile=function(e,t){var n,i=[],o=[],r=Q[e+" "];if(!r){for(t||(t=T(e)),n=t.length;n--;)r=y(t[n]),r[R]?i.push(r):o.push(r);r=Q(e,b(o,i)),r.selector=e}return r},E=t.select=function(e,t,n,i){var o,r,s,a,l,u="function"==typeof e&&e,d=!i&&T(e=u.selector||e);if(n=n||[],1===d.length){if(r=d[0]=d[0].slice(0),r.length>2&&"ID"===(s=r[0]).type&&x.getById&&9===t.nodeType&&P&&C.relative[r[1].type]){if(t=(C.find.ID(s.matches[0].replace(we,xe),t)||[])[0],!t)return n;u&&(t=t.parentNode),e=e.slice(r.shift().value.length)}for(o=he.needsContext.test(e)?0:r.length;o--&&(s=r[o],!C.relative[a=s.type]);)if((l=C.find[a])&&(i=l(s.matches[0].replace(we,xe),ye.test(r[0].type)&&c(t.parentNode)||t))){if(r.splice(o,1),e=i.length&&f(r),!e)return Z.apply(n,i),n;break}}return(u||F(e,d))(i,t,!P,n,!t||ye.test(e)&&c(t.parentNode)||t),n},x.sortStable=R.split("").sort(U).join("")===R,x.detectDuplicates=!!S,D(),x.sortDetached=o(function(e){return 1&e.compareDocumentPosition(O.createElement("div"))}),o(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||r("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),x.attributes&&o(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||r("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),o(function(e){return null==e.getAttribute("disabled")})||r(te,function(e,t,n){var i;if(!n)return e[t]===!0?t.toLowerCase():(i=e.getAttributeNode(t))&&i.specified?i.value:null}),t}(n);ue.find=pe,ue.expr=pe.selectors,ue.expr[":"]=ue.expr.pseudos,ue.uniqueSort=ue.unique=pe.uniqueSort,ue.text=pe.getText,ue.isXMLDoc=pe.isXML,ue.contains=pe.contains;var ge=function(e,t,n){for(var i=[],o=void 0!==n;(e=e[t])&&9!==e.nodeType;)if(1===e.nodeType){if(o&&ue(e).is(n))break;i.push(e)}return i},me=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},ve=ue.expr.match.needsContext,ye=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,be=/^.[^:#\[\.,]*$/;ue.filter=function(e,t,n){var i=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===i.nodeType?ue.find.matchesSelector(i,e)?[i]:[]:ue.find.matches(e,ue.grep(t,function(e){return 1===e.nodeType}))},ue.fn.extend({find:function(e){var t,n=this.length,i=[],o=this;if("string"!=typeof e)return this.pushStack(ue(e).filter(function(){for(t=0;t<n;t++)if(ue.contains(o[t],this))return!0}));for(t=0;t<n;t++)ue.find(e,o[t],i);return i=this.pushStack(n>1?ue.unique(i):i),i.selector=this.selector?this.selector+" "+e:e,i},filter:function(e){return this.pushStack(a(this,e||[],!1))},not:function(e){return this.pushStack(a(this,e||[],!0))},is:function(e){return!!a(this,"string"==typeof e&&ve.test(e)?ue(e):e||[],!1).length}});var we,xe=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,Ce=ue.fn.init=function(e,t,n){var i,o;if(!e)return this;if(n=n||we,"string"==typeof e){if(i="<"===e[0]&&">"===e[e.length-1]&&e.length>=3?[null,e,null]:xe.exec(e),!i||!i[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof ue?t[0]:t,ue.merge(this,ue.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:J,!0)),ye.test(i[1])&&ue.isPlainObject(t))for(i in t)ue.isFunction(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}return o=J.getElementById(i[2]),o&&o.parentNode&&(this.length=1,this[0]=o),this.context=J,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):ue.isFunction(e)?void 0!==n.ready?n.ready(e):e(ue):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),ue.makeArray(e,this))};Ce.prototype=ue.fn,we=ue(J);var ke=/^(?:parents|prev(?:Until|All))/,$e={children:!0,contents:!0,next:!0,prev:!0};ue.fn.extend({has:function(e){var t=ue(e,this),n=t.length;return this.filter(function(){for(var e=0;e<n;e++)if(ue.contains(this,t[e]))return!0})},closest:function(e,t){for(var n,i=0,o=this.length,r=[],s=ve.test(e)||"string"!=typeof e?ue(e,t||this.context):0;i<o;i++)for(n=this[i];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(s?s.index(n)>-1:1===n.nodeType&&ue.find.matchesSelector(n,e))){r.push(n);break}return this.pushStack(r.length>1?ue.uniqueSort(r):r)},index:function(e){return e?"string"==typeof e?ie.call(ue(e),this[0]):ie.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(ue.uniqueSort(ue.merge(this.get(),ue(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),ue.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return ge(e,"parentNode")},parentsUntil:function(e,t,n){return ge(e,"parentNode",n)},next:function(e){return l(e,"nextSibling")},prev:function(e){return l(e,"previousSibling")},nextAll:function(e){return ge(e,"nextSibling")},prevAll:function(e){return ge(e,"previousSibling")},nextUntil:function(e,t,n){return ge(e,"nextSibling",n)},prevUntil:function(e,t,n){return ge(e,"previousSibling",n)},siblings:function(e){return me((e.parentNode||{}).firstChild,e)},children:function(e){return me(e.firstChild)},contents:function(e){return e.contentDocument||ue.merge([],e.childNodes)}},function(e,t){ue.fn[e]=function(n,i){var o=ue.map(this,t,n);return"Until"!==e.slice(-5)&&(i=n),i&&"string"==typeof i&&(o=ue.filter(i,o)),this.length>1&&($e[e]||ue.uniqueSort(o),ke.test(e)&&o.reverse()),this.pushStack(o)}});var Te=/\S+/g;ue.Callbacks=function(e){e="string"==typeof e?u(e):ue.extend({},e);var t,n,i,o,r=[],s=[],a=-1,l=function(){for(o=e.once,i=t=!0;s.length;a=-1)for(n=s.shift();++a<r.length;)r[a].apply(n[0],n[1])===!1&&e.stopOnFalse&&(a=r.length,n=!1);e.memory||(n=!1),t=!1,o&&(r=n?[]:"")},c={add:function(){return r&&(n&&!t&&(a=r.length-1,s.push(n)),function i(t){ue.each(t,function(t,n){ue.isFunction(n)?e.unique&&c.has(n)||r.push(n):n&&n.length&&"string"!==ue.type(n)&&i(n)})}(arguments),n&&!t&&l()),this},remove:function(){return ue.each(arguments,function(e,t){for(var n;(n=ue.inArray(t,r,n))>-1;)r.splice(n,1),n<=a&&a--}),this},has:function(e){return e?ue.inArray(e,r)>-1:r.length>0},empty:function(){return r&&(r=[]),this},disable:function(){return o=s=[],r=n="",this},disabled:function(){return!r},lock:function(){return o=s=[],n||(r=n=""),this},locked:function(){return!!o},fireWith:function(e,n){return o||(n=n||[],n=[e,n.slice?n.slice():n],s.push(n),t||l()),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!i}};return c},ue.extend({Deferred:function(e){var t=[["resolve","done",ue.Callbacks("once memory"),"resolved"],["reject","fail",ue.Callbacks("once memory"),"rejected"],["notify","progress",ue.Callbacks("memory")]],n="pending",i={state:function(){return n},always:function(){return o.done(arguments).fail(arguments),this},then:function(){var e=arguments;return ue.Deferred(function(n){ue.each(t,function(t,r){var s=ue.isFunction(e[t])&&e[t];o[r[1]](function(){var e=s&&s.apply(this,arguments);e&&ue.isFunction(e.promise)?e.promise().progress(n.notify).done(n.resolve).fail(n.reject):n[r[0]+"With"](this===i?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?ue.extend(e,i):i}},o={};return i.pipe=i.then,ue.each(t,function(e,r){var s=r[2],a=r[3];i[r[1]]=s.add,a&&s.add(function(){n=a},t[1^e][2].disable,t[2][2].lock),o[r[0]]=function(){return o[r[0]+"With"](this===o?i:this,arguments),this},o[r[0]+"With"]=s.fireWith}),i.promise(o),e&&e.call(o,o),o},when:function(e){var t,n,i,o=0,r=ee.call(arguments),s=r.length,a=1!==s||e&&ue.isFunction(e.promise)?s:0,l=1===a?e:ue.Deferred(),u=function(e,n,i){return function(o){n[e]=this,i[e]=arguments.length>1?ee.call(arguments):o,i===t?l.notifyWith(n,i):--a||l.resolveWith(n,i)}};if(s>1)for(t=new Array(s),n=new Array(s),i=new Array(s);o<s;o++)r[o]&&ue.isFunction(r[o].promise)?r[o].promise().progress(u(o,n,t)).done(u(o,i,r)).fail(l.reject):--a;return a||l.resolveWith(i,r),l.promise()}});var Fe;ue.fn.ready=function(e){return ue.ready.promise().done(e),this},ue.extend({isReady:!1,readyWait:1,holdReady:function(e){e?ue.readyWait++:ue.ready(!0)},ready:function(e){(e===!0?--ue.readyWait:ue.isReady)||(ue.isReady=!0,e!==!0&&--ue.readyWait>0||(Fe.resolveWith(J,[ue]),ue.fn.triggerHandler&&(ue(J).triggerHandler("ready"),ue(J).off("ready"))))}}),ue.ready.promise=function(e){return Fe||(Fe=ue.Deferred(),"complete"===J.readyState||"loading"!==J.readyState&&!J.documentElement.doScroll?n.setTimeout(ue.ready):(J.addEventListener("DOMContentLoaded",c),n.addEventListener("load",c))),Fe.promise(e)},ue.ready.promise();var Ee=function(e,t,n,i,o,r,s){var a=0,l=e.length,u=null==n;if("object"===ue.type(n)){o=!0;for(a in n)Ee(e,t,a,n[a],!0,r,s)}else if(void 0!==i&&(o=!0,ue.isFunction(i)||(s=!0),u&&(s?(t.call(e,i),t=null):(u=t,t=function(e,t,n){return u.call(ue(e),n)})),t))for(;a<l;a++)t(e[a],n,s?i:i.call(e[a],a,t(e[a],n)));return o?e:u?t.call(e):l?t(e[0],n):r},Ae=function(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType};d.uid=1,d.prototype={register:function(e,t){var n=t||{};return e.nodeType?e[this.expando]=n:Object.defineProperty(e,this.expando,{value:n,writable:!0,configurable:!0}),e[this.expando]},cache:function(e){if(!Ae(e))return{};var t=e[this.expando];return t||(t={},Ae(e)&&(e.nodeType?e[this.expando]=t:Object.defineProperty(e,this.expando,{value:t,configurable:!0}))),t},set:function(e,t,n){var i,o=this.cache(e);if("string"==typeof t)o[t]=n;else for(i in t)o[i]=t[i];return o},get:function(e,t){return void 0===t?this.cache(e):e[this.expando]&&e[this.expando][t]},access:function(e,t,n){var i;return void 0===t||t&&"string"==typeof t&&void 0===n?(i=this.get(e,t),void 0!==i?i:this.get(e,ue.camelCase(t))):(this.set(e,t,n),void 0!==n?n:t)},remove:function(e,t){var n,i,o,r=e[this.expando];if(void 0!==r){if(void 0===t)this.register(e);else{ue.isArray(t)?i=t.concat(t.map(ue.camelCase)):(o=ue.camelCase(t),t in r?i=[t,o]:(i=o,i=i in r?[i]:i.match(Te)||[])),n=i.length;for(;n--;)delete r[i[n]]}(void 0===t||ue.isEmptyObject(r))&&(e.nodeType?e[this.expando]=void 0:delete e[this.expando])}},hasData:function(e){var t=e[this.expando];return void 0!==t&&!ue.isEmptyObject(t)}};var _e=new d,Se=new d,De=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Oe=/[A-Z]/g;ue.extend({hasData:function(e){return Se.hasData(e)||_e.hasData(e)},data:function(e,t,n){return Se.access(e,t,n)},removeData:function(e,t){Se.remove(e,t)},_data:function(e,t,n){return _e.access(e,t,n)},_removeData:function(e,t){_e.remove(e,t)}}),ue.fn.extend({data:function(e,t){var n,i,o,r=this[0],s=r&&r.attributes;if(void 0===e){if(this.length&&(o=Se.get(r),1===r.nodeType&&!_e.get(r,"hasDataAttrs"))){for(n=s.length;n--;)s[n]&&(i=s[n].name,0===i.indexOf("data-")&&(i=ue.camelCase(i.slice(5)),f(r,i,o[i])));_e.set(r,"hasDataAttrs",!0)}return o}return"object"==typeof e?this.each(function(){Se.set(this,e)}):Ee(this,function(t){var n,i;if(r&&void 0===t){if(n=Se.get(r,e)||Se.get(r,e.replace(Oe,"-$&").toLowerCase()),void 0!==n)return n;if(i=ue.camelCase(e),n=Se.get(r,i),void 0!==n)return n;if(n=f(r,i,void 0),void 0!==n)return n}else i=ue.camelCase(e),this.each(function(){var n=Se.get(this,i);Se.set(this,i,t),e.indexOf("-")>-1&&void 0!==n&&Se.set(this,e,t)})},null,t,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){Se.remove(this,e)})}}),ue.extend({queue:function(e,t,n){var i;if(e)return t=(t||"fx")+"queue",i=_e.get(e,t),n&&(!i||ue.isArray(n)?i=_e.access(e,t,ue.makeArray(n)):i.push(n)),i||[]},dequeue:function(e,t){t=t||"fx";var n=ue.queue(e,t),i=n.length,o=n.shift(),r=ue._queueHooks(e,t),s=function(){ue.dequeue(e,t)};"inprogress"===o&&(o=n.shift(),i--),o&&("fx"===t&&n.unshift("inprogress"),delete r.stop,o.call(e,s,r)),!i&&r&&r.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return _e.get(e,n)||_e.access(e,n,{empty:ue.Callbacks("once memory").add(function(){_e.remove(e,[t+"queue",n])})})}}),ue.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?ue.queue(this[0],e):void 0===t?this:this.each(function(){var n=ue.queue(this,e,t);ue._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&ue.dequeue(this,e)})},dequeue:function(e){return this.each(function(){ue.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,i=1,o=ue.Deferred(),r=this,s=this.length,a=function(){--i||o.resolveWith(r,[r])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";s--;)n=_e.get(r[s],e+"queueHooks"),n&&n.empty&&(i++,n.empty.add(a));return a(),o.promise(t)}});var ze=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Pe=new RegExp("^(?:([+-])=|)("+ze+")([a-z%]*)$","i"),qe=["Top","Right","Bottom","Left"],Ne=function(e,t){return e=t||e,"none"===ue.css(e,"display")||!ue.contains(e.ownerDocument,e)},je=/^(?:checkbox|radio)$/i,He=/<([\w:-]+)/,Re=/^$|\/(?:java|ecma)script/i,Le={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};Le.optgroup=Le.option,Le.tbody=Le.tfoot=Le.colgroup=Le.caption=Le.thead,Le.th=Le.td;var Me=/<|&#?\w+;/;!function(){var e=J.createDocumentFragment(),t=e.appendChild(J.createElement("div")),n=J.createElement("input");n.setAttribute("type","radio"),n.setAttribute("checked","checked"),n.setAttribute("name","t"),t.appendChild(n),ae.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,t.innerHTML="<textarea>x</textarea>",ae.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue}();var Ie=/^key/,Be=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,We=/^([^.]*)(?:\.(.+)|)/;ue.event={global:{},add:function(e,t,n,i,o){var r,s,a,l,u,c,d,f,h,p,g,m=_e.get(e);if(m)for(n.handler&&(r=n,n=r.handler,o=r.selector),n.guid||(n.guid=ue.guid++),(l=m.events)||(l=m.events={}),(s=m.handle)||(s=m.handle=function(t){return"undefined"!=typeof ue&&ue.event.triggered!==t.type?ue.event.dispatch.apply(e,arguments):void 0}),t=(t||"").match(Te)||[""],u=t.length;u--;)a=We.exec(t[u])||[],h=g=a[1],p=(a[2]||"").split(".").sort(),h&&(d=ue.event.special[h]||{},h=(o?d.delegateType:d.bindType)||h,d=ue.event.special[h]||{},c=ue.extend({type:h,origType:g,data:i,handler:n,guid:n.guid,selector:o,needsContext:o&&ue.expr.match.needsContext.test(o),namespace:p.join(".")},r),(f=l[h])||(f=l[h]=[],f.delegateCount=0,d.setup&&d.setup.call(e,i,p,s)!==!1||e.addEventListener&&e.addEventListener(h,s)),d.add&&(d.add.call(e,c),c.handler.guid||(c.handler.guid=n.guid)),o?f.splice(f.delegateCount++,0,c):f.push(c),ue.event.global[h]=!0)},remove:function(e,t,n,i,o){var r,s,a,l,u,c,d,f,h,p,g,m=_e.hasData(e)&&_e.get(e);if(m&&(l=m.events)){for(t=(t||"").match(Te)||[""],u=t.length;u--;)if(a=We.exec(t[u])||[],h=g=a[1],p=(a[2]||"").split(".").sort(),h){for(d=ue.event.special[h]||{},h=(i?d.delegateType:d.bindType)||h,f=l[h]||[],a=a[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),s=r=f.length;r--;)c=f[r],!o&&g!==c.origType||n&&n.guid!==c.guid||a&&!a.test(c.namespace)||i&&i!==c.selector&&("**"!==i||!c.selector)||(f.splice(r,1),
c.selector&&f.delegateCount--,d.remove&&d.remove.call(e,c));s&&!f.length&&(d.teardown&&d.teardown.call(e,p,m.handle)!==!1||ue.removeEvent(e,h,m.handle),delete l[h])}else for(h in l)ue.event.remove(e,h+t[u],n,i,!0);ue.isEmptyObject(l)&&_e.remove(e,"handle events")}},dispatch:function(e){e=ue.event.fix(e);var t,n,i,o,r,s=[],a=ee.call(arguments),l=(_e.get(this,"events")||{})[e.type]||[],u=ue.event.special[e.type]||{};if(a[0]=e,e.delegateTarget=this,!u.preDispatch||u.preDispatch.call(this,e)!==!1){for(s=ue.event.handlers.call(this,e,l),t=0;(o=s[t++])&&!e.isPropagationStopped();)for(e.currentTarget=o.elem,n=0;(r=o.handlers[n++])&&!e.isImmediatePropagationStopped();)e.rnamespace&&!e.rnamespace.test(r.namespace)||(e.handleObj=r,e.data=r.data,i=((ue.event.special[r.origType]||{}).handle||r.handler).apply(o.elem,a),void 0!==i&&(e.result=i)===!1&&(e.preventDefault(),e.stopPropagation()));return u.postDispatch&&u.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,i,o,r,s=[],a=t.delegateCount,l=e.target;if(a&&l.nodeType&&("click"!==e.type||isNaN(e.button)||e.button<1))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(i=[],n=0;n<a;n++)r=t[n],o=r.selector+" ",void 0===i[o]&&(i[o]=r.needsContext?ue(o,this).index(l)>-1:ue.find(o,this,null,[l]).length),i[o]&&i.push(r);i.length&&s.push({elem:l,handlers:i})}return a<t.length&&s.push({elem:this,handlers:t.slice(a)}),s},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,i,o,r=t.button;return null==e.pageX&&null!=t.clientX&&(n=e.target.ownerDocument||J,i=n.documentElement,o=n.body,e.pageX=t.clientX+(i&&i.scrollLeft||o&&o.scrollLeft||0)-(i&&i.clientLeft||o&&o.clientLeft||0),e.pageY=t.clientY+(i&&i.scrollTop||o&&o.scrollTop||0)-(i&&i.clientTop||o&&o.clientTop||0)),e.which||void 0===r||(e.which=1&r?1:2&r?3:4&r?2:0),e}},fix:function(e){if(e[ue.expando])return e;var t,n,i,o=e.type,r=e,s=this.fixHooks[o];for(s||(this.fixHooks[o]=s=Be.test(o)?this.mouseHooks:Ie.test(o)?this.keyHooks:{}),i=s.props?this.props.concat(s.props):this.props,e=new ue.Event(r),t=i.length;t--;)n=i[t],e[n]=r[n];return e.target||(e.target=J),3===e.target.nodeType&&(e.target=e.target.parentNode),s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==b()&&this.focus)return this.focus(),!1},delegateType:"focusin"},blur:{trigger:function(){if(this===b()&&this.blur)return this.blur(),!1},delegateType:"focusout"},click:{trigger:function(){if("checkbox"===this.type&&this.click&&ue.nodeName(this,"input"))return this.click(),!1},_default:function(e){return ue.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}}},ue.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)},ue.Event=function(e,t){return this instanceof ue.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?v:y):this.type=e,t&&ue.extend(this,t),this.timeStamp=e&&e.timeStamp||ue.now(),void(this[ue.expando]=!0)):new ue.Event(e,t)},ue.Event.prototype={constructor:ue.Event,isDefaultPrevented:y,isPropagationStopped:y,isImmediatePropagationStopped:y,isSimulated:!1,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=v,e&&!this.isSimulated&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=v,e&&!this.isSimulated&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=v,e&&!this.isSimulated&&e.stopImmediatePropagation(),this.stopPropagation()}},ue.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){ue.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,i=this,o=e.relatedTarget,r=e.handleObj;return o&&(o===i||ue.contains(i,o))||(e.type=r.origType,n=r.handler.apply(this,arguments),e.type=t),n}}}),ue.fn.extend({on:function(e,t,n,i){return w(this,e,t,n,i)},one:function(e,t,n,i){return w(this,e,t,n,i,1)},off:function(e,t,n){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,ue(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,t,e[o]);return this}return t!==!1&&"function"!=typeof t||(n=t,t=void 0),n===!1&&(n=y),this.each(function(){ue.event.remove(this,e,n,t)})}});var Qe=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,Ue=/<script|<style|<link/i,Ye=/checked\s*(?:[^=]|=\s*.checked.)/i,Xe=/^true\/(.*)/,Ke=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;ue.extend({htmlPrefilter:function(e){return e.replace(Qe,"<$1></$2>")},clone:function(e,t,n){var i,o,r,s,a=e.cloneNode(!0),l=ue.contains(e.ownerDocument,e);if(!(ae.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ue.isXMLDoc(e)))for(s=p(a),r=p(e),i=0,o=r.length;i<o;i++)T(r[i],s[i]);if(t)if(n)for(r=r||p(e),s=s||p(a),i=0,o=r.length;i<o;i++)$(r[i],s[i]);else $(e,a);return s=p(a,"script"),s.length>0&&g(s,!l&&p(e,"script")),a},cleanData:function(e){for(var t,n,i,o=ue.event.special,r=0;void 0!==(n=e[r]);r++)if(Ae(n)){if(t=n[_e.expando]){if(t.events)for(i in t.events)o[i]?ue.event.remove(n,i):ue.removeEvent(n,i,t.handle);n[_e.expando]=void 0}n[Se.expando]&&(n[Se.expando]=void 0)}}}),ue.fn.extend({domManip:F,detach:function(e){return E(this,e,!0)},remove:function(e){return E(this,e)},text:function(e){return Ee(this,function(e){return void 0===e?ue.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return F(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.appendChild(e)}})},prepend:function(){return F(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return F(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return F(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(ue.cleanData(p(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return ue.clone(this,e,t)})},html:function(e){return Ee(this,function(e){var t=this[0]||{},n=0,i=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Ue.test(e)&&!Le[(He.exec(e)||["",""])[1].toLowerCase()]){e=ue.htmlPrefilter(e);try{for(;n<i;n++)t=this[n]||{},1===t.nodeType&&(ue.cleanData(p(t,!1)),t.innerHTML=e);t=0}catch(o){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=[];return F(this,arguments,function(t){var n=this.parentNode;ue.inArray(this,e)<0&&(ue.cleanData(p(this)),n&&n.replaceChild(t,this))},e)}}),ue.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){ue.fn[e]=function(e){for(var n,i=[],o=ue(e),r=o.length-1,s=0;s<=r;s++)n=s===r?this:this.clone(!0),ue(o[s])[t](n),ne.apply(i,n.get());return this.pushStack(i)}});var Ge,Ve={HTML:"block",BODY:"block"},Ze=/^margin/,Je=new RegExp("^("+ze+")(?!px)[a-z%]+$","i"),et=function(e){var t=e.ownerDocument.defaultView;return t&&t.opener||(t=n),t.getComputedStyle(e)},tt=function(e,t,n,i){var o,r,s={};for(r in t)s[r]=e.style[r],e.style[r]=t[r];o=n.apply(e,i||[]);for(r in t)e.style[r]=s[r];return o},nt=J.documentElement;!function(){function e(){a.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",a.innerHTML="",nt.appendChild(s);var e=n.getComputedStyle(a);t="1%"!==e.top,r="2px"===e.marginLeft,i="4px"===e.width,a.style.marginRight="50%",o="4px"===e.marginRight,nt.removeChild(s)}var t,i,o,r,s=J.createElement("div"),a=J.createElement("div");a.style&&(a.style.backgroundClip="content-box",a.cloneNode(!0).style.backgroundClip="",ae.clearCloneStyle="content-box"===a.style.backgroundClip,s.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",s.appendChild(a),ue.extend(ae,{pixelPosition:function(){return e(),t},boxSizingReliable:function(){return null==i&&e(),i},pixelMarginRight:function(){return null==i&&e(),o},reliableMarginLeft:function(){return null==i&&e(),r},reliableMarginRight:function(){var e,t=a.appendChild(J.createElement("div"));return t.style.cssText=a.style.cssText="-webkit-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",t.style.marginRight=t.style.width="0",a.style.width="1px",nt.appendChild(s),e=!parseFloat(n.getComputedStyle(t).marginRight),nt.removeChild(s),a.removeChild(t),e}}))}();var it=/^(none|table(?!-c[ea]).+)/,ot={position:"absolute",visibility:"hidden",display:"block"},rt={letterSpacing:"0",fontWeight:"400"},st=["Webkit","O","Moz","ms"],at=J.createElement("div").style;ue.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=S(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(e,t,n,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,r,s,a=ue.camelCase(t),l=e.style;return t=ue.cssProps[a]||(ue.cssProps[a]=O(a)||a),s=ue.cssHooks[t]||ue.cssHooks[a],void 0===n?s&&"get"in s&&void 0!==(o=s.get(e,!1,i))?o:l[t]:(r=typeof n,"string"===r&&(o=Pe.exec(n))&&o[1]&&(n=h(e,t,o),r="number"),null!=n&&n===n&&("number"===r&&(n+=o&&o[3]||(ue.cssNumber[a]?"":"px")),ae.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),s&&"set"in s&&void 0===(n=s.set(e,n,i))||(l[t]=n)),void 0)}},css:function(e,t,n,i){var o,r,s,a=ue.camelCase(t);return t=ue.cssProps[a]||(ue.cssProps[a]=O(a)||a),s=ue.cssHooks[t]||ue.cssHooks[a],s&&"get"in s&&(o=s.get(e,!0,n)),void 0===o&&(o=S(e,t,i)),"normal"===o&&t in rt&&(o=rt[t]),""===n||n?(r=parseFloat(o),n===!0||isFinite(r)?r||0:o):o}}),ue.each(["height","width"],function(e,t){ue.cssHooks[t]={get:function(e,n,i){if(n)return it.test(ue.css(e,"display"))&&0===e.offsetWidth?tt(e,ot,function(){return q(e,t,i)}):q(e,t,i)},set:function(e,n,i){var o,r=i&&et(e),s=i&&P(e,t,i,"border-box"===ue.css(e,"boxSizing",!1,r),r);return s&&(o=Pe.exec(n))&&"px"!==(o[3]||"px")&&(e.style[t]=n,n=ue.css(e,t)),z(e,n,s)}}}),ue.cssHooks.marginLeft=D(ae.reliableMarginLeft,function(e,t){if(t)return(parseFloat(S(e,"marginLeft"))||e.getBoundingClientRect().left-tt(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),ue.cssHooks.marginRight=D(ae.reliableMarginRight,function(e,t){if(t)return tt(e,{display:"inline-block"},S,[e,"marginRight"])}),ue.each({margin:"",padding:"",border:"Width"},function(e,t){ue.cssHooks[e+t]={expand:function(n){for(var i=0,o={},r="string"==typeof n?n.split(" "):[n];i<4;i++)o[e+qe[i]+t]=r[i]||r[i-2]||r[0];return o}},Ze.test(e)||(ue.cssHooks[e+t].set=z)}),ue.fn.extend({css:function(e,t){return Ee(this,function(e,t,n){var i,o,r={},s=0;if(ue.isArray(t)){for(i=et(e),o=t.length;s<o;s++)r[t[s]]=ue.css(e,t[s],!1,i);return r}return void 0!==n?ue.style(e,t,n):ue.css(e,t)},e,t,arguments.length>1)},show:function(){return N(this,!0)},hide:function(){return N(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){Ne(this)?ue(this).show():ue(this).hide()})}}),ue.Tween=j,j.prototype={constructor:j,init:function(e,t,n,i,o,r){this.elem=e,this.prop=n,this.easing=o||ue.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=i,this.unit=r||(ue.cssNumber[n]?"":"px")},cur:function(){var e=j.propHooks[this.prop];return e&&e.get?e.get(this):j.propHooks._default.get(this)},run:function(e){var t,n=j.propHooks[this.prop];return this.options.duration?this.pos=t=ue.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):j.propHooks._default.set(this),this}},j.prototype.init.prototype=j.prototype,j.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=ue.css(e.elem,e.prop,""),t&&"auto"!==t?t:0)},set:function(e){ue.fx.step[e.prop]?ue.fx.step[e.prop](e):1!==e.elem.nodeType||null==e.elem.style[ue.cssProps[e.prop]]&&!ue.cssHooks[e.prop]?e.elem[e.prop]=e.now:ue.style(e.elem,e.prop,e.now+e.unit)}}},j.propHooks.scrollTop=j.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},ue.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},ue.fx=j.prototype.init,ue.fx.step={};var lt,ut,ct=/^(?:toggle|show|hide)$/,dt=/queueHooks$/;ue.Animation=ue.extend(B,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return h(n.elem,e,Pe.exec(t),n),n}]},tweener:function(e,t){ue.isFunction(e)?(t=e,e=["*"]):e=e.match(Te);for(var n,i=0,o=e.length;i<o;i++)n=e[i],B.tweeners[n]=B.tweeners[n]||[],B.tweeners[n].unshift(t)},prefilters:[M],prefilter:function(e,t){t?B.prefilters.unshift(e):B.prefilters.push(e)}}),ue.speed=function(e,t,n){var i=e&&"object"==typeof e?ue.extend({},e):{complete:n||!n&&t||ue.isFunction(e)&&e,duration:e,easing:n&&t||t&&!ue.isFunction(t)&&t};return i.duration=ue.fx.off?0:"number"==typeof i.duration?i.duration:i.duration in ue.fx.speeds?ue.fx.speeds[i.duration]:ue.fx.speeds._default,null!=i.queue&&i.queue!==!0||(i.queue="fx"),i.old=i.complete,i.complete=function(){ue.isFunction(i.old)&&i.old.call(this),i.queue&&ue.dequeue(this,i.queue)},i},ue.fn.extend({fadeTo:function(e,t,n,i){return this.filter(Ne).css("opacity",0).show().end().animate({opacity:t},e,n,i)},animate:function(e,t,n,i){var o=ue.isEmptyObject(e),r=ue.speed(t,n,i),s=function(){var t=B(this,ue.extend({},e),r);(o||_e.get(this,"finish"))&&t.stop(!0)};return s.finish=s,o||r.queue===!1?this.each(s):this.queue(r.queue,s)},stop:function(e,t,n){var i=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,o=null!=e&&e+"queueHooks",r=ue.timers,s=_e.get(this);if(o)s[o]&&s[o].stop&&i(s[o]);else for(o in s)s[o]&&s[o].stop&&dt.test(o)&&i(s[o]);for(o=r.length;o--;)r[o].elem!==this||null!=e&&r[o].queue!==e||(r[o].anim.stop(n),t=!1,r.splice(o,1));!t&&n||ue.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=_e.get(this),i=n[e+"queue"],o=n[e+"queueHooks"],r=ue.timers,s=i?i.length:0;for(n.finish=!0,ue.queue(this,e,[]),o&&o.stop&&o.stop.call(this,!0),t=r.length;t--;)r[t].elem===this&&r[t].queue===e&&(r[t].anim.stop(!0),r.splice(t,1));for(t=0;t<s;t++)i[t]&&i[t].finish&&i[t].finish.call(this);delete n.finish})}}),ue.each(["toggle","show","hide"],function(e,t){var n=ue.fn[t];ue.fn[t]=function(e,i,o){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(R(t,!0),e,i,o)}}),ue.each({slideDown:R("show"),slideUp:R("hide"),slideToggle:R("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){ue.fn[e]=function(e,n,i){return this.animate(t,e,n,i)}}),ue.timers=[],ue.fx.tick=function(){var e,t=0,n=ue.timers;for(lt=ue.now();t<n.length;t++)e=n[t],e()||n[t]!==e||n.splice(t--,1);n.length||ue.fx.stop(),lt=void 0},ue.fx.timer=function(e){ue.timers.push(e),e()?ue.fx.start():ue.timers.pop()},ue.fx.interval=13,ue.fx.start=function(){ut||(ut=n.setInterval(ue.fx.tick,ue.fx.interval))},ue.fx.stop=function(){n.clearInterval(ut),ut=null},ue.fx.speeds={slow:600,fast:200,_default:400},ue.fn.delay=function(e,t){return e=ue.fx?ue.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,i){var o=n.setTimeout(t,e);i.stop=function(){n.clearTimeout(o)}})},function(){var e=J.createElement("input"),t=J.createElement("select"),n=t.appendChild(J.createElement("option"));e.type="checkbox",ae.checkOn=""!==e.value,ae.optSelected=n.selected,t.disabled=!0,ae.optDisabled=!n.disabled,e=J.createElement("input"),e.value="t",e.type="radio",ae.radioValue="t"===e.value}();var ft,ht=ue.expr.attrHandle;ue.fn.extend({attr:function(e,t){return Ee(this,ue.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){ue.removeAttr(this,e)})}}),ue.extend({attr:function(e,t,n){var i,o,r=e.nodeType;if(3!==r&&8!==r&&2!==r)return"undefined"==typeof e.getAttribute?ue.prop(e,t,n):(1===r&&ue.isXMLDoc(e)||(t=t.toLowerCase(),o=ue.attrHooks[t]||(ue.expr.match.bool.test(t)?ft:void 0)),void 0!==n?null===n?void ue.removeAttr(e,t):o&&"set"in o&&void 0!==(i=o.set(e,n,t))?i:(e.setAttribute(t,n+""),n):o&&"get"in o&&null!==(i=o.get(e,t))?i:(i=ue.find.attr(e,t),null==i?void 0:i))},attrHooks:{type:{set:function(e,t){if(!ae.radioValue&&"radio"===t&&ue.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,i,o=0,r=t&&t.match(Te);if(r&&1===e.nodeType)for(;n=r[o++];)i=ue.propFix[n]||n,ue.expr.match.bool.test(n)&&(e[i]=!1),e.removeAttribute(n)}}),ft={set:function(e,t,n){return t===!1?ue.removeAttr(e,n):e.setAttribute(n,n),n}},ue.each(ue.expr.match.bool.source.match(/\w+/g),function(e,t){var n=ht[t]||ue.find.attr;ht[t]=function(e,t,i){var o,r;return i||(r=ht[t],ht[t]=o,o=null!=n(e,t,i)?t.toLowerCase():null,ht[t]=r),o}});var pt=/^(?:input|select|textarea|button)$/i,gt=/^(?:a|area)$/i;ue.fn.extend({prop:function(e,t){return Ee(this,ue.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[ue.propFix[e]||e]})}}),ue.extend({prop:function(e,t,n){var i,o,r=e.nodeType;if(3!==r&&8!==r&&2!==r)return 1===r&&ue.isXMLDoc(e)||(t=ue.propFix[t]||t,o=ue.propHooks[t]),void 0!==n?o&&"set"in o&&void 0!==(i=o.set(e,n,t))?i:e[t]=n:o&&"get"in o&&null!==(i=o.get(e,t))?i:e[t]},propHooks:{tabIndex:{get:function(e){var t=ue.find.attr(e,"tabindex");return t?parseInt(t,10):pt.test(e.nodeName)||gt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),ae.optSelected||(ue.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),ue.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ue.propFix[this.toLowerCase()]=this});var mt=/[\t\r\n\f]/g;ue.fn.extend({addClass:function(e){var t,n,i,o,r,s,a,l=0;if(ue.isFunction(e))return this.each(function(t){ue(this).addClass(e.call(this,t,W(this)))});if("string"==typeof e&&e)for(t=e.match(Te)||[];n=this[l++];)if(o=W(n),i=1===n.nodeType&&(" "+o+" ").replace(mt," ")){for(s=0;r=t[s++];)i.indexOf(" "+r+" ")<0&&(i+=r+" ");a=ue.trim(i),o!==a&&n.setAttribute("class",a)}return this},removeClass:function(e){var t,n,i,o,r,s,a,l=0;if(ue.isFunction(e))return this.each(function(t){ue(this).removeClass(e.call(this,t,W(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof e&&e)for(t=e.match(Te)||[];n=this[l++];)if(o=W(n),i=1===n.nodeType&&(" "+o+" ").replace(mt," ")){for(s=0;r=t[s++];)for(;i.indexOf(" "+r+" ")>-1;)i=i.replace(" "+r+" "," ");a=ue.trim(i),o!==a&&n.setAttribute("class",a)}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):ue.isFunction(e)?this.each(function(n){ue(this).toggleClass(e.call(this,n,W(this),t),t)}):this.each(function(){var t,i,o,r;if("string"===n)for(i=0,o=ue(this),r=e.match(Te)||[];t=r[i++];)o.hasClass(t)?o.removeClass(t):o.addClass(t);else void 0!==e&&"boolean"!==n||(t=W(this),t&&_e.set(this,"__className__",t),this.setAttribute&&this.setAttribute("class",t||e===!1?"":_e.get(this,"__className__")||""))})},hasClass:function(e){var t,n,i=0;for(t=" "+e+" ";n=this[i++];)if(1===n.nodeType&&(" "+W(n)+" ").replace(mt," ").indexOf(t)>-1)return!0;return!1}});var vt=/\r/g,yt=/[\x20\t\r\n\f]+/g;ue.fn.extend({val:function(e){var t,n,i,o=this[0];{if(arguments.length)return i=ue.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,ue(this).val()):e,null==o?o="":"number"==typeof o?o+="":ue.isArray(o)&&(o=ue.map(o,function(e){return null==e?"":e+""})),t=ue.valHooks[this.type]||ue.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,o,"value")||(this.value=o))});if(o)return t=ue.valHooks[o.type]||ue.valHooks[o.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(o,"value"))?n:(n=o.value,"string"==typeof n?n.replace(vt,""):null==n?"":n)}}}),ue.extend({valHooks:{option:{get:function(e){var t=ue.find.attr(e,"value");return null!=t?t:ue.trim(ue.text(e)).replace(yt," ")}},select:{get:function(e){for(var t,n,i=e.options,o=e.selectedIndex,r="select-one"===e.type||o<0,s=r?null:[],a=r?o+1:i.length,l=o<0?a:r?o:0;l<a;l++)if(n=i[l],(n.selected||l===o)&&(ae.optDisabled?!n.disabled:null===n.getAttribute("disabled"))&&(!n.parentNode.disabled||!ue.nodeName(n.parentNode,"optgroup"))){if(t=ue(n).val(),r)return t;s.push(t)}return s},set:function(e,t){for(var n,i,o=e.options,r=ue.makeArray(t),s=o.length;s--;)i=o[s],(i.selected=ue.inArray(ue.valHooks.option.get(i),r)>-1)&&(n=!0);return n||(e.selectedIndex=-1),r}}}}),ue.each(["radio","checkbox"],function(){ue.valHooks[this]={set:function(e,t){if(ue.isArray(t))return e.checked=ue.inArray(ue(e).val(),t)>-1}},ae.checkOn||(ue.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var bt=/^(?:focusinfocus|focusoutblur)$/;ue.extend(ue.event,{trigger:function(e,t,i,o){var r,s,a,l,u,c,d,f=[i||J],h=se.call(e,"type")?e.type:e,p=se.call(e,"namespace")?e.namespace.split("."):[];if(s=a=i=i||J,3!==i.nodeType&&8!==i.nodeType&&!bt.test(h+ue.event.triggered)&&(h.indexOf(".")>-1&&(p=h.split("."),h=p.shift(),p.sort()),u=h.indexOf(":")<0&&"on"+h,e=e[ue.expando]?e:new ue.Event(h,"object"==typeof e&&e),e.isTrigger=o?2:3,e.namespace=p.join("."),e.rnamespace=e.namespace?new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=i),t=null==t?[e]:ue.makeArray(t,[e]),d=ue.event.special[h]||{},o||!d.trigger||d.trigger.apply(i,t)!==!1)){if(!o&&!d.noBubble&&!ue.isWindow(i)){for(l=d.delegateType||h,bt.test(l+h)||(s=s.parentNode);s;s=s.parentNode)f.push(s),a=s;a===(i.ownerDocument||J)&&f.push(a.defaultView||a.parentWindow||n)}for(r=0;(s=f[r++])&&!e.isPropagationStopped();)e.type=r>1?l:d.bindType||h,c=(_e.get(s,"events")||{})[e.type]&&_e.get(s,"handle"),c&&c.apply(s,t),c=u&&s[u],c&&c.apply&&Ae(s)&&(e.result=c.apply(s,t),e.result===!1&&e.preventDefault());return e.type=h,o||e.isDefaultPrevented()||d._default&&d._default.apply(f.pop(),t)!==!1||!Ae(i)||u&&ue.isFunction(i[h])&&!ue.isWindow(i)&&(a=i[u],a&&(i[u]=null),ue.event.triggered=h,i[h](),ue.event.triggered=void 0,a&&(i[u]=a)),e.result}},simulate:function(e,t,n){var i=ue.extend(new ue.Event,n,{type:e,isSimulated:!0});ue.event.trigger(i,null,t)}}),ue.fn.extend({trigger:function(e,t){return this.each(function(){ue.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return ue.event.trigger(e,t,n,!0)}}),ue.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){ue.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),ue.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),ae.focusin="onfocusin"in n,ae.focusin||ue.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){ue.event.simulate(t,e.target,ue.event.fix(e))};ue.event.special[t]={setup:function(){var i=this.ownerDocument||this,o=_e.access(i,t);o||i.addEventListener(e,n,!0),_e.access(i,t,(o||0)+1)},teardown:function(){var i=this.ownerDocument||this,o=_e.access(i,t)-1;o?_e.access(i,t,o):(i.removeEventListener(e,n,!0),_e.remove(i,t))}}});var wt=n.location,xt=ue.now(),Ct=/\?/;ue.parseJSON=function(e){return JSON.parse(e+"")},ue.parseXML=function(e){var t;if(!e||"string"!=typeof e)return null;try{t=(new n.DOMParser).parseFromString(e,"text/xml")}catch(i){t=void 0}return t&&!t.getElementsByTagName("parsererror").length||ue.error("Invalid XML: "+e),t};var kt=/#.*$/,$t=/([?&])_=[^&]*/,Tt=/^(.*?):[ \t]*([^\r\n]*)$/gm,Ft=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Et=/^(?:GET|HEAD)$/,At=/^\/\//,_t={},St={},Dt="*/".concat("*"),Ot=J.createElement("a");Ot.href=wt.href,ue.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:wt.href,type:"GET",isLocal:Ft.test(wt.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dt,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":ue.parseJSON,"text xml":ue.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Y(Y(e,ue.ajaxSettings),t):Y(ue.ajaxSettings,e)},ajaxPrefilter:Q(_t),ajaxTransport:Q(St),ajax:function(e,t){function i(e,t,i,a){var u,d,y,b,x,k=t;2!==w&&(w=2,l&&n.clearTimeout(l),o=void 0,s=a||"",C.readyState=e>0?4:0,u=e>=200&&e<300||304===e,i&&(b=X(f,C,i)),b=K(f,b,C,u),u?(f.ifModified&&(x=C.getResponseHeader("Last-Modified"),x&&(ue.lastModified[r]=x),x=C.getResponseHeader("etag"),x&&(ue.etag[r]=x)),204===e||"HEAD"===f.type?k="nocontent":304===e?k="notmodified":(k=b.state,d=b.data,y=b.error,u=!y)):(y=k,!e&&k||(k="error",e<0&&(e=0))),C.status=e,C.statusText=(t||k)+"",u?g.resolveWith(h,[d,k,C]):g.rejectWith(h,[C,k,y]),C.statusCode(v),v=void 0,c&&p.trigger(u?"ajaxSuccess":"ajaxError",[C,f,u?d:y]),m.fireWith(h,[C,k]),c&&(p.trigger("ajaxComplete",[C,f]),--ue.active||ue.event.trigger("ajaxStop")))}"object"==typeof e&&(t=e,e=void 0),t=t||{};var o,r,s,a,l,u,c,d,f=ue.ajaxSetup({},t),h=f.context||f,p=f.context&&(h.nodeType||h.jquery)?ue(h):ue.event,g=ue.Deferred(),m=ue.Callbacks("once memory"),v=f.statusCode||{},y={},b={},w=0,x="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===w){if(!a)for(a={};t=Tt.exec(s);)a[t[1].toLowerCase()]=t[2];t=a[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===w?s:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return w||(e=b[n]=b[n]||e,y[e]=t),this},overrideMimeType:function(e){return w||(f.mimeType=e),this},statusCode:function(e){var t;if(e)if(w<2)for(t in e)v[t]=[v[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||x;return o&&o.abort(t),i(0,t),this}};if(g.promise(C).complete=m.add,C.success=C.done,C.error=C.fail,f.url=((e||f.url||wt.href)+"").replace(kt,"").replace(At,wt.protocol+"//"),f.type=t.method||t.type||f.method||f.type,f.dataTypes=ue.trim(f.dataType||"*").toLowerCase().match(Te)||[""],null==f.crossDomain){u=J.createElement("a");try{u.href=f.url,u.href=u.href,f.crossDomain=Ot.protocol+"//"+Ot.host!=u.protocol+"//"+u.host}catch(k){f.crossDomain=!0}}if(f.data&&f.processData&&"string"!=typeof f.data&&(f.data=ue.param(f.data,f.traditional)),U(_t,f,t,C),2===w)return C;c=ue.event&&f.global,c&&0===ue.active++&&ue.event.trigger("ajaxStart"),f.type=f.type.toUpperCase(),f.hasContent=!Et.test(f.type),r=f.url,f.hasContent||(f.data&&(r=f.url+=(Ct.test(r)?"&":"?")+f.data,delete f.data),f.cache===!1&&(f.url=$t.test(r)?r.replace($t,"$1_="+xt++):r+(Ct.test(r)?"&":"?")+"_="+xt++)),f.ifModified&&(ue.lastModified[r]&&C.setRequestHeader("If-Modified-Since",ue.lastModified[r]),ue.etag[r]&&C.setRequestHeader("If-None-Match",ue.etag[r])),(f.data&&f.hasContent&&f.contentType!==!1||t.contentType)&&C.setRequestHeader("Content-Type",f.contentType),C.setRequestHeader("Accept",f.dataTypes[0]&&f.accepts[f.dataTypes[0]]?f.accepts[f.dataTypes[0]]+("*"!==f.dataTypes[0]?", "+Dt+"; q=0.01":""):f.accepts["*"]);for(d in f.headers)C.setRequestHeader(d,f.headers[d]);if(f.beforeSend&&(f.beforeSend.call(h,C,f)===!1||2===w))return C.abort();x="abort";for(d in{success:1,error:1,complete:1})C[d](f[d]);if(o=U(St,f,t,C)){if(C.readyState=1,c&&p.trigger("ajaxSend",[C,f]),2===w)return C;f.async&&f.timeout>0&&(l=n.setTimeout(function(){C.abort("timeout")},f.timeout));try{w=1,o.send(y,i)}catch(k){if(!(w<2))throw k;i(-1,k)}}else i(-1,"No Transport");return C},getJSON:function(e,t,n){return ue.get(e,t,n,"json")},getScript:function(e,t){return ue.get(e,void 0,t,"script")}}),ue.each(["get","post"],function(e,t){ue[t]=function(e,n,i,o){return ue.isFunction(n)&&(o=o||i,i=n,n=void 0),ue.ajax(ue.extend({url:e,type:t,dataType:o,data:n,success:i},ue.isPlainObject(e)&&e))}}),ue._evalUrl=function(e){return ue.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},ue.fn.extend({wrapAll:function(e){var t;return ue.isFunction(e)?this.each(function(t){ue(this).wrapAll(e.call(this,t))}):(this[0]&&(t=ue(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstElementChild;)e=e.firstElementChild;return e}).append(this)),this)},wrapInner:function(e){return ue.isFunction(e)?this.each(function(t){ue(this).wrapInner(e.call(this,t))}):this.each(function(){var t=ue(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=ue.isFunction(e);return this.each(function(n){ue(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){ue.nodeName(this,"body")||ue(this).replaceWith(this.childNodes)}).end()}}),ue.expr.filters.hidden=function(e){return!ue.expr.filters.visible(e)},ue.expr.filters.visible=function(e){return e.offsetWidth>0||e.offsetHeight>0||e.getClientRects().length>0};var zt=/%20/g,Pt=/\[\]$/,qt=/\r?\n/g,Nt=/^(?:submit|button|image|reset|file)$/i,jt=/^(?:input|select|textarea|keygen)/i;ue.param=function(e,t){var n,i=[],o=function(e,t){t=ue.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=ue.ajaxSettings&&ue.ajaxSettings.traditional),ue.isArray(e)||e.jquery&&!ue.isPlainObject(e))ue.each(e,function(){o(this.name,this.value)});else for(n in e)G(n,e[n],t,o);return i.join("&").replace(zt,"+")},ue.fn.extend({serialize:function(){return ue.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=ue.prop(this,"elements");return e?ue.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!ue(this).is(":disabled")&&jt.test(this.nodeName)&&!Nt.test(e)&&(this.checked||!je.test(e))}).map(function(e,t){var n=ue(this).val();return null==n?null:ue.isArray(n)?ue.map(n,function(e){return{name:t.name,value:e.replace(qt,"\r\n")}}):{name:t.name,value:n.replace(qt,"\r\n")}}).get()}}),ue.ajaxSettings.xhr=function(){try{return new n.XMLHttpRequest}catch(e){}};var Ht={0:200,1223:204},Rt=ue.ajaxSettings.xhr();ae.cors=!!Rt&&"withCredentials"in Rt,ae.ajax=Rt=!!Rt,ue.ajaxTransport(function(e){var t,i;if(ae.cors||Rt&&!e.crossDomain)return{send:function(o,r){var s,a=e.xhr();if(a.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(s in e.xhrFields)a[s]=e.xhrFields[s];e.mimeType&&a.overrideMimeType&&a.overrideMimeType(e.mimeType),e.crossDomain||o["X-Requested-With"]||(o["X-Requested-With"]="XMLHttpRequest");
for(s in o)a.setRequestHeader(s,o[s]);t=function(e){return function(){t&&(t=i=a.onload=a.onerror=a.onabort=a.onreadystatechange=null,"abort"===e?a.abort():"error"===e?"number"!=typeof a.status?r(0,"error"):r(a.status,a.statusText):r(Ht[a.status]||a.status,a.statusText,"text"!==(a.responseType||"text")||"string"!=typeof a.responseText?{binary:a.response}:{text:a.responseText},a.getAllResponseHeaders()))}},a.onload=t(),i=a.onerror=t("error"),void 0!==a.onabort?a.onabort=i:a.onreadystatechange=function(){4===a.readyState&&n.setTimeout(function(){t&&i()})},t=t("abort");try{a.send(e.hasContent&&e.data||null)}catch(l){if(t)throw l}},abort:function(){t&&t()}}}),ue.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return ue.globalEval(e),e}}}),ue.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),ue.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(i,o){t=ue("<script>").prop({charset:e.scriptCharset,src:e.url}).on("load error",n=function(e){t.remove(),n=null,e&&o("error"===e.type?404:200,e.type)}),J.head.appendChild(t[0])},abort:function(){n&&n()}}}});var Lt=[],Mt=/(=)\?(?=&|$)|\?\?/;ue.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Lt.pop()||ue.expando+"_"+xt++;return this[e]=!0,e}}),ue.ajaxPrefilter("json jsonp",function(e,t,i){var o,r,s,a=e.jsonp!==!1&&(Mt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Mt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return o=e.jsonpCallback=ue.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Mt,"$1"+o):e.jsonp!==!1&&(e.url+=(Ct.test(e.url)?"&":"?")+e.jsonp+"="+o),e.converters["script json"]=function(){return s||ue.error(o+" was not called"),s[0]},e.dataTypes[0]="json",r=n[o],n[o]=function(){s=arguments},i.always(function(){void 0===r?ue(n).removeProp(o):n[o]=r,e[o]&&(e.jsonpCallback=t.jsonpCallback,Lt.push(o)),s&&ue.isFunction(r)&&r(s[0]),s=r=void 0}),"script"}),ue.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||J;var i=ye.exec(e),o=!n&&[];return i?[t.createElement(i[1])]:(i=m([e],t,o),o&&o.length&&ue(o).remove(),ue.merge([],i.childNodes))};var It=ue.fn.load;ue.fn.load=function(e,t,n){if("string"!=typeof e&&It)return It.apply(this,arguments);var i,o,r,s=this,a=e.indexOf(" ");return a>-1&&(i=ue.trim(e.slice(a)),e=e.slice(0,a)),ue.isFunction(t)?(n=t,t=void 0):t&&"object"==typeof t&&(o="POST"),s.length>0&&ue.ajax({url:e,type:o||"GET",dataType:"html",data:t}).done(function(e){r=arguments,s.html(i?ue("<div>").append(ue.parseHTML(e)).find(i):e)}).always(n&&function(e,t){s.each(function(){n.apply(this,r||[e.responseText,t,e])})}),this},ue.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ue.fn[t]=function(e){return this.on(t,e)}}),ue.expr.filters.animated=function(e){return ue.grep(ue.timers,function(t){return e===t.elem}).length},ue.offset={setOffset:function(e,t,n){var i,o,r,s,a,l,u,c=ue.css(e,"position"),d=ue(e),f={};"static"===c&&(e.style.position="relative"),a=d.offset(),r=ue.css(e,"top"),l=ue.css(e,"left"),u=("absolute"===c||"fixed"===c)&&(r+l).indexOf("auto")>-1,u?(i=d.position(),s=i.top,o=i.left):(s=parseFloat(r)||0,o=parseFloat(l)||0),ue.isFunction(t)&&(t=t.call(e,n,ue.extend({},a))),null!=t.top&&(f.top=t.top-a.top+s),null!=t.left&&(f.left=t.left-a.left+o),"using"in t?t.using.call(e,f):d.css(f)}},ue.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){ue.offset.setOffset(this,e,t)});var t,n,i=this[0],o={top:0,left:0},r=i&&i.ownerDocument;if(r)return t=r.documentElement,ue.contains(t,i)?(o=i.getBoundingClientRect(),n=V(r),{top:o.top+n.pageYOffset-t.clientTop,left:o.left+n.pageXOffset-t.clientLeft}):o},position:function(){if(this[0]){var e,t,n=this[0],i={top:0,left:0};return"fixed"===ue.css(n,"position")?t=n.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),ue.nodeName(e[0],"html")||(i=e.offset()),i.top+=ue.css(e[0],"borderTopWidth",!0),i.left+=ue.css(e[0],"borderLeftWidth",!0)),{top:t.top-i.top-ue.css(n,"marginTop",!0),left:t.left-i.left-ue.css(n,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent;e&&"static"===ue.css(e,"position");)e=e.offsetParent;return e||nt})}}),ue.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n="pageYOffset"===t;ue.fn[e]=function(i){return Ee(this,function(e,i,o){var r=V(e);return void 0===o?r?r[t]:e[i]:void(r?r.scrollTo(n?r.pageXOffset:o,n?o:r.pageYOffset):e[i]=o)},e,i,arguments.length)}}),ue.each(["top","left"],function(e,t){ue.cssHooks[t]=D(ae.pixelPosition,function(e,n){if(n)return n=S(e,t),Je.test(n)?ue(e).position()[t]+"px":n})}),ue.each({Height:"height",Width:"width"},function(e,t){ue.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,i){ue.fn[i]=function(i,o){var r=arguments.length&&(n||"boolean"!=typeof i),s=n||(i===!0||o===!0?"margin":"border");return Ee(this,function(t,n,i){var o;return ue.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(o=t.documentElement,Math.max(t.body["scroll"+e],o["scroll"+e],t.body["offset"+e],o["offset"+e],o["client"+e])):void 0===i?ue.css(t,n,s):ue.style(t,n,i,s)},t,r?i:void 0,r,null)}})}),ue.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,i){return this.on(t,e,n,i)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},size:function(){return this.length}}),ue.fn.andSelf=ue.fn.addBack,i=[],o=function(){return ue}.apply(t,i),!(void 0!==o&&(e.exports=o));var Bt=n.jQuery,Wt=n.$;return ue.noConflict=function(e){return n.$===ue&&(n.$=Wt),e&&n.jQuery===ue&&(n.jQuery=Bt),ue},r||(n.jQuery=n.$=ue),ue})},function(e,t){(function(t){e.exports=t}).call(t,{})}]);
|
import cv2
import numpy as np
class FLIRLeptonPT2:
def __init__(self, id=1):
self.id = id
self.connect()
def connect(self):
self.handle = cv2.VideoCapture(self.id, cv2.CAP_DSHOW)
if not self.handle.isOpened():
self.handle = None
raise ValueError(f"Could not connect to IR Camera at id {self.id}!")
self.handle.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc("Y", "1", "6", " "))
self.handle.set(cv2.CAP_PROP_CONVERT_RGB, 0)
def disconnect(self):
self.handle.release() # TODO maybe not correct syntax for opencv
def __counts_to_celsius(self, cts):
return cts / 100 - 273.15 # from centikelvin (camera output units) to Celsius
def capture(self):
"""Captures a single shot infrared image. Data returned in Celsius
Returns:
np.array: Temperature image (Celsius)
"""
self.handle.read() # dummy frame, buffer is weird
rval, frame = self.handle.read() # actual frame
if rval:
frame = frame[:-2, :]
return self.__counts_to_celsius(frame)
else:
return np.nan
# def preview(self):
# if self.handle.isOpened(): # try to get the first frame
# rval, frame = video.read()
# else:
# rval = False
# while rval:
# normed = cv2.normalize(frame, None, 0, 65535, cv2.NORM_MINMAX)
# nor=cv2.cvtColor(np.uint8(normed),cv2.COLOR_GRAY2BGR)
# cv2.imshow(“preview”, cv2.resize(nor, dsize= (640, 480), interpolation = cv2.INTER_LINEAR))
# key = cv2.waitKey(1)
# if key == 27: # exit on ESC
# break
|
from math import sqrt
import math
import numpy as np
import pandas as pd
import streamlit as st
from datetime import date
from sklearn.metrics import mean_squared_error, mean_absolute_error
from plotly import graph_objs as go
import matplotlib.pyplot as plt
from pandas_datareader.data import DataReader as web
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LinearRegression
import pickle
with st.expander("Nous répondrons aux questions suivantes en cours de route"):
st.write("""
1. Quelle a été la variation du prix de l'action au fil du temps?.
2. Quel était le rendement quotidien du stock en moyenne?.
3. Quelle était la moyenne mobile des différentes actions?.
4. Quelle était la corrélation entre les différentes actions?.
5. Quelle valeur mettons-nous en danger en investissant dans une action particulière?.
6. Comment pouvons-nous tenter de prédire le comportement futur des stocks?.
7. Prédire le cours de clôture du cours de l'action inc en utilisant RF.
""")
#st.title("Analyse boursière - Prédiction du prix des actions: ")
st.text("Analyse boursière - Prédiction du prix des actions: ")
#input_Date = st.date_input('start date', date(2012, 1, 1))
#input_end = st.date_input('end date', date.today())
input_Date = st.sidebar.date_input('Start date', date(2012, 1, 1))
input_end = st.sidebar.date_input('End date', date.today())
select_stock = st.sidebar.selectbox('Action', ('AAL', 'AAPL', 'AMZN', 'MAR', 'NFLX', 'WMT'))
st.sidebar.text("Travaux réalisés par :")
st.sidebar.text("David Jeanette")
st.sidebar.text("David Medina")
st.sidebar.text("Julma Pierrot")
st.sidebar.text("Raul Chavez Aquino")
if len(str(input_Date)) > 1:
StartDate = input_Date
# '2012-01-01'
EndDate = date.today().strftime('%Y-%m-%d')
else:
StartDate = '2012-01-01'
EndDate = date.today().strftime('%Y-%m-%d')
if len(str(input_end)) > 1:
EndDate = input_end
else:
EndDate = input_end
#stocks = ('AAL', 'AAPL', 'AMZN', 'MAR', 'NFLX', 'WMT')
#select_stock = st.selectbox('selection du dataset pour la prediction', stocks)
n_years = st.slider('Année de la prediction :', 1, 6)
period = n_years * 365
@st.cache(allow_output_mutation=True)
def load_data(ticker):
dfl = web(ticker, 'yahoo', StartDate, EndDate)
dfl.reset_index(inplace=True)
return dfl
df_load = st.text("Chargement des données ...")
df = load_data(select_stock)
df_load.text("Chargement des données terminées")
#
st.markdown("Données brutes de " + select_stock+" du "+str(StartDate)+" au "+str(EndDate))
st.write(df.tail())
# plot raw data
def plot_data():
fig = go.Figure()
fig.add_trace(go.Scatter(x=df["Date"], y=df["Open"], name="open price"))
fig.add_trace(go.Scatter(x=df["Date"], y=df["Adj Close"], name="close price"))
fig.layout.update(title_text="Series de données temporelles de " + select_stock, xaxis_rangeslider_visible=True)
st.plotly_chart(fig)
plot_data()
df = df.set_index('Date')
data = df.filter(['Adj Close'])
# Convert the dataframe to a numpy array
dataset = data.values
# Get the number of rows to train the model on
training_data_len = int(np.ceil(len(dataset) * .8))
# Scale the data
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(dataset)
# number of days used for the prediction of a day.
ndays = 60
# Create the training data set
# Create the scaled training data set
train_data = scaled_data[0:training_data_len, :]
# Split the data into x_train and y_train data sets
x_train = [];
y_train = []
for i in range(ndays, len(train_data)):
x_train.append(train_data[i - ndays:i, 0])
y_train.append(train_data[i, 0])
# Convert the x_train and y_train to numpy arrays
x_train, y_train = np.array(x_train), np.array(y_train)
# Create the testing data set
test_data = scaled_data[training_data_len - ndays:, :]
# Create the data sets x_test and y_test
x_test = [];
y_test = dataset[training_data_len:, :]
for i in range(ndays, len(test_data)):
x_test.append(test_data[i - ndays:i, 0])
# Convert the data to a numpy array
x_test = np.array(x_test)
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(dataset)
# number of days used for the prediction of a day.
ndays = 60
# Create the training data set
# Create the scaled training data set
train_data = scaled_data[0:training_data_len, :]
# Split the data into x_train and y_train data sets
x_train = [];
y_train = []
for i in range(ndays, len(train_data)):
x_train.append(train_data[i - ndays:i, 0])
y_train.append(train_data[i, 0])
# Convert the x_train and y_train to numpy arrays
x_train, y_train = np.array(x_train), np.array(y_train)
# Create the testing data set
test_data = scaled_data[training_data_len - ndays:, :]
# Create the data sets x_test and y_test
x_test = [];
y_test = dataset[training_data_len:, :]
for i in range(ndays, len(test_data)):
x_test.append(test_data[i - ndays:i, 0])
# Convert the data to a numpy array
x_test = np.array(x_test)
# train an test with linear regression
# Build the Linear Regression model
model = LinearRegression()
# Train the model
model.fit(x_train, y_train)
# Train
# Get the models predicted price values
predictions_train = model.predict(x_train)
# predictions_train = scaler.inverse_transform([predictions_train]).T
# Get the root mean squared error (RMSE)
rmse_train = np.sqrt(np.mean(((predictions_train - y_train) ** 2)))
print("rmse_train = ", rmse_train)
mae_train = mean_absolute_error(y_train, predictions_train)
print('MAE _train: ' + str(mae_train))
mse_train = mean_squared_error(y_train, predictions_train)
print('MSE _train: ' + str(mse_train))
mape_train = np.mean(np.abs(predictions_train - y_train) / np.abs(y_train))
print('MAPE _train: ' + str(mape_train))
# Test
# Get the models predicted price values
predictions = model.predict(x_test)
predictions = scaler.inverse_transform([predictions]).T
print('-------------------------------------')
# Get the root mean squared error (RMSE)
rmse = np.sqrt(np.mean(((predictions - y_test) ** 2)))
print("rmse = ", rmse)
mae = mean_absolute_error(y_test, predictions)
print('MAE: ' + str(mae))
mse = mean_squared_error(y_test, predictions)
print('MSE: ' + str(mse))
mape = np.mean(np.abs(predictions - y_test) / np.abs(y_test))
print('MAPE: ' + str(mape))
# Write scores to a file
with open("metrics_linear.txt", 'w') as outfile:
outfile.write("MSE Train: {0:2.5f} \n".format(mse_train))
outfile.write("MAE Train: {0:2.5f}\n".format(mae_train))
outfile.write("RMSE Train: {0:2.5f}\n".format(rmse_train))
outfile.write("MAPE Train: {0:2.5f}\n".format(mape_train))
# test
outfile.write("MSE Test: {0:2.5f} \n".format(mse))
outfile.write("MAE Test: {0:2.5f}\n".format(mae))
outfile.write("RMSE Test: {0:2.5f}\n".format(rmse))
outfile.write("MAPE Test: {0:2.5f}\n".format(mape))
# st.metric(label, value, delta=None, delta_color="normal")
#
# Plot the data
train = data[:training_data_len]
valid = data[training_data_len:]
valid['Predictions'] = predictions
valid['Erreur'] = predictions - data[training_data_len:]
# Visualize the data
figl = plt.figure(figsize=(16, 8))
plt.title('Model - Linear Regression de '+select_stock, fontsize=28)
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.plot(train['Adj Close'])
plt.plot(valid[['Adj Close', 'Predictions']])
plt.legend(['Train', 'Test', 'Predictions'], loc='lower right')
st.pyplot(figl)
#st.metric(label="Train", value="{0:2.5f}\n".format(mse_train), delta="mse")
# Metriques de performance des données et de test
st.markdown('Les métriques de performance du modèle de ' + select_stock)
# Train
coltr1, coltr2, coltr3, coltr4 = st.columns(4)
coltr1.metric("mse", "{0:2.5f}\n".format(mse_train), "train")
coltr2.metric("rmse", "{0:2.5f}\n".format(rmse_train), "train")
coltr3.metric("mae", "{0:2.5f}\n".format(mae_train), "tain")
coltr4.metric("mape", "{0:2.5f}\n".format(mape_train), "train")
# Test
colte1, colte2, colte3, colte4 = st.columns(4)
colte1.metric("mse", "{0:2.5f}\n".format(mse), "test")
colte2.metric("rmse", "{0:2.5f}\n".format(rmse), "test")
colte3.metric("mae", "{0:2.5f}\n".format(mae), "test")
colte4.metric("mape", "{0:2.5f}\n".format(mape), "test")
|
import json
import logging
import sys
import click
from click import Context
from click.testing import CliRunner
import pytest
import rasterio
from rasterio.rio import info
from rasterio.rio.main import main_group
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
def test_edit_nodata_err(data):
runner = CliRunner()
inputfile = str(data.join('RGB.byte.tif'))
result = runner.invoke(info.edit, [inputfile, '--nodata', '-1'])
assert result.exit_code == 2
def test_edit_nodata(data):
runner = CliRunner()
inputfile = str(data.join('RGB.byte.tif'))
result = runner.invoke(info.edit, [inputfile, '--nodata', '255'])
assert result.exit_code == 0
with rasterio.open(inputfile) as src:
assert src.nodata == 255.0
def test_edit_crs_err(data):
runner = CliRunner()
inputfile = str(data.join('RGB.byte.tif'))
result = runner.invoke(info.edit, [inputfile, '--crs', 'LOL:WUT'])
assert result.exit_code == 2
def test_edit_crs_epsg(data):
runner = CliRunner()
inputfile = str(data.join('RGB.byte.tif'))
result = runner.invoke(info.edit, [inputfile, '--crs', 'EPSG:32618'])
assert result.exit_code == 0
with rasterio.open(inputfile) as src:
assert src.crs == {'init': 'epsg:32618'}
def test_edit_crs_proj4(data):
runner = CliRunner()
inputfile = str(data.join('RGB.byte.tif'))
result = runner.invoke(info.edit, [inputfile, '--crs', '+init=epsg:32618'])
assert result.exit_code == 0
with rasterio.open(inputfile) as src:
assert src.crs == {'init': 'epsg:32618'}
def test_edit_crs_obj(data):
runner = CliRunner()
inputfile = str(data.join('RGB.byte.tif'))
result = runner.invoke(
info.edit, [inputfile, '--crs', '{"init": "epsg:32618"}'])
assert result.exit_code == 0
with rasterio.open(inputfile) as src:
assert src.crs == {'init': 'epsg:32618'}
def test_edit_transform_err_not_json(data):
runner = CliRunner()
inputfile = str(data.join('RGB.byte.tif'))
result = runner.invoke(info.edit, [inputfile, '--transform', 'LOL'])
assert result.exit_code == 2
def test_edit_transform_err_bad_array(data):
runner = CliRunner()
inputfile = str(data.join('RGB.byte.tif'))
result = runner.invoke(info.edit, [inputfile, '--transform', '[1,2]'])
assert result.exit_code == 2
def test_edit_transform_affine(data):
runner = CliRunner()
inputfile = str(data.join('RGB.byte.tif'))
input_t = '[300.038, 0.0, 101985.0, 0.0, -300.042, 2826915.0]'
result = runner.invoke(info.edit, [inputfile, '--transform', input_t])
assert result.exit_code == 0
with rasterio.open(inputfile) as src:
for a, b in zip(src.affine, json.loads(input_t)):
assert round(a, 6) == round(b, 6)
def test_edit_transform_gdal(data):
runner = CliRunner()
inputfile = str(data.join('RGB.byte.tif'))
input_t = '[300.038, 0.0, 101985.0, 0.0, -300.042, 2826915.0]'
result = runner.invoke(info.edit, [
inputfile,
'--transform', '[101985.0, 300.038, 0.0, 2826915.0, 0.0, -300.042]'])
assert result.exit_code == 0
with rasterio.open(inputfile) as src:
for a, b in zip(src.affine, json.loads(input_t)):
assert round(a, 6) == round(b, 6)
def test_edit_tags(data):
runner = CliRunner()
inputfile = str(data.join('RGB.byte.tif'))
result = runner.invoke(info.edit, [
inputfile, '--tag', 'lol=1', '--tag', 'wut=2'])
assert result.exit_code == 0
with rasterio.open(inputfile) as src:
assert src.tags()['lol'] == '1'
assert src.tags()['wut'] == '2'
class MockContext:
def __init__(self):
self.obj = {}
class MockOption:
def __init__(self, name):
self.name = name
def test_all_callback_pass(data):
ctx = MockContext()
ctx.obj['like'] = {'transform': 'foo'}
assert info.all_handler(ctx, None, None) == None
def test_all_callback(data):
ctx = MockContext()
ctx.obj['like'] = {'transform': 'foo'}
assert info.all_handler(ctx, None, True) == {'transform': 'foo'}
def test_all_callback_None(data):
ctx = MockContext()
assert info.all_handler(ctx, None, None) is None
def test_transform_callback_pass(data):
"""Always return None if the value is None"""
ctx = MockContext()
ctx.obj['like'] = {'transform': 'foo'}
assert info.transform_handler(ctx, MockOption('transform'), None) is None
def test_transform_callback_err(data):
ctx = MockContext()
ctx.obj['like'] = {'transform': 'foo'}
with pytest.raises(click.BadParameter):
info.transform_handler(ctx, MockOption('transform'), '?')
def test_transform_callback(data):
ctx = MockContext()
ctx.obj['like'] = {'transform': 'foo'}
assert info.transform_handler(ctx, MockOption('transform'), 'like') == 'foo'
def test_crs_callback_pass(data):
"""Always return None if the value is None"""
ctx = MockContext()
ctx.obj['like'] = {'crs': 'foo'}
assert info.crs_handler(ctx, MockOption('crs'), None) is None
def test_crs_callback(data):
ctx = MockContext()
ctx.obj['like'] = {'crs': 'foo'}
assert info.crs_handler(ctx, MockOption('crs'), 'like') == 'foo'
def test_tags_callback_err(data):
ctx = MockContext()
ctx.obj['like'] = {'tags': {'foo': 'bar'}}
with pytest.raises(click.BadParameter):
info.tags_handler(ctx, MockOption('tags'), '?') == {'foo': 'bar'}
def test_tags_callback(data):
ctx = MockContext()
ctx.obj['like'] = {'tags': {'foo': 'bar'}}
assert info.tags_handler(ctx, MockOption('tags'), 'like') == {'foo': 'bar'}
def test_edit_crs_like(data):
runner = CliRunner()
# Set up the file to be edited.
inputfile = str(data.join('RGB.byte.tif'))
with rasterio.open(inputfile, 'r+') as dst:
dst.crs = {'init': 'epsg:32617'}
dst.nodata = 1.0
# Double check.
with rasterio.open(inputfile) as src:
assert src.crs == {'init': 'epsg:32617'}
assert src.nodata == 1.0
# The test.
templatefile = 'tests/data/RGB.byte.tif'
result = runner.invoke(info.edit, [
inputfile, '--like', templatefile, '--crs', 'like'])
assert result.exit_code == 0
with rasterio.open(inputfile) as src:
assert src.crs == {'init': 'epsg:32618'}
assert src.nodata == 1.0
def test_edit_nodata_like(data):
runner = CliRunner()
# Set up the file to be edited.
inputfile = str(data.join('RGB.byte.tif'))
with rasterio.open(inputfile, 'r+') as dst:
dst.crs = {'init': 'epsg:32617'}
dst.nodata = 1.0
# Double check.
with rasterio.open(inputfile) as src:
assert src.crs == {'init': 'epsg:32617'}
assert src.nodata == 1.0
# The test.
templatefile = 'tests/data/RGB.byte.tif'
result = runner.invoke(info.edit, [
inputfile, '--like', templatefile, '--nodata', 'like'])
assert result.exit_code == 0
with rasterio.open(inputfile) as src:
assert src.crs == {'init': 'epsg:32617'}
assert src.nodata == 0.0
def test_edit_all_like(data):
runner = CliRunner()
inputfile = str(data.join('RGB.byte.tif'))
with rasterio.open(inputfile, 'r+') as dst:
dst.crs = {'init': 'epsg:32617'}
dst.nodata = 1.0
# Double check.
with rasterio.open(inputfile) as src:
assert src.crs == {'init': 'epsg:32617'}
assert src.nodata == 1.0
templatefile = 'tests/data/RGB.byte.tif'
result = runner.invoke(info.edit, [
inputfile, '--like', templatefile, '--all'])
assert result.exit_code == 0
with rasterio.open(inputfile) as src:
assert src.crs == {'init': 'epsg:32618'}
assert src.nodata == 0.0
def test_env():
runner = CliRunner()
result = runner.invoke(main_group, [
'env',
'--formats'
])
assert result.exit_code == 0
assert 'GTiff' in result.output
def test_info_err():
runner = CliRunner()
result = runner.invoke(
info.info,
['tests'])
assert result.exit_code == 1
def test_info():
runner = CliRunner()
result = runner.invoke(
info.info,
['tests/data/RGB.byte.tif'])
assert result.exit_code == 0
assert '"count": 3' in result.output
def test_info_verbose():
runner = CliRunner()
result = runner.invoke(main_group, [
'-v',
'info',
'tests/data/RGB.byte.tif'
])
assert result.exit_code == 0
def test_info_quiet():
runner = CliRunner()
result = runner.invoke(main_group, [
'-q',
'info',
'tests/data/RGB.byte.tif'
])
assert result.exit_code == 0
def test_info_count():
runner = CliRunner()
result = runner.invoke(
info.info,
['tests/data/RGB.byte.tif', '--count'])
assert result.exit_code == 0
assert result.output == '3\n'
def test_info_nodatavals():
runner = CliRunner()
result = runner.invoke(
info.info,
['tests/data/RGB.byte.tif', '--bounds'])
assert result.exit_code == 0
assert result.output == '101985.0 2611485.0 339315.0 2826915.0\n'
def test_info_tags():
runner = CliRunner()
result = runner.invoke(
info.info,
['tests/data/RGB.byte.tif', '--tags'])
assert result.exit_code == 0
assert result.output == '{"AREA_OR_POINT": "Area"}\n'
def test_info_res():
runner = CliRunner()
result = runner.invoke(
info.info,
['tests/data/RGB.byte.tif', '--res'])
assert result.exit_code == 0
assert result.output.startswith('300.037')
def test_info_lnglat():
runner = CliRunner()
result = runner.invoke(
info.info,
['tests/data/RGB.byte.tif', '--lnglat'])
assert result.exit_code == 0
assert result.output.startswith('-77.757')
def test_mo_info():
runner = CliRunner()
result = runner.invoke(info.info, ['tests/data/RGB.byte.tif'])
assert result.exit_code == 0
assert '"res": [300.037' in result.output
assert '"lnglat": [-77.757' in result.output
def test_info_stats():
runner = CliRunner()
result = runner.invoke(
info.info, ['tests/data/RGB.byte.tif', '--tell-me-more'])
assert result.exit_code == 0
assert '"max": 255.0' in result.output
assert '"min": 1.0' in result.output
assert '"mean": 44.4344' in result.output
def test_info_stats_only():
runner = CliRunner()
result = runner.invoke(
info.info, ['tests/data/RGB.byte.tif', '--stats', '--bidx', '2'])
assert result.exit_code == 0
assert result.output.startswith('1.000000 255.000000 66.02')
def test_transform_err():
runner = CliRunner()
result = runner.invoke(main_group, [
'transform'
], "[-78.0]")
assert result.exit_code == 1
def test_transform_point():
runner = CliRunner()
result = runner.invoke(main_group, [
'transform',
'--dst-crs', 'EPSG:32618',
'--precision', '2'
], "[-78.0, 23.0]", catch_exceptions=False)
assert result.exit_code == 0
assert result.output.strip() == '[192457.13, 2546667.68]'
def test_transform_point_dst_file():
runner = CliRunner()
result = runner.invoke(main_group, [
'transform',
'--dst-crs', 'tests/data/RGB.byte.tif', '--precision', '2'
], "[-78.0, 23.0]")
assert result.exit_code == 0
assert result.output.strip() == '[192457.13, 2546667.68]'
def test_transform_point_src_file():
runner = CliRunner()
result = runner.invoke(main_group, [
'transform',
'--src-crs',
'tests/data/RGB.byte.tif',
'--precision', '2'
], "[192457.13, 2546667.68]")
assert result.exit_code == 0
assert result.output.strip() == '[-78.0, 23.0]'
def test_transform_point_2():
runner = CliRunner()
result = runner.invoke(main_group, [
'transform',
'[-78.0, 23.0]',
'--dst-crs', 'EPSG:32618',
'--precision', '2'
])
assert result.exit_code == 0
assert result.output.strip() == '[192457.13, 2546667.68]'
def test_transform_point_multi():
runner = CliRunner()
result = runner.invoke(main_group, [
'transform',
'--dst-crs', 'EPSG:32618',
'--precision', '2'
], "[-78.0, 23.0]\n[-78.0, 23.0]", catch_exceptions=False)
assert result.exit_code == 0
assert result.output.strip() == (
'[192457.13, 2546667.68]\n[192457.13, 2546667.68]')
def test_bounds_defaults():
runner = CliRunner()
result = runner.invoke(main_group, [
'bounds',
'tests/data/RGB.byte.tif'
])
assert result.exit_code == 0
assert 'FeatureCollection' in result.output
def test_bounds_err():
runner = CliRunner()
result = runner.invoke(main_group, [
'bounds',
'tests'
])
assert result.exit_code == 1
def test_bounds_feature():
runner = CliRunner()
result = runner.invoke(main_group, [
'bounds',
'tests/data/RGB.byte.tif',
'--feature'
])
assert result.exit_code == 0
assert result.output.count('Polygon') == 1
def test_bounds_obj_bbox():
runner = CliRunner()
result = runner.invoke(main_group, [
'bounds',
'tests/data/RGB.byte.tif',
'--bbox',
'--precision', '2'
])
assert result.exit_code == 0
assert result.output.strip() == '[-78.96, 23.56, -76.57, 25.55]'
def test_bounds_compact():
runner = CliRunner()
result = runner.invoke(main_group, [
'bounds',
'tests/data/RGB.byte.tif',
'--bbox',
'--precision', '2',
'--compact'
])
assert result.exit_code == 0
assert result.output.strip() == '[-78.96,23.56,-76.57,25.55]'
def test_bounds_indent():
runner = CliRunner()
result = runner.invoke(main_group, [
'bounds',
'tests/data/RGB.byte.tif',
'--bbox',
'--indent', '2',
'--precision', '2'
])
assert result.exit_code == 0
assert len(result.output.split('\n')) == 7
def test_bounds_obj_bbox_mercator():
runner = CliRunner()
result = runner.invoke(main_group, [
'bounds',
'tests/data/RGB.byte.tif',
'--bbox',
'--mercator',
'--precision', '3'
])
assert result.exit_code == 0
assert result.output.strip() == (
'[-8789636.708, 2700489.278, -8524281.514, 2943560.235]')
def test_bounds_obj_bbox_projected():
runner = CliRunner()
result = runner.invoke(main_group, [
'bounds',
'tests/data/RGB.byte.tif',
'--bbox',
'--projected',
'--precision', '3'
])
assert result.exit_code == 0
assert result.output.strip() == (
'[101985.0, 2611485.0, 339315.0, 2826915.0]')
def test_bounds_crs_bbox():
runner = CliRunner()
result = runner.invoke(main_group, [
'bounds',
'tests/data/RGB.byte.tif',
'--bbox',
'--dst-crs', 'EPSG:32618',
'--precision', '3'
])
assert result.exit_code == 0
assert result.output.strip() == (
'[101985.0, 2611485.0, 339315.0, 2826915.0]')
def test_bounds_seq():
runner = CliRunner()
result = runner.invoke(main_group, [
'bounds',
'tests/data/RGB.byte.tif',
'tests/data/RGB.byte.tif',
'--sequence'
])
assert result.exit_code == 0
assert result.output.count('Polygon') == 2
result = runner.invoke(main_group, [
'bounds',
'tests/data/RGB.byte.tif',
'tests/data/RGB.byte.tif',
'--sequence',
'--bbox',
'--precision', '2'
])
assert result.exit_code == 0
assert result.output == (
'[-78.96, 23.56, -76.57, 25.55]\n[-78.96, 23.56, -76.57, 25.55]\n')
assert '\x1e' not in result.output
def test_bounds_seq_rs():
runner = CliRunner()
result = runner.invoke(main_group, [
'bounds',
'tests/data/RGB.byte.tif',
'tests/data/RGB.byte.tif',
'--sequence',
'--rs',
'--bbox',
'--precision', '2'
])
assert result.exit_code == 0
assert result.output == (
'\x1e[-78.96, 23.56, -76.57, 25.55]\n\x1e[-78.96, 23.56, -76.57, 25.55]\n')
def test_insp():
runner = CliRunner()
result = runner.invoke(main_group, [
'insp',
'tests/data/RGB.byte.tif'
])
assert result.exit_code == 0
def test_insp_err():
runner = CliRunner()
result = runner.invoke(main_group, [
'insp',
'tests'
])
assert result.exit_code == 1
def test_info_checksums():
runner = CliRunner()
result = runner.invoke(
info.info, ['tests/data/RGB.byte.tif', '--tell-me-more'])
assert result.exit_code == 0
assert '"checksum": [25420, 29131, 37860]' in result.output
def test_info_checksums_only():
runner = CliRunner()
result = runner.invoke(
info.info, ['tests/data/RGB.byte.tif', '--checksum', '--bidx', '2'])
assert result.exit_code == 0
assert result.output.strip() == '29131'
|
// show API error/sucess toastr
import * as toastr from 'toastr';
import { toArrayIfNot } from '~/utils/array-utils';
const toastrOption = {
error: {
closeButton: true,
progressBar: true,
newestOnTop: false,
showDuration: '100',
hideDuration: '100',
timeOut: '0',
},
success: {
closeButton: true,
progressBar: true,
newestOnTop: false,
showDuration: '100',
hideDuration: '100',
timeOut: '3000',
},
warning: {
closeButton: true,
progressBar: true,
newestOnTop: false,
showDuration: '100',
hideDuration: '100',
timeOut: '6000',
},
};
// accepts both a single error and an array of errors
export const toastError = (err, header = 'Error', option = toastrOption.error) => {
const errs = toArrayIfNot(err);
if (err.length === 0) {
toastr.error('', header);
}
for (const err of errs) {
toastr.error(err.message || err, header, option);
}
};
// only accepts a single item
export const toastSuccess = (body, header = 'Success', option = toastrOption.success) => {
toastr.success(body, header, option);
};
export const toastWarning = (body, header = 'Warning', option = toastrOption.warning) => {
toastr.warning(body, header, option);
};
|
/**
*
* 选择排序
* O(n^2)复杂度
*/
const selectSort = (arr, n) => {
for (let i = 0; i < n; i++) {
let minIndex = i
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j
}
}
const temp = arr[minIndex]
arr[minIndex] = arr[i]
arr[i] = temp
}
return arr
}
module.exports = selectSort
|
const puppeteer = require('puppeteer')
const fs = require('fs');
const { Console } = require('console');
const { SSL_OP_EPHEMERAL_RSA } = require('constants');
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const csvWriter = createCsvWriter({
path: 'papers.csv',
header: [
{id: 'title', title: 'Title'},
{id: 'link', title: 'Cambridge link'},
{id: 'analytics_link', title: 'Link to Altmetric'},
{id: 'date', title: 'Date of online publication'},
{id: 'attention', title: 'Attention Score'},
{id: 'tweets', title: 'Number of tweets'},
{id: 'users', title: 'Number of users tweeted'},
{id: 'upper_bound', title: 'Upper bound of followers'},
{id: 'citations_num', title: 'Number of citations'}
]
});
let papers = [];
let numPages = 10;
async function getData() {
try {
// Load the headless browser adn the first page
const browser = await puppeteer.launch();
let page = await browser.newPage();
await page.goto(`https://www.cambridge.org/core/journals/american-political-science-review/most-cited`)
page.waitForSelector("div.altmetric-embed > a")
// click on Last 3 years
console.log("Clicking the last 3 years button")
const lastYearsButton = await page.$(".sort-content .checkbox[data-agg-container='Last 3 years'] .styled");
await lastYearsButton.evaluate(lastYearsButton => lastYearsButton.click());
await page.waitForNavigation();
await page.waitForTimeout(2000);
console.log("Clicked it")
// Iterate through the last 3 years
for (let i = 1; i <= numPages; ++i){
console.log("Analayzing page " + i)
let papersInfo = await page.evaluate(() => {
let paperTitle = document.querySelectorAll(".part-link")
let paperDate = document.querySelectorAll(".published .date")
let analytics_link = document.querySelectorAll(".altmetric-embed.medium-1 > a")
let citations_num = document.querySelectorAll(".listing-citation-modal > .number")
let paperInfoArray = []
for (let i = 0; i < analytics_link.length; i++) {
paperInfoArray[i] = {
title: paperTitle[i].innerText.trim(),
date : paperDate[i].innerText.trim(),
link: "https://www.cambridge.org" + paperTitle[i].getAttribute("href"),
analytics_link: "https://cambridge.altmetric.com/details/" + analytics_link[i].getAttribute("href").substr(75) + "/twitter",
citations_num: citations_num[i].innerText.trim()
};
}
return paperInfoArray;
});
// Extend the papers object
papers = papers.concat(papersInfo);
console.log(`Got data from page ${i}. There were ${papersInfo.length} elements found on that page.`);
// Click on next page
let nextPageButton = await page.$(".pagination > .current + li a");
if (nextPageButton){
await nextPageButton.evaluate(nextPageButton => nextPageButton.click());
await page.waitForNavigation();
await page.waitForTimeout(2000);
}
}
console.log(`Now getting twitter data for ${papers.length} papers`);
// Get analytics data
for (let j = 0; j < papers.length; ++j) {
let paper = papers[j];
console.log(`Getting popularity data for paper ${j + 1}`);
let url = paper.analytics_link;
let analytics_page = await browser.newPage();
await analytics_page.goto(url);
analytics_page.waitForSelector(".section-summary > .text strong");
[paper.attention, paper.tweets, paper.users, paper.upper_bound] = await analytics_page.evaluate(() => {
// Get twitter values
let twitter_data = document.querySelectorAll(".section-summary > .text strong");
// Get attention score
let attention_url = document.querySelector(".altmetric-badge-wrapper > .altmetric-badge").style["background-image"];
let beginIndex = attention_url.indexOf("score=") + 6;
let endIndex = attention_url.indexOf("&", beginIndex);
let attention_score = attention_url.substr(beginIndex, endIndex - beginIndex);
// Return Twitter data
if (twitter_data.length == 3){
return [parseInt(attention_score), twitter_data[0].innerText, twitter_data[1].innerText, twitter_data[2].innerText]
}
else if (twitter_data.length == 2){
return [parseInt(attention_score), twitter_data[0].innerText, 1, twitter_data[1].innerText]
}
else {
return [parseInt(attention_score), 0, 0, 0];
}
});
}
await browser.close()
} catch (error) {
console.error(error)
}
}
getData().then(() => {
csvWriter
.writeRecords(papers)
.then(()=> console.log('The CSV file was written successfully'));
}).catch(err => console.error(err))
|
// @flow
import type { DayText, LessonTime, ModuleCode, RawLesson } from 'types/modules';
export type Venue = string;
export type VenueList = Venue[];
// Components within a venue availability class:
export type VenueOccupiedState = 'vacant' | 'occupied';
export const VACANT: VenueOccupiedState = 'vacant';
export const OCCUPIED: VenueOccupiedState = 'occupied';
export type Availability = { [LessonTime]: VenueOccupiedState }; // E.g. { "1000": "vacant", "1030": "occupied", ... }
// Raw lessons obtained from venue info API includes ModuleCode by default
export type VenueLesson = RawLesson & {
ModuleCode: ModuleCode,
};
// A venue's availability info for one day
// E.g. { "Day": "Monday", "Classes": [...], "Availability": {...} }
export type DayAvailability = {
Day: DayText,
Classes: VenueLesson[],
Availability: Availability,
};
// Describes venueInformation.json
// E.g. { "LT16": [DayAvailability1, DayAvailability2, ...], "LT17": [...], ... }
export type VenueInfo = { [Venue]: DayAvailability[] };
// Used to specify availability search options
// All properties are number to make (de)serialization into query string simpler to handle
export type VenueSearchOptions = {
day: number, // Day of week (ie. 0 = Monday, 1 = Tuesday etc.)
time: number, // in hours (ie. 9 = 9am, 13 = 1pm etc.)
duration: number, // in hours
};
export type VenueDetailList = [Venue, DayAvailability[]][];
export type VenueLocation = {
roomName: string,
floor: ?number,
location?: { x: number, y: number },
};
export type LatLngTuple = [number, number];
// data/venues.json is of this type
export type VenueLocationMap = { [string]: VenueLocation };
|
require('dotenv').config()
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const mysql = require('mysql')
const auth = require('./auth');
const app = express();
const items = require('./items.js');
const admin = require('./admin.js');
const port = process.env.PORT || 5000;
//serve static files (react components)
app.use(express.static(path.join(__dirname, '/client/build')));
//HTTP methods logging
app.use(morgan('short'));
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true, parameterLimit: 50000 }));
//authentication
app.use('/', auth);
//items
app.use('/', items);
//admin
app.use('/', admin)
let pool = mysql.createPool({
connectionLimit: 10,
host: process.env.MYSQL_HOST ,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PW,
port: process.env.MYSQL_PORT,
database: process.env.MYSQL_DB
})
app.get('/', (req, res) => {
res.send("Welcome to Cuddles's server.");
});
app.get('/api/users/:username/confirmation', (req, res) => {
pool.query(`SELECT fullname, email, phone, street, city, zip, state, payment, cardnumber FROM user WHERE username="${req.params.username}"`, (err, result) => {
if (err) {
res.status(400);
throw err;
}
else {
res.status(200).send(result);
}
})
})
app.post('/api/users/:username/orders', (req, res) => {
let today = new Date()
pool.query(`INSERT INTO ordertable (ItemID, username, quantity, status, charge, orderDate) VALUES (${req.body.id}, "${req.params.username}", "1","PENDING","${req.body.price}","${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}")`, (err, result) => {
if (err) {
res.status(400);
throw err;
}
else {
res.status(200).send("Successfully inserted");
}
})
});
app.get('/api/users/:username/orders', (req, res) => {
pool.query(`SELECT item.ItemImage, OrderID, status, orderDate, charge, item.ItemName, quantity, item.ItemPrice FROM ordertable INNER JOIN item ON item.ItemID = ordertable.ItemID WHERE username = "${req.params.username}";`, (err, result) => {
if (err) {
res.status(400);
throw err;
}
else {
res.status(200).send(result);
}
})
});
app.post('/api/users/:username/cart', (req, res) => {
});
app.put('/api/users/:username/accountInfo/username', (req, res) => {
if (req.body.username != req.params.username) {
pool.query(`SELECT username FROM user WHERE username = "${req.body.username}"`, (err, result) => {
if (err) {
throw err;
}
if (result.length === 0) {
pool.query(`UPDATE user SET username= "${req.body.username}" WHERE username="${req.params.username}"`, (err) => {
if (err) {
res.status(400).send("Cannot update Username");
throw err;
}
else {
res.status(200).send("Username updated");
}
})
}
else {
res.status(400).send("Username exists!");
}
})
}
})
app.put('/api/users/:username/accountInfo/password', (req, res) => {
pool.query(`UPDATE user SET password = "${req.body.password}" WHERE username="${req.params.username}"`, (err) => {
if (err) {
res.status(400).send("Cannot update password");
throw err;
}
else {
res.status(200).send("Password updated");
}
})
})
app.put('/api/users/:username/accountInfo/email', (req, res) => {
pool.query(`UPDATE user SET email= "${req.body.email}" WHERE username="${req.params.username}"`, (err) => {
if (err) {
res.status(400).send("Cannot update email");
throw err;
}
else {
res.status(200).send("Email updated");
}
})
})
app.put('/api/users/:username/accountInfo/fullname', (req, res) => {
pool.query(`UPDATE user SET fullname= "${req.body.fullname}" WHERE username="${req.params.username}"`, (err) => {
if (err) {
res.status(400).send("Cannot update full name");
throw err;
}
else {
res.status(200).send("Full name updated");
}
})
})
app.put('/api/users/:username/accountInfo/phone', (req, res) => {
pool.query(`UPDATE user SET username= "${req.body.phone}" WHERE username="${req.params.username}"`, (err) => {
if (err) {
res.status(400).send("Cannot update billing information");
throw err;
}
else {
res.status(200).send("Username updated");
}
})
})
app.get('/api/users/:username/accountInfo/billing', (req, res) => {
pool.query(`SELECT cardnumber FROM user WHERE cardnumber IS NOT NULL AND username="${req.params.username}"`, (err, result) => {
if (err) {
res.status(400).send("Billing information does not exists.");
throw err;
}
if (result.length > 0) {
res.status(200).send("Billing information exsits.");
}
else {
res.status(400).send("Billing information does not exists.");
}
})
});
app.put('/api/users/:username/accountInfo/billing', (req, res) => {
pool.query(`UPDATE user SET payment="${req.body.payment}", cardnumber="${req.body.cardNumber}", cvv="${req.body.cvv}", expiration_date="${req.body.expirationDate}" WHERE username="${req.params.username}"`, (err) => {
if (err) {
res.status(400).send("Cannot update billing information");
throw err;
}
else {
res.status(200).send("Billing information updated");
}
})
})
app.get('/api/users/:username/accountInfo/address', (req, res) => {
pool.query(`SELECT street FROM user WHERE street IS NOT NULL AND username="${req.params.username}"`, (err, result) => {
if (err) {
res.status(400).send("Address information does not exists.");
throw err
}
else if (result.length > 0) {
res.status(200).send("Address information exists.");
}
else {
res.status(400).send("Address information does not exists.");
}
})
});
app.put('/api/users/:username/accountInfo/address', (req, res) => {
pool.query(`UPDATE user SET street="${req.body.street}", city="${req.body.city}", zip="${req.body.zip}", state="${req.body.state}" WHERE username="${req.params.username}"`, (err) => {
if (err) {
res.status(400).send("Cannot update address information.");
throw err;
}
else {
res.status(200).send("Address information updated.");
}
});
})
app.get('/api/users/:username/accountInfo', (req, res) => {
pool.query(`SELECT * FROM user WHERE username = '${req.params.username}'`, (err, result) => {
if (err) {
res.status(400).send("Cannot fetch account information.");
throw err;
}
else {
res.status(200).send(result[0]);
}
})
})
app.get('*', function (req, res) {
res.sendFile(path.resolve('./client/build', 'index.html'));
});
app.listen(port, () => console.log(`Listening on port ${port}`));
|
/** \file
* \brief IUP Core pre-defined dialogs (not exported API)
*
* See Copyright Notice in "iup.h"
*/
#ifndef __IUP_PREDIAL_H
#define __IUP_PREDIAL_H
#ifdef __cplusplus
extern "C" {
#endif
#include "iup_export.h"
/* Used by the IupScanf implementation */
IUP_EXPORTI int iupDataEntry(int maxlin, int* maxcol, int* maxscr, char* title, char** text, char** data);
/* Popups a dialog with IUP Version, used in IupOpen */
void iupShowVersion(void);
/* Other functions declared in <iup.h> and implemented here.
IupListDialog
IupAlarm
IupMessagef
IupGetFile
IupGetText
*/
#ifdef __cplusplus
}
#endif
#endif
|
# -*- coding: utf-8 -*-
#############################################################################
##
## Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
## Contact: http:#www.qt-project.org/legal
##
## This file is part of the Qt Solutions component.
##
## $QT_BEGIN_LICENSE:BSD$
## You may use this file under the terms of the BSD license as follows:
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are
## met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in
## the documentation and/or other materials provided with the
## distribution.
## * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
## of its contributors may be used to endorse or promote products derived
## from this software without specific prior written permission.
##
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
##
## $QT_END_LICENSE$
##
#############################################################################
import sys
import os
filePath = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(filePath,'QtProperty'))
sys.path.append(os.path.join(filePath,'libqt5'))
#print(sys.path)
from array import array
from qtpy.QtGui import QTransform as QMatrix
from qtpy.QtCore import (
Qt,
QRect,
QTimer,
QPoint,
QSize,
qWarning,
QRectF,
Signal,
QObject
)
from qtpy.QtGui import (
QRegion,
QImage,
QPolygon,
QPixmap,
QPainter,
QPainterPath,
QPen,
QBrush,
QFontMetrics,
QFont,
QColor
)
from qtpy.QtWidgets import (
QWidget,
QApplication,
QScrollArea
)
from pyqtcore import QSet, QList
from enum import Enum
class QPolygonEx(QPolygon):
def resize(self, n):
_n = self.size()
for i in range(n-_n):
self.append(QPoint())
for i in range(_n-n):
self.remove(self.size()-1)
def detach(self):
pass
def qt_testCollision(s1, s2):
s2image = s2.imageAdvanced().collision_mask
s2area = s2.boundingRectAdvanced()
cyourarea = QRect(s2area.x(), s2area.y(), s2area.width(), s2area.height())
s1image = s1.imageAdvanced().collision_mask
s1area = s1.boundingRectAdvanced()
ourarea = s1area.intersected(cyourarea)
if (ourarea.isEmpty()):
return False
x2 = ourarea.x()-cyourarea.x()
y2 = ourarea.y()-cyourarea.y()
x1 = ourarea.x()-s1area.x()
y1 = ourarea.y()-s1area.y()
w = ourarea.width()
h = ourarea.height()
if (not s2image):
if (not s1image):
return w>0 and h>0
# swap everything around
t = x1; x1 = x2; x2 = t
t = y1; x1 = y2; y2 = t
s2image = s1image
s1image = 0
# s2image != 0
# A non-linear search may be more efficient.
# Perhaps spiralling out from the center, or a simpler
# vertical expansion from the centreline.
# We assume that sprite masks don't have
# different bit orders.
#
# Q_ASSERT(s1image.bitOrder() == s2image.bitOrder())
if (s1image):
if (s1image.format() == QImage.Format_MonoLSB):
for j in range(h):
ml = s1image.scanLine(y1+j)
yl = s2image.scanLine(y2+j)
for i in range(w):
if (yl + ((x2+i) >> 3) & (1 << ((x2+i) & 7)) and ml + ((x1+i) >> 3) & (1 << ((x1+i) & 7))):
return True
else:
for j in range(h):
ml = s1image.scanLine(y1+j)
yl = s2image.scanLine(y2+j)
for i in range(w):
if (yl + ((x2+i) >> 3) & (1 << (7-((x2+i) & 7))) and ml + ((x1+i) >> 3) & (1 << (7-((x1+i) & 7)))):
return True
else:
if (s2image.format() == QImage.Format_MonoLSB):
for j in range(h):
yl = s2image.scanLine(y2+j)
for i in range(w):
if ((yl + ((x2+i) >> 3)) & (1 << ((x2+i) & 7))):
return True
else:
for j in range(h):
yl = s2image.scanLine(y2+j)
for i in range(w):
if ((yl + ((x2+i) >> 3)) & (1 << (7-((x2+i) & 7)))):
return True
return False
def collision_double_dispatch(s1, p1, r1, e1, t1, s2, p2, r2, e2, t2):
if s1:
i1 = s1
elif p1:
i1 = p1
elif r1:
i1 = r1
elif e1:
i1 = e1
elif t1:
i1 = t1
if s2:
i2 = s2
elif p2:
i2 = p2
elif r2:
i2 = r2
elif e2:
i2 = e2
elif t2:
i2 = t2
if (s1 and s2):
# a
return qt_testCollision(s1, s2)
elif ((r1 or t1 or s1) and (r2 or t2 or s2)):
# b
rc1 = i1.boundingRectAdvanced()
rc2 = i2.boundingRectAdvanced()
return rc1.intersects(rc2)
elif (e1 and e2
and e1.angleLength()>= 360*16 and e2.angleLength()>= 360*16
and e1.width() == e1.height()
and e2.width() == e2.height()):
# c
xd = (e1.x()+e1.xVelocity())-(e2.x()+e1.xVelocity())
yd = (e1.y()+e1.yVelocity())-(e2.y()+e1.yVelocity())
rd = (e1.width()+e2.width())/2
return xd*xd+yd*yd <= rd*rd
elif (p1 and (p2 or s2 or t2)):
# d
pa1 = p1.areaPointsAdvanced()
if p2:
pa2 = p2.areaPointsAdvanced()
else:
pa2 = QPolygonEx(i2.boundingRectAdvanced())
col = not (QRegion(pa1) & QRegion(pa2, Qt.WindingFill)).isEmpty()
return col
else:
return collision_double_dispatch(s2, p2, r2, e2, t2,
s1, p1, r1, e1, t1)
class Edge(Enum):
Left = 1
Right = 2
Top = 4
Bottom = 8
###
# \enum RttiValues
#
# This enum is used to name the different types of canvas item.
#
# \value Rtti_Item Canvas item abstract base class
# \value Rtti_Ellipse
# \value Rtti_Line
# \value Rtti_Polygon
# \value Rtti_PolygonalItem
# \value Rtti_Rectangle
# \value Rtti_Spline
# \value Rtti_Sprite
# \value Rtti_Text
#
###
class RttiValues(Enum):
Rtti_Item = 0
Rtti_Sprite = 1
Rtti_PolygonalItem = 2
Rtti_Text = 3
Rtti_Polygon = 4
Rtti_Rectangle = 5
Rtti_Ellipse = 6
Rtti_Line = 7
Rtti_Spline = 8
class QtCanvasData():
def __init__(self):
self.viewList = QList()
self.itemDict = QSet()
self.animDict = QSet()
class QtCanvasViewData():
def __init__(self):
self.xform = QMatrix()
self.ixform = QMatrix()
self.highQuality = False
def include(r, rect):
if (rect.left() < r.left()):
r.setLeft(rect.left())
if (rect.right()>r.right()):
r.setRight(rect.right())
if (rect.top() < r.top()):
r.setTop(rect.top())
if (rect.bottom()>r.bottom()):
r.setBottom(rect.bottom())
###
#A QtCanvasClusterizer groups rectangles (QRects) into non-overlapping rectangles
#by a merging heuristic.
###
class QtCanvasClusterizer():
def __init__(self, maxclusters):
self.cluster = QList()
for i in range(maxclusters):
self.cluster.append(QRect())
self.count = 0
self.maxcl = maxclusters
def __del__(self):
del self.cluster
def clear(self):
self.count = 0
def add(self, x, y, w=1, h=1):
self.__add(QRect(x, y, w, h))
def __add(self, rect):
biggerrect = QRect(rect.x()-1, rect.y()-1, rect.width()+2, rect.height()+2)
#assert(rect.width()>0 and rect.height()>0)
for cursor in range(self.count):
if (self.cluster[cursor].contains(rect)):
# Wholly contained already.
return
lowestcost = 9999999
cheapest = -1
cursor = 0
while(cursor < self.count):
if (self.cluster[cursor].intersects(biggerrect)):
larger = self.cluster[cursor]
include(larger, rect)
cost = larger.width()*larger.height() - self.cluster[cursor].width()*self.cluster[cursor].height()
if (cost < lowestcost):
bad = False
for c in range(self.count):
if not bad:
bad = self.cluster[c].intersects(larger) and c!= cursor
if (not bad):
cheapest = cursor
lowestcost = cost
cursor += 1
if (cheapest>= 0):
include(self.cluster[cheapest], rect)
return
if (self.count < self.maxcl):
self.cluster[self.count] = rect
self.count += 1
return
# Do cheapest of:
# add to closest self.cluster
# do cheapest self.cluster merge, add to new self.cluster
lowestcost = 9999999
cheapest = -1
cursor = 0
while(cursor < self.count):
larger = self.cluster[cursor]
include(larger, rect)
cost = larger.width()*larger.height() - self.cluster[cursor].width()*self.cluster[cursor].height()
if (cost < lowestcost):
bad = False
for c in range(self.count):
if not bad:
bad = self.cluster[c].intersects(larger) and c!= cursor
if (not bad):
cheapest = cursor
lowestcost = cost
cursor += 1
# ###
# could make an heuristic guess as to whether we need to bother
# looking for a cheap merge.
cheapestmerge1 = -1
cheapestmerge2 = -1
merge1 = 0
while(merge1 < self.count):
merge2 = 0
while(merge2 < self.count):
if(merge1!= merge2):
larger = self.cluster[merge1]
include(larger, self.cluster[merge2])
cost = larger.width()*larger.height() - self.cluster[merge1].width()*self.cluster[merge1].height()
if (cost < lowestcost):
bad = False
for c in range(self.count):
if not bad:
bad = self.cluster[c].intersects(larger) and c!= cursor
if (not bad):
cheapestmerge1 = merge1
cheapestmerge2 = merge2
lowestcost = cost
merge2 += 1
merge1 += 1
if (cheapestmerge1>= 0):
include(self.cluster[cheapestmerge1], self.cluster[cheapestmerge2])
self.cluster[cheapestmerge2] = self.cluster[self.count]
self.count -= 1
else:
# if (not cheapest) debugRectangles(rect):
include(self.cluster[cheapest], rect)
# NB: clusters do not intersect (or intersection will
# overwrite). This is a result of the above algorithm,
# given the assumption that (x, y) are ordered topleft
# to bottomright.
# ###
#
# add explicit x/y ordering to that comment, move it to the top
# and rephrase it as pre-/post-conditions.
def __getItem__(self, i):
return self.cluster[i]
# end of clusterizer
class QtCanvasItemLess():
def func(self, i1, i2):
if (i1.z() == i2.z()):
return i1 > i2
return (i1.z() > i2.z())
class QtCanvasChunk():
def __init__(self):
self.changed = True
self.m_list = QList()
# Other code assumes lists are not deleted. Assignment is also
# done on ChunkRecs. So don't add that sort of thing here.
def sort(self):
self.m_list = QList(sorted(self.m_list, key=lambda x:x.z(), reverse=True))
def list(self):
return self.m_list
def add(self, item):
self.m_list.prepend(item)
self.changed = True
def remove(self, item):
self.m_list.removeAll(item)
self.changed = True
def change(self):
self.changed = True
def hasChanged(self):
return self.changed
def takeChange(self):
y = self.changed
self.changed = False
return y
def gcd(a, b):
r = 0
while r:
r = a%b
a = b
b = r
return b
def scm(a, b):
g = gcd(a, b)
return a/g*b
###
# \class QtCanvas qtcanvas.h
# \brief The QtCanvas class provides a 2D area that can contain QtCanvasItem objects.
#
# The QtCanvas class manages its 2D graphic area and all the canvas
# items the area contains. The canvas has no visual appearance of
# its own. Instead, it is displayed on screen using a QtCanvasView.
# Multiple QtCanvasView widgets may be associated with a canvas to
# provide multiple views of the same canvas.
#
# The canvas is optimized for large numbers of items, particularly
# where only a small percentage of the items change at any
# one time. If the entire display changes very frequently, you should
# consider using your own custom QtScrollView subclass.
#
# Qt provides a rich
# set of canvas item classes, e.g. QtCanvasEllipse, QtCanvasLine,
# QtCanvasPolygon, QtCanvasPolygonalItem, QtCanvasRectangle, QtCanvasSpline,
# QtCanvasSprite and QtCanvasText. You can subclass to create your own
# canvas items; QtCanvasPolygonalItem is the most common base class used
# for this purpose.
#
# Items appear on the canvas after their \link QtCanvasItem.show()
# show()\endlink function has been called (or \link
# QtCanvasItem.setVisible() setVisible(True)\endlink), and \e after
# update() has been called. The canvas only shows items that are
# \link QtCanvasItem.setVisible() visible\endlink, and then only if
# \l update() is called. (By default the canvas is white and so are
# canvas items, so if nothing appears try changing colors.):
#
# If you created the canvas without passing a width and height to
# the constructor you must also call resize().
#
# Although a canvas may appear to be similar to a widget with child
# widgets, there are several notable differences:
#
# \list
# \i Canvas items are usually much faster to manipulate and redraw than
# child widgets, with the speed advantage becoming especially great when
# there are \e many canvas items and non-rectangular items. In most
# situations canvas items are also a lot more memory efficient than child
# widgets.
#
# \i It's easy to detect overlapping items (collision detection).
#
# \i The canvas can be larger than a widget. A million-by-million canvas
# is perfectly possible. At such a size a widget might be very
# inefficient, and some window systems might not support it at all,
# whereas QtCanvas scales well. Even with a billion pixels and a million
# items, finding a particular canvas item, detecting collisions, etc.,
# is still fast (though the memory consumption may be prohibitive
# at such extremes).
#
# \i Two or more QtCanvasView objects can view the same canvas.
#
# \i An arbitrary transformation matrix can be set on each QtCanvasView
# which makes it easy to zoom, rotate or shear the viewed canvas.
#
# \i Widgets provide a lot more functionality, such as input (QKeyEvent,
# QMouseEvent etc.) and layout management (QGridLayout etc.).
#
# \endlist
#
# A canvas consists of a background, a number of canvas items organized by
# x, y and z coordinates, and a foreground. A canvas item's z coordinate
# can be treated as a layer number -- canvas items with a higher z
# coordinate appear in front of canvas items with a lower z coordinate.
#
# The background is white by default, but can be set to a different color
# using setBackgroundColor(), or to a repeated pixmap using
# setBackgroundPixmap() or to a mosaic of smaller pixmaps using
# setTiles(). Individual tiles can be set with setTile(). There
# are corresponding get functions, e.g. backgroundColor() and
# backgroundPixmap().
#
# Note that QtCanvas does not inherit from QWidget, even though it has some
# functions which provide the same functionality as those in QWidget. One
# of these is setBackgroundPixmap(); some others are resize(), size(),
# width() and height(). \l QtCanvasView is the widget used to display a
# canvas on the screen.
#
# Canvas items are added to a canvas by constructing them and passing the
# canvas to the canvas item's constructor. An item can be moved to a
# different canvas using QtCanvasItem.setCanvas().
#
# Canvas items are movable (and in the case of QtCanvasSprites, animated)
# objects that inherit QtCanvasItem. Each canvas item has a position on the
# canvas (x, y coordinates) and a height (z coordinate), all of which are
# held as floating-point numbers. Moving canvas items also have x and y
# velocities. It's possible for a canvas item to be outside the canvas
# (for example QtCanvasItem.x() is greater than width()). When a canvas
# item is off the canvas, onCanvas() returns False and the canvas
# disregards the item. (Canvas items off the canvas do not slow down any
# of the common operations on the canvas.)
#
# Canvas items can be moved with QtCanvasItem.move(). The advance()
# function moves all QtCanvasItem.animated() canvas items and
# setAdvancePeriod() makes QtCanvas move them automatically on a periodic
# basis. In the context of the QtCanvas classes, to `animate' a canvas item
# is to set it in motion, i.e. using QtCanvasItem.setVelocity(). Animation
# of a canvas item itself, i.e. items which change over time, is enabled
# by calling QtCanvasSprite.setFrameAnimation(), or more generally by
# subclassing and reimplementing QtCanvasItem.advance(). To detect collisions
# use one of the QtCanvasItem.collisions() functions.
#
# The changed parts of the canvas are redrawn (if they are visible in a
# canvas view) whenever update() is called. You can either call update()
# manually after having changed the contents of the canvas, or force
# periodic updates using setUpdatePeriod(). If you have moving objects on
# the canvas, you must call advance() every time the objects should
# move one step further. Periodic calls to advance() can be forced using
# setAdvancePeriod(). The advance() function will call
# QtCanvasItem.advance() on every item that is \link
# QtCanvasItem.animated() animated\endlink and trigger an update of the
# affected areas afterwards. (A canvas item that is `animated' is simply
# a canvas item that is in motion.)
#
# QtCanvas organizes its canvas items into \e chunks; these are areas on
# the canvas that are used to speed up most operations. Many operations
# start by eliminating most chunks (i.e. those which haven't changed)
# and then process only the canvas items that are in the few interesting
# (i.e. changed) chunks. A valid chunk, validChunk(), is one which is on
# the canvas.
#
# The chunk size is a key factor to QtCanvas's speed: if there are too many
# chunks, the speed benefit of grouping canvas items into chunks is
# reduced. If the chunks are too large, it takes too long to process each
# one. The QtCanvas constructor tries to pick a suitable size, but you
# can call retune() to change it at any time. The chunkSize() function
# returns the current chunk size. The canvas items always make sure
# they're in the right chunks; all you need to make sure of is that
# the canvas uses the right chunk size. A good rule of thumb is that
# the size should be a bit smaller than the average canvas item
# size. If you have moving objects, the chunk size should be a bit
# smaller than the average size of the moving items.
#
# The foreground is normally nothing, but if you reimplement
# drawForeground(), you can draw things in front of all the canvas
# items.
#
# Areas can be set as changed with setChanged() and set unchanged with
# setUnchanged(). The entire canvas can be set as changed with
# setAllChanged(). A list of all the items on the canvas is returned by
# allItems().
#
# An area can be copied (painted) to a QPainter with drawArea().
#
# If the canvas is resized it emits the resized() signal.
#
# The examples/canvas application and the 2D graphics page of the
# examples/demo application demonstrate many of QtCanvas's facilities.
#
# \sa QtCanvasView QtCanvasItem
###
class QtCanvas(QObject):
resized = Signal()
###
# Create a QtCanvas with no size. \a parent is passed to the QObject
# superclass.
#
# \warning You \e must call resize() at some time after creation to
# be able to use the canvas.
###
def __init__(self, parent=None, *arg):
self.pm = QPixmap()
l = len(arg)
if l==0:
super(QtCanvas, self).__init__(parent)
self.init(0, 0)
#Constructs a QtCanvas that is \a w pixels wide and \a h pixels high.
elif l==1:
super(QtCanvas, self).__init__()
self.init(parent, arg[0])
##
# Constructs a QtCanvas which will be composed of \a h tiles
# horizontally and \a v tiles vertically. Each tile will be an image
# \a tilewidth by \a tileheight pixels taken from pixmap \a p.
# The pixmap \a p is a list of tiles, arranged left to right, (and
# in the case of pixmaps that have multiple rows of tiles, top to
# bottom), with tile 0 in the top-left corner, tile 1 next to the
# right, and so on, e.g.
# \table
# \row \i 0 \i 1 \i 2 \i 3
# \row \i 4 \i 5 \i 6 \i 7
# \endtable
# The QtCanvas is initially sized to show exactly the given number of
# tiles horizontally and vertically. If it is resized to be larger,
# the entire matrix of tiles will be repeated as often as necessary
# to cover the area. If it is smaller, tiles to the right and bottom
# will not be visible.
# \sa setTiles()
##
elif l==4:
super(QtCanvas, self).__init__()
self.init(arg[0]*arg[2], arg[1]*arg[3], scm(arg[2], arg[3]))
self.setTiles(parent, arg[0], arg[1], arg[2], arg[3])
def init(self, w, h, chunksze=16, mxclusters=100):
self.d = QtCanvasData()
self.awidth = w
self.aheight = h
self.chunksize = chunksze
self.maxclusters = mxclusters
self.chwidth = int((w+self.chunksize-1)/self.chunksize)
self.chheight = int((h+self.chunksize-1)/self.chunksize)
self.chunks = QList()
for i in range(self.chwidth*self.chheight):
self.chunks.append(QtCanvasChunk())
self.update_timer = 0
self.bgcolor = Qt.white
self.grid = 0
self.htiles = 0
self.vtiles = 0
self.debug_redraw_areas = False
def tile(self, x, y):
return self.grid[x+y*self.htiles]
def tilesHorizontally(self):
return self.htiles
def tilesVertically(self):
return self.vtiles
def tileWidth(self):
return self.tilew
def tileHeight(self):
return self.tileh
def width(self):
return self.awidth
def height(self):
return self.aheight
def size(self):
return QSize(self.awidth, self.aheight)
def rect(self):
return QRect(0, 0, self.awidth, self.aheight)
def onCanvas(self, arg1, arg2=None):
tp = type(arg1)
if tp==QPoint:
x = arg1.x()
y = arg2.y()
elif tp==int:
x = arg1
y = arg2
return x>=0 and y>=0 and x<self.awidth and y<self.aheight
def validChunk(self, arg1, arg2=None):
tp = type(arg1)
if tp==QPoint:
x = arg1.x()
y = arg2.y()
elif tp==int:
x = arg1
y = arg2
return x>=0 and y>=0 and x<self.chwidth and y<self.chheight
def chunkSize(self):
return self.chunksize
def sameChunk(self, x1, y1, x2, y2):
return self.x1/self.chunksize==x2/self.chunksize and y1/self.chunksize==y2/self.chunksize
###
# Destroys the canvas and all the canvas's canvas items.
###
def __del__(self):
for i in range(self.d.viewList.size()):
self.d.viewList[i].viewing = 0
all = self.allItems()
for it in all:
del it
del self.chunks
del self.grid
del self.d
###
# Returns a list of canvas items that collide with the point \a p.
# The list is ordered by z coordinates, from highest z coordinate
# (front-most item) to lowest z coordinate (rear-most item).
###
# def collisions(self, p):
# return collisions(QRect(p, QSize(1, 1)))
###
# \overload
#
# Returns a list of items which collide with the rectangle \a r. The
# list is ordered by z coordinates, from highest z coordinate
# (front-most item) to lowest z coordinate (rear-most item).
###
def collisions(self, r, item=None, exact=None):
tp = type(r)
if tp in [QPoint, QRect]:
if tp == QPoint:
r = QRect(r, QSize(1, 1))
i = QtCanvasRectangle(r, self)
i.setPen(QPen(Qt.NoPen))
i.show(); # doesn't actually show, since we destroy it
l = QList(i.collisions(True))
l = QList(sorted(l, key=lambda x:x.z(), reverse=True))
self.removeItem(i)
return l
elif tp==QPolygonEx:
###
# \overload
#
# Returns a list of canvas items which intersect with the chunks
# listed in \a chunklist, excluding \a item. If \a exact is True,
# only those which actually \link QtCanvasItem.collidesWith()
# collide with\endlink \a item are returned; otherwise canvas items
# are included just for being in the chunks.
#
# This is a utility function mainly used to implement the simpler
# QtCanvasItem.collisions() function.
###
chunklist = r
seen = QSet()
result = QList()
for i in range(chunklist.count()):
x = chunklist[i].x()
y = chunklist[i].y()
if (self.validChunk(x, y)):
l = self.chunk(x, y).list()
for i in range(l.size()):
g = l.at(i)
if (g != item):
if (not seen.contains(g)):
seen.insert(g)
if (not exact or item.collidesWith(g)):
item.collidesWith(g)
result.append(g)
return result
###
#\internal
#Returns the chunk at a chunk position \a i, \a j.
###
def chunk(self, i, j):
return self.chunks[i+self.chwidth*j]
###
#\internal
#Returns the chunk at a pixel position \a x, \a y.
###
def chunkContaining(self, x, y):
return self.chunk(x/self.chunksize, y/self.chunksize)
###
# Returns a list of all the items in the canvas.
###
def allItems(self):
return self.d.itemDict.toList()
###
# Changes the size of the canvas to have a width of \a w and a
# height of \a h. This is a slow operation.
###
def resize(self, w, h):
if (self.awidth == w and self.aheight == h):
return
hidden = QList()
for it in self.d.itemDict:
if (it.isVisible()):
it.hide()
hidden.append(it)
nchwidth = (w+self.chunksize-1)/self.chunksize
nchheight = (h+self.chunksize-1)/self.chunksize
newchunks = QList()
for i in range(nchwidth*nchheight):
newchunks.append(QtCanvasChunk())
# Commit the new values.
#
self.awidth = w
self.aheight = h
self.chwidth = nchwidth
self.chheight = nchheight
del self.chunks
self.chunks = newchunks
for i in range(hidden.size()):
hidden.at(i).show()
self.setAllChanged()
self.resized.emit()
###
# \fn void QtCanvas.resized()
#
# This signal is emitted whenever the canvas is resized. Each
# QtCanvasView connects to this signal to keep the scrollview's size
# correct.
###
###
# Change the efficiency tuning parameters to \a mxclusters clusters,
# each of size \a chunksze. This is a slow operation if there are
# many objects on the canvas.
#
# The canvas is divided into chunks which are rectangular areas \a
# chunksze wide by \a chunksze high. Use a chunk size which is about
# the average size of the canvas items. If you choose a chunk size
# which is too small it will increase the amount of calculation
# required when drawing since each change will affect many chunks.
# If you choose a chunk size which is too large the amount of
# drawing required will increase because for each change, a lot of
# drawing will be required since there will be many (unchanged)
# canvas items which are in the same chunk as the changed canvas
# items.
#
# Internally, a canvas uses a low-resolution "chunk matrix" to keep
# track of all the items in the canvas. A 64x64 chunk matrix is the
# default for a 1024x1024 pixel canvas, where each chunk collects
# canvas items in a 16x16 pixel square. This default is also
# affected by setTiles(). You can tune this default using this
# function. For example if you have a very large canvas and want to
# trade off speed for memory then you might set the chunk size to 32
# or 64.
#
# The \a mxclusters argument is the number of rectangular groups of
# chunks that will be separately drawn. If the canvas has a large
# number of small, dispersed items, this should be about that
# number. Our testing suggests that a large number of clusters is
# almost always best.
#
###
def retune(self, chunksze, mxclusters=100):
self.maxclusters = mxclusters
if (self.chunksize!= chunksze):
hidden = QList()
for it in self.d.itemDict:
if (it.isVisible()):
it.hide()
hidden.appendit
self.chunksize = chunksze
nchwidth = (self.awidth+self.chunksize-1)/self.chunksize
nchheight = (self.aheight+self.chunksize-1)/self.chunksize
newchunks = QList()
for i in range(nchwidth*nchheight):
newchunks.append(QtCanvasChunk())
# Commit the new values.
#
self.chwidth = nchwidth
self.chheight = nchheight
del self.chunks
self.chunks = newchunks
for i in range(hidden.size()):
hidden.at(i).show()
###
# \fn int QtCanvas.width()
#
# Returns the width of the canvas, in pixels.
###
###
# \fn int QtCanvas.height()
#
# Returns the height of the canvas, in pixels.
###
###
# \fn QSize QtCanvas.size()
#
# Returns the size of the canvas, in pixels.
###
###
# \fn QRect QtCanvas.rect()
#
# Returns a rectangle the size of the canvas.
###
###
# \fn bool QtCanvas.onCanvas(x, y)
#
# Returns True if the pixel position (\a x, \a y) is on the canvas
# otherwise returns False.
#
# \sa validChunk()
###
###
# \fn bool QtCanvas.onCanvas(p)
# \overload
#
# Returns True if the pixel position \a p is on the canvas
# otherwise returns False.
#
# \sa validChunk()
###
###
# \fn bool QtCanvas.validChunk(x, y)
#
# Returns True if the chunk position (\a x, \a y) is on the canvas
# otherwise returns False.
#
# \sa onCanvas()
###
###
# \fn bool QtCanvas.validChunk(p)
# \overload
#
# Returns True if the chunk position \a p is on the canvas; otherwise
# returns False.
#
# \sa onCanvas()
###
###
# \fn int QtCanvas.chunkSize()
#
# Returns the chunk size of the canvas.
#
# \sa retune()
###
###
#\fn bool QtCanvas.sameChunk(x1, y1, x2, y2)
#\internal
#Tells if the points (\a x1, \a y1) and (\a x2, \a y2) are within the same chunk.
###
###
#\internal
#This method adds an the item \a item to the list of QtCanvasItem objects
#in the QtCanvas. The QtCanvasItem class calls this.
###
def addItem(self, item):
self.d.itemDict.insert(item)
###
#\internal
#This method adds the item \a item to the list of QtCanvasItem objects
#to be moved. The QtCanvasItem class calls this.
###
def addAnimation(self, item):
self.d.animDict.insert(item)
###
#\internal
#This method adds the item \a item to the list of QtCanvasItem objects
#which are no longer to be moved. The QtCanvasItem class calls this.
###
def removeAnimation(self, item):
self.d.animDict.remove(item)
###
#\internal
#This method removes the item \a item from the list of QtCanvasItem objects
#in this QtCanvas. The QtCanvasItem class calls this.
###
def removeItem(self, item):
self.d.itemDict.remove(item)
item.hide()
###
#\internal
#This method adds the view \a view to the list of QtCanvasView objects
#viewing this QtCanvas. The QtCanvasView class calls this.
###
def addView(self, view):
self.d.viewList.append(view)
if (self.htiles>1 or self.vtiles>1 or self.pm.isNull()):
role = view.widget().backgroundRole()
viewPalette = view.widget().palette()
viewPalette.setColor(role, self.backgroundColor())
view.widget().setPalette(viewPalette)
###
#\internal
#This method removes the view \a view from the list of QtCanvasView objects
#viewing this QtCanvas. The QtCanvasView class calls this.
###
def removeView(self, view):
self.d.viewList.removeAll(view)
###
# Sets the canvas to call advance() every \a ms milliseconds. Any
# previous setting by setAdvancePeriod() or setUpdatePeriod() is
# overridden.
#
# If \a ms is less than 0 advancing will be stopped.
###
def setAdvancePeriod(self, ms):
if (ms < 0):
if (self.update_timer):
self.update_timer.stop()
else:
if (self.update_timer):
del self.update_timer
self.update_timer = QTimer(self)
self.update_timer.timeout.connect(self.advance)
self.update_timer.start(ms)
###
# Sets the canvas to call update() every \a ms milliseconds. Any
# previous setting by setAdvancePeriod() or setUpdatePeriod() is
# overridden.
#
# If \a ms is less than 0 automatic updating will be stopped.
###
def setUpdatePeriod(self, ms):
if (ms < 0):
if (self.update_timer):
self.update_timer.stop()
else:
if (self.update_timer):
del self.update_timer
self.update_timer = QTimer(self)
self.update_timer.timeout.connect(self.update)
self.update_timer.start(ms)
###
# Moves all QtCanvasItem.animated() canvas items on the canvas and
# refreshes all changes to all views of the canvas. (An `animated'
# item is an item that is in motion; see setVelocity().)
#
# The advance takes place in two phases. In phase 0, the
# QtCanvasItem.advance() function of each QtCanvasItem.animated()
# canvas item is called with paramater 0. Then all these canvas
# items are called again, with parameter 1. In phase 0, the canvas
# items should not change position, merely examine other items on
# the canvas for which special processing is required, such as
# collisions between items. In phase 1, all canvas items should
# change positions, ignoring any other items on the canvas. This
# two-phase approach allows for considerations of "fairness",
# although no QtCanvasItem subclasses supplied with Qt do anything
# interesting in phase 0.
#
# The canvas can be configured to call this function periodically
# with setAdvancePeriod().
#
# \sa update()
###
def advance(self):
for i in self.d.animDict:
if (i):
i.advance(0)
# we expect the dict contains the exact same items as in the
# first pass.
for i in self.d.animDict:
if (i):
i.advance(1)
self.update()
# Don't call this unless you know what you're doing.
# p is in the content's co-ordinate example.
###
# \internal
###
def drawViewArea(self, view, p, vr, bool):
wm = view.worldMatrix()
iwm = wm.inverted()[0]
# ivr = covers all chunks in vr
ivr = iwm.mapRect(vr)
p.setTransform(wm)
self.drawCanvasArea(ivr, p, False)
###
# Repaints changed areas in all views of the canvas.
#
# \sa advance()
###
def update(self):
r = self.changeBounds()
if r.isEmpty():
r = self.changeBounds()
for i in range(self.d.viewList.size()):
view = self.d.viewList.at(i)
if (not r.isEmpty()):
tr = view.worldMatrix().mapRect(r)
view.widget().update(tr)
self.setUnchanged(r)
###
# Marks the whole canvas as changed.
# All views of the canvas will be entirely redrawn when
# update() is called next.
###
def setAllChanged(self):
self.setChanged(QRect(0, 0, self.width(), self.height()))
###
# Marks \a area as changed. This \a area will be redrawn in all
# views that are showing it when update() is called next.
###
def setChanged(self, area):
thearea = area.intersected(QRect(0, 0, self.width(), self.height()))
mx = (thearea.x()+thearea.width()+self.chunksize)/self.chunksize
my = (thearea.y()+thearea.height()+self.chunksize)/self.chunksize
if (mx>self.chwidth):
mx = self.chwidth
if (my>self.chheight):
my = self.chheight
x = int(thearea.x()/self.chunksize)
while(x < mx):
y = int(thearea.y()/self.chunksize)
while(y < my):
self.chunk(x, y).change()
y += 1
x += 1
###
# Marks \a area as \e unchanged. The area will \e not be redrawn in
# the views for the next update(), unless it is marked or changed
# again before the next call to update().
###
def setUnchanged(self, area):
thearea = area.intersected(QRect(0, 0, self.width(), self.height()))
mx = (thearea.x()+thearea.width()+self.chunksize)/self.chunksize
my = (thearea.y()+thearea.height()+self.chunksize)/self.chunksize
if (mx>self.chwidth):
mx = self.chwidth
if (my>self.chheight):
my = self.chheight
x = int(thearea.x()/self.chunksize)
while(x < mx):
y = int(thearea.y()/self.chunksize)
while(y < my):
self.chunk(x, y).takeChange()
y += 1
x += 1
###
# \internal
###
def changeBounds(self):
area = QRect(0, 0, self.width(), self.height())
mx = (area.x()+area.width()+self.chunksize)/self.chunksize
my = (area.y()+area.height()+self.chunksize)/self.chunksize
if (mx > self.chwidth):
mx = self.chwidth
if (my > self.chheight):
my = self.chheight
result = QRect()
x = int(area.x()/self.chunksize)
while(x < mx):
y = int(area.y()/self.chunksize)
while(y < my):
ch = self.chunk(x, y)
if (ch.hasChanged()):
result |= QRect(x*self.chunksize, y*self.chunksize, self.chunksize + 1, self.chunksize + 1)
y += 1
x += 1
return result
###
# Paints all canvas items that are in the area \a clip to \a
# painter, using double-buffering if \a dbuf is True.
#
# e.g. to print the canvas to a printer:
# \code
# QPrinter pr
# if (pr.setup()):
# QPainter p(&pr)
# canvas.drawArea(canvas.rect(), &p)
# \endcode
###
def drawArea(self, clip, painter, dbuf=False):
if (painter):
self.drawCanvasArea(clip, painter, dbuf)
#include <QDebug>
###
# \internal
###
def drawCanvasArea(self, inarea, p=0, double_buffer=True):###double_buffer###
area = inarea.intersected(QRect(0, 0, self.width(), self.height()))
if not p:
return; # Nothing to do.
lx = int(area.x()/self.chunksize)
ly = int(area.y()/self.chunksize)
mx = int(area.right()/self.chunksize)
my = int(area.bottom()/self.chunksize)
if (mx>= self.chwidth):
mx = self.chwidth-1
if (my>= self.chheight):
my = self.chheight-1
allvisible = QList()
# Stores the region within area that need to be drawn. It is relative
# to area.topLeft() (so as to keep within bounds of 16-bit XRegions)
rgn = QRegion()
for x in range(lx, mx+1):
for y in range(ly, my+1):
# Only reset change if all views updating, and
# wholy within area. (conservative: ignore entire boundary)
#
# Disable this to help debugging.
#
if (not p):
if (self.chunk(x, y).takeChange()):
# ### should at least make bands
rgn |= QRegion(x*self.chunksize-area.x(), y*self.chunksize-area.y(),
self.chunksize, self.chunksize)
allvisible += self.chunk(x, y).list()
else:
allvisible += self.chunk(x, y).list()
allvisible = QSet(allvisible)
allvisible = QList(sorted(allvisible, key=lambda item:item.z(), reverse=True))
self.drawBackground(p, area)
if (not allvisible.isEmpty()):
prev = 0
for i in range(allvisible.size()-1, -1, -1):
g = allvisible[i]
if (g != prev):
g.draw(p)
prev = g
self.drawForeground(p, area)
###
#\internal
#This method to informs the QtCanvas that a given chunk is
#`dirty' and needs to be redrawn in the next Update.
#
#(\a x, \a y) is a chunk location.
#
#The sprite classes call this. Any new derived class of QtCanvasItem
#must do so too. SetChangedChunkContaining can be used instead.
###
def setChangedChunk(self, x, y):
if (self.validChunk(x, y)):
ch = self.chunk(x, y)
ch.change()
###
#\internal
#This method to informs the QtCanvas that the chunk containing a given
#pixel is `dirty' and needs to be redrawn in the next Update.
#
#(\a x, \a y) is a pixel location.
#
#The item classes call this. Any new derived class of QtCanvasItem must
#do so too. SetChangedChunk can be used instead.
###
def setChangedChunkContaining(self, x, y):
if (x>= 0 and x < self.width() and y>= 0 and y < self.height()):
chunk = self.chunkContaining(x, y)
chunk.change()
###
#\internal
#This method adds the QtCanvasItem \a g to the list of those which need to be
#drawn if the given chunk at location (\a x, \a y) is redrawn. Like
#SetChangedChunk and SetChangedChunkContaining, this method marks the
#chunk as `dirty'.
###
def addItemToChunk(self, g, x, y):
if (self.validChunk(x, y)):
self.chunk(x, y).add(g)
###
#\internal
#This method removes the QtCanvasItem \a g from the list of those which need to
#be drawn if the given chunk at location (\a x, \a y) is redrawn. Like
#SetChangedChunk and SetChangedChunkContaining, this method marks the chunk
#as `dirty'.
###
def removeItemFromChunk(self, g, x, y):
if (self.validChunk(x, y)):
self.chunk(x, y).remove(g)
###
#\internal
#This method adds the QtCanvasItem \a g to the list of those which need to be
#drawn if the chunk containing the given pixel (\a x, \a y) is redrawn. Like
#SetChangedChunk and SetChangedChunkContaining, this method marks the
#chunk as `dirty'.
###
def addItemToChunkContaining(self, g, x, y):
if (x>= 0 and x < self.width() and y>= 0 and y < self.height()):
self.chunkContaining(x, y).add(g)
###
#\internal
#This method removes the QtCanvasItem \a g from the list of those which need to
#be drawn if the chunk containing the given pixel (\a x, \a y) is redrawn.
#Like SetChangedChunk and SetChangedChunkContaining, this method
#marks the chunk as `dirty'.
###
def removeItemFromChunkContaining(self, g, x, y):
if (x>= 0 and x < self.width() and y>= 0 and y < self.height()):
self.chunkContaining(x, y).remove(g)
###
# Returns the color set by setBackgroundColor(). By default, this is
# white.
#
# This function is not a reimplementation of
# QWidget.backgroundColor() (QtCanvas is not a subclass of QWidget),
# but all QtCanvasViews that are viewing the canvas will set their
# backgrounds to this color.
#
# \sa setBackgroundColor(), backgroundPixmap()
###
def backgroundColor(self):
return self.bgcolor
###
# Sets the solid background to be the color \a c.
#
# \sa backgroundColor(), setBackgroundPixmap(), setTiles()
###
def setBackgroundColor(self, c):
if (self.bgcolor != c):
self.bgcolor = c
for i in range(self.d.viewList.size()):
view = self.d.viewList.at(i)
role = view.widget().backgroundRole()
viewPalette = view.widget().palette()
viewPalette.setColor(role, self.bgcolor)
view.widget().setPalette(viewPalette)
self.setAllChanged()
###
# Returns the pixmap set by setBackgroundPixmap(). By default,
# this is a null pixmap.
#
# \sa setBackgroundPixmap(), backgroundColor()
###
def backgroundPixmap(self):
return self.pm
###
# Sets the solid background to be the pixmap \a p repeated as
# necessary to cover the entire canvas.
#
# \sa backgroundPixmap(), setBackgroundColor(), setTiles()
###
def setBackgroundPixmap(self, p):
self.setTiles(p, 1, 1, p.width(), p.height())
for i in range(self.d.viewList.size()):
view = self.d.viewList.at(i)
view.widget().update()
###
# This virtual function is called for all updates of the canvas. It
# renders any background graphics using the painter \a painter, in
# the area \a clip. If the canvas has a background pixmap or a tiled
# background, that graphic is used, otherwise the canvas is cleared
# using the background color.
#
# If the graphics for an area change, you must explicitly call
# setChanged(QRect&) for the result to be visible when
# update() is next called.
#
# \sa setBackgroundColor(), setBackgroundPixmap(), setTiles()
###
def drawBackground(self, painter, clip):
if (self.pm.isNull()):
painter.fillRect(clip, self.bgcolor)
elif (not self.grid):
for x in range(int(clip.x()/self.pm.width()), int((clip.x()+clip.width()+self.pm.width()-1)/self.pm.width())):
for y in range(int(clip.y()/self.pm.height()), int((clip.y()+clip.height()+self.pm.height()-1)/self.pm.height())):
painter.drawPixmap(x*self.pm.width(), y*self.pm.height(), self.pm)
else:
x1 = clip.left()/self.tilew
x2 = clip.right()/self.tilew
y1 = clip.top()/self.tileh
y2 = clip.bottom()/self.tileh
roww = self.pm.width()/self.tilew
for j in range(y1, y2+1):
jj = j%self.tilesVertically()
for i in range(x1, x2+1):
t = self.tile(i%self.tilesHorizontally(), jj)
tx = t % roww
ty = t / roww
painter.drawPixmap(i*self.tilew, j*self.tileh, self.pm, tx*self.tilew, ty*self.tileh, self.tilew, self.tileh)
###
# This virtual function is called for all updates of the canvas. It
# renders any foreground graphics using the painter \a painter, in
# the area \a clip.
#
# If the graphics for an area change, you must explicitly call
# setChanged(QRect&) for the result to be visible when
# update() is next called.
#
# The default is to draw nothing.
###
def drawForeground(self, painter, clip):
if (self.debug_redraw_areas):
painter.setPen(self.red)
painter.setBrush(self.NoBrush)
painter.drawRect(clip)
###
# Sets the QtCanvas to be composed of \a h tiles horizontally and \a
# v tiles vertically. Each tile will be an image \a tilewidth by \a
# tileheight pixels from pixmap \a p.
#
# The pixmap \a p is a list of tiles, arranged left to right, (and
# in the case of pixmaps that have multiple rows of tiles, top to
# bottom), with tile 0 in the top-left corner, tile 1 next to the
# right, and so on, e.g.
#
# \table
# \row \i 0 \i 1 \i 2 \i 3
# \row \i 4 \i 5 \i 6 \i 7
# \endtable
#
# If the canvas is larger than the matrix of tiles, the entire
# matrix is repeated as necessary to cover the whole canvas. If it
# is smaller, tiles to the right and bottom are not visible.
#
# The width and height of \a p must be a multiple of \a tilewidth
# and \a tileheight. If they are not the function will do nothing.
#
# If you want to unset any tiling set, then just pass in a null
# pixmap and 0 for \a h, \a v, \a tilewidth, and
# \a tileheight.
###
def setTiles(self, p, h, v, tilewidth, tileheight):
if (not p.isNull() and (not tilewidth or not tileheight or p.width() % tilewidth != 0 or p.height() % tileheight != 0)):
return
self.htiles = h
self.vtiles = v
del self.grid
self.pm = p
if (h and v and not p.isNull()):
self.grid = array('H')
for i in range(h*v):
self.grid.append(0)
self.tilew = tilewidth
self.tileh = tileheight
else:
self.grid = 0
if (h + v > 10):
s = scm(tilewidth, tileheight)
if s<128:
self.retune(s)
else:
self.retune(max(tilewidth, tileheight))
self.setAllChanged()
###
# \fn int QtCanvas.tile(x, y)
#
# Returns the tile at position (\a x, \a y). Initially, all tiles
# are 0.
#
# The parameters must be within range, i.e.
# 0 \< \a x \< tilesHorizontally() and
# 0 \< \a y \< tilesVertically().
#
# \sa setTile()
###
###
# \fn int QtCanvas.tilesHorizontally()
#
# Returns the number of tiles horizontally.
###
###
# \fn int QtCanvas.tilesVertically()
#
# Returns the number of tiles vertically.
###
###
# \fn int QtCanvas.tileWidth()
#
# Returns the width of each tile.
###
###
# \fn int QtCanvas.tileHeight()
#
# Returns the height of each tile.
###
###
# Sets the tile at (\a x, \a y) to use tile number \a tilenum, which
# is an index into the tile pixmaps. The canvas will update
# appropriately when update() is next called.
#
# The images are taken from the pixmap set by setTiles() and are
# arranged left to right, (and in the case of pixmaps that have
# multiple rows of tiles, top to bottom), with tile 0 in the
# top-left corner, tile 1 next to the right, and so on, e.g.
#
# \table
# \row \i 0 \i 1 \i 2 \i 3
# \row \i 4 \i 5 \i 6 \i 7
# \endtable
#
# \sa tile() setTiles()
###
def setTile(self, x, y, tilenum):
t = self.grid[x+y*self.htiles]
if (t != tilenum):
t = tilenum
if (self.tilew == self.tileh and self.tilew == self.chunksize):
self.setChangedChunk(x, y); # common case
else:
self.setChanged(QRect(x*self.tilew, y*self.tileh, self.tilew, self.tileh))
# lesser-used data in canvas item, plus room for extension.
# Be careful adding to this - check all usages.
class QtCanvasItemExtra():
def __init__(self):
self.vx = 0.0
self.vy = 0.0
###
# \class QtCanvasItem qtcanvas.h
# \brief The QtCanvasItem class provides an abstract graphic object on a QtCanvas.
#
# A variety of QtCanvasItem subclasses provide immediately usable
# behaviour. This class is a pure abstract superclass providing the
# behaviour that is shared among all the concrete canvas item classes.
# QtCanvasItem is not intended for direct subclassing. It is much easier
# to subclass one of its subclasses, e.g. QtCanvasPolygonalItem (the
# commonest base class), QtCanvasRectangle, QtCanvasSprite, QtCanvasEllipse
# or QtCanvasText.
#
# Canvas items are added to a canvas by constructing them and passing the
# canvas to the canvas item's constructor. An item can be moved to a
# different canvas using setCanvas().
#
# Items appear on the canvas after their \link show() show()\endlink
# function has been called (or \link setVisible()
# setVisible(True)\endlink), and \e after update() has been called. The
# canvas only shows items that are \link setVisible() visible\endlink,
# and then only if \l update() is called. If you created the canvas
# without passing a width and height to the constructor you'll also need
# to call \link QtCanvas.resize() resize()\endlink. Since the canvas
# background defaults to white and canvas items default to white,
# you may need to change colors to see your items.
#
# A QtCanvasItem object can be moved in the x(), y() and z() dimensions
# using functions such as move(), moveBy(), setX(), setY() and setZ(). A
# canvas item can be set in motion, `animated', using setAnimated() and
# given a velocity in the x and y directions with setXVelocity() and
# setYVelocity() -- the same effect can be achieved by calling
# setVelocity(). Use the collidesWith() function to see if the canvas item
# will collide on the \e next advance(1) and use collisions() to see what
# collisions have occurred.
#
# Use QtCanvasSprite or your own subclass of QtCanvasSprite to create canvas
# items which are animated, i.e. which change over time.
#
# The size of a canvas item is given by boundingRect(). Use
# boundingRectAdvanced() to see what the size of the canvas item will be
# \e after the next advance(1) call.
#
# The rtti() function is used for identifying subclasses of QtCanvasItem.
# The canvas() function returns a pointer to the canvas which contains the
# canvas item.
#
# QtCanvasItem provides the show() and isVisible() functions like those in
# QWidget.
#
# QtCanvasItem also provides the setEnabled(), setActive() and
# setSelected() functions; these functions set the relevant boolean and
# cause a repaint but the boolean values they set are not used in
# QtCanvasItem itself. You can make use of these booleans in your subclasses.
#
# By default, canvas items have no velocity, no size, and are not in
# motion. The subclasses provided in Qt do not change these defaults
# except where noted.
#
###
class QtCanvasItem():
###
# Constructs a QtCanvasItem on canvas \a canvas.
#
# \sa setCanvas()
###
def __init__(self, canvas):
self.cnv = canvas
self.myx = 0.0
self.myy = 0.0
self.myz = 0.0
self.ani = 0
self.vis = 0
self.val = 0
self.sel = 0
self.ena = 0
self.act = 0
self.ext = 0
if (self.cnv):
self.cnv.addItem(self)
def isNone(self):
return self.cnv==None
###
# Destroys the QtCanvasItem and removes it from its canvas.
###
def __del__(self):
if (self.cnv):
self.cnv.removeItem(self)
self.cnv.removeAnimation(self)
del self.ext
###
# Returns the list of canvas items that this canvas item has
# collided with.
#
# A collision is generally defined as occurring when the pixels of
# one item draw on the pixels of another item, but not all
# subclasses are so precise. Also, since pixel-wise collision
# detection can be slow, this function works in either exact or
# inexact mode, according to the \a exact parameter.
#
# If \a exact is True, the canvas items returned have been
# accurately tested for collision with the canvas item.
#
# If \a exact is False, the canvas items returned are \e near the
# canvas item. You can test the canvas items returned using
# collidesWith() if any are interesting collision candidates. By
# using this approach, you can ignore some canvas items for which
# collisions are not relevant.
#
# The returned list is a list of QtCanvasItems, but often you will
# need to cast the items to their subclass types. The safe way to do
# this is to use rtti() before casting. This provides some of the
# functionality of the standard C++ dynamic cast operation even on
# compilers where dynamic casts are not available.
#
# Note that a canvas item may be `on' a canvas, e.g. it was created
# with the canvas as parameter, even though its coordinates place it
# beyond the edge of the canvas's area. Collision detection only
# works for canvas items which are wholly or partly within the
# canvas's area.
#
# Note that if items have a velocity (see \l setVelocity()), then
# collision testing is done based on where the item \e will be when
# it moves, not its current location. For example, a "ball" item
# doesn't need to actually embed into a "wall" item before a
# collision is detected. For items without velocity, plain
# intersection is used.
###
def collisions(self, exact):
return self.canvas().collisions(self.chunks(), self, exact)
###
# Returns 0 (RttiValues.Rtti_Item).
#
# Make your derived classes return their own values for rtti(), so
# that you can distinguish between objects returned by
# QtCanvas.at(). You should use values greater than 1000 to allow
# for extensions to this class.
#
# Overuse of this functionality can damage its extensibility. For
# example, once you have identified a base class of a QtCanvasItem
# found by QtCanvas.at(), cast it to that type and call meaningful
# methods rather than acting upon the object based on its rtti
# value.
#
# For example:
#
# \code
# item
# # Find an item, e.g. with QtCanvasItem.collisions().
# ...
# if (item.rtti() == MySprite.RTTI):
# s = (MySprite*)item
# if (s.isDamagable()) s.loseHitPoints(1000):
# if (s.isHot()) myself.loseHitPoints(1000):
# ...
# \endcode
###
def rtti(self):
return self.RTTI
RTTI = RttiValues.Rtti_Item
def extra(self):
if (not self.ext):
self.ext = QtCanvasItemExtra
return self.ext
###
# \fn double QtCanvasItem.x()
#
# Returns the horizontal position of the canvas item. Note that
# subclasses often have an origin other than the top-left corner.
###
def x(self):
return self.myx
###
# \fn double QtCanvasItem.y()
#
# Returns the vertical position of the canvas item. Note that
# subclasses often have an origin other than the top-left corner.
###
def y(self):
return self.myy
###
# \fn double QtCanvasItem.z()
#
# Returns the z index of the canvas item, which is used for visual
# order: higher-z items obscure (are in front of) lower-z items.
###
def z(self):
return self.myz
###
# \fn void QtCanvasItem.setX(double x)
#
# Moves the canvas item so that its x-position is \a x.
#
# \sa x(), move()
###
def setX(self, a):
self.move(a,self.y())
###
# \fn void QtCanvasItem.setY(double y)
#
# Moves the canvas item so that its y-position is \a y.
#
# \sa y(), move()
###
def setY(self, a):
self.move(self.x(), a)
###
# \fn void QtCanvasItem.setZ(double z)
#
# Sets the z index of the canvas item to \a z. Higher-z items
# obscure (are in front of) lower-z items.
#
# \sa z(), move()
###
def setZ(self, a):
self.myz=a
self.changeChunks()
###
# Moves the canvas item relative to its current position by (\a dx,
# \a dy).
###
def moveBy(self, dx, dy):
if (dx or dy):
self.removeFromChunks()
self.myx += dx
self.myy += dy
self.addToChunks()
###
# Moves the canvas item to the absolute position (\a x, \a y).
###
def move(self, x, y):
self.moveBy(x-self.myx, y-self.myy)
###
# \internal
# Removes the item from all the chunks it covers.
###
def removeFromChunks(self):
if (self.isVisible() and self.canvas()):
pa = QPolygonEx(self.chunks())
for i in range(pa.count()):
self.canvas().removeItemFromChunk(self, pa[i].x(), pa[i].y())
###
# Returns True if the canvas item is in motion; otherwise returns
# False.
#
# \sa setVelocity(), setAnimated()
###
def animated(self):
return self.ani
###
# Sets the canvas item to be in motion if \a y is True, or not if \a
# y is False. The speed and direction of the motion is set with
# setVelocity(), or with setXVelocity() and setYVelocity().
#
# \sa advance(), QtCanvas.advance()
###
def setAnimated(self, y):
if (y != self.ani):
self.ani = y
if (y):
self.cnv.addAnimation(self)
else:
self.cnv.removeAnimation(self)
###
# \fn void QtCanvasItem.setXVelocity(double vx)
#
# Sets the horizontal component of the canvas item's velocity to \a vx.
#
# \sa setYVelocity() setVelocity()
###
def setXVelocity(self, vx):
self.setVelocity(vx, self.yVelocity())
###
# \fn void QtCanvasItem.setYVelocity(double vy)
#
# Sets the vertical component of the canvas item's velocity to \a vy.
#
# \sa setXVelocity() setVelocity()
###
def setYVelocity(self, vy):
self.setVelocity(self.xVelocity(), vy)
###
# Sets the canvas item to be in motion, moving by \a vx and \a vy
# pixels in the horizontal and vertical directions respectively.
#
# \sa advance() setXVelocity() setYVelocity()
###
def setVelocity(self, vx, vy):
if (self.ext or vx!= 0.0 or vy!= 0.0):
if (not self.ani):
self.setAnimated(True)
self.extra().vx = vx
self.extra().vy = vy
###
# Returns the horizontal velocity component of the canvas item.
###
def xVelocity(self):
if self.ext:
return self.ext.vx
return 0
###
# Returns the vertical velocity component of the canvas item.
###
def yVelocity(self):
if self.ext:
return self.ext.vy
return 0
###
# The default implementation moves the canvas item, if it is
# animated(), by the preset velocity if \a phase is 1, and does
# nothing if \a phase is 0.
#
# Note that if you reimplement this function, the reimplementation
# must not change the canvas in any way, for example it must not add
# or remove items.
#
# \sa QtCanvas.advance() setVelocity()
###
def advance(self, phase):
if (self.ext and phase == 1):
self.moveBy(self.ext.vx, self.ext.vy)
###
# \fn void QtCanvasItem.draw(painter)
#
# This abstract virtual function draws the canvas item using \a painter.
###
###
# Sets the QtCanvas upon which the canvas item is to be drawn to \a c.
#
# \sa canvas()
###
def setCanvas(self, c):
v = self.isVisible()
self.setVisible(False)
if (self.cnv):
if (self.ext):
self.cnv.removeAnimation(self)
self.cnv.removeItem(self)
self.cnv = c
if (self.cnv):
self.cnv.addItem(self)
if (self.ext):
self.cnv.addAnimation(self)
self.setVisible(v)
###
# \fn QtCanvasItem.canvas()
#
# Returns the canvas containing the canvas item.
###
def canvas(self):
return self.cnv
###
# \internal
# Returns the chunks covered by the item.
###
def chunks(self):
r = QPolygonEx()
n = 0
br = self.boundingRect()
if (self.isVisible() and self.canvas()):
self.chunksize = self.canvas().chunkSize()
br &= QRect(0, 0, self.canvas().width(), self.canvas().height())
if (br.isValid()):
r.resize(int(br.width()/self.chunksize+2)*int(br.height()/self.chunksize+2))
for j in range(int(br.top()/self.chunksize), int(br.bottom()/self.chunksize+1)):
for i in range(int(br.left()/self.chunksize), int(br.right()/self.chunksize+1)):
r[n] = QPoint(i, j)
n += 1
r.resize(n)
return r
### Shorthand for setVisible(True). ###
def show(self):
self.setVisible(True)
### Shorthand for setVisible(False). ###
def hide(self):
self.setVisible(False)
###
# Makes the canvas item visible if \a yes is True, or invisible if
# \a yes is False. The change takes effect when QtCanvas.update() is
# next called.
###
def setVisible(self, yes):
if (self.vis != yes):
if (yes):
self.vis = yes
self.addToChunks()
else:
self.removeFromChunks()
self.vis = yes
###
# \obsolete
# \fn bool QtCanvasItem.visible()
# Use isVisible() instead.
###
def visible(self):
return self.vis
###
# \fn bool QtCanvasItem.isVisible()
#
# Returns True if the canvas item is visible; otherwise returns
# False.
#
# Note that in this context True does \e not mean that the canvas
# item is currently in a view, merely that if a view is showing the
# area where the canvas item is positioned, and the item is not
# obscured by items with higher z values, and the view is not
# obscured by overlaying windows, it would be visible.
#
# \sa setVisible(), z()
###
def isVisible(self):
return self.vis
###
# \obsolete
# \fn bool QtCanvasItem.selected()
# Use isSelected() instead.
###
def selected(self):
return self.sel
###
# \fn bool QtCanvasItem.isSelected()
#
# Returns True if the canvas item is selected; otherwise returns False.
###
def isSelected(self):
return self.sel
###
# Sets the selected flag of the item to \a yes. If this changes the
# item's selected state the item will be redrawn when
# QtCanvas.update() is next called.
#
# The QtCanvas, QtCanvasItem and the Qt-supplied QtCanvasItem
# subclasses do not make use of this value. The setSelected()
# function is supplied because many applications need it, but it is
# up to you how you use the isSelected() value.
###
def setSelected(self, yes):
if (self.sel != yes):
self.sel = yes
self.changeChunks()
###
# \obsolete
# \fn bool QtCanvasItem.enabled()
# Use isEnabled() instead.
###
def enabled(self):
return self.ena
###
# \fn bool QtCanvasItem.isEnabled()
#
# Returns True if the QtCanvasItem is enabled; otherwise returns False.
###
def isEnabled(self):
return self.ena
###
# Sets the enabled flag of the item to \a yes. If this changes the
# item's enabled state the item will be redrawn when
# QtCanvas.update() is next called.
#
# The QtCanvas, QtCanvasItem and the Qt-supplied QtCanvasItem
# subclasses do not make use of this value. The setEnabled()
# function is supplied because many applications need it, but it is
# up to you how you use the isEnabled() value.
###
def setEnabled(self, yes):
if (self.ena!= yes):
self.ena = yes
self.changeChunks()
###
# \obsolete
# \fn bool QtCanvasItem.active()
# Use isActive() instead.
###
def active(self):
return self.act
###
# \fn bool QtCanvasItem.isActive()
#
# Returns True if the QtCanvasItem is active; otherwise returns False.
###
def isActive(self):
return self.act
###
# Sets the active flag of the item to \a yes. If this changes the
# item's active state the item will be redrawn when
# QtCanvas.update() is next called.
#
# The QtCanvas, QtCanvasItem and the Qt-supplied QtCanvasItem
# subclasses do not make use of this value. The setActive() function
# is supplied because many applications need it, but it is up to you
# how you use the isActive() value.
###
def setActive(self, yes):
if (self.act!= yes):
self.act = yes
self.changeChunks()
###
# \fn void QtCanvasItem.update()
#
# Call this function to repaint the canvas's changed chunks.
###
def update(self):
self.changeChunks()
###
# \class QtCanvasSprite qtcanvas.h
# \brief The QtCanvasSprite class provides an animated canvas item on a QtCanvas.
#
# A canvas sprite is an object which can contain any number of images
# (referred to as frames), only one of which is current, i.e.
# displayed, at any one time. The images can be passed in the
# constructor or set or changed later with setSequence(). If you
# subclass QtCanvasSprite you can change the frame that is displayed
# periodically, e.g. whenever QtCanvasItem.advance(1) is called to
# create the effect of animation.
#
# The current frame can be set with setFrame() or with move(). The
# number of frames available is given by frameCount(). The bounding
# rectangle of the current frame is returned by boundingRect().
#
# The current frame's image can be retrieved with image(); use
# imageAdvanced() to retrieve the image for the frame that will be
# shown after advance(1) is called. Use the image() overload passing
# it an integer index to retrieve a particular image from the list of
# frames.
#
# Use width() and height() to retrieve the dimensions of the current
# frame.
#
# Use leftEdge() and rightEdge() to retrieve the current frame's
# left-hand and right-hand x-coordinates respectively. Use
# bottomEdge() and topEdge() to retrieve the current frame's bottom
# and top y-coordinates respectively. These functions have an overload
# which will accept an integer frame number to retrieve the
# coordinates of a particular frame.
#
# QtCanvasSprite draws very quickly, at the expense of memory.
#
# The current frame's image can be drawn on a painter with draw().
#
# Like any other canvas item, canvas sprites can be moved with
# move() which sets the x and y coordinates and the frame number, as
# well as with QtCanvasItem.move() and QtCanvasItem.moveBy(), or by
# setting coordinates with QtCanvasItem.setX(), QtCanvasItem.setY()
# and QtCanvasItem.setZ().
#
###
###
# \internal
# Adds the item to all the chunks it covers.
###
def addToChunks(self):
if (self.isVisible() and self.canvas()):
pa = self.chunks()
for i in range(pa.count()):
self.canvas().addItemToChunk(self, pa[i].x(), pa[i].y())
self.val = True
###
# \internal
# Sets all the chunks covered by the item to be refreshed with QtCanvas.update()
# is next called.
###
def changeChunks(self):
if (self.isVisible() and self.canvas()):
if (not self.val):
self.addToChunks()
pa = QPolygonEx(self.chunks())
for i in range(pa.count()):
self.canvas().setChangedChunk(pa[i].x(), pa[i].y())
###
# \fn QRect QtCanvasItem.boundingRect()
#
# Returns the bounding rectangle in pixels that the canvas item covers.
#
# \sa boundingRectAdvanced()
###
###
# Returns the bounding rectangle of pixels that the canvas item \e
# will cover after advance(1) is called.
#
# \sa boundingRect()
###
def boundingRectAdvanced(self):
dx = int(self.x()+self.xVelocity())-int(self.x())
dy = int(self.y()+self.yVelocity())-int(self.y())
r = self.boundingRect()
r.translate(dx, dy)
return r
###
# \class QtCanvasPixmap qtcanvas.h
# \brief The QtCanvasPixmap class provides pixmaps for QtCanvasSprites.
#
# If you want to show a single pixmap on a QtCanvas use a
# QtCanvasSprite with just one pixmap.
#
# When pixmaps are inserted into a QtCanvasPixmapArray they are held
# as QtCanvasPixmaps. \l{QtCanvasSprite}s are used to show pixmaps on
# \l{QtCanvas}es and hold their pixmaps in a QtCanvasPixmapArray. If
# you retrieve a frame (pixmap) from a QtCanvasSprite it will be
# returned as a QtCanvasPixmap.
#
# The pixmap is a QPixmap and can only be set in the constructor.
# There are three different constructors, one taking a QPixmap, one
# a QImage and one a file name that refers to a file in any
# supported file format (see QImageReader).
#
# QtCanvasPixmap can have a hotspot which is defined in terms of an (x,
# y) offset. When you create a QtCanvasPixmap from a PNG file or from
# a QImage that has a QImage.offset(), the offset() is initialized
# appropriately, otherwise the constructor leaves it at (0, 0). You
# can set it later using setOffset(). When the QtCanvasPixmap is used
# in a QtCanvasSprite, the offset position is the point at
# QtCanvasItem.x() and QtCanvasItem.y(), not the top-left corner of
# the pixmap.
#
# Note that for QtCanvasPixmap objects created by a QtCanvasSprite, the
# position of each QtCanvasPixmap object is set so that the hotspot
# stays in the same position.
#
# \sa QtCanvasPixmapArray QtCanvasItem QtCanvasSprite
###
class QtCanvasPixmap(QPixmap):
def __init__(self, image, offset=None):
self.hotx = 0
self.hoty = 0
self.collision_mask = None
if not offset:
###
# Constructs a QtCanvasPixmap from the pixmap \a pm using the offset
# \a offset.
###
self.init(self.pm, offset.x(), offset.y())
else:
if type(image)==str:
###
# Constructs a QtCanvasPixmap that uses the image stored in \a
# datafilename.
###
image = QImage(image)
###
# Constructs a QtCanvasPixmap from the image \a image.
###
self.init(image)
def offsetX(self):
return self.hotx
def offsetY(self):
return self.hoty
def setOffset(self, x, y):
self.hotx = x
self.hoty = y
def init(self, pixmap, hx=None, hy=None):
t = type(pixmap)
if t==QImage:
image = pixmap
self.QPixmap.operator = QPixmap.fromImage(image)
self.hotx = image.offset().x()
self.hoty = image.offset().y()
#ifndef QT_NO_IMAGE_DITHER_TO_1
if(image.hasAlphaChannel()):
i = image.createAlphaMask()
self.collision_mask = QImage(i)
else:
#endif
self.collision_mask = 0
elif t==QPixmap:
self = pixmap
self.hotx = hx
self.hoty = hy
if(pixmap.hasAlphaChannel()):
i = self.mask().toImage()
self.collision_mask = QImage(i)
else:
self.collision_mask = 0
###
# Destroys the pixmap.
###
def __del__(self):
del self.collision_mask
###
# \fn int QtCanvasPixmap.offsetX()
#
# Returns the x-offset of the pixmap's hotspot.
#
# \sa setOffset()
###
###
# \fn int QtCanvasPixmap.offsetY()
#
# Returns the y-offset of the pixmap's hotspot.
#
# \sa setOffset()
###
###
# \fn void QtCanvasPixmap.setOffset(x, y)
#
# Sets the offset of the pixmap's hotspot to (\a x, \a y).
#
# \warning Do not call this function if any QtCanvasSprites are
# currently showing this pixmap.
###
###
# \class QtCanvasPixmapArray qtcanvas.h
# \brief The QtCanvasPixmapArray class provides an array of QtCanvasPixmaps.
#
# This class is used by QtCanvasSprite to hold an array of pixmaps.
# It is used to implement animated sprites, i.e. images that change
# over time, with each pixmap in the array holding one frame.
#
# Depending on the constructor you use you can load multiple pixmaps
# into the array either from a directory (specifying a wildcard
# pattern for the files), or from a list of QPixmaps. You can also
# read in a set of pixmaps after construction using readPixmaps().
#
# Individual pixmaps can be set with setImage() and retrieved with
# image(). The number of pixmaps in the array is returned by
# count().
#
# QtCanvasSprite uses an image's mask for collision detection. You
# can change this by reading in a separate set of image masks using
# readCollisionMasks().
#
###
###
# Constructs an invalid array (i.e. isValid() will return False).
# You must call readPixmaps() before being able to use this
# QtCanvasPixmapArray.
###
class QtCanvasPixmapArray():
def __init__(self, arg1=None, arg2=None):
self.framecount = 0
self.img = 0
t1 = type(arg1)
if t1 == str:
###
# Constructs a QtCanvasPixmapArray from files.
#
# The \a fc parameter sets the number of frames to be loaded for
# this image.
#
# If \a fc is not 0, \a datafilenamepattern should contain "%1",
# e.g. "foo%1.png". The actual filenames are formed by replacing the
# %1 with four-digit integers from 0 to (fc - 1), e.g. foo0000.png,
# foo0001.png, foo0002.png, etc.
#
# If \a fc is 0, \a datafilenamepattern is asssumed to be a
# filename, and the image contained in this file will be loaded as
# the first (and only) frame.
#
# If \a datafilenamepattern does not exist, is not readable, isn't
# an image, or some other error occurs, the array ends up empty and
# isValid() returns False.
###
datafilenamepattern = arg1
fc = arg2
self.readPixmaps(datafilenamepattern, fc)
elif t1 == QList:
###
# \obsolete
#class QtCanvasPixmapArray():(QtValueList<QPixmap>, QPolygon)
# instead.
#
# Constructs a QtCanvasPixmapArray from the list of QPixmaps \a
# list. The \a hotspots list has to be of the same size as \a list.
###
l = arg1
hotspots = arg2
self.framecount = l.count()
self.img = QList()
for i in range(self.framecount):
self.img.append(0)
if (l.count() != self.hotspots.count()):
qWarning("QtCanvasPixmapArray: lists have different lengths")
self.reset()
self.img = 0
else:
for i in range(self.framecount):
self.img[i] = QtCanvasPixmap(l.at(i), hotspots.at(i))
###
# Destroys the pixmap array and all the pixmaps it contains.
###
def __del__(self):
self.reset()
def reset(self):
for i in range(self.framecount):
del self.img[i]
del self.img
self.img = 0
self.framecount = 0
###
# Reads one or more pixmaps into the pixmap array.
#
# If \a fc is not 0, \a filenamepattern should contain "%1", e.g.
# "foo%1.png". The actual filenames are formed by replacing the %1
# with four-digit integers from 0 to (fc - 1), e.g. foo0000.png,
# foo0001.png, foo0002.png, etc.
#
# If \a fc is 0, \a filenamepattern is asssumed to be a filename,
# and the image contained in this file will be loaded as the first
# (and only) frame.
#
# If \a filenamepattern does not exist, is not readable, isn't an
# image, or some other error occurs, this function will return
# False, and isValid() will return False; otherwise this function
# will return True.
#
# \sa isValid()
###
# def readPixmaps(self, filenamepattern, fc):
# return self.readPixmaps(filenamepattern, fc, False)
###
# Reads new collision masks for the array.
#
# By default, QtCanvasSprite uses the image mask of a sprite to
# detect collisions. Use this function to set your own collision
# image masks.
#
# If count() is 1 \a filename must specify a real filename to read
# the mask from. If count() is greater than 1, the \a filename must
# contain a "%1" that will get replaced by the number of the mask to
# be loaded, just like QtCanvasPixmapArray.readPixmaps().
#
# All collision masks must be 1-bit images or this function call
# will fail.
#
# If the file isn't readable, contains the wrong number of images,
# or there is some other error, this function will return False, and
# the array will be flagged as invalid; otherwise this function
# returns True.
#
# \sa isValid()
###
def readCollisionMasks(self, filename):
return self.readPixmaps(filename, self.framecount, True)
def readPixmaps(self, datafilenamepattern, fc, maskonly=False):
if (not maskonly):
self.reset()
framecount = fc
if (not framecount):
framecount = 1
img = QtCanvasPixmap[framecount]
if (not img):
return False
ok = True
arg = fc > 1
if (not arg):
framecount = 1
for i in range(framecount):
r = ''
r.format("%04d", i)
if (maskonly):
if (not img[i].collision_mask):
img[i].collision_mask = QImage()
if arg:
img[i].collision_mask.load(datafilenamepattern%r)
else:
img[i].collision_mask.load(datafilenamepattern)
ok = ok and not img[i].collision_mask.isNull() and self.img[i].collision_mask.depth() == 1
else:
if arg:
img[i] = QtCanvasPixmap(datafilenamepattern%r)
else:
img[i] = QtCanvasPixmap(datafilenamepattern)
ok = ok and not img[i].isNull()
if (not ok):
self.reset()
return ok
###
# \obsolete
#
# Use isValid() instead.
#
# This returns False if the array is valid, and True if it is not.
###
# def operator!(self):
# return img == 0
###
# Returns True if the pixmap array is valid; otherwise returns
# False.
###
def isValid(self):
return self.img != 0
###
# \fn QtCanvasPixmapArray.image(i)
#
# Returns pixmap \a i in the array, if \a i is non-negative and less
# than than count(), and returns an unspecified value otherwise.
###
# ### wouldn't it be better to put empty QtCanvasPixmaps in there instead of
# initializing the additional elements in the array to 0? Lars
###
# Replaces the pixmap at index \a i with pixmap \a p.
#
# The array takes ownership of \a p and will delete \a p when the
# array itself is deleted.
#
# If \a i is beyond the end of the array the array is extended to at
# least i+1 elements, with elements count() to i-1 being initialized
# to 0.
###
def setImage(self, i, p):
if (i >= self.framecount):
for x in range(i+1-self.framecount):
self.img.append(0)
del self.img[i]
self.img[i] = p
###
# \fn uint QtCanvasPixmapArray.count()
#
# Returns the number of pixmaps in the array.
###
###
# Returns the x-coordinate of the current left edge of the sprite.
# (This may change as the sprite animates since different frames may
# have different left edges.)
#
# \sa rightEdge() bottomEdge() topEdge()
###
# def leftEdge(self):
# return int(self.x()) - self.image().hotx
###
# \overload
#
# Returns what the x-coordinate of the left edge of the sprite would
# be if the sprite (actually its hotspot) were moved to x-position
# \a nx.
#
# \sa rightEdge() bottomEdge() topEdge()
###
def leftEdge(self, nx=None):
if nx is None:
nx = self.x()
return nx - self.image().hotx
###
# Returns the y-coordinate of the top edge of the sprite. (This may
# change as the sprite animates since different frames may have
# different top edges.)
#
# \sa leftEdge() rightEdge() bottomEdge()
###
# def topEdge(self):
# return int(self.y()) - self.image().hoty
###
# \overload
#
# Returns what the y-coordinate of the top edge of the sprite would
# be if the sprite (actually its hotspot) were moved to y-position
# \a ny.
#
# \sa leftEdge() rightEdge() bottomEdge()
###
def topEdge(self, ny=None):
if ny is None:
ny = self.y()
return ny - self.image().hoty
###
# Returns the x-coordinate of the current right edge of the sprite.
# (This may change as the sprite animates since different frames may
# have different right edges.)
#
# \sa leftEdge() bottomEdge() topEdge()
###
# def rightEdge(self):
# return self.leftEdge() + self.image().width()-1
###
# \overload
#
# Returns what the x-coordinate of the right edge of the sprite
# would be if the sprite (actually its hotspot) were moved to
# x-position \a nx.
#
# \sa leftEdge() bottomEdge() topEdge()
###
def rightEdge(self, nx=None):
if nx is None:
x = self.leftEdge()
else:
x = self.leftEdge(nx)
return x + self.image().width()-1
###
# Returns the y-coordinate of the current bottom edge of the sprite.
# (This may change as the sprite animates since different frames may
# have different bottom edges.)
#
# \sa leftEdge() rightEdge() topEdge()
###
# def bottomEdge(self):
# return self.topEdge() + self.image().height()-1
###
# \overload
#
# Returns what the y-coordinate of the top edge of the sprite would
# be if the sprite (actually its hotspot) were moved to y-position
# \a ny.
#
# \sa leftEdge() rightEdge() topEdge()
###
def bottomEdge(self, ny=None):
if ny is None:
x = self.topEdge()
else:
x = self.topEdge(ny)
return x + self.image().height()-1
###
# \fn QtCanvasSprite.image()
#
# Returns the current frame's image.
#
# \sa frame(), setFrame()
###
###
# \fn QtCanvasSprite.image(f)
# \overload
#
# Returns the image for frame \a f. Does not do any bounds checking on \a f.
###
def image(self, f=None):
x = f
if x is None:
x = self.frm
return self.images.image(x)
###
# Returns the image the sprite \e will have after advance(1) is
# called. By default this is the same as image().
###
def imageAdvanced(self):
return self.image()
###
# Returns the bounding rectangle for the image in the sprite's
# current frame. This assumes that the images are tightly cropped
# (i.e. do not have transparent pixels all along a side).
###
def boundingRect(self):
return QRect(self.leftEdge(), self.topEdge(), self.width(), self.height())
def canvas(self):
return self.cnv
###
# \internal
# Add the sprite to the chunks in its QtCanvas which it overlaps.
###
def addToChunks(self):
if (self.isVisible() and self.canvas()):
self.chunksize = self.canvas().chunkSize()
for j in range(int(self.topEdge()/self.chunksize), int(self.bottomEdge()/self.chunksize+1)):
for i in range(int(self.leftEdge()/self.chunksize), int(self.rightEdge()/self.chunksize+1)):
self.canvas().addItemToChunk(self, i, j)
###
# \internal
# Remove the sprite from the chunks in its QtCanvas which it overlaps.
#
# \sa addToChunks()
###
def removeFromChunks(self):
if (self.isVisible() and self.canvas()):
self.chunksize = self.canvas().chunkSize()
for j in range(int(self.topEdge()/self.chunksize), int(self.bottomEdge()/self.chunksize+1)):
for i in range(int(self.leftEdge()/self.chunksize), int(self.rightEdge()/self.chunksize+1)):
self.canvas().removeItemFromChunk(self, i, j)
###
# The width of the sprite for the current frame's image.
#
# \sa frame()
###
#### mark: Why don't we have width(int) and height(int) to be
#consistent with leftEdge() and leftEdge(int)?
def width(self):
return self.image().width()
###
# The height of the sprite for the current frame's image.
#
# \sa frame()
###
def height(self):
return self.image().height()
###
# Draws the current frame's image at the sprite's current position
# on painter \a painter.
###
def draw(self, painter):
painter.drawPixmap(self.leftEdge(), self.topEdge(), self.image())
###
# \class QtCanvasView qtcanvas.h
# \brief The QtCanvasView class provides an on-screen view of a QtCanvas.
#
# A QtCanvasView is widget which provides a view of a QtCanvas.
#
# If you want users to be able to interact with a canvas view,
# subclass QtCanvasView. You might then reimplement
# QtScrollView.contentsMousePressEvent(). For example:
#
# \code
# def MyCanvasView.contentsMousePressEvent(self, e):
# QtCanvasItemList l = canvas().collisions(e.pos())
# for (QtCanvasItemList.Iterator it = l.begin(); it!= l.end(); ++it):
# if (it.rtti() == QtCanvasRectangle.RTTI):
# qDebug("A QtCanvasRectangle lies somewhere at this point")
# \endcode
#
# The canvas view shows canvas canvas(); this can be changed using
# setCanvas().
#
# A transformation matrix can be used to transform the view of the
# canvas in various ways, for example, zooming in or out or rotating.
# For example:
#
# \code
# QMatrix wm
# wm.scale(2, 2); # Zooms in by 2 times
# wm.rotate(90); # Rotates 90 degrees counter clockwise
# # around the origin.
# wm.translate(0, -canvas.height())
# # moves the canvas down so what was visible
# # before is still visible.
# myCanvasView.setWorldMatrix(wm)
# \endcode
#
# Use setWorldMatrix() to set the canvas view's world matrix: you must
# ensure that the world matrix is invertible. The current world matrix
# is retrievable with worldMatrix(), and its inversion is retrievable
# with inverseWorldMatrix().
#
# Example:
#
# The following code finds the part of the canvas that is visible in
# this view, i.e. the bounding rectangle of the view in canvas coordinates.
#
# \code
# rc = QRect(myCanvasView.contentsX(), myCanvasView.contentsY(),
# myCanvasView.visibleWidth(), myCanvasView.visibleHeight())
# canvasRect = myCanvasView.inverseWorldMatrix().mapRect(rc)
# \endcode
#
# \sa QMatrix QPainter.setWorldMatrix()
#
###
class QtCanvasWidget(QWidget):
def __init__(self, view):
super(QtCanvasWidget, self).__init__(view)
self.m_view = view
def mousePressEvent(self, e):
self.m_view.contentsMousePressEvent(e)
def mouseMoveEvent(self, e):
self.m_view.contentsMouseMoveEvent(e)
def mouseReleaseEvent(self, e):
self.m_view.contentsMouseReleaseEvent(e)
def mouseDoubleClickEvent(self, e):
self.m_view.contentsMouseDoubleClickEvent(e)
def dragEnterEvent(self, e):
self.m_view.contentsDragEnterEvent(e)
def dragMoveEvent(self, e):
self.m_view.contentsDragMoveEvent(e)
def dragLeaveEvent(self, e):
self.m_view.contentsDragLeaveEvent(e)
def dropEvent(self, e):
self.m_view.contentsDropEvent(e)
def wheelEvent(self, e):
self.m_view.contentsWheelEvent(e)
def contextMenuEvent(self, e):
self.m_view.contentsContextMenuEvent(e)
def paintEvent(self, e):
p = QPainter(self)
if (self.m_view.d.highQuality):
p.setRenderHint(QPainter.Antialiasing)
p.setRenderHint(QPainter.SmoothPixmapTransform)
self.m_view.drawContents(p, e.rect().x(), e.rect().y(), e.rect().width(), e.rect().height())
###
# Constructs a QtCanvasView with parent \a parent. The canvas view
# is not associated with a canvas, so you must to call setCanvas()
# to view a canvas.
###
class QtCanvasView(QScrollArea):
def __init__(self, arg1=None, arg2=None):
if arg2 is None:
super(QtCanvasView, self).__init__(arg1)
canvas = 0
else:
###
# \overload
#
# Constructs a QtCanvasView which views canvas \a canvas, with parent
# \a parent.
###
super(QtCanvasView, self).__init__(arg2)
canvas = arg1
self.d = QtCanvasViewData()
self.d.highQuality = False
self.setWidget(QtCanvasWidget(self))
self.viewing = 0
self.setCanvas(canvas)
###
# Destroys the canvas view. The associated canvas is \e not deleted.
###
def __del__(self):
del self.d
self.d = 0
self.setCanvas(0)
###
# \property QtCanvasView.highQualityRendering
# \brief whether high quality rendering is turned on
#
# If high quality rendering is turned on, the canvas view will paint itself
# using the QPainter.Antialiasing and QPainter.SmoothPixmapTransform
# rendering flags.
#
# Enabling these flag will usually improve the visual appearance on the screen
# at the cost of rendering speed.
###
def highQualityRendering(self):
return self.d.highQuality
def setHighQualityRendering(self, enable):
self.d.highQuality = enable
self.widget().update()
def contentsMousePressEvent(self, e):
e.ignore()
def contentsMouseReleaseEvent(self, e):
e.ignore()
def contentsMouseDoubleClickEvent(self, e):
e.ignore()
def contentsMouseMoveEvent(self, e):
e.ignore()
def contentsDragEnterEvent(self):
pass
def contentsDragMoveEvent(self):
pass
def contentsDragLeaveEvent(self):
pass
def contentsDropEvent(self):
pass
def contentsWheelEvent(self, e):
e.ignore()
def contentsContextMenuEvent(self, e):
e.ignore()
###
# \fn QtCanvasView.canvas()
#
# Returns a pointer to the canvas which the QtCanvasView is currently
# showing.
###
def canvas(self):
return self.viewing
###
# Sets the canvas that the QtCanvasView is showing to the canvas \a
# canvas.
###
def setCanvas(self, canvas):
if (self.viewing == canvas):
return
if (self.viewing):
self.viewing.disconnect()
self.viewing.removeView(self)
self.viewing = canvas
if (self.viewing):
self.viewing.resized.connect(self.updateContentsSize)
self.viewing.addView(self)
if self.d: # called by d'tor
self.updateContentsSize()
self.update()
###
# Returns a reference to the canvas view's current transformation matrix.
#
# \sa setWorldMatrix() inverseWorldMatrix()
###
def worldMatrix(self):
return self.d.xform
###
# Returns a reference to the inverse of the canvas view's current
# transformation matrix.
#
# \sa setWorldMatrix() worldMatrix()
###
def inverseWorldMatrix(self):
return self.d.ixform
###
# Sets the transformation matrix of the QtCanvasView to \a wm. The
# matrix must be invertible (i.e. if you create a world matrix that
# zooms out by 2 times, then the inverse of this matrix is one that
# will zoom in by 2 times).
#
# When you use this, you should note that the performance of the
# QtCanvasView will decrease considerably.
#
# Returns False if \a wm is not invertable; otherwise returns True.
#
# \sa worldMatrix() inverseWorldMatrix() QMatrix.isInvertible()
###
def setWorldMatrix(self, wm):
ok = wm.isInvertible()
if (ok):
self.d.xform = wm
self.d.ixform = wm.inverted()
self.updateContentsSize()
self.widget().update()
return ok
def updateContentsSize(self):
if (self.viewing):
br = self.d.xform.mapRect(QRect(0, 0, self.viewing.width(), self.viewing.height()))
self.widget().resize(br.size())
else:
self.widget().resize(self.size())
###
# Repaints part of the QtCanvas that the canvas view is showing
# starting at \a cx by \a cy, with a width of \a cw and a height of \a
# ch using the painter \a p.
###
def drawContents(self, p, cx, cy, cw, ch):
if (not self.viewing):
return
clipPath = QPainterPath()
clipPath.addRect(QRectF(self.viewing.rect()))
p.setClipPath(self.d.xform.map(clipPath), Qt.IntersectClip)
self.viewing.drawViewArea(self, p, QRect(cx, cy, cw, ch), False)
###
# Suggests a size sufficient to view the entire canvas.
###
def sizeHint(self):
if (not self.canvas()):
return QScrollArea.sizeHint()
# should maybe take transformations into account
return (self.canvas().size() + 2 * QSize(self.frameWidth(), self.frameWidth())).boundedTo(3 * QApplication.desktop().size() / 4)
###
# \class QtCanvasPolygonalItem qtcanvas.h
# \brief The QtCanvasPolygonalItem class provides a polygonal canvas item
# on a QtCanvas.
#
# The mostly rectangular classes, such as QtCanvasSprite and
# QtCanvasText, use the object's bounding rectangle for movement,
# repainting and collision calculations. For most other items, the
# bounding rectangle can be far too large -- a diagonal line being
# the worst case, and there are many other cases which are also bad.
# QtCanvasPolygonalItem provides polygon-based bounding rectangle
# handling, etc., which is much faster for non-rectangular items.
#
# Derived classes should try to define as small an area as possible
# to maximize efficiency, but the polygon must \e definitely be
# contained completely within the polygonal area. Calculating the
# exact requirements is usually difficult, but if you allow a small
# overestimate it can be easy and quick, while still getting almost
# all of QtCanvasPolygonalItem's speed.
#
# Note that all subclasses \e must call hide() in their destructor
# since hide() needs to be able to access areaPoints().
#
# Normally, QtCanvasPolygonalItem uses the odd-even algorithm for
# determining whether an object intersects this object. You can
# change this to the winding algorithm using setWinding().
#
# The bounding rectangle is available using boundingRect(). The
# points bounding the polygonal item are retrieved with
# areaPoints(). Use areaPointsAdvanced() to retrieve the bounding
# points the polygonal item \e will have after
# QtCanvasItem.advance(1) has been called.
#
# If the shape of the polygonal item is about to change while the
# item is visible, call invalidate() before updating with a
# different result from \l areaPoints().
#
# By default, QtCanvasPolygonalItem objects have a black pen and no
# brush (the default QPen and QBrush constructors). You can change
# this with setPen() and setBrush(), but note that some
# QtCanvasPolygonalItem subclasses only use the brush, ignoring the
# pen setting.
#
# The polygonal item can be drawn on a painter with draw().
# Subclasses must reimplement drawShape() to draw themselves.
#
# Like any other canvas item polygonal items can be moved with
# QtCanvasItem.move() and QtCanvasItem.moveBy(), or by setting coordinates
# with QtCanvasItem.setX(), QtCanvasItem.setY() and QtCanvasItem.setZ().
#
###
###
# Since most polygonal items don't have a pen, the default is
# NoPen and a black brush.
###
dp = 0
def defaultPolygonPen():
global dp
if (not dp):
dp = QPen()
return dp
db = 0
def defaultPolygonBrush():
global db
if (not db):
db = QBrush()
return db
###
# Constructs a QtCanvasPolygonalItem on the canvas \a canvas.
###
class QtCanvasPolygonalItem(QtCanvasItem):
def __init__(self, canvas):
super(QtCanvasPolygonalItem, self).__init__(canvas)
self.br = defaultPolygonBrush()
self.pn = defaultPolygonPen()
self.wind = 0
self.ani = 0
self.vis = 0
self.val = 0
self.sel = 0
self.ena = 0
self.act = 0
###
# Note that all subclasses \e must call hide() in their destructor
# since hide() needs to be able to access areaPoints().
###
def __del__(self):
pass
def pen(self):
return self.pn
def brush(self):
return self.br
def scanPolygon(self, pa, winding, process):
scanner = QtCanvasPolygonScanner(process)
scanner.scan(pa, winding)
def chunks(self):
pa = self.areaPoints()
if (not pa.size()):
#pa.detach() # Explicit sharing is stupid.
return pa
processor = QPolygonalProcessor(self.canvas(), pa)
self.scanPolygon(pa, self.wind, processor)
return processor.result
###
# Returns the bounding rectangle of the polygonal item, based on
# areaPoints().
###
def boundingRect(self):
return self.areaPoints().boundingRect()
###
# Reimplemented from QtCanvasItem, this draws the polygonal item by
# setting the pen and brush for the item on the painter \a p and
# calling drawShape().
###
def draw(self, p):
p.setPen(self.pn)
p.setBrush(self.br)
self.drawShape(p)
###
# \fn void QtCanvasPolygonalItem.drawShape(QPainter & p)
#
# Subclasses must reimplement this function to draw their shape. The
# pen and brush of \a p are already set to pen() and brush() prior
# to calling this function.
#
# \sa draw()
###
###
# \fn QPen QtCanvasPolygonalItem.pen()
#
# Returns the QPen used to draw the outline of the item, if any.
#
# \sa setPen()
###
###
# \fn QBrush QtCanvasPolygonalItem.brush()
#
# Returns the QBrush used to fill the item, if filled.
#
# \sa setBrush()
###
###
# Sets the QPen used when drawing the item to the pen \a p.
# Note that many QtCanvasPolygonalItems do not use the pen value.
#
# \sa setBrush(), pen(), drawShape()
###
def setPen(self, p):
if (self.pn != p):
if p in [0, None]:
p = 0
self.removeFromChunks()
self.pn = p
self.addToChunks()
###
# Sets the QBrush used when drawing the polygonal item to the brush \a b.
#
# \sa setPen(), brush(), drawShape()
###
def setBrush(self, b):
if (self.br != b):
self.br = b
self.changeChunks()
###
# Returns 2 (RttiValues.Rtti_PolygonalItem).
#
# \sa QtCanvasItem.rtti()
###
def rtti(self):
return self.RTTI
RTTI = RttiValues.Rtti_PolygonalItem
###
# \fn bool QtCanvasItem.collidesWith(other)
#
# Returns True if the canvas item will collide with the \a other
# item \e after they have moved by their current velocities
# otherwise returns False.
#
# \sa collisions()
###
def collidesWith(self, s, *args):
if len(args) == 0:
return s.collidesWith(0, self, 0, 0, 0)
return collision_double_dispatch(s, args[0], args[1], args[2], args[3], 0, self, 0, 0, 0)
###
# Returns True if the polygonal item uses the winding algorithm to
# determine the "inside" of the polygon. Returns False if it uses
# the odd-even algorithm.
#
# The default is to use the odd-even algorithm.
#
# \sa setWinding()
###
def winding(self):
return self.wind
###
# If \a enable is True, the polygonal item will use the winding
# algorithm to determine the "inside" of the polygon; otherwise the
# odd-even algorithm will be used.
#
# The default is to use the odd-even algorithm.
#
# \sa winding()
###
def setWinding(self, enable):
self.wind = enable
###
# Invalidates all information about the area covered by the canvas
# item. The item will be updated automatically on the next call that
# changes the item's status, for example, move() or update(). Call
# this function if you are going to change the shape of the item (as
# returned by areaPoints()) while the item is visible.
###
def invalidate(self):
self.val = False
self.removeFromChunks()
###
# \fn QtCanvasPolygonalItem.isValid()
#
# Returns True if the polygonal item's area information has not been
# invalidated; otherwise returns False.
#
# \sa invalidate()
###
def isValid(self):
return self.val
###
# Returns the points the polygonal item \e will have after
# QtCanvasItem.advance(1) is called, i.e. what the points are when
# advanced by the current xVelocity() and yVelocity().
###
def areaPointsAdvanced(self):
dx = int(self.x()+self.xVelocity())-int(self.x())
dy = int(self.y()+self.yVelocity())-int(self.y())
r = self.areaPoints()
#r.detach(); # Explicit sharing is stupid.
if (dx or dy):
r.translate(dx, dy)
return r
class QPolygonalProcessor():
def __init__(self, c, pa):
self.pn = QPen()
self.br = QBrush()
self.wind = 1
self.canvas = c
self.result = QPolygonEx()
self.bounds = QRect()
pixelbounds = pa.boundingRect()
cs = self.canvas.chunkSize()
canvasbounds = pixelbounds.intersected(self.canvas.rect())
self.bounds.setLeft(int(canvasbounds.left()/cs))
self.bounds.setRight(int(canvasbounds.right()/cs))
self.bounds.setTop(int(canvasbounds.top()/cs))
self.bounds.setBottom(int(canvasbounds.bottom()/cs))
self.bitmap = QImage(self.bounds.width(), self.bounds.height(), QImage.Format_MonoLSB)
self.pnt = 0
self.bitmap.fill(0)
#ifdef QCANVAS_POLYGONS_DEBUG
# dbg_start()
#endif
def add(self, x, y):
if (self.pnt >= self.result.size()):
self.result.resize(self.pnt*2+10)
self.result[self.pnt] = QPoint(x+self.bounds.x(), y+self.bounds.y())
self.pnt += 1
#ifdef QCANVAS_POLYGONS_DEBUG
# if (dbg_ptr):
# cs = canvas.chunkSize()
# r(x*cs+bounds.x()*cs, y*cs+bounds.y()*cs, cs-1, cs-1)
# dbg_ptr.setPen(Qt.blue)
# dbg_ptr.drawRect(r)
#endif
def addBits(self, x1, x2, newbits, xo, yo):
for i in range(x1, x2+1):
if (newbits & (1 <<i)):
self.add(xo+i, yo)
#ifdef QCANVAS_POLYGONS_DEBUG
# def dbg_start(self):
# if (not dbg_wid):
# dbg_wid = QWidget
# dbg_wid.resize(800, 600)
# dbg_wid.show()
# dbg_ptr = QPainter(dbg_wid)
# dbg_ptr.setBrush(Qt.NoBrush)
# dbg_ptr.fillRect(dbg_wid.rect(), Qt.white)
#endif
def doSpans(self, n, pt, w):
cs = self.canvas.chunkSize()
for j in range(n):
y = int(pt[j].y/cs-self.bounds.y())
if (y >= self.bitmap.height() or y < 0):
continue
l = self.bitmap.scanLine(y).asarray(self.bitmap.bytesPerLine())
x = int(pt[j].x)
x1 = int(x/cs-self.bounds.x())
if (x1 > self.bounds.width()):
continue
x1 = max(0,x1)
x2 = int((x+w[j])/cs-self.bounds.x())
if (x2 < 0):
continue
x2 = min(self.bounds.width(), x2)
x1q = int(x1/8)
x1r = int(x1%8)
x2q = int(x2/8)
x2r = int(x2%8)
#ifdef QCANVAS_POLYGONS_DEBUG
# if (dbg_ptr) dbg_ptr.setPen(Qt.yellow):
#endif
if (x1q == x2q):
newbits = (~l[x1q]) & (((2 <<(x2r-x1r))-1) <<x1r)
if (newbits):
#ifdef QCANVAS_POLYGONS_DEBUG
# if (dbg_ptr) dbg_ptr.setPen(Qt.darkGreen):
#endif
self.addBits(x1r, x2r, newbits, x1q*8, y)
l[x1q] |= newbits
else:
#ifdef QCANVAS_POLYGONS_DEBUG
# if (dbg_ptr) dbg_ptr.setPen(Qt.blue):
#endif
newbits1 = (~l[x1q]) & (0xff <<x1r)
if (newbits1):
#ifdef QCANVAS_POLYGONS_DEBUG
# if (dbg_ptr) dbg_ptr.setPen(Qt.green):
#endif
self.addBits(x1r, 7, newbits1, x1q*8, y)
l[x1q] |= newbits1
for i in range(x1q+1, x2q):
if (l[i] != 0xff):
self.addBits(0, 7, ~l[i], i*8, y)
l[i] = 0xff
newbits2 = (~l[x2q]) & (0xff>>(7-x2r))
if (newbits2):
#ifdef QCANVAS_POLYGONS_DEBUG
# if (dbg_ptr) dbg_ptr.setPen(Qt.red):
#endif
self.addBits(0, x2r, newbits2, x2q*8, y)
l[x2q] |= newbits2
#ifdef QCANVAS_POLYGONS_DEBUG
# if (dbg_ptr):
# dbg_ptr.drawLine(pt[j], pt[j]+QPoint(w[j], 0))
#endif
self.result.resize(self.pnt)
###
# \class QtCanvasPolygon qtcanvas.h
# \brief The QtCanvasPolygon class provides a polygon on a QtCanvas.
#
# Paints a polygon with a QBrush. The polygon's points can be set in
# the constructor or set or changed later using setPoints(). Use
# points() to retrieve the points, or areaPoints() to retrieve the
# points relative to the canvas's origin.
#
# The polygon can be drawn on a painter with drawShape().
#
# Like any other canvas item polygons can be moved with
# QtCanvasItem.move() and QtCanvasItem.moveBy(), or by setting
# coordinates with QtCanvasItem.setX(), QtCanvasItem.setY() and
# QtCanvasItem.setZ().
#
# Note: QtCanvasPolygon does not use the pen.
###
class QtCanvasPolygon(QtCanvasPolygonalItem):
###
# Constructs a point-less polygon on the canvas \a canvas. You
# should call setPoints() before using it further.
###
def __init__(self, canvas):
super(QtCanvasPolygon, self).__init__(canvas)
self.poly = QPolygonEx()
self.current_canvas = None
self.ext = None
self.cnv = canvas
self.myx = 0
self.myy = 0
self.myz = 0
self.ani = 0
self.vis = 0
self.val = 0
self.sel = 0
self.ena = 0
self.act = 0
self.ext = 0
if self.cnv:
self.cnv.addItem(self)
###
# Destroys the polygon.
###
def __del__(self):
self.hide()
###
# Returns 4 (RttiValues.Rtti_Polygon).
#
# \sa QtCanvasItem.rtti()
###
def rtti(self):
return self.RTTI
RTTI = RttiValues.Rtti_Polygon
###
# Draws the polygon using the painter \a p.
#
# Note that QtCanvasPolygon does not support an outline (the pen is
# always NoPen).
###
def drawShape(self, p):
# ### why can't we draw outlines? We could use drawPolyline for it. Lars
# ### see other message. Warwick
p.setPen(QPen(Qt.NoPen)); # since QRegion(QPolygon) excludes outline :-()-:
p.drawPolygon(self.poly)
###
# Sets the points of the polygon to be \a pa. These points will have
# their x and y coordinates automatically translated by x(), y() as
# the polygon is moved.
###
def setPoints(self, pa):
self.removeFromChunks()
poly = pa
#poly.detach() # Explicit sharing is stupid.
poly.translate(self.x(), self.y())
self.addToChunks()
###
# \reimp
###
def moveBy(self, dx, dy):
# Note: does NOT call QtCanvasPolygonalItem.moveBy(), since that
# only does half this work.
#
idx = int(self.x()+dx)-int(self.x())
idy = int(self.y()+dy)-int(self.y())
if (idx or idy):
self.removeFromChunks()
self.poly.translate(idx, idy)
self.myx += dx
self.myy += dy
if (idx or idy):
self.addToChunks()
###
# \class QtCanvasSpline qtcanvas.h
# \brief The QtCanvasSpline class provides multi-bezier splines on a QtCanvas.
#
# A QtCanvasSpline is a sequence of 4-point bezier curves joined
# together to make a curved shape.
#
# You set the control points of the spline with setControlPoints().
#
# If the bezier is closed(), then the first control point will be
# re-used as the last control point. Therefore, a closed bezier must
# have a multiple of 3 control points and an open bezier must have
# one extra point.
#
# The beziers are not necessarily joined "smoothly". To ensure this,
# set control points appropriately (general reference texts about
# beziers will explain this in detail).
#
# Like any other canvas item splines can be moved with
# QtCanvasItem.move() and QtCanvasItem.moveBy(), or by setting
# coordinates with QtCanvasItem.setX(), QtCanvasItem.setY() and
# QtCanvasItem.setZ().
#
###
class QtCanvasSpline(QtCanvasPolygon):
###
# Create a spline with no control points on the canvas \a canvas.
#
# \sa setControlPoints()
###
def __init__(self, canvas):
super(QtCanvasSpline, self).__init__(canvas)
self.cl = True
###
# Destroy the spline.
###
def __del__(self):
pass
###
# Returns 8 (RttiValues.Rtti_Spline).
#
# \sa QtCanvasItem.rtti()
###
def rtti(self):
return self.RTTI
RTTI = RttiValues.Rtti_Spline
###
# Set the spline control points to \a ctrl.
#
# If \a close is True, then the first point in \a ctrl will be
# re-used as the last point, and the number of control points must
# be a multiple of 3. If \a close is False, one additional control
# point is required, and the number of control points must be one of
# (4, 7, 10, 13, ...).
#
# If the number of control points doesn't meet the above conditions,
# the number of points will be truncated to the largest number of
# points that do meet the requirement.
###
def setControlPoints(self, ctrl, close):
x = 1
if close:
x = 0
if (ctrl.count() % 3 != x):
qWarning("QtCanvasSpline.setControlPoints(): Number of points doesn't fit.")
numCurves = (ctrl.count() - x)/ 3
ctrl.resize(numCurves*3 + x)
self.cl = close
self.bez = ctrl
self.recalcPoly()
###
# Returns the current set of control points.
#
# \sa setControlPoints(), closed()
###
def controlPoints(self):
return self.bez
###
# Returns True if the control points are a closed set; otherwise
# returns False.
###
def closed(self):
return self.cl
def recalcPoly(self):
if (self.bez.count() == 0):
return
path = QPainterPath()
path.moveTo(self.bez[0])
for i in range(1, self.bez.count()-1, 3):
if self.cl:
path.cubicTo(self.bez[i], self.bez[i+1], self.bez[(i+2)%self.bez.size()])
else:
path.cubicTo(self.bez[i], self.bez[i+1], self.bez[i+2])
p = path.toFillPolygon().toPolygon()
super(QtCanvasSpline, self).setPoints(p)
###
# \fn QPolygon QtCanvasPolygonalItem.areaPoints()
#
# This function must be reimplemented by subclasses. It \e must
# return the points bounding (i.e. outside and not touching) the
# shape or drawing errors will occur.
###
###
# \fn QPolygon QtCanvasPolygon.points()
#
# Returns the vertices of the polygon, not translated by the position.
#
# \sa setPoints(), areaPoints()
###
def points(self):
pa = self.areaPoints()
pa.translate(int(-self.x()), int(-self.y()))
return pa
###
# Returns the vertices of the polygon translated by the polygon's
# current x(), y() position, i.e. relative to the canvas's origin.
#
# \sa setPoints(), points()
###
def areaPoints(self):
return self.poly
###
# \class QtCanvasLine qtcanvas.h
# \brief The QtCanvasLine class provides a line on a QtCanvas.
#
# The line inherits functionality from QtCanvasPolygonalItem, for
# example the setPen() function. The start and end points of the
# line are set with setPoints().
#
# Like any other canvas item lines can be moved with
# QtCanvasItem.move() and QtCanvasItem.moveBy(), or by setting
# coordinates with QtCanvasItem.setX(), QtCanvasItem.setY() and
# QtCanvasItem.setZ().
###
class QtCanvasLine(QtCanvasPolygonalItem):
###
# Constructs a line from (0, 0) to (0, 0) on \a canvas.
#
# \sa setPoints()
###
def __init__(self, canvas):
super(QtCanvasLine, self).__init__(canvas)
self.x1 = self.y1 = self.x2 = self.y2 = 0
def startPoint(self):
return QPoint(self.x1, self.y1)
def endPoint(self):
return QPoint(self.x2, self.y2)
###
# Destroys the line.
###
def __del__(self):
self.hide()
###
# Returns 7 (RttiValues.Rtti_Line).
#
# \sa QtCanvasItem.rtti()
###
def rtti(self):
return self.RTTI
RTTI = RttiValues.Rtti_Line
###
# \reimp
###
def setPen(self, p):
super(QtCanvasLine, self).setPen(p)
###
# \fn QPoint QtCanvasLine.startPoint ()
#
# Returns the start point of the line.
#
# \sa setPoints(), endPoint()
###
###
# \fn QPoint QtCanvasLine.endPoint ()
#
# Returns the end point of the line.
#
# \sa setPoints(), startPoint()
###
###
# Sets the line's start point to (\a xa, \a ya) and its end point to
# (\a xb, \a yb).
###
def setPoints(self, xa, ya, xb, yb):
if (self.x1 != xa or self.x2 != xb or self.y1 != ya or self.y2 != yb):
self.removeFromChunks()
self.x1 = xa
self.y1 = ya
self.x2 = xb
self.y2 = yb
self.addToChunks()
###
# \reimp
###
def drawShape(self, p):
p.drawLine((self.x()+self.x1), (self.y()+self.y1), (self.x()+self.x2), (self.y()+self.y2))
###
# \reimp
#
# Note that the area defined by the line is somewhat thicker than
# the line that is actually drawn.
###
def areaPoints(self):
p = QPolygonEx(4)
xi = int(self.x())
yi = int(self.y())
pw = self.pen().width()
dx = abs(self.x1-self.x2)
dy = abs(self.y1-self.y2)
pw = pw*4/3+2; # approx pw*sqrt(2)
if self.x1 < self.x2:
px = -pw
else:
px = pw
if self.y1 < self.y2:
py = -pw
else:
py = pw
if dx>0 and dy>0:
if dx > dy:
_dxy = dx*2/dy <= 2
else:
_dxy = dy*2/dx <= 2
if _dxy:
# steep
if (px == py):
p[0] = QPoint(self.x1+xi, self.y1+yi+py)
p[1] = QPoint(self.x2+xi-px, self.y2+yi)
p[2] = QPoint(self.x2+xi, self.y2+yi-py)
p[3] = QPoint(self.x1+xi+px, self.y1+yi)
else:
p[0] = QPoint(self.x1+xi+px, self.y1+yi)
p[1] = QPoint(self.x2+xi, self.y2+yi-py)
p[2] = QPoint(self.x2+xi-px, self.y2+yi)
p[3] = QPoint(self.x1+xi, self.y1+yi+py)
elif (dx > dy):
# horizontal
p[0] = QPoint(self.x1+xi+px, self.y1+yi+py)
p[1] = QPoint(self.x2+xi-px, self.y2+yi+py)
p[2] = QPoint(self.x2+xi-px, self.y2+yi-py)
p[3] = QPoint(self.x1+xi+px, self.y1+yi-py)
else:
# vertical
p[0] = QPoint(self.x1+xi+px, self.y1+yi+py)
p[1] = QPoint(self.x2+xi+px, self.y2+yi-py)
p[2] = QPoint(self.x2+xi-px, self.y2+yi-py)
p[3] = QPoint(self.x1+xi-px, self.y1+yi+py)
return p
###
# \reimp
#
###
def moveBy(self, dx, dy):
super(QtCanvasLine, self).moveBy(dx, dy)
###
# \class QtCanvasRectangle qtcanvas.h
# \brief The QtCanvasRectangle class provides a rectangle on a QtCanvas.
#
# This item paints a single rectangle which may have any pen() and
# brush(), but may not be tilted/rotated. For rotated rectangles,
# use QtCanvasPolygon.
#
# The rectangle's size and initial position can be set in the
# constructor. The size can be set or changed later using setSize().
# Use height() and width() to retrieve the rectangle's dimensions.
#
# The rectangle can be drawn on a painter with drawShape().
#
# Like any other canvas item rectangles can be moved with
# QtCanvasItem.move() and QtCanvasItem.moveBy(), or by setting
# coordinates with QtCanvasItem.setX(), QtCanvasItem.setY() and
# QtCanvasItem.setZ().
#
###
class QtCanvasRectangle(QtCanvasPolygonalItem):
def __init__(self, arg1, arg2=None, arg3=None, arg4=None, arg5=None):
if type(arg1)==QtCanvas:
###
# Constructs a rectangle at position (0,0) with both width and
# height set to 32 pixels on \a canvas.
###
super(QtCanvasRectangle, self).__init__(arg1)
self.w = 32
self.h = 32
elif type(arg2)==QtCanvas:
###
# Constructs a rectangle positioned and sized by \a r on \a canvas.
###
super(QtCanvasRectangle, self).__init__(arg2)
self.w = arg1.width()
self.h = arg1.height()
self.move(arg1.x(), arg1.y())
elif type(arg5)==QtCanvas:
###
# Constructs a rectangle at position (\a x, \a y) and size \a width
# by \a height, on \a canvas.
###
super(QtCanvasRectangle, self).__init__(arg5)
self.w = arg3
self.h = arg4
self.move(arg1, arg2)
def size(self):
return QSize(self.w, self.h)
def rect(self):
return QRect(int(self.x()), int(self.y()), self.w, self.h)
###
# Destroys the rectangle.
###
def __del__(self):
self.hide()
###
# Simply calls QtCanvasItem.chunks().
###
def chunks(self):
# No need to do a polygon scan!
return super(QtCanvasPolygonalItem, self).chunks()
###
# Returns 5 (RttiValues.Rtti_Rectangle).
#
# \sa QtCanvasItem.rtti()
###
def rtti(self):
return self.RTTI
RTTI = RttiValues.Rtti_Rectangle
###
# \reimp
###
def collidesWith(self, s, *args):
if len(args) == 0:
return s.collidesWith(0, self, self, 0, 0)
return collision_double_dispatch(s, args[0], args[1], args[2], args[3], 0, self, self, 0, 0)
###
# Returns the width of the rectangle.
###
def width(self):
return self.w
###
# Returns the height of the rectangle.
###
def height(self):
return self.h
###
# Sets the \a width and \a height of the rectangle.
###
def setSize(self, width, height):
if (self.w != width or self.h != height):
self.removeFromChunks()
self.w = width
self.h = height
self.addToChunks()
###
# \fn QSize QtCanvasRectangle.size()
#
# Returns the width() and height() of the rectangle.
#
# \sa rect(), setSize()
###
###
# \fn QRect QtCanvasRectangle.rect()
#
# Returns the integer-converted x(), y() position and size() of the
# rectangle as a QRect.
###
###
# \reimp
###
def areaPoints(self):
pa = QPolygonEx(4)
pw = (self.pen().width()+1)/2
if (pw < 1):
pw = 1
if (self.pen() == Qt.NoPen):
pw = 0
pa[0] = QPoint(self.x()-pw, self.y()-pw)
pa[1] = pa[0] + QPoint(self.w+pw*2, 0)
pa[2] = pa[1] + QPoint(0, self.h+pw*2)
pa[3] = pa[0] + QPoint(0, self.h+pw*2)
return pa
###
# Draws the rectangle on painter \a p.
###
def drawShape(self, p):
p.drawRect(self.x(), self.y(), self.w, self.h)
###
# \class QtCanvasEllipse qtcanvas.h
# \brief The QtCanvasEllipse class provides an ellipse or ellipse segment on a QtCanvas.
#
# A canvas item that paints an ellipse or ellipse segment with a QBrush.
# The ellipse's height, width, start angle and angle length can be set
# at construction time. The size can be changed at runtime with
# setSize(), and the angles can be changed (if you're displaying an
# ellipse segment rather than a whole ellipse) with setAngles().
#
# Note that angles are specified in 16ths of a degree.
#
# \target anglediagram
# \img qcanvasellipse.png Ellipse
#
# If a start angle and length angle are set then an ellipse segment
# will be drawn. The start angle is the angle that goes from zero in a
# counter-clockwise direction (shown in green in the diagram). The
# length angle is the angle from the start angle in a
# counter-clockwise direction (shown in blue in the diagram). The blue
# segment is the segment of the ellipse that would be drawn. If no
# start angle and length angle are specified the entire ellipse is
# drawn.
#
# The ellipse can be drawn on a painter with drawShape().
#
# Like any other canvas item ellipses can be moved with move() and
# moveBy(), or by setting coordinates with setX(), setY() and setZ().
#
# Note: QtCanvasEllipse does not use the pen.
###
class QtCanvasEllipse(QtCanvasPolygonalItem):
def __init__(self, arg1, arg2=None, arg3=None, arg4=None, arg5=None):
t = type(arg1)
if t==QtCanvas:
###
# Constructs a 32x32 ellipse, centered at (0, 0) on \a canvas.
###
self.w = 32
self.h = 32
self.a1 = 0
self.a2 = 360*16
canvas = arg1
elif t==int:
t = type(arg3)
if t==QtCanvas:
###
# Constructs a \a width by \a height pixel ellipse, centered at
# (0, 0) on \a canvas.
###
self.w = arg1
self.h = arg2
self.a1 = 0
self.a2 = 360*16
canvas = arg3
elif t==int:
# ### add a constructor taking degrees in float. 1/16 degrees is stupid. Lars
# ### it's how QPainter does it, so QtCanvas does too for consistency. If it's
# ### a good idea, it should be added to QPainter, not just to QtCanvas. Warwick
###
# Constructs a \a width by \a height pixel ellipse, centered at
# (0, 0) on \a canvas. Only a segment of the ellipse is drawn,
# starting at angle \a startangle, and extending for angle \a angle
# (the angle length).
#
# Note that angles are specified in sixteenths of a degree.
###
self.w = arg1
self.h = arg2
self.a1 = arg3
self.a2 = arg4
canvas = arg5
super(QtCanvasEllipse, self).__init__(canvas)
###
# Destroys the ellipse.
###
def __del__(self):
self.hide()
###
# Returns 6 (RttiValues.Rtti_Ellipse).
#
# \sa QtCanvasItem.rtti()
###
def rtti(self):
return self.RTTI
RTTI = RttiValues.Rtti_Ellipse
###
# \reimp
###
def collidesWith(self, s, *args):
if len(args) == 0:
return s.collidesWith(0,self, 0, self, 0)
return collision_double_dispatch(s, args[0], args[1], args[2], args[3], 0, self, 0, self, 0)
###
# Returns the width of the ellipse.
###
def width(self):
return self.w
###
# Returns the height of the ellipse.
###
def height(self):
return self.h
###
# Sets the \a width and \a height of the ellipse.
###
def setSize(self, width, height):
if (self.w != width or self.h != height):
self.removeFromChunks()
self.w = width
self.h = height
self.addToChunks()
###
# \fn int QtCanvasEllipse.angleStart()
#
# Returns the start angle in 16ths of a degree. Initially
# this will be 0.
#
# \sa setAngles(), angleLength()
###
###
# \fn int QtCanvasEllipse.angleLength()
#
# Returns the length angle (the extent of the ellipse segment) in
# 16ths of a degree. Initially this will be 360 * 16 (a complete
# ellipse).
#
# \sa setAngles(), angleStart()
###
###
# Sets the angles for the ellipse. The start angle is \a start and
# the extent of the segment is \a length (the angle length) from the
# \a start. The angles are specified in 16ths of a degree. By
# default the ellipse will start at 0 and have an angle length of
# 360 * 16 (a complete ellipse).
#
# \sa angleStart(), angleLength()
###
def setAngles(self, start, length):
if (self.a1 != start or self.a2 != length):
self.removeFromChunks()
self.a1 = start
self.a2 = length
self.addToChunks()
###
# \reimp
###
def areaPoints(self):
path = QPainterPath()
path.arcTo(QRectF(self.x()-self.w/2.0+0.5-1, self.y()-self.h/2.0+0.5-1, self.w+3, self.h+3), self.a1/16., self.a2/16.)
return path.toFillPolygon(QMatrix()).toPolygon()
###
# Draws the ellipse, centered at x(), y() using the painter \a p.
#
# Note that QtCanvasEllipse does not support an outline (the pen is
# always NoPen).
###
def drawShape(self, p):
p.setPen(QPen(Qt.NoPen)); # since QRegion(QPolygon) excludes outline :-()-:
if (not self.a1 and self.a2 == 360*16):
p.drawEllipse(int(self.x()-self.w/2.0+0.5), int(self.y()-self.h/2.0+0.5), self.w, self.h)
else:
p.drawPie(int(self.x()-self.w/2.0+0.5), int(self.y()-self.h/2.0+0.5), self.w, self.h, self.a1, self.a2)
###
# \class QtCanvasText
# \brief The QtCanvasText class provides a text object on a QtCanvas.
#
# A canvas text item has text with font, color and alignment
# attributes. The text and font can be set in the constructor or set
# or changed later with setText() and setFont(). The color is set
# with setColor() and the alignment with setTextFlags(). The text
# item's bounding rectangle is retrieved with boundingRect().
#
# The text can be drawn on a painter with draw().
#
# Like any other canvas item text items can be moved with
# QtCanvasItem.move() and QtCanvasItem.moveBy(), or by setting
# coordinates with QtCanvasItem.setX(), QtCanvasItem.setY() and
# QtCanvasItem.setZ().
###
class QtCanvasText(QtCanvasItem):
def __init__(self, arg1, arg2=None, arg3=None):
self.brect = QRect()
self.txt = ''
self.flags = 0
self.fnt = QFont()
self.col = QColor()
t1 = type(arg1)
t2 = type(arg2)
t3 = type(arg3)
if t1==QtCanvas:
###
# Constructs a QtCanvasText with the text "\<text\>", on \a canvas.
###
self.txt = "<text>"
canvas = arg1
elif t2==QtCanvas:
# ### add textflags to the constructor? Lars
###
# Constructs a QtCanvasText with the text \a t, on canvas \a canvas.
###
self.txt = arg1
canvas = arg2
elif t3==QtCanvas:
# ### see above
###
# Constructs a QtCanvasText with the text \a t and font \a f, on the
# canvas \a canvas.
###
self.txt = arg1
self.fnt = arg2
canvas = arg3
super(QtCanvasText, self).__init__(canvas)
self.flags = 0
self.setRect()
###
# Destroys the canvas text item.
###
def __del__(self):
self.removeFromChunks()
###
# Returns 3 (RttiValues.Rtti_Text).
#
# \sa QtCanvasItem.rtti()
###
def rtti(self):
return self.RTTI
RTTI = RttiValues.Rtti_Text
###
# \reimp
###
def collidesWith(self, s, *args):
if len(args) == 0:
return s.collidesWith(0, 0, 0, 0, self)
return collision_double_dispatch(s, args[0], args[1], args[2], args[3], 0, 0, 0, 0, self)
###
# Returns the bounding rectangle of the text.
###
def boundingRect(self):
return self.brect
def setRect(self):
self.brect = QFontMetrics(self.fnt).boundingRect(int(self.x()), int(self.y()), 0, 0, self.flags, self.txt)
###
# \fn int QtCanvasText.textFlags()
#
# Returns the currently set alignment flags.
#
# \sa setTextFlags() Qt.AlignmentFlag Qt.TextFlag
###
###
# Sets the alignment flags to \a f. These are a bitwise OR of the
# flags available to QPainter.drawText() -- see the
# \l{Qt.AlignmentFlag}s and \l{Qt.TextFlag}s.
#
# \sa setFont() setColor()
###
def setTextFlags(self, f):
if (self.flags != f):
self.removeFromChunks()
self.flags = f
self.setRect()
self.addToChunks()
###
# Returns the text item's text.
#
# \sa setText()
###
def text(self):
return self.txt
###
# Sets the text item's text to \a t. The text may contain newlines.
#
# \sa text(), setFont(), setColor() setTextFlags()
###
def setText(self, t):
if (self.txt != t):
self.removeFromChunks()
self.txt = t
self.setRect()
self.addToChunks()
###
# Returns the font in which the text is drawn.
#
# \sa setFont()
###
def font(self):
return self.fnt
###
# Sets the font in which the text is drawn to font \a f.
#
# \sa font()
###
def setFont(self, f):
if (f != self.fnt):
self.removeFromChunks()
self.fnt = f
self.setRect()
self.addToChunks()
###
# Returns the color of the text.
#
# \sa setColor()
###
def color(self):
return self.col
###
# Sets the color of the text to the color \a c.
#
# \sa color(), setFont()
###
def setColor(self, c):
self.col = c
self.changeChunks()
###
# \reimp
###
def moveBy(self, dx, dy):
idx = int(self.x()+dx)-int(self.x())
idy = int(self.y()+dy)-int(self.y())
if (idx or idy):
self.removeFromChunks()
self.myx += dx
self.myy += dy
if (idx or idy):
self.brect.translate(idx, idy)
self.addToChunks()
###
# Draws the text using the painter \a painter.
###
def draw(self, painter):
painter.setFont(self.fnt)
painter.setPen(self.col)
painter.drawText(painter.fontMetrics().boundingRect(int(self.x()), int(self.y()), 0, 0, self.flags, self.txt), self.flags, self.txt)
###
# \reimp
###
def changeChunks(self):
if (self.isVisible() and self.canvas()):
self.chunksize = self.canvas().chunkSize()
for j in range(int(self.brect.top()/self.chunksize), int(self.brect.bottom()/self.chunksize+1)):
for i in range(int(self.brect.left()/self.chunksize), int(self.brect.right()/self.chunksize+1)):
self.canvas().setChangedChunk(i, j)
###
# Adds the text item to the appropriate chunks.
###
def addToChunks(self):
if (self.isVisible() and self.canvas()):
self.chunksize = self.canvas().chunkSize()
for j in range(int(self.brect.top()/self.chunksize), int(self.brect.bottom()/self.chunksize+1)):
for i in range(int(self.brect.left()/self.chunksize), int(self.brect.right()/self.chunksize+1)):
self.canvas().addItemToChunk(self, i, j)
###
# Removes the text item from the appropriate chunks.
###
def removeFromChunks(self):
if (self.isVisible() and self.canvas()):
self.chunksize = self.canvas().chunkSize()
for j in range(int(self.brect.top()/self.chunksize), int(self.brect.bottom()/self.chunksize+1)):
for i in range(int(self.brect.left()/self.chunksize), int(self.brect.right()/self.chunksize+1)):
self.canvas().removeItemFromChunk(self, i, j)
class QtCanvasSprite(QtCanvasItem):
###
# Constructs a QtCanvasSprite which uses images from the
# QtCanvasPixmapArray \a a.
#
# The sprite in initially positioned at (0, 0) on \a canvas, using
# frame 0.
###
def __init__(self, a, canvas):
super(QtCanvasSprite, self).__init__(canvas)
self.frm = 0
self.anim_val = 0
self.anim_state = 0
self.anim_type = 0
self.images = a
###
# Returns 1 (RttiValues.Rtti_Sprite).
#
# \sa QtCanvasItem.rtti()
###
def rtti(self):
return self.RTTI
RTTI = RttiValues.Rtti_Sprite
def image(self):
return self.images.image(self.frm)
###
# Returns True if the canvas item collides with any of the given
# items; otherwise returns False. The parameters, \a s, \a p, \a r,
# \a e and \a t, are all the same object, this is just a type
# resolution trick.
###
def collidesWith(self, s, *args):
if len(args) == 0:
return s.collidesWith(self, 0, 0, 0, 0)
return collision_double_dispatch(s, args[0], args[1], args[2], args[3], self, 0, 0, 0, 0)
###
# Set the array of images used for displaying the sprite to the
# QtCanvasPixmapArray \a a.
#
# If the current frame() is larger than the number of images in \a
# a, the current frame will be reset to 0.
###
def setSequence(self, a):
isvisible = self.isVisible()
if (isvisible and self.images):
self.hide()
images = a
if (self.frm >= images.count()):
self.frm = 0
if (isvisible):
self.show()
###
#\internal
#
#Marks any chunks the sprite touches as changed.
###
def changeChunks(self):
if (self.isVisible() and self.canvas()):
self.chunksize = self.canvas().chunkSize()
for j in range(int(self.topEdge()/self.chunksize, self.bottomEdge()/self.chunksize+1)):
for i in range(int(self.leftEdge()/self.chunksize, self.rightEdge()/self.chunksize+1)):
self.canvas().setChangedChunk(i, j)
###
# Destroys the sprite and removes it from the canvas. Does \e not
# del the images.
###
def __del__(self):
self.removeFromChunks()
def frame(self):
return self.frm
def frameCount(self):
return self.images.count()
###
# Sets the animation frame used for displaying the sprite to \a f,
# an index into the QtCanvasSprite's QtCanvasPixmapArray. The call
# will be ignored if \a f is larger than frameCount() or smaller
# than 0.
#
# \sa frame() move()
###
def setFrame(self, f):
self.move(self.x(), self.y(), f)
###
# \enum QtCanvasSprite.FrameAnimationType
#
# This enum is used to identify the different types of frame
# animation offered by QtCanvasSprite.
#
# \value Cycle at each advance the frame number will be incremented by
# 1 (modulo the frame count).
# \value Oscillate at each advance the frame number will be
# incremented by 1 up to the frame count then decremented to by 1 to
# 0, repeating this sequence forever.
###
###
# Sets the animation characteristics for the sprite.
#
# For \a type == \c Cycle, the frames will increase by \a step
# at each advance, modulo the frameCount().
#
# For \a type == \c Oscillate, the frames will increase by \a step
# at each advance, up to the frameCount(), then decrease by \a step
# back to 0, repeating forever.
#
# The \a state parameter is for internal use.
###
def setFrameAnimation(self, type, step=1, state=0):
self.anim_val = step
self.anim_type = type
self.anim_state = state
self.setAnimated(True)
###
# Extends the default QtCanvasItem implementation to provide the
# functionality of setFrameAnimation().
#
# The \a phase is 0 or 1: see QtCanvasItem.advance() for details.
#
# \sa QtCanvasItem.advance() setVelocity()
###
def advance(self, phase):
if (phase == 1):
nf = self.frame()
if (self.anim_type == self.Oscillate):
if (self.anim_state):
nf += self.anim_val
else:
nf -= self.anim_val
if (nf < 0):
nf = abs(self.anim_val)
self.anim_state = not self.anim_state
elif (nf >= self.frameCount()):
nf = self.frameCount()-1-abs(self.anim_val)
self.anim_state = not self.anim_state
else:
nf = (nf + self.anim_val + self.frameCount()) % self.frameCount()
self.move(self.x()+self.xVelocity(), self.y()+self.yVelocity(), nf)
###
# \fn int QtCanvasSprite.frame()
#
# Returns the index of the current animation frame in the
# QtCanvasSprite's QtCanvasPixmapArray.
#
# \sa setFrame(), move()
###
###
# \fn int QtCanvasSprite.frameCount()
#
# Returns the number of frames in the QtCanvasSprite's
# QtCanvasPixmapArray.
###
###
# \fn void QtCanvasSprite.move(double nx, ny, nf)
#
# Moves the sprite to (\a nx, \a ny) and sets the current
# frame to \a nf. \a nf will be ignored if it is larger than
# frameCount() or smaller than 0.
###
def move(self, nx, ny, nf=None):
if nf is None:
###
# Moves the sprite to (\a x, \a y).
###
super(QtCanvasSprite, self).move(self, nx, ny)
else:
if (self.isVisible() and self.canvas()):
self.hide()
super(QtCanvasSprite, self).move(nx, ny)
if (nf >= 0 and nf < self.frameCount()):
self.frm = nf
self.show()
else:
super(QtCanvasSprite, self).move(nx, ny)
if (nf >= 0 and nf < self.frameCount()):
self.frm = nf
class QtPolygonScanner():
def __del__(self):
pass
class Edge(Enum):
Left = 1
Right = 2
Top = 4
Bottom = 8
###
# \overload
#
# If \a stitchable is False, the right and bottom edges of the
# polygon are included. This causes adjacent polygons to overlap.
###
def scan(self, pa, winding, index=0, npoints=-1, stitchable=True):
if stitchable:
edge = Edge.Left.value+Edge.Top.value
else:
edge = Edge.Left.value+Edge.Right.value+Edge.Top.value+Edge.Bottom.value
self.__scan(pa, winding, index, npoints, edge)
###
# Calls processSpans() for all scanlines of the polygon defined by
# \a npoints starting at \a index in \a pa.
#
# If \a winding is True, the Winding algorithm rather than the
# Odd-Even rule is used.
#
# The \a edges is any bitwise combination of:
# \list
# \i QtPolygonScanner.Left
# \i QtPolygonScanner.Right
# \i QtPolygonScanner.Top
# \i QtPolygonScanner.Bottom
# \endlist
# \a edges determines which edges are included.
#
# \warning The edges feature does not work properly.
#
###
def __scan(self, pa, winding, index, npoints, edges):
ptsIn = pa
pAET = None ### the Active Edge Table ###
y = 0 ### the current scanline ###
nPts = 0 ### number of pts in buffer ###
pWETE = None ### Winding Edge Table ###
pSLL = None ### Current ScanLineList ###
ptsOut = None ### ptr to output buffers ###
#width
FirstPoint = QList()
FirstWidth = QList()
for i in range(NUMPTSTOBUFFER):
FirstPoint.append(DDXPointRec()) ### the output buffers ###
FirstWidth.append(0)
pPrevAET = None ### previous AET entry ###
ET = EdgeTable() ### Edge Table header node ###
AET = EdgeTableEntry() ### Active ET header node ###
pETEs = QList() ### Edge Table Entries buff ###
SLLBlock = ScanLineListBlock() ### header for ScanLineList ###
fixWAET = 0
if edges & Edge.Left.value:
edge_l = 1
else:
edge_l = 0
if edges & Edge.Right.value:
edge_r = 1
else:
edge_r = 0
if edges & Edge.Bottom.value:
edge_b = 1
else:
edge_b = 0
edge_t = 1 ##### (edges & Top) ? 1 : 0
if (npoints == -1):
npoints = pa.size()
if (npoints < 3):
return
for i in range(npoints):
pETEs.append(EdgeTableEntry())
ptsOut = FirstPoint
width = FirstWidth
if (not miCreateETandAET(npoints, ptsIn, ET, AET, pETEs, SLLBlock)):
del pETEs
return
pSLL = ET.scanlines.next
if (not winding):
###
# for each scanline
###
i = 0
iwidth = 0
for y in range(ET.ymin+1-edge_t, ET.ymax+edge_b):
###
# Add a new edge to the active edge table when we
# get to the next edge.
###
if (pSLL and y == pSLL.scanline):
miloadAET(AET, pSLL.edgelist)
pSLL = pSLL.next
pPrevAET = AET
pAET = AET.next
###
# for each active edge
###
while (pAET):
ptsOut[i].x = pAET.bres.minor + 1 - edge_l
ptsOut[i].y = y
i += 1
width[iwidth] = pAET.next.bres.minor - pAET.bres.minor - 1 + edge_l + edge_r
iwidth += 1
nPts += 1
###
# send out the buffer when its full
###
if (nPts == NUMPTSTOBUFFER):
self.processSpans(nPts, FirstPoint, FirstWidth)
i = 0
iwidth = 0
nPts = 0
pAET, pPrevAET = EVALUATEEDGEEVENODD(pAET, pPrevAET, y)
pAET, pPrevAET = EVALUATEEDGEEVENODD(pAET, pPrevAET, y)
miInsertionSort(AET)
else: ### default to WindingNumber ###
###
# for each scanline
###
i = 0
for y in range(ET.ymin+1-edge_t, ET.ymax+edge_b):
###
# Add a new edge to the active edge table when we
# get to the next edge.
###
if (pSLL and y == pSLL.scanline):
miloadAET(AET, pSLL.edgelist)
micomputeWAET(AET)
pSLL = pSLL.next
pPrevAET = AET
pAET = AET.next
pWETE = pAET
###
# for each active edge
###
while (pAET):
###
# if the next edge in the active edge table is
# also the next edge in the winding active edge
# table.
###
if (pWETE == pAET):
ptsOut[i].x = pAET.bres.minor + 1 - edge_l
ptsOut[i].y = y
i += 1
#width++ = pAET.nextWETE.bres.minor - pAET.bres.minor - 1 + edge_l + edge_r
nPts += 1
###
# send out the buffer
###
if (nPts == NUMPTSTOBUFFER):
self.processSpans(nPts, FirstPoint, FirstWidth)
i = 0
iwidth = 0
nPts = 0
pWETE = pWETE.nextWETE
while (pWETE != pAET):
pAET, pPrevAET = EVALUATEEDGEWINDING(pAET, pPrevAET, y, fixWAET)
pWETE = pWETE.nextWETE
pAET, pPrevAET = EVALUATEEDGEWINDING(pAET, pPrevAET, y, fixWAET)
###
# reevaluate the Winding active edge table if we
# just had to resort it or if we just exited an edge.
###
if (miInsertionSort(AET) or fixWAET):
micomputeWAET(AET)
fixWAET = 0
###
# Get any spans that we missed by buffering
###
self.processSpans(nPts, FirstPoint, FirstWidth)
miFreeStorage(SLLBlock.next)
###**** END OF X11-based CODE ****###
# Based on Xserver code miFillGeneralPoly...
###
# *
# * Written by Brian Kelleher; Oct. 1985
# *
# * Routine to fill a polygon. Two fill rules are
# * supported: frWINDING and frEVENODD.
# *
# * See fillpoly.h for a complete description of the algorithm.
# ###
#
###
# These are the data structures needed to scan
# convert regions. Two different scan conversion
# methods are available -- the even-odd method, and
# the winding number method.
# The even-odd rule states that a point is inside
# the polygon if a ray drawn from that point in any
# direction will pass through an odd number of
# path segments.
# By the winding number rule, a point is decided
# to be inside the polygon if a ray drawn from that
# point in any direction passes through a different
# number of clockwise and counterclockwise path
# segments.
#
# These data structures are adapted somewhat from
# the algorithm in (Foley/Van Dam) for scan converting
# polygons.
# The basic algorithm is to start at the top (smallest y)
# of the polygon, stepping down to the bottom of
# the polygon by incrementing the y coordinate. We
# keep a list of edges which the current scanline crosses,
# sorted by x. This list is called the Active Edge Table (AET)
# As we change the y-coordinate, we update each entry in
# in the active edge table to reflect the edges new xcoord.
# This list must be sorted at each scanline in case
# two edges intersect.
# We also keep a data structure known as the Edge Table (ET),
# which keeps track of all the edges which the current
# scanline has not yet reached. The ET is basically a
# list of ScanLineList structures containing a list of
# edges which are entered at a given scanline. There is one
# ScanLineList per scanline at which an edge is entered.
# When we enter a new edge, we move it from the ET to the AET.
#
# From the AET, we can implement the even-odd rule as in
# (Foley/Van Dam).
# The winding number rule is a little trickier. We also
# keep the EdgeTableEntries in the AET linked by the
# nextWETE (winding EdgeTableEntry) link. This allows
# the edges to be linked just as before for updating
# purposes, but only uses the edges linked by the nextWETE
# link as edges representing spans of the polygon to
# drawn (as with the even-odd rule).
###
### $XConsortium: miscanfill.h, v 1.5 94/04/17 20:27:50 dpw Exp $ ###
###
#
#Copyright (c) 1987 X Consortium
#
#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 X CONSORTIUM 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.
#
#Except as contained in this notice, the name of the X Consortium shall
#not be used in advertising or otherwise to promote the sale, use or
#other dealings in this Software without prior written authorization
#from the X Consortium.
#
###
###
# * scanfill.h
# *
# * Written by Brian Kelleher; Jan 1985
# *
# * This file contains a few macros to help track
# * the edge of a filled object. The object is assumed
# * to be filled in scanline order, and thus the
# * algorithm used is an extension of Bresenham's line
# * drawing algorithm which assumes that y is always the
# * major axis.
# * Since these pieces of code are the same for any filled shape,
# * it is more convenient to gather the library in one
# * place, but since these pieces of code are also in
# * the inner loops of output primitives, procedure call
# * overhead is out of the question.
# * See the author for a derivation if needed.
# ###
#
###
# In scan converting polygons, we want to choose those pixels
# which are inside the polygon. Thus, we add .5 to the starting
# x coordinate for both left and right edges. Now we choose the
# first pixel which is inside the pgon for the left edge and the
# first pixel which is outside the pgon for the right edge.
# Draw the left pixel, but not the right.
#
# How to add .5 to the starting x coordinate:
# If the edge is moving to the right, then subtract dy from the
# error term from the general form of the algorithm.
# If the edge is moving to the left, then add dy to the error term.
#
# The reason for the difference between edges moving to the left
# and edges moving to the right is simple: If an edge is moving
# to the right, then we want the algorithm to flip immediately.
# If it is moving to the left, then we don't want it to flip until
# we traverse an entire pixel.
###
###
# * This structure contains all of the information needed
# * to run the bresenham algorithm.
# * The variables may be hardcoded into the declarations
# * instead of using this structure to make use of
# * register declarations.
# ###
class BRESINFO():
def __init__(self):
self.minor = 0 ### minor axis ###
self.d = 0 ### decision variable ###
self.m = self.m1 = 0 ### slope and slope+1 ###
self.incr1 = self.incr2 = 0 ### error increments ###
def BRESINCRPGONSTRUCT(bres):
if bres.m1 > 0:
if (bres.d > 0):
bres.minor += bres.m1
bres.d += bres.incr1
else:
bres.minor += bres.m
bres.d += bres.incr2
else:
if bres.d >= 0:
bres.minor += bres.m1
bres.d += bres.incr1
else:
bres.minor += bres.m
bres.d += bres.incr2
return bres
class EdgeTableEntry():
def __init__(self):
self.ymax = 0 ### ycoord at which we exit this edge. ###
self.bres = BRESINFO() ### Bresenham info to run the edge ###
self.next = None ### next in the list ###
self.back = None ### for insertion sort ###
self.nextWETE = None ### for winding num rule ###
self.ClockWise = 0 ### flag for winding number rule ###
class ScanLineList():
def __init__(self):
self.scanline = 0 ### the scanline represented ###
self.edgelist = None ### header node ###
self.next = None ### next in the list ###
class EdgeTable():
def __init__(self):
self.ymax = 0 ### ymax for the polygon ###
self.ymin = 0 ### ymin for the polygon ###
self.scanlines = ScanLineList() ### header node ###
###
# Here is a struct to help with storage allocation
# so we can allocate a big chunk at a time, and then take
# pieces from this heap when we need to.
###
SLLSPERBLOCK = 25
class ScanLineListBlock():
def __init__(self):
self.SLLs = QList()
for i in range(SLLSPERBLOCK):
self.SLLs.append(ScanLineList())
self.next = None
###
# * number of points to buffer before sending them off
# * to scanlines() : Must be an even number
# ###
NUMPTSTOBUFFER = 200
#
###
#
# a few macros for the inner loops of the fill code where
# performance considerations don't allow a procedure call.
#
# Evaluate the given edge at the given scanline.
# If the edge has expired, then we leave it and fix up
# the active edge table; otherwise, we increment the
# x value to be ready for the next scanline.
# The winding number rule is in effect, so we must notify
# the caller when the edge has been removed so he
# can reorder the Winding Active Edge Table.
###
def EVALUATEEDGEWINDING(pAET, pPrevAET, y, fixWAET=1):
if pAET.ymax == y: ## leaving this edge ##
pPrevAET.next = pAET.next
pAET = pPrevAET.next
#fixWAET = 1
if pAET:
pAET.back = pPrevAET
else:
BRESINCRPGONSTRUCT(pAET.bres)
pPrevAET = pAET
pAET = pAET.next
return (pAET, pPrevAET)
###
# * Evaluate the given edge at the given scanline.
# * If the edge has expired, then we leave it and fix up
# * the active edge table; otherwise, we increment the
# * x value to be ready for the next scanline.
# * The even-odd rule is in effect.
# ###
def EVALUATEEDGEEVENODD(pAET, pPrevAET, y):
if pAET:
if (pAET.ymax == y): ### leaving this edge ###
pPrevAET.next = pAET.next
pAET = pPrevAET.next
if pAET:
pAET.back = pPrevAET
else:
pAET.bres = BRESINCRPGONSTRUCT(pAET.bres)
pPrevAET = pAET
pAET = pAET.next
return pAET, pPrevAET
##############################################################
#
#Copyright (c) 1987 X Consortium
#
#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
#X CONSORTIUM 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.
#
#Except as contained in this notice, the name of the X Consortium shall not be
#used in advertising or otherwise to promote the sale, use or other dealings
#in this Software without prior written authorization from the X Consortium.
#
#
#Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
#
# All Rights Reserved
#
#Permission to use, copy, modify, and distribute this software and its
#documentation for any purpose and without fee is hereby granted,
#provided that the above copyright notice appear in all copies and that
#both that copyright notice and this permission notice appear in
#supporting documentation, and that the name of Digital not be
#used in advertising or publicity pertaining to distribution of the
#software without specific, written prior permission.
#
#DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
#ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
#DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
#ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
#WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
#ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
#SOFTWARE.
#
###***************************************************************###
#
MAXINT = 0x7fffffff
MININT = -MAXINT
#
###
# fillUtils.c
#
# Written by Brian Kelleher; Oct. 1985
#
# This module contains all of the utility functions
# needed to scan convert a polygon.
#
###
###
# * InsertEdgeInET
# *
# * Insert the given edge into the edge table.
# * First we must find the correct bucket in the
# * Edge table, then find the right slot in the
# * bucket. Finally, we can insert it.
# *
# ###
def miInsertEdgeInET(ET, ETE, scanline, SLLBlock, iSLLBlock):
###
# find the right bucket to put the edge into
###
pPrevSLL = ET.scanlines
pSLL = pPrevSLL.next
while (pSLL and (pSLL.scanline < scanline)):
pPrevSLL = pSLL
pSLL = pSLL.next
###
# reassign pSLL (pointer to ScanLineList) if necessary
###
if ((not pSLL) or (pSLL.scanline > scanline)):
if (iSLLBlock > SLLSPERBLOCK-1):
tmpSLLBlock = ScanLineListBlock()
if (not tmpSLLBlock):
return -1
SLLBlock.next = tmpSLLBlock
tmpSLLBlock.next = 0
SLLBlock = tmpSLLBlock
iSLLBlock = 0
pSLL = SLLBlock.SLLs[iSLLBlock]
iSLLBlock += 1
pSLL.next = pPrevSLL.next
pSLL.edgelist = 0
pPrevSLL.next = pSLL
pSLL.scanline = scanline
###
# now insert the edge in the right bucket
###
prev = 0
start = pSLL.edgelist
while (start and (start.bres.minor < ETE.bres.minor)):
prev = start
start = start.next
ETE.next = start
if (prev):
prev.next = ETE
else:
pSLL.edgelist = ETE
return iSLLBlock
###
# CreateEdgeTable
#
# This routine creates the edge table for
# scan converting polygons.
# The Edge Table (ET) looks like:
#
# EdgeTable
# --------
# | ymax | ScanLineLists
# |scanline|-.-----------.-------------....
# -------- |scanline| |scanline|
# |edgelist| |edgelist|
# --------- ---------
# | |
# | |
# V V
# list of ETEs list of ETEs
#
# where ETE is an EdgeTableEntry data structure,
# and there is one ScanLineList per scanline at
# which an edge is initially entered.
#
###
class DDXPointRec():
def __init__(self):
self.x = self.y = 0
###
# * Clean up our act.
# ###
def miFreeStorage(pSLLBlock):
while pSLLBlock:
tmpSLLBlock = pSLLBlock.next
del pSLLBlock
pSLLBlock = tmpSLLBlock
del pSLLBlock
def BRESINITPGONSTRUCT(dy, x1, x2, bres):
dx = 0 # local storage #
###
# if the edge is horizontal, then it is ignored
# and assumed not to be processed. Otherwise, do this stuff.
###
if dy != 0:
bres.minor = x1
dx = x2 - bres.minor
if dx < 0:
bres.m = int(dx / dy)
bres.m1 = bres.m - 1
bres.incr1 = -2 * dx + 2 * dy * bres.m1
bres.incr2 = -2 * dx + 2 * dy * bres.m
bres.d = 2 * bres.m * dy - 2 * dx - 2 * dy
else:
bres.m = int(dx / dy)
bres.m1 = bres.m + 1
bres.incr1 = 2 * dx - 2 * dy * bres.m1
bres.incr2 = 2 * dx - 2 * dy * bres.m
bres.d = -2 * bres.m * dy + 2 * dx
return bres
def miCreateETandAET(count, pts, ET, AET, pETEs, pSLLBlock):
iSLLBlock = 0
if count < 2:
return True
###
# initialize the Active Edge Table
###
AET.next = 0
AET.back = 0
AET.nextWETE = 0
AET.bres.minor = MININT
###
# initialize the Edge Table.
###
ET.scanlines.next = 0
ET.ymax = MININT
ET.ymin = MAXINT
pSLLBlock.next = 0
PrevPt = pts[-1]
###
# for each vertex in the array of points.
# In this loop we are dealing with two vertices at
# a time -- these make up one edge of the polygon.
###
i = 0
j = 0
while (count):
CurrPt = pts[i]
i += 1
###
# find out which point is above and which is below.
###
if (PrevPt.y() > CurrPt.y()):
bottom = PrevPt
top = CurrPt
pETEs[j].ClockWise = 0
else:
bottom = CurrPt
top = PrevPt
pETEs[j].ClockWise = 1
###
# don't add horizontal edges to the Edge table.
###
if (bottom.y() != top.y()):
pETEs[j].ymax = bottom.y()-1; ### -1 so we don't get last scanline ###
###
# initialize integer edge algorithm
###
dy = bottom.y() - top.y()
BRESINITPGONSTRUCT(dy, top.x(), bottom.x(), pETEs[j].bres)
iSLLBlock = miInsertEdgeInET(ET, pETEs[j], top.y(), pSLLBlock, iSLLBlock)
if iSLLBlock==-1:
miFreeStorage(pSLLBlock.next)
return False
ET.ymax = max(ET.ymax, PrevPt.y())
ET.ymin = min(ET.ymin, PrevPt.y())
j += 1
PrevPt = CurrPt
count -= 1
return True
###
# loadAET
#
# This routine moves EdgeTableEntries from the
# EdgeTable into the Active Edge Table,
# leaving them sorted by smaller x coordinate.
#
###
def miloadAET(AET, ETEs):
pPrevAET = AET
AET = AET.next
while (ETEs):
while (AET and (AET.bres.minor < ETEs.bres.minor)):
pPrevAET = AET
AET = AET.next
tmp = ETEs.next
ETEs.next = AET
if (AET):
AET.back = ETEs
ETEs.back = pPrevAET
pPrevAET.next = ETEs
pPrevAET = ETEs
ETEs = tmp
###
# * computeWAET
# *
# * This routine links the AET by the
# * nextWETE (winding EdgeTableEntry) link for
# * use by the winding number rule. The final
# * Active Edge Table (AET) might look something
# * like:
# *
# * AET
# * ---------- --------- ---------
# * |ymax | |ymax | |ymax |
# * | ... | |... | |... |
# * |next |.|next |.|next |....
# * |nextWETE| |nextWETE| |nextWETE|
# * --------- --------- ^--------
# * | | |
# * V------------------. V--. ...
# *
# ###
def micomputeWAET(AET):
inside = 1
isInside = 0
AET.nextWETE = 0
pWETE = AET
AET = AET.next
while (AET):
if (AET.ClockWise):
isInside += 1
else:
isInside -= 1
if ((not inside and not isInside) or (inside and isInside)):
pWETE.nextWETE = AET
pWETE = AET
inside = not inside
AET = AET.next
pWETE.nextWETE = 0
###
# InsertionSort
#
# Just a simple insertion sort using
# pointers and back pointers to sort the Active
# Edge Table.
#
###
def miInsertionSort(AET):
changed = 0
AET = AET.next
while (AET):
pETEinsert = AET
pETEchase = AET
while (pETEchase.back.bres.minor > AET.bres.minor):
pETEchase = pETEchase.back
AET = AET.next
if (pETEchase != pETEinsert):
pETEchaseBackTMP = pETEchase.back
pETEinsert.back.next = AET
if (AET):
AET.back = pETEinsert.back
pETEinsert.next = pETEchase
pETEchase.back.next = pETEinsert
pETEchase.back = pETEinsert
pETEinsert.back = pETEchaseBackTMP
changed = 1
return changed
class QtCanvasPolygonScanner(QtPolygonScanner):
def __init__(self, p):
self.processor = p
def processSpans(self, n, point, width):
self.processor.doSpans(n, point, width)
|
const nomes = ["Carlos", "Celso", "Eduardo"];
const nameList = document.querySelector('ul');
for(nome of nomes){
const newName = document.createElement('li');
const itemList = document.createTextNode(nome);
newName.appendChild(itemList);
nameList.appendChild(newName);
nameList.style.fontSize = '28px';
nameList.style.fontWeight = '550';
nameList.style.fontFamily = 'Arial';
nameList.style.color = '#00EE00';
}
|
#
# D_{x,y,z} = alpha * A_{z,y,x} + beta * B_{y,z,x} + gamma * C_{x,y,z}
#
import numpy
import cupy
from cupy import cutensor
from cupy.cuda import stream
dtype = numpy.float32
mode_a = ('z', 'y', 'x')
mode_b = ('y', 'z', 'x')
mode_c = ('x', 'y', 'z')
extent = {'x': 400, 'y': 200, 'z': 300}
a = cupy.random.random([extent[i] for i in mode_a])
b = cupy.random.random([extent[i] for i in mode_b])
c = cupy.random.random([extent[i] for i in mode_c])
a = a.astype(dtype)
b = b.astype(dtype)
c = c.astype(dtype)
desc_a = cutensor.create_tensor_descriptor(a)
desc_b = cutensor.create_tensor_descriptor(b)
desc_c = cutensor.create_tensor_descriptor(c)
alpha = 1.1
beta = 1.2
gamma = 1.3
# rehearsal
d = cutensor.elementwise_trinary(alpha, a, desc_a, mode_a,
beta, b, desc_b, mode_b,
gamma, c, desc_c, mode_c)
ev_start = stream.Event()
ev_end = stream.Event()
st = stream.Stream()
with st:
# measurement
ev_start.record()
d = cutensor.elementwise_trinary(alpha, a, desc_a, mode_a,
beta, b, desc_b, mode_b,
gamma, c, desc_c, mode_c)
ev_end.record()
st.synchronize()
elapsed_ms = stream.get_elapsed_time(ev_start, ev_end)
transfer_byte = d.size * d.itemsize
if alpha != 0.0:
transfer_byte += a.size * a.itemsize
if beta != 0.0:
transfer_byte += b.size * b.itemsize
if gamma != 0.0:
transfer_byte += c.size * c.itemsize
gbs = transfer_byte / elapsed_ms / 1e6
print('dtype: {}'.format(numpy.dtype(dtype).name))
print('time (ms): {}'.format(elapsed_ms))
print('effective memory bandwidth (GB/s): {}'.format(gbs))
|
from enum import Enum, IntEnum
from hidparser.DeviceBuilder import DeviceBuilder
# Toddo create a Enum like class that happily converts subclasses into byte arrays
from abc import ABCMeta as _ABCMeta
import struct as _struct
import copy as _copy
from array import array as _array
class ItemType(IntEnum):
MAIN = 0x00
GLOBAL = 0x04
LOCAL = 0x08
RESERVED = 0x0C
class Item(metaclass=_ABCMeta):
from abc import abstractmethod
_item_map = None
data = None # type: _array
# Abstract methods
# @abstractmethod
def visit(self, descriptor: DeviceBuilder):
pass
@classmethod
@abstractmethod
def _get_tag(cls):
pass
@classmethod
@abstractmethod
def _get_type(cls):
pass
# Concrete methods
def __init__(self, data: _array = None, long: bool = False, *args, **kwargs):
self.data = data
def __repr__(self):
return "<{}: {}>".format(self.__class__.__name__, repr(self.data))
@property
def tag(self) -> int:
"""
Gets the item tag number including the item type (bTag | bType)
:return int:
"""
return self._get_tag()
@property
def type(self) -> ItemType:
"""
Gets the tag type of the item
:return TagType:
"""
return self._get_type()
@classmethod
def _map_subclasses(cls, parent_class):
for c in parent_class.__subclasses__():
if not issubclass(c, cls):
continue
try:
key = c._get_tag()
cls._item_map[key] = c
except NotImplementedError:
cls._map_subclasses(c)
@classmethod
def create(cls, tag: int, item_type: ItemType = None, data: _array = [], long: bool = False):
if cls._item_map is None:
cls._item_map = {}
cls._map_subclasses(cls)
if long:
raise NotImplementedError("Log items are not supported by this parser yet")
if item_type is not None:
if (tag & ~0x0F) > 0:
raise ValueError("tag is not valid")
tag = (tag << 4) | item_type.value
if tag not in cls._item_map:
raise ValueError("Unknown tag {0} ({1})".format(tag, hex(tag)))
return cls._item_map[tag](data=data, long=long)
class ValueItem(Item):
value = None
def __init__(self, **kwargs):
super(ValueItem, self).__init__(**kwargs)
signed = kwargs["signed"] if "signed" in kwargs.keys() else True
if len(self.data) == 1:
self.value = _struct.unpack("<b" if signed else "<B", bytes(self.data))[0]
if len(self.data) == 2:
self.value = _struct.unpack("<h"if signed else "<H", bytes(self.data))[0]
if len(self.data) == 4:
self.value = _struct.unpack("<i" if signed else "<I", bytes(self.data))[0]
@classmethod
def _get_tag(cls):
raise NotImplementedError()
@classmethod
def _get_type(cls):
raise NotImplementedError()
def __repr__(self):
return "<{}: {}>".format(self.__class__.__name__, repr(self.value))
|
const menuadmin = (prefix, pushname) => {
return `oiin aqui e o menu dos admins
_obs para o bot executar esses comandos e nescessario dar adm para o bot_
◪ *COMANDO DOS ADMINS*
│
├─ ❏ ${prefix}opengc
├─ ❏ ${prefix}closegc
├─ ❏ ${prefix}promote
├─ ❏ ${prefix}demote
├─ ❏ ${prefix}tagall
├─ ❏ ${prefix}add
├─ ❏ ${prefix}kick
├─ ❏ ${prefix}listadmins
├─ ❏ ${prefix}linkgroup
├─ ❏ ${prefix}leave
├─ ❏ ${prefix}welcome
├─ ❏ ${prefix}nsfw
├─ ❏ ${prefix}leveling
├─ ❏ ${prefix}level
├─ ❏ ${prefix}delete
├─ ❏ ${prefix}simih
└─ ❏ ${prefix}ownergroup
`
}
exports.menuadmin = menuadmin
|
import { request } from "request";
request("https://source.unsplash.com/5760x1080/?colorful", function(
error,
response,
body
) {
if (error) {
console.log(error);
} else {
// write file to disk before calling next piece of the machinery.
}
});
|
import atexit
import datetime
import string
import difflib
import shutil
import tempfile
import secrets
from collections import defaultdict, Counter
from random import Random
import json
import re
from urllib.parse import urlparse
from io import StringIO
import hail
import hail as hl
from hail.typecheck import enumeration, typecheck, nullable
from hail.utils.java import Env, error
@typecheck(n_rows=int, n_cols=int, n_partitions=nullable(int))
def range_matrix_table(n_rows, n_cols, n_partitions=None) -> 'hail.MatrixTable':
"""Construct a matrix table with row and column indices and no entry fields.
Examples
--------
>>> range_ds = hl.utils.range_matrix_table(n_rows=100, n_cols=10)
>>> range_ds.count_rows()
100
>>> range_ds.count_cols()
10
Notes
-----
The resulting matrix table contains the following fields:
- `row_idx` (:py:data:`.tint32`) - Row index (row key).
- `col_idx` (:py:data:`.tint32`) - Column index (column key).
It contains no entry fields.
This method is meant for testing and learning, and is not optimized for
production performance.
Parameters
----------
n_rows : :obj:`int`
Number of rows.
n_cols : :obj:`int`
Number of columns.
n_partitions : int, optional
Number of partitions (uses Spark default parallelism if None).
Returns
-------
:class:`.MatrixTable`
"""
check_nonnegative_and_in_range('range_matrix_table', 'n_rows', n_rows)
check_nonnegative_and_in_range('range_matrix_table', 'n_cols', n_cols)
if n_partitions is not None:
check_positive_and_in_range('range_matrix_table', 'n_partitions', n_partitions)
return hail.MatrixTable(hail.ir.MatrixRead(hail.ir.MatrixRangeReader(n_rows, n_cols, n_partitions)))
@typecheck(n=int, n_partitions=nullable(int))
def range_table(n, n_partitions=None) -> 'hail.Table':
"""Construct a table with the row index and no other fields.
Examples
--------
>>> df = hl.utils.range_table(100)
>>> df.count()
100
Notes
-----
The resulting table contains one field:
- `idx` (:py:data:`.tint32`) - Row index (key).
This method is meant for testing and learning, and is not optimized for
production performance.
Parameters
----------
n : int
Number of rows.
n_partitions : int, optional
Number of partitions (uses Spark default parallelism if None).
Returns
-------
:class:`.Table`
"""
check_nonnegative_and_in_range('range_table', 'n', n)
if n_partitions is not None:
check_positive_and_in_range('range_table', 'n_partitions', n_partitions)
return hail.Table(hail.ir.TableRange(n, n_partitions))
def check_positive_and_in_range(caller, name, value):
if value <= 0:
raise ValueError(f"'{caller}': parameter '{name}' must be positive, found {value}")
elif value > hail.tint32.max_value:
raise ValueError(f"'{caller}': parameter '{name}' must be less than or equal to {hail.tint32.max_value}, "
f"found {value}")
def check_nonnegative_and_in_range(caller, name, value):
if value < 0:
raise ValueError(f"'{caller}': parameter '{name}' must be non-negative, found {value}")
elif value > hail.tint32.max_value:
raise ValueError(f"'{caller}': parameter '{name}' must be less than or equal to {hail.tint32.max_value}, "
f"found {value}")
def wrap_to_list(s):
if isinstance(s, list):
return s
elif isinstance(s, tuple):
return list(s)
else:
return [s]
def wrap_to_tuple(x):
if isinstance(x, tuple):
return x
else:
return x,
def wrap_to_sequence(x):
if isinstance(x, tuple):
return x
if isinstance(x, list):
return tuple(x)
else:
return x,
def get_env_or_default(maybe, envvar, default):
import os
return maybe or os.environ.get(envvar) or default
def uri_path(uri):
return urlparse(uri).path
def local_path_uri(path):
return 'file://' + path
def new_temp_file(prefix=None, extension=None):
tmpdir = Env.hc()._tmpdir
alphabet = string.ascii_letters + string.digits
token = ''.join([secrets.choice(alphabet) for _ in range(22)])
f = token
if prefix is not None:
f = f'{prefix}-{f}'
if extension is not None:
f = f'{f}.{extension}'
return f'{tmpdir}/{f}'
def new_local_temp_dir(suffix=None, prefix=None, dir=None):
local_temp_dir = tempfile.mkdtemp(suffix, prefix, dir)
atexit.register(shutil.rmtree, local_temp_dir)
return local_temp_dir
def new_local_temp_file(filename="temp"):
local_temp_dir = new_local_temp_dir()
path = local_temp_dir + "/" + filename
return path
storage_level = enumeration('NONE', 'DISK_ONLY', 'DISK_ONLY_2', 'MEMORY_ONLY',
'MEMORY_ONLY_2', 'MEMORY_ONLY_SER', 'MEMORY_ONLY_SER_2',
'MEMORY_AND_DISK', 'MEMORY_AND_DISK_2', 'MEMORY_AND_DISK_SER',
'MEMORY_AND_DISK_SER_2', 'OFF_HEAP')
def run_command(args):
import subprocess as sp
try:
sp.check_output(args, stderr=sp.STDOUT)
except sp.CalledProcessError as e:
print(e.output)
raise e
def plural(orig, n, alternate=None):
if n == 1:
return orig
elif alternate:
return alternate
else:
return orig + 's'
def get_obj_metadata(obj):
from hail.matrixtable import MatrixTable, GroupedMatrixTable
from hail.table import Table, GroupedTable
from hail.utils import Struct
from hail.expr.expressions import StructExpression, ArrayStructExpression, SetStructExpression
def table_error(index_obj):
def fmt_field(field):
assert field in index_obj._fields
inds = index_obj[field]._indices
if inds == index_obj._global_indices:
return "'{}' [globals]".format(field)
elif inds == index_obj._row_indices:
return "'{}' [row]".format(field)
elif inds == index_obj._col_indices: # Table will never get here
return "'{}' [col]".format(field)
else:
assert inds == index_obj._entry_indices
return "'{}' [entry]".format(field)
return fmt_field
def struct_error(s):
def fmt_field(field):
assert field in s._fields
return "'{}'".format(field)
return fmt_field
if isinstance(obj, MatrixTable):
return 'MatrixTable', MatrixTable, table_error(obj), True
elif isinstance(obj, GroupedMatrixTable):
return 'GroupedMatrixTable', GroupedMatrixTable, table_error(obj._parent), True
elif isinstance(obj, Table):
return 'Table', Table, table_error(obj), True
elif isinstance(obj, GroupedTable):
return 'GroupedTable', GroupedTable, table_error(obj), False
elif isinstance(obj, Struct):
return 'Struct', Struct, struct_error(obj), False
elif isinstance(obj, StructExpression):
return 'StructExpression', StructExpression, struct_error(obj), True
elif isinstance(obj, ArrayStructExpression):
return 'ArrayStructExpression', StructExpression, struct_error(obj), True
elif isinstance(obj, SetStructExpression):
return 'SetStructExpression', StructExpression, struct_error(obj), True
else:
raise NotImplementedError(obj)
def get_nice_attr_error(obj, item):
class_name, cls, handler, has_describe = get_obj_metadata(obj)
if item.startswith('_'):
# don't handle 'private' attribute access
return "{} instance has no attribute '{}'".format(class_name, item)
else:
field_names = obj._fields.keys()
field_dict = defaultdict(lambda: [])
for f in field_names:
field_dict[f.lower()].append(f)
obj_namespace = {x for x in dir(cls) if not x.startswith('_')}
inherited = {x for x in obj_namespace if x not in cls.__dict__}
methods = {x for x in obj_namespace if x in cls.__dict__ and callable(cls.__dict__[x])}
props = obj_namespace - methods - inherited
item_lower = item.lower()
field_matches = difflib.get_close_matches(item_lower, field_dict, n=5)
inherited_matches = difflib.get_close_matches(item_lower, inherited, n=5)
method_matches = difflib.get_close_matches(item_lower, methods, n=5)
prop_matches = difflib.get_close_matches(item_lower, props, n=5)
s = ["{} instance has no field, method, or property '{}'".format(class_name, item)]
if any([field_matches, method_matches, prop_matches, inherited_matches]):
s.append('\n Did you mean:')
if field_matches:
fs = []
for f in field_matches:
fs.extend(field_dict[f])
word = plural('field', len(fs))
s.append('\n Data {}: {}'.format(word, ', '.join(handler(f) for f in fs)))
if method_matches:
word = plural('method', len(method_matches))
s.append('\n {} {}: {}'.format(class_name, word,
', '.join("'{}'".format(m) for m in method_matches)))
if prop_matches:
word = plural('property', len(prop_matches), 'properties')
s.append('\n {} {}: {}'.format(class_name, word,
', '.join("'{}'".format(p) for p in prop_matches)))
if inherited_matches:
word = plural('inherited method', len(inherited_matches))
s.append('\n {} {}: {}'.format(class_name, word,
', '.join("'{}'".format(m) for m in inherited_matches)))
elif has_describe:
s.append("\n Hint: use 'describe()' to show the names of all data fields.")
return ''.join(s)
def get_nice_field_error(obj, item):
class_name, _, handler, has_describe = get_obj_metadata(obj)
field_names = obj._fields.keys()
dd = defaultdict(lambda: [])
for f in field_names:
dd[f.lower()].append(f)
item_lower = item.lower()
field_matches = difflib.get_close_matches(item_lower, dd, n=5)
s = ["{} instance has no field '{}'".format(class_name, item)]
if field_matches:
s.append('\n Did you mean:')
for f in field_matches:
for orig_f in dd[f]:
s.append("\n {}".format(handler(orig_f)))
if has_describe:
s.append("\n Hint: use 'describe()' to show the names of all data fields.")
return ''.join(s)
def check_collisions(caller, names, indices, override_protected_indices=None):
from hail.expr.expressions import ExpressionException
fields = indices.source._fields
if override_protected_indices is not None:
def invalid(e):
return e._indices in override_protected_indices
else:
def invalid(e):
return e._indices != indices
# check collisions with fields on other axes
for name in names:
if name in fields and invalid(fields[name]):
msg = f"{caller!r}: name collision with field indexed by {list(fields[name]._indices.axes)}: {name!r}"
error('Analysis exception: {}'.format(msg))
raise ExpressionException(msg)
# check duplicate fields
for k, v in Counter(names).items():
if v > 1:
from hail.expr.expressions import ExpressionException
raise ExpressionException(f"{caller!r}: selection would produce duplicate field {k!r}")
def get_key_by_exprs(caller, exprs, named_exprs, indices, override_protected_indices=None):
from hail.expr.expressions import to_expr, ExpressionException, analyze
exprs = [indices.source[e] if isinstance(e, str) else e for e in exprs]
named_exprs = {k: to_expr(v) for k, v in named_exprs.items()}
bindings = []
def is_top_level_field(e):
return e in indices.source._fields_inverse
existing_key_fields = []
final_key = []
for e in exprs:
analyze(caller, e, indices, broadcast=False)
if not e._ir.is_nested_field:
raise ExpressionException(f"{caller!r} expects keyword arguments for complex expressions\n"
f" Correct: ht = ht.key_by('x')\n"
f" Correct: ht = ht.key_by(ht.x)\n"
f" Correct: ht = ht.key_by(x = ht.x.replace(' ', '_'))\n"
f" INCORRECT: ht = ht.key_by(ht.x.replace(' ', '_'))")
name = e._ir.name
final_key.append(name)
if not is_top_level_field(e):
bindings.append((name, e))
else:
existing_key_fields.append(name)
final_key.extend(named_exprs)
bindings.extend(named_exprs.items())
check_collisions(caller, final_key, indices, override_protected_indices=override_protected_indices)
return final_key, dict(bindings)
def check_keys(caller, name, protected_key):
from hail.expr.expressions import ExpressionException
if name in protected_key:
msg = f"{caller!r}: cannot overwrite key field {name!r} with annotate, select or drop; " \
f"use key_by to modify keys."
error('Analysis exception: {}'.format(msg))
raise ExpressionException(msg)
def get_select_exprs(caller, exprs, named_exprs, indices, base_struct):
from hail.expr.expressions import to_expr, ExpressionException, analyze
exprs = [indices.source[e] if isinstance(e, str) else e for e in exprs]
named_exprs = {k: to_expr(v) for k, v in named_exprs.items()}
select_fields = indices.protected_key[:]
protected_key = set(select_fields)
insertions = {}
final_fields = select_fields[:]
def is_top_level_field(e):
return e in indices.source._fields_inverse
for e in exprs:
if not e._ir.is_nested_field:
raise ExpressionException(f"{caller!r} expects keyword arguments for complex expressions\n"
f" Correct: ht = ht.select('x')\n"
f" Correct: ht = ht.select(ht.x)\n"
f" Correct: ht = ht.select(x = ht.x.replace(' ', '_'))\n"
f" INCORRECT: ht = ht.select(ht.x.replace(' ', '_'))")
analyze(caller, e, indices, broadcast=False)
name = e._ir.name
check_keys(caller, name, protected_key)
final_fields.append(name)
if is_top_level_field(e):
select_fields.append(name)
else:
insertions[name] = e
for k, e in named_exprs.items():
check_keys(caller, k, protected_key)
final_fields.append(k)
insertions[k] = e
check_collisions(caller, final_fields, indices)
if final_fields == select_fields + list(insertions):
# don't clog the IR with redundant field names
s = base_struct.select(*select_fields).annotate(**insertions)
else:
s = base_struct.select(*select_fields)._annotate_ordered(insertions, final_fields)
assert list(s) == final_fields
return s
def check_annotate_exprs(caller, named_exprs, indices):
protected_key = set(indices.protected_key)
for k in named_exprs:
check_keys(caller, k, protected_key)
check_collisions(caller, list(named_exprs), indices)
return named_exprs
def process_joins(obj, exprs):
all_uids = []
left = obj
used_joins = set()
for e in exprs:
joins = e._ir.search(lambda a: isinstance(a, hail.ir.Join))
for j in sorted(joins, key=lambda j: j.idx): # Make sure joins happen in order
if j.idx not in used_joins:
left = j.join_func(left)
all_uids.extend(j.temp_vars)
used_joins.add(j.idx)
def cleanup(table):
remaining_uids = [uid for uid in all_uids if uid in table._fields]
return table.drop(*remaining_uids)
return left, cleanup
def divide_null(num, denom):
from hail.expr.expressions.base_expression import unify_types_limited
from hail.expr import null, cond
typ = unify_types_limited(num.dtype, denom.dtype)
assert typ is not None
return cond(denom != 0, num / denom, null(typ))
class HailSeedGenerator(object):
def __init__(self, seed):
self.seed = seed
self.generator = Random(seed)
def set_seed(self, seed):
self.__init__(seed)
def next_seed(self):
return self.generator.randint(0, (1 << 63) - 1)
def timestamp_path(base, suffix=''):
return ''.join([base,
'-',
datetime.datetime.now().strftime("%Y%m%d-%H%M"),
suffix])
def upper_hex(n, num_digits=None):
if num_digits is None:
return "{0:X}".format(n)
else:
return "{0:0{1}X}".format(n, num_digits)
def escape_str(s, backticked=False):
sb = StringIO()
rewrite_dict = {
'\b': '\\b',
'\n': '\\n',
'\t': '\\t',
'\f': '\\f',
'\r': '\\r'
}
for ch in s:
chNum = ord(ch)
if chNum > 0x7f:
sb.write("\\u" + upper_hex(chNum, 4))
elif chNum < 32:
if ch in rewrite_dict:
sb.write(rewrite_dict[ch])
else:
if chNum > 0xf:
sb.write("\\u00" + upper_hex(chNum))
else:
sb.write("\\u000" + upper_hex(chNum))
else:
if ch == '"':
if backticked:
sb.write('"')
else:
sb.write('\\\"')
elif ch == '`':
if backticked:
sb.write("\\`")
else:
sb.write("`")
elif ch == '\\':
sb.write('\\\\')
else:
sb.write(ch)
escaped = sb.getvalue()
sb.close()
return escaped
def escape_id(s):
if re.fullmatch(r'[_a-zA-Z]\w*', s):
return s
else:
return "`{}`".format(escape_str(s, backticked=True))
def dump_json(obj):
return f'"{escape_str(json.dumps(obj))}"'
def parsable_strings(strs):
strs = ' '.join(f'"{escape_str(s)}"' for s in strs)
return f"({strs})"
def _dumps_partitions(partitions, row_key_type):
parts_type = partitions.dtype
if not (isinstance(parts_type, hl.tarray)
and isinstance(parts_type.element_type, hl.tinterval)):
raise ValueError(f'partitions type invalid: {parts_type} must be array of intervals')
point_type = parts_type.element_type.point_type
f1, t1 = next(iter(row_key_type.items()))
if point_type == t1:
partitions = hl.map(lambda x: hl.interval(
start=hl.struct(**{f1: x.start}),
end=hl.struct(**{f1: x.end}),
includes_start=x.includes_start,
includes_end=x.includes_end),
partitions)
else:
if not isinstance(point_type, hl.tstruct):
raise ValueError(f'partitions has wrong type: {point_type} must be struct or type of first row key field')
if not point_type._is_prefix_of(row_key_type):
raise ValueError(f'partitions type invalid: {point_type} must be prefix of {row_key_type}')
s = json.dumps(partitions.dtype._convert_to_json(hl.eval(partitions)))
return s, partitions.dtype
def default_handler():
try:
from IPython.display import display
return display
except ImportError:
return print
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M21 7v10.88l2 2V5h-9.58l3.29-3.3L16 1l-4 4-4-4-.7.7L10.58 5H8.12l2 2zM2.41 2.13l-.14.14L1 3.54l1.53 1.53H1V21h17.46l1.99 1.99 1.26-1.26.15-.15L2.41 2.13zM3 19V7h1.46l12 12H3z" />
, 'TvOffSharp');
|
import os
import shutil
import time
from .base import PluginBase
class BatteryPlugin(PluginBase):
def configure(self):
defaults = {
'path': '/',
'cache_time': '1',
'format': '{status}'
}
self.sysfs_path = "/sys/class/power_supply"
self.last_charge = 0
self.last_time = time.time() - 21
self.time_rem = ''
self.prev_status = 'Unknown'
self.start_time = time.time()
self.get_battery_data()
return defaults
def get_battery_data(self):
data = self.read_file(os.path.join(self.sysfs_path, 'BAT0', 'uevent'))
batinfo = {}
for line in data.split("\n"):
try:
line_l = line.strip().split("=")
batinfo[line_l[0]] = line_l[1]
except:
pass
batinfo_h = {
'status': batinfo['POWER_SUPPLY_STATUS'],
'charge': int(batinfo['POWER_SUPPLY_ENERGY_NOW']),
'full': int(batinfo['POWER_SUPPLY_ENERGY_FULL']),
'time_rem': '',
'percent': 0,
}
if batinfo_h['status'] == 'Charging':
batinfo_h['charge_indicator'] = "🗲"
else:
batinfo_h['charge_indicator'] = ""
batinfo_h['percent'] = int((batinfo_h['charge']/batinfo_h['full']) * 100)
check_time = (batinfo_h['status'] != 'Unknown')
if check_time and (time.time() - self.last_time > 10):
check_time = True
else:
check_time = False
if batinfo_h['status'] != self.prev_status:
check_time = True
if (time.time() - self.start_time) < 5:
check_time = True
self.prev_status = batinfo_h['status']
if check_time:
try:
delta_c = batinfo_h['charge'] - self.last_charge
delta_t = time.time() - self.last_time
charge_left = batinfo_h['full'] - batinfo_h['charge']
time_left = int(charge_left * (delta_t/delta_c))
self.last_charge = batinfo_h['charge']
self.last_time = time.time()
m, s = divmod(time_left, 60)
h, m = divmod(m, 60)
batinfo_h['time_rem'] = "%dh %02dm" % (abs(h), m)
self.time_rem = batinfo_h['time_rem']
except:
pass
else:
batinfo_h['time_rem'] = self.time_rem
return batinfo_h
def update(self):
try:
data = self.get_battery_data()
status = data['status']
locals().update(data)
self.set_text(self.config['format'] % locals())
except Exception as e:
self.set_text(str(e))
|
# -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/CoverageEligibilityRequest
Release: R5
Version: 4.5.0
Build ID: 0d95498
Last updated: 2021-04-03T00:34:11.075+00:00
"""
from pydantic.validators import bytes_validator # noqa: F401
from fhir.resources import fhirtypes # noqa: F401
from fhir.resources import coverageeligibilityrequest
def impl_coverageeligibilityrequest_1(inst):
assert inst.created == fhirtypes.DateTime.validate("2014-08-16")
assert inst.id == "52345"
assert (
inst.identifier[0].system == "http://happyvalley.com/coverageelegibilityrequest"
)
assert inst.identifier[0].value == "52345"
assert inst.insurance[0].coverage.reference == "Coverage/9876B1"
assert inst.insurance[0].focal is True
assert inst.insurer.reference == "Organization/2"
assert inst.meta.tag[0].code == "HTEST"
assert inst.meta.tag[0].display == "test health data"
assert (
inst.meta.tag[0].system == "http://terminology.hl7.org/CodeSystem/v3-ActReason"
)
assert inst.patient.reference == "Patient/pat1"
assert inst.priority.coding[0].code == "normal"
assert inst.provider.reference == "Organization/1"
assert inst.purpose[0] == "validation"
assert inst.status == "active"
assert inst.text.div == (
'<div xmlns="http://www.w3.org/1999/xhtml">A human-readable'
" rendering of the CoverageEligibilityRequest</div>"
)
assert inst.text.status == "generated"
def test_coverageeligibilityrequest_1(base_settings):
"""No. 1 tests collection for CoverageEligibilityRequest.
Test File: coverageeligibilityrequest-example.json
"""
filename = (
base_settings["unittest_data_dir"] / "coverageeligibilityrequest-example.json"
)
inst = coverageeligibilityrequest.CoverageEligibilityRequest.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "CoverageEligibilityRequest" == inst.resource_type
impl_coverageeligibilityrequest_1(inst)
# testing reverse by generating data from itself and create again.
data = inst.dict()
assert "CoverageEligibilityRequest" == data["resourceType"]
inst2 = coverageeligibilityrequest.CoverageEligibilityRequest(**data)
impl_coverageeligibilityrequest_1(inst2)
def impl_coverageeligibilityrequest_2(inst):
assert inst.created == fhirtypes.DateTime.validate("2014-08-16")
assert inst.enterer.identifier.system == "http://happyvalleyclinic.com/staff"
assert inst.enterer.identifier.value == "14"
assert inst.facility.identifier.system == "http://statecliniclicensor.com/clinicid"
assert inst.facility.identifier.value == "G35B9"
assert inst.id == "52346"
assert (
inst.identifier[0].system == "http://happyvalley.com/coverageelegibilityrequest"
)
assert inst.identifier[0].value == "52346"
assert inst.insurance[0].businessArrangement == "NB8742"
assert inst.insurance[0].coverage.reference == "Coverage/9876B1"
assert inst.insurer.reference == "Organization/2"
assert inst.item[0].category.coding[0].code == "69"
assert inst.item[0].category.coding[0].display == "Maternity"
assert (
inst.item[0].category.coding[0].system
== "http://terminology.hl7.org/CodeSystem/ex-benefitcategory"
)
assert inst.meta.tag[0].code == "HTEST"
assert inst.meta.tag[0].display == "test health data"
assert (
inst.meta.tag[0].system == "http://terminology.hl7.org/CodeSystem/v3-ActReason"
)
assert inst.patient.reference == "Patient/pat1"
assert inst.priority.coding[0].code == "normal"
assert inst.provider.reference == "Organization/1"
assert inst.purpose[0] == "validation"
assert inst.purpose[1] == "benefits"
assert inst.servicedDate == fhirtypes.Date.validate("2014-09-17")
assert inst.status == "active"
assert inst.text.div == (
'<div xmlns="http://www.w3.org/1999/xhtml">A human-readable'
" rendering of the CoverageEligibilityRequest</div>"
)
assert inst.text.status == "generated"
def test_coverageeligibilityrequest_2(base_settings):
"""No. 2 tests collection for CoverageEligibilityRequest.
Test File: coverageeligibilityrequest-example-2.json
"""
filename = (
base_settings["unittest_data_dir"] / "coverageeligibilityrequest-example-2.json"
)
inst = coverageeligibilityrequest.CoverageEligibilityRequest.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "CoverageEligibilityRequest" == inst.resource_type
impl_coverageeligibilityrequest_2(inst)
# testing reverse by generating data from itself and create again.
data = inst.dict()
assert "CoverageEligibilityRequest" == data["resourceType"]
inst2 = coverageeligibilityrequest.CoverageEligibilityRequest(**data)
impl_coverageeligibilityrequest_2(inst2)
|
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) {{ cookiecutter.author_name }}.
# Distributed under the terms of the Modified BSD License.
from ..example import example_function
import pytest
import matplotlib.pyplot as plt
import numpy as np
@pytest.mark.mpl_image_compare(filename="test_example.png")
def test_example():
fig, ax = plt.subplots()
# data = np.hstack([np.linspace(-10, 10)[:, None], np.linspace(10, -10)[:, None]])
example_function(ax, data, above_color='b', below_color='g')
return fig
|
__report = {"info":{"file":"libs/beez-mvcr/s/beez-mvcr/view.js","fileShort":"libs/beez-mvcr/s/beez-mvcr/view.js","fileSafe":"libs_beez_mvcr_s_beez_mvcr_view_js","link":"files/libs_beez_mvcr_s_beez_mvcr_view_js/index.html"},"complexity":{"aggregate":{"line":7,"complexity":{"sloc":{"physical":959,"logical":304},"cyclomatic":48,"halstead":{"operators":{"distinct":27,"total":780,"identifiers":["__stripped__"]},"operands":{"distinct":177,"total":940,"identifiers":["__stripped__"]},"length":1720,"vocabulary":204,"difficulty":71.69491525423729,"volume":13196.571588190971,"effort":946127.0816618273,"bugs":4.398857196063657,"time":52562.61564787929},"params":68}},"functions":[{"name":"<anonymous>","line":7,"complexity":{"sloc":{"physical":959,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":2,"total":2,"identifiers":["__stripped__"]},"operands":{"distinct":3,"total":3,"identifiers":["__stripped__"]},"length":5,"vocabulary":5,"difficulty":1,"volume":11.60964047443681,"effort":11.60964047443681,"bugs":0.0038698801581456034,"time":0.6449800263576005},"params":1}},{"name":"__View__","line":8,"complexity":{"sloc":{"physical":957,"logical":55},"cyclomatic":1,"halstead":{"operators":{"distinct":8,"total":127,"identifiers":["__stripped__"]},"operands":{"distinct":61,"total":145,"identifiers":["__stripped__"]},"length":272,"vocabulary":69,"difficulty":9.508196721311476,"volume":1661.5186522436622,"effort":15798.046201661053,"bugs":0.5538395507478874,"time":877.669233425614},"params":3}},{"name":"initialize","line":33,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":2,"total":2,"identifiers":["__stripped__"]},"operands":{"distinct":2,"total":4,"identifiers":["__stripped__"]},"length":6,"vocabulary":4,"difficulty":2,"volume":12,"effort":24,"bugs":0.004,"time":1.3333333333333333},"params":1}},{"name":"root","line":45,"complexity":{"sloc":{"physical":6,"logical":2},"cyclomatic":1,"halstead":{"operators":{"distinct":6,"total":6,"identifiers":["__stripped__"]},"operands":{"distinct":5,"total":6,"identifiers":["__stripped__"]},"length":12,"vocabulary":11,"difficulty":3.5999999999999996,"volume":41.51317942364757,"effort":149.44744592513123,"bugs":0.01383772647454919,"time":8.302635884729513},"params":1}},{"name":"<anonymous>","line":47,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":3,"total":4,"identifiers":["__stripped__"]},"operands":{"distinct":3,"total":4,"identifiers":["__stripped__"]},"length":8,"vocabulary":6,"difficulty":2,"volume":20.67970000576925,"effort":41.3594000115385,"bugs":0.006893233335256416,"time":2.2977444450854723},"params":0}},{"name":"create","line":62,"complexity":{"sloc":{"physical":8,"logical":2},"cyclomatic":1,"halstead":{"operators":{"distinct":6,"total":6,"identifiers":["__stripped__"]},"operands":{"distinct":7,"total":8,"identifiers":["__stripped__"]},"length":14,"vocabulary":13,"difficulty":3.4285714285714284,"volume":51.80615605397529,"effort":177.62110647077242,"bugs":0.01726871868465843,"time":9.867839248376246},"params":3}},{"name":"<anonymous>","line":64,"complexity":{"sloc":{"physical":5,"logical":3},"cyclomatic":2,"halstead":{"operators":{"distinct":6,"total":12,"identifiers":["__stripped__"]},"operands":{"distinct":11,"total":15,"identifiers":["__stripped__"]},"length":27,"vocabulary":17,"difficulty":4.090909090909091,"volume":110.36149671375918,"effort":451.4788501926512,"bugs":0.03678716557125306,"time":25.082158344036177},"params":0}},{"name":"child","line":80,"complexity":{"sloc":{"physical":9,"logical":2},"cyclomatic":1,"halstead":{"operators":{"distinct":6,"total":6,"identifiers":["__stripped__"]},"operands":{"distinct":6,"total":7,"identifiers":["__stripped__"]},"length":13,"vocabulary":12,"difficulty":3.5,"volume":46.604512509375034,"effort":163.11579378281263,"bugs":0.015534837503125011,"time":9.06198854348959},"params":2}},{"name":"<anonymous>","line":82,"complexity":{"sloc":{"physical":6,"logical":4},"cyclomatic":2,"halstead":{"operators":{"distinct":6,"total":16,"identifiers":["__stripped__"]},"operands":{"distinct":12,"total":21,"identifiers":["__stripped__"]},"length":37,"vocabulary":18,"difficulty":5.25,"volume":154.28722505336555,"effort":810.0079315301691,"bugs":0.05142907501778852,"time":45.00044064056495},"params":1}},{"name":"parent","line":97,"complexity":{"sloc":{"physical":11,"logical":2},"cyclomatic":1,"halstead":{"operators":{"distinct":6,"total":6,"identifiers":["__stripped__"]},"operands":{"distinct":4,"total":5,"identifiers":["__stripped__"]},"length":11,"vocabulary":10,"difficulty":3.75,"volume":36.541209043760986,"effort":137.0295339141037,"bugs":0.012180403014586996,"time":7.6127518841168715},"params":0}},{"name":"<anonymous>","line":99,"complexity":{"sloc":{"physical":8,"logical":5},"cyclomatic":2,"halstead":{"operators":{"distinct":9,"total":12,"identifiers":["__stripped__"]},"operands":{"distinct":8,"total":14,"identifiers":["__stripped__"]},"length":26,"vocabulary":17,"difficulty":7.875,"volume":106.27403387250884,"effort":836.9080167460071,"bugs":0.03542467795750295,"time":46.494889819222614},"params":1}},{"name":"bro","line":117,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":3,"total":5,"identifiers":["__stripped__"]},"operands":{"distinct":5,"total":7,"identifiers":["__stripped__"]},"length":12,"vocabulary":8,"difficulty":2.0999999999999996,"volume":36,"effort":75.6,"bugs":0.012,"time":4.199999999999999},"params":2}},{"name":"dispose","line":127,"complexity":{"sloc":{"physical":6,"logical":4},"cyclomatic":1,"halstead":{"operators":{"distinct":3,"total":10,"identifiers":["__stripped__"]},"operands":{"distinct":9,"total":12,"identifiers":["__stripped__"]},"length":22,"vocabulary":12,"difficulty":2,"volume":78.86917501586544,"effort":157.73835003173087,"bugs":0.026289725005288478,"time":8.763241668429494},"params":0}},{"name":"initialize","line":153,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":2,"total":4,"identifiers":["__stripped__"]},"operands":{"distinct":6,"total":6,"identifiers":["__stripped__"]},"length":10,"vocabulary":8,"difficulty":1,"volume":30,"effort":30,"bugs":0.01,"time":1.6666666666666667},"params":0}},{"name":"async","line":164,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":2,"total":2,"identifiers":["__stripped__"]},"operands":{"distinct":2,"total":2,"identifiers":["__stripped__"]},"length":4,"vocabulary":4,"difficulty":1,"volume":8,"effort":8,"bugs":0.0026666666666666666,"time":0.4444444444444444},"params":0}},{"name":"root","line":176,"complexity":{"sloc":{"physical":24,"logical":15},"cyclomatic":4,"halstead":{"operators":{"distinct":13,"total":41,"identifiers":["__stripped__"]},"operands":{"distinct":21,"total":47,"identifiers":["__stripped__"]},"length":88,"vocabulary":34,"difficulty":14.547619047619047,"volume":447.6967300300299,"effort":6512.921477341626,"bugs":0.1492322433433433,"time":361.82897096342367},"params":1}},{"name":"DummyRootView","line":177,"complexity":{"sloc":{"physical":1,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":2,"total":2,"identifiers":["__stripped__"]},"operands":{"distinct":3,"total":3,"identifiers":["__stripped__"]},"length":5,"vocabulary":5,"difficulty":1,"volume":11.60964047443681,"effort":11.60964047443681,"bugs":0.0038698801581456034,"time":0.6449800263576005},"params":0}},{"name":"create","line":212,"complexity":{"sloc":{"physical":24,"logical":11},"cyclomatic":7,"halstead":{"operators":{"distinct":13,"total":47,"identifiers":["__stripped__"]},"operands":{"distinct":21,"total":49,"identifiers":["__stripped__"]},"length":96,"vocabulary":34,"difficulty":15.166666666666668,"volume":488.39643276003267,"effort":7407.345896860496,"bugs":0.1627988109200109,"time":411.5192164922498},"params":3}},{"name":"_createObj","line":244,"complexity":{"sloc":{"physical":8,"logical":5},"cyclomatic":2,"halstead":{"operators":{"distinct":10,"total":14,"identifiers":["__stripped__"]},"operands":{"distinct":10,"total":19,"identifiers":["__stripped__"]},"length":33,"vocabulary":20,"difficulty":9.5,"volume":142.62362713128297,"effort":1354.9244577471882,"bugs":0.04754120904376099,"time":75.2735809859549},"params":3}},{"name":"_createArray","line":261,"complexity":{"sloc":{"physical":23,"logical":8},"cyclomatic":2,"halstead":{"operators":{"distinct":10,"total":21,"identifiers":["__stripped__"]},"operands":{"distinct":11,"total":28,"identifiers":["__stripped__"]},"length":49,"vocabulary":21,"difficulty":12.727272727272727,"volume":215.22355371615927,"effort":2739.2088654783906,"bugs":0.07174118457205308,"time":152.17827030435504},"params":3}},{"name":"<anonymous>","line":269,"complexity":{"sloc":{"physical":5,"logical":3},"cyclomatic":2,"halstead":{"operators":{"distinct":6,"total":9,"identifiers":["__stripped__"]},"operands":{"distinct":9,"total":14,"identifiers":["__stripped__"]},"length":23,"vocabulary":15,"difficulty":4.666666666666667,"volume":89.85848369899593,"effort":419.33959059531435,"bugs":0.02995282789966531,"time":23.29664392196191},"params":2}},{"name":"<anonymous>","line":275,"complexity":{"sloc":{"physical":5,"logical":2},"cyclomatic":2,"halstead":{"operators":{"distinct":7,"total":8,"identifiers":["__stripped__"]},"operands":{"distinct":6,"total":8,"identifiers":["__stripped__"]},"length":16,"vocabulary":13,"difficulty":4.666666666666666,"volume":59.207035490257475,"effort":276.29949895453484,"bugs":0.019735678496752493,"time":15.349972164140825},"params":1}},{"name":"remove","line":293,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":2,"total":4,"identifiers":["__stripped__"]},"operands":{"distinct":7,"total":7,"identifiers":["__stripped__"]},"length":11,"vocabulary":9,"difficulty":1,"volume":34.86917501586544,"effort":34.86917501586544,"bugs":0.011623058338621813,"time":1.937176389770302},"params":1}},{"name":"dispose","line":303,"complexity":{"sloc":{"physical":11,"logical":4},"cyclomatic":1,"halstead":{"operators":{"distinct":5,"total":16,"identifiers":["__stripped__"]},"operands":{"distinct":17,"total":21,"identifiers":["__stripped__"]},"length":37,"vocabulary":22,"difficulty":3.088235294117647,"volume":164.99896988958,"effort":509.5556423060559,"bugs":0.05499965662986,"time":28.308646794780884},"params":0}},{"name":"<anonymous>","line":308,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":2,"total":2,"identifiers":["__stripped__"]},"operands":{"distinct":2,"total":3,"identifiers":["__stripped__"]},"length":5,"vocabulary":4,"difficulty":1.5,"volume":10,"effort":15,"bugs":0.0033333333333333335,"time":0.8333333333333334},"params":1}},{"name":"initialize","line":336,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":2,"total":2,"identifiers":["__stripped__"]},"operands":{"distinct":3,"total":4,"identifiers":["__stripped__"]},"length":6,"vocabulary":5,"difficulty":1.3333333333333333,"volume":13.931568569324174,"effort":18.575424759098897,"bugs":0.004643856189774725,"time":1.0319680421721609},"params":1}},{"name":"_render","line":348,"complexity":{"sloc":{"physical":129,"logical":9},"cyclomatic":3,"halstead":{"operators":{"distinct":6,"total":27,"identifiers":["__stripped__"]},"operands":{"distinct":12,"total":26,"identifiers":["__stripped__"]},"length":53,"vocabulary":18,"difficulty":6.5,"volume":221.00602507644254,"effort":1436.5391629968765,"bugs":0.07366867502548084,"time":79.80773127760425},"params":1}},{"name":"<anonymous>","line":351,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":1,"total":1,"identifiers":["__stripped__"]},"operands":{"distinct":1,"total":1,"identifiers":["__stripped__"]},"length":2,"vocabulary":2,"difficulty":0.5,"volume":2,"effort":1,"bugs":0.0006666666666666666,"time":0.05555555555555555},"params":0}},{"name":"beforeOnce","line":357,"complexity":{"sloc":{"physical":21,"logical":10},"cyclomatic":3,"halstead":{"operators":{"distinct":7,"total":21,"identifiers":["__stripped__"]},"operands":{"distinct":15,"total":28,"identifiers":["__stripped__"]},"length":49,"vocabulary":22,"difficulty":6.533333333333333,"volume":218.51214931322758,"effort":1427.6127088464202,"bugs":0.0728373831044092,"time":79.31181715813446},"params":2}},{"name":"wrappedDone","line":366,"complexity":{"sloc":{"physical":4,"logical":2},"cyclomatic":1,"halstead":{"operators":{"distinct":3,"total":4,"identifiers":["__stripped__"]},"operands":{"distinct":6,"total":7,"identifiers":["__stripped__"]},"length":11,"vocabulary":9,"difficulty":1.75,"volume":34.86917501586544,"effort":61.021056277764515,"bugs":0.011623058338621813,"time":3.3900586820980285},"params":0}},{"name":"before","line":382,"complexity":{"sloc":{"physical":19,"logical":9},"cyclomatic":3,"halstead":{"operators":{"distinct":6,"total":18,"identifiers":["__stripped__"]},"operands":{"distinct":12,"total":24,"identifiers":["__stripped__"]},"length":42,"vocabulary":18,"difficulty":6,"volume":175.1368500605771,"effort":1050.8211003634626,"bugs":0.05837895002019237,"time":58.37895002019237},"params":2}},{"name":"wrappedDone","line":391,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":1,"total":1,"identifiers":["__stripped__"]},"operands":{"distinct":3,"total":3,"identifiers":["__stripped__"]},"length":4,"vocabulary":4,"difficulty":0.5,"volume":8,"effort":4,"bugs":0.0026666666666666666,"time":0.2222222222222222},"params":0}},{"name":"render","line":404,"complexity":{"sloc":{"physical":20,"logical":10},"cyclomatic":3,"halstead":{"operators":{"distinct":6,"total":19,"identifiers":["__stripped__"]},"operands":{"distinct":12,"total":24,"identifiers":["__stripped__"]},"length":43,"vocabulary":18,"difficulty":6,"volume":179.30677506201943,"effort":1075.8406503721167,"bugs":0.059768925020673144,"time":59.76892502067315},"params":2}},{"name":"wrappedDone","line":413,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":1,"total":1,"identifiers":["__stripped__"]},"operands":{"distinct":3,"total":3,"identifiers":["__stripped__"]},"length":4,"vocabulary":4,"difficulty":0.5,"volume":8,"effort":4,"bugs":0.0026666666666666666,"time":0.2222222222222222},"params":0}},{"name":"after","line":426,"complexity":{"sloc":{"physical":20,"logical":10},"cyclomatic":3,"halstead":{"operators":{"distinct":6,"total":19,"identifiers":["__stripped__"]},"operands":{"distinct":12,"total":24,"identifiers":["__stripped__"]},"length":43,"vocabulary":18,"difficulty":6,"volume":179.30677506201943,"effort":1075.8406503721167,"bugs":0.059768925020673144,"time":59.76892502067315},"params":2}},{"name":"wrappedDone","line":435,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":1,"total":1,"identifiers":["__stripped__"]},"operands":{"distinct":3,"total":3,"identifiers":["__stripped__"]},"length":4,"vocabulary":4,"difficulty":0.5,"volume":8,"effort":4,"bugs":0.0026666666666666666,"time":0.2222222222222222},"params":0}},{"name":"afterOnce","line":450,"complexity":{"sloc":{"physical":23,"logical":11},"cyclomatic":3,"halstead":{"operators":{"distinct":7,"total":22,"identifiers":["__stripped__"]},"operands":{"distinct":15,"total":28,"identifiers":["__stripped__"]},"length":50,"vocabulary":22,"difficulty":6.533333333333333,"volume":222.97158093186488,"effort":1456.747662088184,"bugs":0.07432386031062163,"time":80.93042567156577},"params":2}},{"name":"wrappedDone","line":459,"complexity":{"sloc":{"physical":4,"logical":2},"cyclomatic":1,"halstead":{"operators":{"distinct":3,"total":4,"identifiers":["__stripped__"]},"operands":{"distinct":6,"total":7,"identifiers":["__stripped__"]},"length":11,"vocabulary":9,"difficulty":1.75,"volume":34.86917501586544,"effort":61.021056277764515,"bugs":0.011623058338621813,"time":3.3900586820980285},"params":0}},{"name":"_remove","line":487,"complexity":{"sloc":{"physical":7,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":4,"total":4,"identifiers":["__stripped__"]},"operands":{"distinct":4,"total":4,"identifiers":["__stripped__"]},"length":8,"vocabulary":8,"difficulty":2,"volume":24,"effort":48,"bugs":0.008,"time":2.6666666666666665},"params":1}},{"name":"<anonymous>","line":489,"complexity":{"sloc":{"physical":4,"logical":2},"cyclomatic":1,"halstead":{"operators":{"distinct":3,"total":3,"identifiers":["__stripped__"]},"operands":{"distinct":2,"total":3,"identifiers":["__stripped__"]},"length":6,"vocabulary":5,"difficulty":2.25,"volume":13.931568569324174,"effort":31.34602928097939,"bugs":0.004643856189774725,"time":1.7414460711655217},"params":0}},{"name":"show","line":510,"complexity":{"sloc":{"physical":6,"logical":3},"cyclomatic":2,"halstead":{"operators":{"distinct":7,"total":10,"identifiers":["__stripped__"]},"operands":{"distinct":7,"total":11,"identifiers":["__stripped__"]},"length":21,"vocabulary":14,"difficulty":5.5,"volume":79.95445336320968,"effort":439.74949349765325,"bugs":0.026651484454403226,"time":24.430527416536293},"params":1}},{"name":"_show","line":533,"complexity":{"sloc":{"physical":60,"logical":15},"cyclomatic":5,"halstead":{"operators":{"distinct":10,"total":34,"identifiers":["__stripped__"]},"operands":{"distinct":22,"total":40,"identifiers":["__stripped__"]},"length":74,"vocabulary":32,"difficulty":9.09090909090909,"volume":370,"effort":3363.636363636363,"bugs":0.12333333333333334,"time":186.86868686868684},"params":2}},{"name":"<anonymous>","line":547,"complexity":{"sloc":{"physical":10,"logical":5},"cyclomatic":3,"halstead":{"operators":{"distinct":6,"total":12,"identifiers":["__stripped__"]},"operands":{"distinct":5,"total":13,"identifiers":["__stripped__"]},"length":25,"vocabulary":11,"difficulty":7.800000000000001,"volume":86.48579046593244,"effort":674.5891656342731,"bugs":0.02882859682197748,"time":37.477175868570725},"params":2}},{"name":"makeTask","line":561,"complexity":{"sloc":{"physical":10,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":2,"total":2,"identifiers":["__stripped__"]},"operands":{"distinct":2,"total":2,"identifiers":["__stripped__"]},"length":4,"vocabulary":4,"difficulty":1,"volume":8,"effort":8,"bugs":0.0026666666666666666,"time":0.4444444444444444},"params":1}},{"name":"task","line":562,"complexity":{"sloc":{"physical":8,"logical":3},"cyclomatic":2,"halstead":{"operators":{"distinct":6,"total":8,"identifiers":["__stripped__"]},"operands":{"distinct":9,"total":11,"identifiers":["__stripped__"]},"length":19,"vocabulary":15,"difficulty":3.666666666666667,"volume":74.23092131656186,"effort":272.1800448273935,"bugs":0.024743640438853954,"time":15.121113601521861},"params":3}},{"name":"<anonymous>","line":566,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":1,"total":1,"identifiers":["__stripped__"]},"operands":{"distinct":4,"total":5,"identifiers":["__stripped__"]},"length":6,"vocabulary":5,"difficulty":0.625,"volume":13.931568569324174,"effort":8.707230355827608,"bugs":0.004643856189774725,"time":0.48373501976820044},"params":2}},{"name":"renderC","line":577,"complexity":{"sloc":{"physical":12,"logical":7},"cyclomatic":3,"halstead":{"operators":{"distinct":9,"total":20,"identifiers":["__stripped__"]},"operands":{"distinct":11,"total":21,"identifiers":["__stripped__"]},"length":41,"vocabulary":20,"difficulty":8.590909090909092,"volume":177.19905189038187,"effort":1522.3009457855535,"bugs":0.05906635063012729,"time":84.57227476586408},"params":2}},{"name":"hide","line":609,"complexity":{"sloc":{"physical":6,"logical":3},"cyclomatic":2,"halstead":{"operators":{"distinct":7,"total":10,"identifiers":["__stripped__"]},"operands":{"distinct":7,"total":11,"identifiers":["__stripped__"]},"length":21,"vocabulary":14,"difficulty":5.5,"volume":79.95445336320968,"effort":439.74949349765325,"bugs":0.026651484454403226,"time":24.430527416536293},"params":1}},{"name":"_hide","line":631,"complexity":{"sloc":{"physical":44,"logical":12},"cyclomatic":4,"halstead":{"operators":{"distinct":10,"total":27,"identifiers":["__stripped__"]},"operands":{"distinct":19,"total":32,"identifiers":["__stripped__"]},"length":59,"vocabulary":29,"difficulty":8.421052631578947,"volume":286.6208787125268,"effort":2413.649504947594,"bugs":0.0955402929041756,"time":134.09163916375522},"params":2}},{"name":"makeTask","line":645,"complexity":{"sloc":{"physical":10,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":2,"total":2,"identifiers":["__stripped__"]},"operands":{"distinct":2,"total":2,"identifiers":["__stripped__"]},"length":4,"vocabulary":4,"difficulty":1,"volume":8,"effort":8,"bugs":0.0026666666666666666,"time":0.4444444444444444},"params":1}},{"name":"task","line":646,"complexity":{"sloc":{"physical":8,"logical":3},"cyclomatic":2,"halstead":{"operators":{"distinct":6,"total":8,"identifiers":["__stripped__"]},"operands":{"distinct":9,"total":11,"identifiers":["__stripped__"]},"length":19,"vocabulary":15,"difficulty":3.666666666666667,"volume":74.23092131656186,"effort":272.1800448273935,"bugs":0.024743640438853954,"time":15.121113601521861},"params":3}},{"name":"<anonymous>","line":650,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":1,"total":1,"identifiers":["__stripped__"]},"operands":{"distinct":4,"total":5,"identifiers":["__stripped__"]},"length":6,"vocabulary":5,"difficulty":0.625,"volume":13.931568569324174,"effort":8.707230355827608,"bugs":0.004643856189774725,"time":0.48373501976820044},"params":2}},{"name":"hideC","line":660,"complexity":{"sloc":{"physical":11,"logical":7},"cyclomatic":3,"halstead":{"operators":{"distinct":9,"total":20,"identifiers":["__stripped__"]},"operands":{"distinct":11,"total":21,"identifiers":["__stripped__"]},"length":41,"vocabulary":20,"difficulty":8.590909090909092,"volume":177.19905189038187,"effort":1522.3009457855535,"bugs":0.05906635063012729,"time":84.57227476586408},"params":2}},{"name":"dispopse","line":682,"complexity":{"sloc":{"physical":4,"logical":2},"cyclomatic":1,"halstead":{"operators":{"distinct":3,"total":6,"identifiers":["__stripped__"]},"operands":{"distinct":7,"total":8,"identifiers":["__stripped__"]},"length":14,"vocabulary":10,"difficulty":1.7142857142857142,"volume":46.50699332842308,"effort":79.7262742772967,"bugs":0.01550233110947436,"time":4.4292374598498165},"params":0}},{"name":"constructor","line":710,"complexity":{"sloc":{"physical":27,"logical":8},"cyclomatic":2,"halstead":{"operators":{"distinct":9,"total":24,"identifiers":["__stripped__"]},"operands":{"distinct":24,"total":31,"identifiers":["__stripped__"]},"length":55,"vocabulary":33,"difficulty":5.8125,"volume":277.44167656471495,"effort":1612.6297450324057,"bugs":0.09248055885490498,"time":89.59054139068921},"params":0}},{"name":"initialize","line":745,"complexity":{"sloc":{"physical":4,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":2,"total":4,"identifiers":["__stripped__"]},"operands":{"distinct":6,"total":6,"identifiers":["__stripped__"]},"length":10,"vocabulary":8,"difficulty":1,"volume":30,"effort":30,"bugs":0.01,"time":1.6666666666666667},"params":0}},{"name":"async","line":856,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":2,"total":2,"identifiers":["__stripped__"]},"operands":{"distinct":2,"total":2,"identifiers":["__stripped__"]},"length":4,"vocabulary":4,"difficulty":1,"volume":8,"effort":8,"bugs":0.0026666666666666666,"time":0.4444444444444444},"params":0}},{"name":"isRendered","line":868,"complexity":{"sloc":{"physical":3,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":4,"total":9,"identifiers":["__stripped__"]},"operands":{"distinct":3,"total":5,"identifiers":["__stripped__"]},"length":14,"vocabulary":7,"difficulty":3.3333333333333335,"volume":39.302968908806456,"effort":131.00989636268818,"bugs":0.01310098963626882,"time":7.278327575704899},"params":0}},{"name":"setVisible","line":881,"complexity":{"sloc":{"physical":7,"logical":4},"cyclomatic":2,"halstead":{"operators":{"distinct":8,"total":9,"identifiers":["__stripped__"]},"operands":{"distinct":6,"total":10,"identifiers":["__stripped__"]},"length":19,"vocabulary":14,"difficulty":6.666666666666667,"volume":72.33974351909447,"effort":482.26495679396317,"bugs":0.024113247839698156,"time":26.79249759966462},"params":1}},{"name":"dispose","line":899,"complexity":{"sloc":{"physical":26,"logical":15},"cyclomatic":1,"halstead":{"operators":{"distinct":3,"total":34,"identifiers":["__stripped__"]},"operands":{"distinct":24,"total":38,"identifiers":["__stripped__"]},"length":72,"vocabulary":27,"difficulty":2.375,"volume":342.3519001557698,"effort":813.0857628699532,"bugs":0.11411730005192326,"time":45.17143127055296},"params":0}},{"name":"remove","line":933,"complexity":{"sloc":{"physical":4,"logical":1},"cyclomatic":1,"halstead":{"operators":{"distinct":2,"total":4,"identifiers":["__stripped__"]},"operands":{"distinct":6,"total":6,"identifiers":["__stripped__"]},"length":10,"vocabulary":8,"difficulty":1,"volume":30,"effort":30,"bugs":0.01,"time":1.6666666666666667},"params":0}}],"maintainability":70.98538919547134,"params":1.1147540983606556,"module":"libs/beez-mvcr/s/beez-mvcr/view.js"},"jshint":{"messages":[{"severity":"error","line":45,"column":41,"message":"'root' is already defined.","source":"'{a}' is already defined."},{"severity":"error","line":177,"column":35,"message":"Weird construction. Is 'new' unnecessary?","source":"Weird construction. Is 'new' unnecessary?"},{"severity":"error","line":177,"column":83,"message":"Missing '()' invoking a constructor.","source":"Missing '()' invoking a constructor."},{"severity":"error","line":182,"column":30,"message":"'root' is already defined.","source":"'{a}' is already defined."}]}}
|
class TknExpError(Exception):
"""Raise exception when refresh or access token is expired.
Args:
Exception (Exception): The base python exception class
"""
def __init__(self, message):
"""Print out message for this exception.
Args:
message (str): Pass in the message returned by the server.
"""
self.message = message
super().__init__(self.message)
class ExdLmtError(Exception):
"""Raise exception when exceeding query limit of the server.
Args:
Exception (Exception): The base python exception class
"""
def __init__(self, message):
"""Print out message for this exception.
Args:
message (str): Pass in the message returned by the server.
"""
self.message = message
super().__init__(self.message)
class NotNulError(Exception):
"""Raise exception when a null value is passed into non-null field.
Args:
Exception (Exception): The base python exception class
"""
def __init__(self, message):
"""Print out message for this exception.
Args:
message (str): Pass in the message returned by the server.
"""
self.message = message
super().__init__(self.message)
class ForbidError(Exception):
"""Raise forbidden exception. This usually occurs when the app does
not have access to the account.
Args:
Exception (Exception): The base python exception class
"""
def __init__(self, message):
"""Print out message for this exception.
Args:
message (str): Pass in the message returned by the server.
"""
self.message = message
super().__init__(self.message)
class NotFndError(Exception):
"""Raise exception when criteria is not found.
Args:
Exception (Exception): The base python exception class
"""
def __init__(self, message):
"""Print out message for this exception.
Args:
message (str): Pass in the message returned by the server.
"""
self.message = message
super().__init__(self.message)
class ServerError(Exception):
"""Raise exception when there is an error with the service or the server
cannot provide response.
Args:
Exception (Exception): The base python exception class
"""
def __init__(self, message):
"""Print out message for this exception.
Args:
message (str): Pass in the message returned by the server.
"""
self.message = message
super().__init__(self.message)
class GeneralError(Exception):
"""Raise exception for all other status code >400 errors which are not
defined above.
Args:
Exception (Exception): The base python exception class
"""
def __init__(self, message):
"""Print out message for this exception.
Args:
message (str): Pass in the message returned by the server.
"""
self.message = message
super().__init__(self.message)
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M19 5v14H5V5h14m-2 1h-3.3l-5 9H7c-.83 0-1.5.67-1.5 1.5S6.17 18 7 18h3.3l5-9H17c.83 0 1.5-.67 1.5-1.5S17.83 6 17 6z" opacity=".3" /><path d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-2 3h-3.3l-5 9H7c-.83 0-1.5.67-1.5 1.5S6.17 18 7 18h3.3l5-9H17c.83 0 1.5-.67 1.5-1.5S17.83 6 17 6z" /></React.Fragment>
, 'EscalatorTwoTone');
|
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import viewsets, mixins, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from core.models import Tag, Ingredient, Recipe
from recipe import serializers
class BaseRecipeAttributeViewSet(viewsets.GenericViewSet,
mixins.ListModelMixin,
mixins.CreateModelMixin):
"""Common code for permission,authentication and and saving"""
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
def get_queryset(self):
"""return objects for current authenticated user"""
return self.queryset.filter(user=self.request.user).order_by('-name')
def perform_create(self, serializer):
"""create new ingredient"""
serializer.save(user=self.request.user)
class TagViewSet(BaseRecipeAttributeViewSet):
"""Manage Tag in Database"""
queryset = Tag.objects.all()
serializer_class = serializers.TagSerializer
class IngredientViewSet(BaseRecipeAttributeViewSet):
"""manage ingredient in database"""
queryset = Ingredient.objects.all()
serializer_class = serializers.IngredientSerializer
class RecipeViewSet(viewsets.ModelViewSet):
"""Manage recipe in database"""
serializer_class = serializers.RecipeSerializer
queryset = Recipe.objects.all()
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
def get_queryset(self):
"""Retrive recipe for the authenticated users"""
return self.queryset.filter(user=self.request.user)
def get_serializer_class(self):
"""Return appropriate serializer class"""
if self.action == 'retrieve':
return serializers.RecipeDetailSerializer
elif self.action == 'upload_image':
return serializers.RecipeImageSerializer
return self.serializer_class
def perform_create(self, serializer):
serializer.save(user=self.request.user)
@action(methods=['POST'], detail=True, url_path='upload-image')
def upload_image(self, request, pk=None):
"""upload a image to recipe"""
recipe = self.get_object()
serializer = self.get_serializer(
recipe,
data=request.data
)
if serializer.is_valid():
serializer.save()
return Response(
serializer.data,
status=status.HTTP_200_OK
)
return Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST
)
|
/**
*!
* \file b_drv_sd.c
* \version v0.0.1
* \date 2020/06/01
* \author Bean(notrynohigh@outlook.com)
*******************************************************************************
* @attention
*
* Copyright (c) 2020 Bean
*
* 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.
*******************************************************************************
*/
/*Includes ----------------------------------------------*/
#include "drivers/inc/b_drv_sd.h"
/**
* \addtogroup B_DRIVER
* \{
*/
/**
* \addtogroup SD
* \{
*/
/**
* \defgroup SD_Private_TypesDefinitions
* \{
*/
/**
* \}
*/
/**
* \defgroup SD_Private_Macros
* \{
*/
/**
* \}
*/
/**
* \defgroup SD_Private_Variables
* \{
*/
const static bSD_HalIf_t bSD_HalIf = HAL_SD_IF;
bSD_Driver_t bSD_Driver;
/**
* \}
*/
/**
* \defgroup SD_Private_Defines
* \{
*/
#define SD_CS_SET() bHalGPIODriver.pGpioWritePin(bSD_HalIf.cs.port, bSD_HalIf.cs.pin, 1)
#define SD_CS_RESET() bHalGPIODriver.pGpioWritePin(bSD_HalIf.cs.port, bSD_HalIf.cs.pin, 0)
/**
* \}
*/
/**
* \defgroup SD_Private_FunctionPrototypes
* \{
*/
/**
* \}
*/
/**
* \defgroup SD_Private_Functions
* \{
*/
/************************************************************************************************************driver
* interface*******/
static int _bSD_WaitReady()
{
uint32_t tick = bHalGetSysTick();
uint8_t tmp = 0;
for (;;)
{
tmp = bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
if (tmp == 0xff)
{
return 0;
}
if (bHalGetSysTick() - tick > 500)
{
break;
}
}
return -1;
}
static void _bSD_SendDump(uint8_t n)
{
uint8_t tmp = 0xff;
uint8_t i = 0;
for (i = 0; i < n; i++)
{
bHalSPIDriver.pSend(&bSD_HalIf, &tmp, 1);
}
}
static int _bSD_PowerON()
{
uint8_t tmp = 0xff;
uint8_t cmd[6] = {CMD0, 0, 0, 0, 0, 0X95};
uint32_t cnt;
bHalDelayMs(100);
bHalSPIDriver.pSetSpeed(&bSD_HalIf, B_HAL_SPI_SLOW);
SD_CS_SET();
_bSD_SendDump(10);
SD_CS_RESET();
bHalSPIDriver.pSend(&bSD_HalIf, cmd, 6);
cnt = 0;
for (;;)
{
tmp = bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
if (tmp == 0x1 || cnt >= 0x1fff)
{
break;
}
cnt++;
}
SD_CS_SET();
_bSD_SendDump(1);
if (cnt >= 0x1fff)
{
return -1;
}
return 0;
}
static int _bSD_SendCmd(uint8_t cmd, uint32_t param, uint8_t crc)
{
uint8_t cmd_table[6];
uint8_t tmp, cnt;
if (_bSD_WaitReady() < 0)
{
return -1;
}
cmd_table[0] = cmd;
cmd_table[1] = (uint8_t)((param >> 24) & 0xff);
cmd_table[2] = (uint8_t)((param >> 16) & 0xff);
cmd_table[3] = (uint8_t)((param >> 8) & 0xff);
cmd_table[4] = (uint8_t)((param >> 0) & 0xff);
cmd_table[5] = crc;
bHalSPIDriver.pSend(&bSD_HalIf, cmd_table, 6);
cnt = 0;
for (;;)
{
tmp = bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
if (tmp != 0xff || cnt > 200)
{
break;
}
cnt++;
}
if (cnt > 200)
{
b_log_e("cmd%d err..\r\n", cmd);
return -1;
}
return tmp;
}
static int _bSD_Init()
{
int retval = -1;
uint32_t cnt = 0;
uint8_t ocr[4];
if (_bSD_PowerON() < 0)
{
b_log_e("power on err\r\n");
return -1;
}
SD_CS_RESET();
retval = _bSD_SendCmd(CMD0, 0, 0x95);
if (retval < 0)
{
SD_CS_SET();
return -1;
}
if (retval == 1)
{
retval = _bSD_SendCmd(CMD8, 0x1AA, 0x87);
if (retval < 0)
{
SD_CS_SET();
return -1;
}
}
else
{
SD_CS_SET();
return -1;
}
if (retval == 0x5)
{
bSD_Driver._private.v = CT_SD1;
SD_CS_SET();
_bSD_SendDump(1);
cnt = 0;
SD_CS_RESET();
do
{
retval = _bSD_SendCmd(CMD55, 0, 0);
if (retval < 0)
{
SD_CS_SET();
return -1;
}
retval = _bSD_SendCmd(CMD41, 0, 0);
if (retval < 0)
{
SD_CS_SET();
return -1;
}
cnt++;
} while ((retval != 0) && (cnt < 400));
if (cnt >= 400)
{
SD_CS_SET();
return -1;
}
bHalSPIDriver.pSetSpeed(&bSD_HalIf, B_HAL_SPI_FAST);
_bSD_SendDump(1);
retval = _bSD_SendCmd(CMD59, 0, 0x95);
if (retval < 0)
{
SD_CS_SET();
return -1;
}
retval = _bSD_SendCmd(CMD16, 512, 0x95);
if (retval < 0)
{
SD_CS_SET();
return -1;
}
}
else if (retval == 0x1)
{
ocr[0] = bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
ocr[1] = bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
ocr[2] = bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
ocr[3] = bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
SD_CS_SET();
_bSD_SendDump(1);
cnt = 0;
SD_CS_RESET();
do
{
retval = _bSD_SendCmd(CMD55, 0, 0);
if (retval < 0)
{
SD_CS_SET();
return -1;
}
retval = _bSD_SendCmd(CMD41, 0x40000000, 0);
if (retval < 0)
{
SD_CS_SET();
return -1;
}
cnt++;
} while ((retval != 0) && (cnt < 400));
if (cnt >= 400)
{
SD_CS_SET();
return -1;
}
retval = _bSD_SendCmd(CMD58, 0, 0);
if (retval != 0)
{
SD_CS_SET();
return -1;
}
ocr[0] = bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
ocr[1] = bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
ocr[2] = bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
ocr[3] = bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
if (ocr[0] & 0x40)
{
bSD_Driver._private.v = CT_SDHC;
}
else
{
bSD_Driver._private.v = CT_SD2;
}
}
SD_CS_SET();
_bSD_SendDump(1);
bHalSPIDriver.pSetSpeed(&bSD_HalIf, B_HAL_SPI_FAST);
b_log("sd type:%d\r\n", bSD_Driver._private.v);
return 0;
}
static int _bSD_WaitResponse(uint8_t exp)
{
uint16_t cnt = 0;
uint8_t tmp;
do
{
tmp = bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
cnt++;
} while (tmp != exp && cnt <= 0xfff);
if (tmp == exp)
{
return 0;
}
return -1;
}
static int _bSD_ReceiveData(uint8_t *buff, uint16_t len)
{
if (_bSD_WaitResponse(0xfe) < 0)
{
return -1;
}
while (len--)
{
*buff = bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
buff++;
}
bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
return len;
}
static int _bSD_ReadSingleBlock(uint32_t sector, uint8_t *pbuf)
{
int retval = 0;
if (bSD_Driver._private.v != CT_SDHC)
{
sector = sector << 9;
}
SD_CS_RESET();
retval = _bSD_SendCmd(CMD17, sector, 0);
if (retval != 0)
{
SD_CS_SET();
return -1;
}
SD_CS_SET();
_bSD_SendDump(1);
SD_CS_RESET();
if (_bSD_ReceiveData(pbuf, 512) < 0)
{
SD_CS_SET();
return -1;
}
SD_CS_SET();
_bSD_SendDump(1);
return 512;
}
static int _bSD_WriteSingleBlock(uint32_t sector, uint8_t *pbuf)
{
int retval = 0;
uint16_t cnt;
if (bSD_Driver._private.v != CT_SDHC)
{
sector = sector << 9;
}
SD_CS_RESET();
retval = _bSD_SendCmd(CMD24, sector, 0);
if (retval != 0)
{
SD_CS_SET();
return -1;
}
SD_CS_SET();
_bSD_SendDump(1);
SD_CS_RESET();
_bSD_SendDump(3);
bHalSPIDriver.pTransfer(&bSD_HalIf, 0xfe);
bHalSPIDriver.pSend(&bSD_HalIf, pbuf, 512);
_bSD_SendDump(2);
retval = bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff);
if ((retval & 0x1f) != 0x05)
{
SD_CS_SET();
return -1;
}
cnt = 0;
while (!bHalSPIDriver.pTransfer(&bSD_HalIf, 0xff))
{
cnt++;
if (cnt >= 0xfffe)
{
SD_CS_SET();
return -1;
}
}
SD_CS_SET();
_bSD_SendDump(1);
return 0;
}
// sector: Sector number to write from
// count: Number of sectors to write
static int _bSD_Write(bSD_Driver_t *pdrv, uint32_t sector, uint8_t *pbuf, uint16_t count)
{
int i = 0;
for (i = 0; i < count; i++)
{
_bSD_WriteSingleBlock(sector + i, pbuf + i * 512);
}
return count;
}
// sector: Sector number to write from
// count: Number of sectors to write
static int _bSD_Read(bSD_Driver_t *pdrv, uint32_t sector, uint8_t *pbuf, uint16_t count)
{
int i = 0;
for (i = 0; i < count; i++)
{
_bSD_ReadSingleBlock(sector + i, pbuf + i * 512);
}
return count;
}
/**
* \}
*/
/**
* \addtogroup SD_Exported_Functions
* \{
*/
int bSD_Init()
{
if (_bSD_Init() < 0)
{
b_log("sd_err\r\n");
return -1;
}
bSD_Driver.status = 0;
bSD_Driver.close = NULL;
bSD_Driver.read = _bSD_Read;
bSD_Driver.ctl = NULL;
bSD_Driver.open = NULL;
bSD_Driver.write = _bSD_Write;
return 0;
}
bDRIVER_REG_INIT(bSD_Init);
/**
* \}
*/
/**
* \}
*/
/**
* \}
*/
/************************ Copyright (c) 2020 Bean *****END OF FILE****/
|
H5.merge(new System.Globalization.CultureInfo("sl-SI", true), {
englishName: "Slovenian (Slovenia)",
nativeName: "slovenščina (Slovenija)",
numberFormat: H5.merge(new System.Globalization.NumberFormatInfo(), {
nanSymbol: "NaN",
negativeSign: "-",
positiveSign: "+",
negativeInfinitySymbol: "-∞",
positiveInfinitySymbol: "∞",
percentSymbol: "%",
percentGroupSizes: [3],
percentDecimalDigits: 2,
percentDecimalSeparator: ",",
percentGroupSeparator: ".",
percentPositivePattern: 0,
percentNegativePattern: 0,
currencySymbol: "€",
currencyGroupSizes: [3],
currencyDecimalDigits: 2,
currencyDecimalSeparator: ",",
currencyGroupSeparator: ".",
currencyNegativePattern: 8,
currencyPositivePattern: 3,
numberGroupSizes: [3],
numberDecimalDigits: 2,
numberDecimalSeparator: ",",
numberGroupSeparator: ".",
numberNegativePattern: 1
}),
dateTimeFormat: H5.merge(new System.Globalization.DateTimeFormatInfo(), {
abbreviatedDayNames: ["ned.","pon.","tor.","sre.","čet.","pet.","sob."],
abbreviatedMonthGenitiveNames: ["jan.","feb.","mar.","apr.","maj","jun.","jul.","avg.","sep.","okt.","nov.","dec.",""],
abbreviatedMonthNames: ["jan.","feb.","mar.","apr.","maj","jun.","jul.","avg.","sep.","okt.","nov.","dec.",""],
amDesignator: "dop.",
dateSeparator: ". ",
dayNames: ["nedelja","ponedeljek","torek","sreda","četrtek","petek","sobota"],
firstDayOfWeek: 1,
fullDateTimePattern: "dddd, dd. MMMM yyyy HH:mm:ss",
longDatePattern: "dddd, dd. MMMM yyyy",
longTimePattern: "HH:mm:ss",
monthDayPattern: "d. MMMM",
monthGenitiveNames: ["januar","februar","marec","april","maj","junij","julij","avgust","september","oktober","november","december",""],
monthNames: ["januar","februar","marec","april","maj","junij","julij","avgust","september","oktober","november","december",""],
pmDesignator: "pop.",
rfc1123: "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
shortDatePattern: "d. MM. yyyy",
shortestDayNames: ["ned.","pon.","tor.","sre.","čet.","pet.","sob."],
shortTimePattern: "HH:mm",
sortableDateTimePattern: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
sortableDateTimePattern1: "yyyy'-'MM'-'dd",
timeSeparator: ":",
universalSortableDateTimePattern: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
yearMonthPattern: "MMMM yyyy",
roundtripFormat: "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffzzz"
}),
TextInfo: H5.merge(new System.Globalization.TextInfo(), {
ANSICodePage: 1250,
CultureName: "sl-SI",
EBCDICCodePage: 20880,
IsRightToLeft: false,
LCID: 1060,
listSeparator: ";",
MacCodePage: 10029,
OEMCodePage: 852,
IsReadOnly: true
})
});
|
/* global $ */
let JQueryReady = false;
$(() => (JQueryReady = true));
class NUILoader {
constructor(pluginName) {
this.pluginName = pluginName;
this.nuiWrapperId = `natuna-nui\\:${this.pluginName}`;
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
(async () => {
while (!JQueryReady) await wait(100);
const html = await this.utils.getContent(`../../../plugins/${this.pluginName}/ui/index.html`);
const parsedHTML = await this.HTMLParser(html);
// Append the Parsed HTML
$("body").prepend(`<section id="${this.nuiWrapperId.replace("\\", "")}" class="nui-wrapper">${parsedHTML}</section>`);
// Set the Z-Index of the NUI
const zIndex = $(`#${this.nuiWrapperId} meta[name="nuiIndex"]`).attr("content") || 1;
$(`#${this.nuiWrapperId}`).css("z-index", parseInt(zIndex));
})();
}
CSSParser = (content) => {
const regex = /url\(("|'|`|)(.*?)("|'|`|)(\))/gm;
const regexMatched = this.utils.getMatchedRegex(regex, content);
for (const match of regexMatched) {
if (match.startsWith(`./`)) {
const newAttribute = match.replace(".", `../../../plugins/${this.pluginName}/ui`);
content = content.replace(match, newAttribute);
}
}
content = this.utils.renderCSSWithSelector(content, `#${this.nuiWrapperId}`);
return content;
};
JSParser = (content) => {
// $("") && document.querySelector()
const regex1 = /(\$|querySelector)\(("|'|`)(.*?)("|'|`)\)/gm;
const regexMatched1 = this.utils.getMatchedRegex(regex1, content);
for (const match of regexMatched1) {
if (match.startsWith(`#`)) {
const newAttribute = match.replace("#", `#${this.pluginName}-`);
content = content.replace(match, newAttribute);
}
}
// document.getElementById()
const regex2 = /(getElementById)\(("|'|`)(.*?)("|'|`)\)/gm;
const regexMatched2 = this.utils.getMatchedRegex(regex2, content);
for (const match of regexMatched2) {
if (!match.startsWith(`getElementById`) && !match.match("(\"|'|`)")) {
// eslint-disable-next-line no-useless-escape
const string = match.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
const regex = new RegExp(`getElementById\\(("|'|\`)${string}("|'|\`)\\)`, "gm");
const newId = `${this.pluginName}-${match}`;
content = content.replace(regex, `getElementById(\`${newId}\`)`);
}
}
return content;
};
HTMLParser = async (content) => {
// Find 'src' and 'href' attributes
const regex1 = /(src|href)=("|'|`)(.*?)("|'|`)/gm;
const regexMatched1 = this.utils.getMatchedRegex(regex1, content);
for (const match of regexMatched1) {
if (match.startsWith(`./`)) {
let file;
const newUrl = match.replace(".", `../../../plugins/${this.pluginName}/ui`);
if (match.endsWith(".js") || match.endsWith(".css")) {
file = await this.utils.getContent(newUrl);
content = content.replace(match, "//:0");
}
if (match.endsWith(".js")) {
content += "<script>" + this.JSParser(file) + "</script>";
} else if (match.endsWith(".css")) {
content += "<style>" + this.CSSParser(file) + "</style>";
} else {
content = content.replace(match, newUrl);
}
}
}
// Find 'id' attributes
const regex2 = /id=("|'|`)(.*?)("|'|`)/gm;
const regexMatched2 = this.utils.getMatchedRegex(regex2, content);
for (const match of regexMatched2) {
if (!match.startsWith(`id=`) && !match.match("(\"|'|`)")) {
// eslint-disable-next-line no-useless-escape
const string = match.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
const regex = new RegExp(`id=("|'|\`)${string}("|'|\`)`, "gm");
const newId = `${this.pluginName}-${match}`;
content = content.replace(regex, `id="${newId}"`);
}
}
return content;
};
utils = {
getContent: (url) => {
return new Promise((resolve, reject) => {
$.ajax(url, {
dataType: "text",
success: function (response) {
// Do something with the response
resolve(response);
},
});
});
},
getMatchedRegex: (regex, content) => {
let regexMatched;
let returnMatch = [];
while ((regexMatched = regex.exec(content)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (regexMatched.index === regex.lastIndex) {
regex.lastIndex++;
}
for (const match of regexMatched) {
returnMatch.push(match);
}
}
return returnMatch;
},
renderCSSWithSelector: (css, selector) => {
return (css + "" || "")
.replace(/\n|\t/g, " ")
.replace(/\s+/g, " ")
.replace(/\s*\/\*.*?\*\/\s*/g, " ")
.replace(/(^|\})(.*?)(\{)/g, function ($0, $1, $2, $3) {
var collector = [],
parts = $2.split(",");
for (var i in parts) {
collector.push(selector + " " + parts[i].replace(/^\s*|\s*$/, ""));
}
return $1 + " " + collector.join(", ") + " " + $3;
})
.replace(/(body|html)/, "");
},
};
}
window.addEventListener("message", (event) => {
if (typeof event.data.name !== "undefined") {
return window.emit(event.data.name, event.data.data);
}
});
window.on("natuna:nui:retrievePluginList", (data) => {
return new NUILoader(data.name);
});
window.on("natuna:nui:debugHTML", () => {
const text = $("html").html();
const node = document.createElement("textarea");
const selection = document.getSelection();
node.textContent = text;
document.body.appendChild(node);
selection.removeAllRanges();
node.select();
document.execCommand("copy");
selection.removeAllRanges();
document.body.removeChild(node);
window.sendData("natuna:client:nuiDebugSuccess");
return true;
});
|
/**
* Created by irelance on 2017/2/10.
*/
UploadClient.modal = {
options: undefined,
target: $('<div class="modal"><div class="modal-dialog"><div class="modal-header"><div class="close">×</div><h3></h3></div><div class="modal-content"></div><div class="modal-footer"></div></div></div>'),
creator: undefined,
init: function (options) {
var self = this,
tbody = UploadClient.table.target.children('tbody');
self.creator = new UploadClient.Creator();
self.options = options;
options.sort(function (a, b) {
return a.sort == b.sort ? 0 : a.sort > b.sort ? 1 : -1;
});
self.target
.on('click', '.close', function () {
self.hide();
})
.on('click', '.upload', function () {
var inputs = self.target.find('input'),
data = {};
inputs.each(function (i, v) {
data[v.name] = v.value;
});
data = $.extend(UploadClient.options.check.hidden, data, self.creator.data);
if (!data.hash) {
self.creator.renderMessage(UploadClient.lang[UploadClient.options.lang]['fileStart'], 'error');
return false;
}
delete data.id;
$.ajax({
type: UploadClient.options.check.method,
url: UploadClient.options.check.url,
data: data,
success: function (result) {
if (result.status) {
var item = new UploadClient.Item();
self.creator.file.off('change');
item.file = self.creator.file;
result.data.chunks = [];
item.init(result.data);
item.render();
item.onHashSuccess();
item.buttons.upload.trigger('click');
tbody.prepend(item.target);
}
}
});
self.hide();
});
},
show: function () {
this.target.show();
},
hide: function () {
this.target.hide();
},
render: function () {
this.target.find('.modal-header h3').html(UploadClient.lang[UploadClient.options.lang].modalTitle);
this.target.find('.modal-footer').html('<button class="close">' +
UploadClient.lang[UploadClient.options.lang].modalCancel +
'</button><button class="upload">' + UploadClient.lang[UploadClient.options.lang].modalUpload +
'</button>');
var content = this.target.find('.modal-content');
content.html('');
this.options.forEach(function (v) {
if (v.uploader) {
this.creator.init();
content.append(this.creator.target);
} else {
content.append('<div class="form-group"><label>' + v.label + '</label><div><input name="' + v.id + '"></div></div>');
}
}.bind(this));
}
};
|
var searchData=
[
['xmlcout',['XmlCout',['../d9/dca/classXmlCout.html',1,'XmlCout'],['../d9/dca/classXmlCout.html#ae895068dd12946b6b57ef1a70b9f0d7a',1,'XmlCout::XmlCout()']]],
['xmlexception',['XmlException',['../da/da5/classXmlException.html',1,'XmlException'],['../da/da5/classXmlException.html#a912e299d8bfb810f42a2d4c95621b221',1,'XmlException::XmlException()']]],
['xmllogs',['XmlLogs',['../da/daf/classXmlLogs.html',1,'XmlLogs'],['../da/daf/classXmlLogs.html#a98546fca3a71b0e5c636bfbdac34e383',1,'XmlLogs::XmlLogs()']]],
['xmlmessage',['XmlMessage',['../df/d0b/classXmlMessage.html',1,'XmlMessage'],['../df/d0b/classXmlMessage.html#a81b72c91fddb884f5aaf88ca26390a75',1,'XmlMessage::XmlMessage()']]]
];
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2015 Corrado Ubezio
#
# 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.
'''Append to PYTHONPATH the path of the script from which it runs.
Ref. http://stackoverflow.com/a/7886092
'''
from web.PyDomoSvr import main
def run():
'''Returns status code
'''
return main()
if __name__ == "__main__":
exit(run())
|
from aleph.core import db # noqa
from aleph.model.role import Role # noqa
from aleph.model.alert import Alert # noqa
from aleph.model.permission import Permission # noqa
from aleph.model.entity import Entity # noqa
from aleph.model.match import Match # noqa
from aleph.model.collection import Collection # noqa
from aleph.model.document import Document # noqa
from aleph.model.event import Event, Events # noqa
from aleph.model.notification import Notification # noqa
from aleph.model.query_log import QueryLog # noqa
from aleph.model.mapping import Mapping # noqa
from aleph.model.diagram import Diagram # noqa
|
[[[0,1,1,0,0,0,0,0,0,0,0,0,1,2,0,0,0,0,0,0,0,0,0,1,3,0,0,0,1,1,0,0,0,0,5,4,0,0,0,1,0,1,0,0,1,5,1,0,0,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,5,3,0,0,1,0,0,0,0,0,1,3,4,1,0,0,0,0,0,1,1],2],["winner",1],[[0,1,1,0,0,0,0,0,0,0,0,0,1,2,0,0,0,0,0,0,0,0,0,1,3,0,0,0,1,1,0,0,0,0,5,4,0,0,0,1,0,1,0,0,1,5,1,0,0,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,5,5,0,0,1,0,0,0,0,0,1,3,4,1,0,0,0,0,0,1,1],2],[[0,1,1,0,0,0,0,0,0,0,0,0,1,2,0,0,0,0,0,0,0,0,0,1,3,0,0,0,1,1,0,0,0,-1,-1,-1,0,0,0,0,0,0,0,0,1,5,1,0,0,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,5,5,0,0,1,0,0,0,0,0,1,3,4,1,0,0,0,0,0,1,1],2],[[0,1,1,0,0,0,0,0,0,0,0,0,1,2,0,0,0,0,1,0,0,0,0,1,3,0,0,0,0,0,0,0,0,0,1,4,0,0,0,0,0,0,0,0,1,5,1,0,0,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,0,1,5,3,0,0,0,0,0,0,0,0,1,5,4,0,0,0,0,0,0,0,0],1],[[0,1,1,0,0,0,0,0,0,0,0,0,1,2,0,0,0,0,1,0,0,0,0,1,3,0,0,0,0,0,0,0,0,0,1,4,0,0,0,0,0,0,0,0,1,5,1,0,0,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,0,1,5,3,0,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,0],2],[[0,1,1,0,0,0,0,0,0,0,0,0,1,2,0,0,0,0,1,0,0,0,0,1,3,0,0,0,0,0,0,0,0,0,1,4,0,0,0,0,0,0,0,0,1,5,1,0,0,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,0,1,5,3,0,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,0],1],[[0,1,1,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,1,0,0,0,0,1,3,0,0,0,0,0,0,0,0,0,1,4,0,0,0,0,0,0,0,0,1,5,1,0,0,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,0,1,4,2,0,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,0],2],[[0,1,1,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,1,1,0,0,0,1,3,0,0,0,0,0,0,0,0,0,1,4,0,0,0,0,0,0,0,0,1,5,1,0,0,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,0,1,4,2,0,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,0],1],[[0,1,1,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,1,1,0,0,0,1,3,0,0,0,0,0,0,0,0,0,1,4,0,0,0,0,0,0,0,0,1,5,1,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,0,1,4,2,0,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,0],2],[[0,1,1,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,1,1,0,0,0,1,3,0,0,0,0,0,0,0,0,0,1,4,0,0,0,0,0,0,0,0,1,5,1,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,0,1,4,2,0,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,0],1],[[0,1,1,0,0,0,0,0,0,0,0,0,3,2,0,0,0,0,1,1,0,0,0,1,3,0,0,0,0,0,0,0,0,0,1,4,0,0,0,0,0,0,0,0,1,5,1,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,0,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,0],2],[[0,1,1,0,0,0,0,0,0,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,0,0,0,0,0,1,4,0,0,0,0,0,0,0,0,1,5,1,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,0,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,0],1],[[0,1,1,0,0,0,0,0,0,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,0,0,0,0,0,1,4,0,0,0,0,0,0,0,0,1,5,1,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,0,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,1],2],[[0,1,1,0,0,0,0,0,0,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,0,0,0,0,0,1,4,0,0,0,0,0,1,0,0,1,5,1,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,0,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,1],1],[[0,1,1,0,0,0,0,0,0,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,0,0,0,0,0,1,4,0,0,0,0,0,1,0,0,1,3,3,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,0,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,1],2],[[0,1,1,0,0,0,0,0,0,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,0,0,0,0,0,1,4,0,0,0,0,0,1,0,0,1,3,3,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,0,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,1],2],[[0,1,1,0,0,0,0,0,0,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,1,0,0,0,0,1,4,0,0,0,0,0,1,0,0,1,3,3,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,0,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,1],1],[[0,1,1,0,0,0,0,0,0,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,1,0,0,0,0,1,4,0,0,0,0,0,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,0,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,1],2],[[0,1,1,0,0,0,0,0,0,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,1,0,0,0,0,1,4,0,0,0,0,1,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,0,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,1],1],[[0,1,1,0,0,0,0,0,0,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,1,0,0,0,0,1,4,0,0,0,0,1,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,1,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,1],2],[[0,1,1,0,0,0,0,0,0,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,1,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,0,1],1],[[0,1,1,0,0,0,0,0,0,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,1,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,1,1],2],[[0,1,1,0,0,0,0,0,1,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,1,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,0,1,1],1],[[0,1,1,0,0,0,0,0,1,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,1,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,1,1,1],2],[[0,1,1,0,0,0,0,0,1,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,1,0,0,0,0,0,0,1,1,5,4,0,0,0,0,0,1,1,1],1],[[0,2,0,0,0,0,0,0,1,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,1,0,0,0,0,0,0,1,1,5,4,0,0,0,1,0,1,1,1],2],[[0,2,0,0,0,0,0,1,1,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,1,0,0,0,0,0,0,1,1,5,4,0,0,0,1,0,1,1,1],1],[[0,2,0,0,0,0,0,1,1,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,1,0,0,0,0,0,0,1,1,5,4,0,0,0,1,1,1,1,1],2],[[0,2,0,0,0,0,0,1,1,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,4,2,1,0,0,0,0,0,0,1,1,5,4,0,0,0,1,1,1,1,1],1],[[0,3,0,0,0,0,0,1,1,0,0,0,3,2,0,0,0,1,1,1,0,0,0,1,3,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,2,2,1,0,0,0,0,0,0,1,1,5,4,0,0,0,1,1,1,1,1],2],[[0,3,0,0,0,0,0,1,1,0,0,-1,-1,-1,0,0,0,0,0,0,0,0,0,1,3,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,2,2,1,0,0,0,0,0,0,1,1,5,4,0,0,0,1,1,1,1,1],2],[[0,3,0,0,0,0,0,1,1,0,0,-1,-1,-1,0,0,0,0,0,0,0,0,0,1,3,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,1,2,2,1,0,0,0,0,0,0,1,1,5,4,0,0,0,1,1,1,1,1],1],[[0,3,0,0,0,0,0,1,1,0,0,-1,-1,-1,0,0,0,0,0,0,0,0,0,3,1,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,2,4,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,-1,-1,-1,0,0,0,0,0,0,0,0,1,5,4,0,0,0,1,1,1,1,1],1],[[0,3,0,0,0,0,0,1,1,0,0,-1,-1,-1,0,0,0,0,0,0,0,0,0,3,1,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,1,5,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,-1,-1,-1,0,0,0,0,0,0,0,0,1,5,4,0,0,0,1,1,1,1,1],2],[[0,3,0,0,0,0,0,1,1,0,0,-1,-1,-1,0,0,0,0,0,0,0,0,0,3,1,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,1,5,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,0,1,-1,-1,-1,0,0,0,0,0,0,0,0,1,5,4,0,0,0,1,1,1,1,1],1],[[0,3,0,0,0,0,0,1,1,0,0,-1,-1,-1,0,0,0,0,0,0,0,0,0,4,1,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,1,5,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,1,1,-1,-1,-1,0,0,0,0,0,0,0,0,1,5,4,0,0,0,1,1,1,1,1],2],[[0,3,0,0,0,0,0,1,1,0,0,-1,-1,-1,0,0,0,0,0,0,0,0,0,4,1,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,1,5,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,1,1,-1,-1,-1,0,0,0,0,0,0,0,0,1,5,4,0,0,0,1,1,1,1,1],1],[[0,3,0,0,0,0,0,1,1,0,0,-1,-1,-1,0,0,0,0,0,0,0,0,0,5,1,0,0,0,0,1,1,0,0,0,1,4,0,0,0,0,1,1,0,0,1,1,5,0,1,0,0,0,0,0,0,1,5,2,0,0,0,0,0,0,1,1,-1,-1,-1,0,0,0,0,0,0,0,0,1,5,4,0,0,0,1,1,1,1,1],2],["winner",1]]
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var _extends = _interopDefault(require('@babel/runtime/helpers/extends'));
var _regeneratorRuntime = _interopDefault(require('@babel/runtime/regenerator'));
var _asyncToGenerator = _interopDefault(require('@babel/runtime/helpers/asyncToGenerator'));
var React = _interopDefault(require('react'));
var ReactDOM = _interopDefault(require('react-dom'));
var dom = require('@testing-library/dom');
var testUtils = require('react-dom/test-utils');
var reactAct = testUtils.act;
var actSupported = reactAct !== undefined; // act is supported react-dom@16.8.0
// so for versions that don't have act from test utils
// we do this little polyfill. No warnings, but it's
// better than nothing.
function actPolyfill(cb) {
ReactDOM.unstable_batchedUpdates(cb);
ReactDOM.render(React.createElement("div", null), document.createElement('div'));
}
var act = reactAct || actPolyfill;
var youHaveBeenWarned = false;
var isAsyncActSupported = null;
function asyncAct(cb) {
if (actSupported === true) {
if (isAsyncActSupported === null) {
return new Promise(function (resolve, reject) {
// patch console.error here
var originalConsoleError = console.error;
console.error = function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
/* if console.error fired *with that specific message* */
/* istanbul ignore next */
var firstArgIsString = typeof args[0] === 'string';
if (firstArgIsString && args[0].indexOf('Warning: Do not await the result of calling ReactTestUtils.act') === 0) {
// v16.8.6
isAsyncActSupported = false;
} else if (!(firstArgIsString && args[0].indexOf('Warning: The callback passed to ReactTestUtils.act(...) function must not return anything') === 0)) {
originalConsoleError.apply(console, args);
}
};
var cbReturn, result;
try {
result = reactAct(function () {
cbReturn = cb();
return cbReturn;
});
} catch (err) {
console.error = originalConsoleError;
reject(err);
return;
}
result.then(function () {
console.error = originalConsoleError; // if it got here, it means async act is supported
isAsyncActSupported = true;
resolve();
}, function (err) {
console.error = originalConsoleError;
isAsyncActSupported = true;
reject(err);
}); // 16.8.6's act().then() doesn't call a resolve handler, so we need to manually flush here, sigh
if (isAsyncActSupported === false) {
console.error = originalConsoleError;
/* istanbul ignore next */
if (!youHaveBeenWarned) {
// if act is supported and async act isn't and they're trying to use async
// act, then they need to upgrade from 16.8 to 16.9.
// This is a seemless upgrade, so we'll add a warning
console.error("It looks like you're using a version of react-dom that supports the \"act\" function, but not an awaitable version of \"act\" which you will need. Please upgrade to at least react-dom@16.9.0 to remove this warning.");
youHaveBeenWarned = true;
}
cbReturn.then(function () {
// a faux-version.
// todo - copy https://github.com/facebook/react/blob/master/packages/shared/enqueueTask.js
Promise.resolve().then(function () {
// use sync act to flush effects
act(function () {});
resolve();
});
}, reject);
}
});
} else if (isAsyncActSupported === false) {
// use the polyfill directly
var _result;
act(function () {
_result = cb();
});
return _result.then(function () {
return Promise.resolve().then(function () {
// use sync act to flush effects
act(function () {});
});
});
} // all good! regular act
return act(cb);
} // use the polyfill
var result;
act(function () {
result = cb();
});
return result.then(function () {
return Promise.resolve().then(function () {
// use sync act to flush effects
act(function () {});
});
});
}
/* eslint no-console:0 */
/* istanbul ignore file */
// the part of this file that we need tested is definitely being run
// and the part that is not cannot easily have useful tests written
// anyway. So we're just going to ignore coverage for this file
/**
* copied from React's enqueueTask.js
*/
var didWarnAboutMessageChannel = false;
var enqueueTask;
try {
// read require off the module object to get around the bundlers.
// we don't want them to detect a require and bundle a Node polyfill.
var requireString = ("require" + Math.random()).slice(0, 7);
var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's
// version of setImmediate, bypassing fake timers if any.
enqueueTask = nodeRequire('timers').setImmediate;
} catch (_err) {
// we're in a browser
// we can't use regular timers because they may still be faked
// so we try MessageChannel+postMessage instead
enqueueTask = function (callback) {
var supportsMessageChannel = typeof MessageChannel === 'function';
if (supportsMessageChannel) {
var channel = new MessageChannel();
channel.port1.onmessage = callback;
channel.port2.postMessage(undefined);
} else if (didWarnAboutMessageChannel === false) {
didWarnAboutMessageChannel = true; // eslint-disable-next-line no-console
console.error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.');
}
};
}
function flushMicroTasks() {
return {
then: function then(resolve) {
enqueueTask(resolve);
}
};
}
dom.configure({
asyncWrapper: function () {
var _asyncWrapper = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(cb) {
var result;
return _regeneratorRuntime.wrap(function (_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return asyncAct( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
return _regeneratorRuntime.wrap(function (_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return cb();
case 2:
result = _context.sent;
case 3:
case "end":
return _context.stop();
}
}
}, _callee);
})));
case 2:
return _context2.abrupt("return", result);
case 3:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function asyncWrapper() {
return _asyncWrapper.apply(this, arguments);
};
}()
});
var mountedContainers = new Set();
function render(ui, _temp) {
var _ref2 = _temp === void 0 ? {} : _temp,
container = _ref2.container,
_ref2$baseElement = _ref2.baseElement,
baseElement = _ref2$baseElement === void 0 ? container : _ref2$baseElement,
queries = _ref2.queries,
_ref2$hydrate = _ref2.hydrate,
hydrate = _ref2$hydrate === void 0 ? false : _ref2$hydrate,
WrapperComponent = _ref2.wrapper;
if (!baseElement) {
// default to document.body instead of documentElement to avoid output of potentially-large
// head elements (such as JSS style blocks) in debug output
baseElement = document.body;
}
if (!container) {
container = baseElement.appendChild(document.createElement('div'));
} // we'll add it to the mounted containers regardless of whether it's actually
// added to document.body so the cleanup method works regardless of whether
// they're passing us a custom container or not.
mountedContainers.add(container);
var wrapUiIfNeeded = function (innerElement) {
return WrapperComponent ? React.createElement(WrapperComponent, null, innerElement) : innerElement;
};
act(function () {
if (hydrate) {
ReactDOM.hydrate(wrapUiIfNeeded(ui), container);
} else {
ReactDOM.render(wrapUiIfNeeded(ui), container);
}
});
return _extends({
container: container,
baseElement: baseElement,
debug: function debug(el, maxLength, options) {
if (el === void 0) {
el = baseElement;
}
return Array.isArray(el) ? // eslint-disable-next-line no-console
el.forEach(function (e) {
return console.log(dom.prettyDOM(e, maxLength, options));
}) : // eslint-disable-next-line no-console,
console.log(dom.prettyDOM(el, maxLength, options));
},
unmount: function unmount() {
return ReactDOM.unmountComponentAtNode(container);
},
rerender: function rerender(rerenderUi) {
render(wrapUiIfNeeded(rerenderUi), {
container: container,
baseElement: baseElement
}); // Intentionally do not return anything to avoid unnecessarily complicating the API.
// folks can use all the same utilities we return in the first place that are bound to the container
},
asFragment: function asFragment() {
/* istanbul ignore if (jsdom limitation) */
if (typeof document.createRange === 'function') {
return document.createRange().createContextualFragment(container.innerHTML);
}
var template = document.createElement('template');
template.innerHTML = container.innerHTML;
return template.content;
}
}, dom.getQueriesForElement(baseElement, queries));
}
function cleanup() {
return _cleanup.apply(this, arguments);
} // maybe one day we'll expose this (perhaps even as a utility returned by render).
// but let's wait until someone asks for it.
function _cleanup() {
_cleanup = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
return _regeneratorRuntime.wrap(function (_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return flushMicroTasks();
case 2:
mountedContainers.forEach(cleanupAtContainer);
case 3:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return _cleanup.apply(this, arguments);
}
function cleanupAtContainer(container) {
ReactDOM.unmountComponentAtNode(container);
if (container.parentNode === document.body) {
document.body.removeChild(container);
}
mountedContainers.delete(container);
} // react-testing-library's version of fireEvent will call
// dom-testing-library's version of fireEvent wrapped inside
// an "act" call so that after all event callbacks have been
// called, the resulting useEffect callbacks will also be
// called.
function fireEvent() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var returnValue;
act(function () {
returnValue = dom.fireEvent.apply(void 0, args);
});
return returnValue;
}
Object.keys(dom.fireEvent).forEach(function (key) {
fireEvent[key] = function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var returnValue;
act(function () {
returnValue = dom.fireEvent[key].apply(dom.fireEvent, args);
});
return returnValue;
};
}); // React event system tracks native mouseOver/mouseOut events for
// running onMouseEnter/onMouseLeave handlers
// @link https://github.com/facebook/react/blob/b87aabdfe1b7461e7331abb3601d9e6bb27544bc/packages/react-dom/src/events/EnterLeaveEventPlugin.js#L24-L31
var mouseEnter = fireEvent.mouseEnter;
var mouseLeave = fireEvent.mouseLeave;
fireEvent.mouseEnter = function () {
mouseEnter.apply(void 0, arguments);
return fireEvent.mouseOver.apply(fireEvent, arguments);
};
fireEvent.mouseLeave = function () {
mouseLeave.apply(void 0, arguments);
return fireEvent.mouseOut.apply(fireEvent, arguments);
};
var select = fireEvent.select;
fireEvent.select = function (node, init) {
select(node, init); // React tracks this event only on focused inputs
node.focus(); // React creates this event when one of the following native events happens
// - contextMenu
// - mouseUp
// - dragEnd
// - keyUp
// - keyDown
// so we can use any here
// @link https://github.com/facebook/react/blob/b87aabdfe1b7461e7331abb3601d9e6bb27544bc/packages/react-dom/src/events/SelectEventPlugin.js#L203-L224
fireEvent.keyUp(node, init);
}; // just re-export everything from dom-testing-library
// thing for people using react-dom@16.8.0. Anyone else doesn't need it and
// people should just upgrade anyway.
/* eslint func-name-matching:0 */
Object.keys(dom).forEach(function (k) {
if (k !== 'default') Object.defineProperty(exports, k, {
enumerable: true,
get: function () {
return dom[k];
}
});
});
exports.act = act;
exports.cleanup = cleanup;
exports.fireEvent = fireEvent;
exports.render = render;
|
#
# PySNMP MIB module DELL-NETWORKING-BMP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DELL-NETWORKING-BMP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:37:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint")
dellNetMgmt, = mibBuilder.importSymbols("DELL-NETWORKING-SMI", "dellNetMgmt")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
ObjectIdentity, Gauge32, Counter32, Unsigned32, MibIdentifier, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, IpAddress, Bits, TimeTicks, Counter64, Integer32, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "Gauge32", "Counter32", "Unsigned32", "MibIdentifier", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "IpAddress", "Bits", "TimeTicks", "Counter64", "Integer32", "NotificationType")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
dellNetBmpMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 6027, 3, 23))
dellNetBmpMib.setRevisions(('2014-07-21 12:00', '2011-12-07 12:48',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: dellNetBmpMib.setRevisionsDescriptions(('Adding relay related objects - bmpRelay and bmpRelayRemoteID.', 'Initial version of this mib.',))
if mibBuilder.loadTexts: dellNetBmpMib.setLastUpdated('201112071248Z')
if mibBuilder.loadTexts: dellNetBmpMib.setOrganization('Dell Inc.')
if mibBuilder.loadTexts: dellNetBmpMib.setContactInfo('http://www.dell.com/support')
if mibBuilder.loadTexts: dellNetBmpMib.setDescription('Dell Networking OS Baremetal Provisioning MIB.')
dellNetBmp = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 23, 1))
bmpReloadType = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 23, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("normalReload", 1), ("bmpReload", 2))).clone('bmpReload')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: bmpReloadType.setStatus('current')
if mibBuilder.loadTexts: bmpReloadType.setDescription('Configure reload type to enable/disable BMP. normalReload - Regular reload type; BMP process is not initiated. bmpReload - Bmp reload type; BMP process is initiated and image/config files are upgraded based on the DHCP/BOOTP offer. Default is bmpReload.')
bmpAutoSave = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 23, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("bmpActionEnable", 1), ("bmpActionDisable", 2))).clone('bmpActionDisable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: bmpAutoSave.setStatus('current')
if mibBuilder.loadTexts: bmpAutoSave.setDescription('Configure auto-save option for downloaded config file. bmpActionEnable - Enable auto-save option. bmpActionDisable - Disable auto-save option. Default is bmpActionDisable.')
bmpConfigDownload = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 23, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("bmpActionEnable", 1), ("bmpActionDisable", 2))).clone('bmpActionDisable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: bmpConfigDownload.setStatus('current')
if mibBuilder.loadTexts: bmpConfigDownload.setDescription('Enable/disable config file download. bmpActionEnable - Enable config-download option. bmpActionDisable - Disable config-download option. Default is bmpActionEnable.')
bmpDhcpTimeout = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 23, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 50))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: bmpDhcpTimeout.setStatus('current')
if mibBuilder.loadTexts: bmpDhcpTimeout.setDescription('Configure the DHCP timeout value. Default is infinity which can be set using value 0')
bmpRetryCount = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 23, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 6))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: bmpRetryCount.setStatus('current')
if mibBuilder.loadTexts: bmpRetryCount.setDescription('Configure the number of attempts to download a config file. Default value is 3.')
bmpUserDefinedString = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 23, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: bmpUserDefinedString.setStatus('current')
if mibBuilder.loadTexts: bmpUserDefinedString.setDescription('A textual string containing information about the option 60.')
bmpRelay = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 23, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("bmpActionEnable", 1), ("bmpActionDisable", 2))).clone('bmpActionDisable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: bmpRelay.setStatus('current')
if mibBuilder.loadTexts: bmpRelay.setDescription('Configure relay option in bmp to support option82 information. bmpActionEnable - Enable option82 - relay information. bmpActionDisable - Disable option82 - relay information. Default is bmpActionDisable.')
bmpRelayRemoteId = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 23, 1, 8), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: bmpRelayRemoteId.setStatus('current')
if mibBuilder.loadTexts: bmpRelayRemoteId.setDescription('A textual string to be appened for the remote-id value.')
mibBuilder.exportSymbols("DELL-NETWORKING-BMP-MIB", bmpConfigDownload=bmpConfigDownload, dellNetBmp=dellNetBmp, bmpAutoSave=bmpAutoSave, dellNetBmpMib=dellNetBmpMib, PYSNMP_MODULE_ID=dellNetBmpMib, bmpReloadType=bmpReloadType, bmpDhcpTimeout=bmpDhcpTimeout, bmpRelay=bmpRelay, bmpRetryCount=bmpRetryCount, bmpRelayRemoteId=bmpRelayRemoteId, bmpUserDefinedString=bmpUserDefinedString)
|
/*
* GET flow page.
*/
exports.view = function(req, res){
res.render('flow');
};
|
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""
import six
from cfnlint.rules import CloudFormationLintRule
from cfnlint.rules import RuleMatch
from cfnlint.helpers import RESOURCE_SPECS
class Join(CloudFormationLintRule):
"""Check if Join values are correct"""
id = 'E1022'
shortdesc = 'Join validation of parameters'
description = 'Making sure the join function is properly configured'
source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-join.html'
tags = ['functions', 'join']
def __init__(self):
"""Initialize the rule"""
super(Join, self).__init__()
self.list_supported_functions = []
self.singular_supported_functions = []
for intrinsic_type, intrinsic_value in RESOURCE_SPECS.get('us-east-1').get('IntrinsicTypes').items():
if 'List' in intrinsic_value.get('ReturnTypes', []):
self.list_supported_functions.append(intrinsic_type)
if 'Singular' in intrinsic_value.get('ReturnTypes', []):
self.singular_supported_functions.append(intrinsic_type)
def _get_parameters(self, cfn):
"""Get all Parameter Names"""
results = {}
parameters = cfn.template.get('Parameters', {})
if isinstance(parameters, dict):
for param_name, param_values in parameters.items():
# This rule isn't here to check the Types but we need
# something valid if it doesn't exist
results[param_name] = param_values.get('Type', 'String')
return results
def _normalize_getatt(self, getatt):
""" Normalize getatt into an array"""
if isinstance(getatt, six.string_types):
return getatt.split('.', 1)
return getatt
def _is_ref_a_list(self, parameter, template_parameters):
""" Is a Ref a list """
list_params = [
'AWS::NotificationARNs',
]
odd_list_params = [
'CommaDelimitedList',
'AWS::SSM::Parameter::Value<CommaDelimitedList>',
]
if parameter in template_parameters:
if (
template_parameters.get(parameter) in odd_list_params or
template_parameters.get(parameter).startswith('AWS::SSM::Parameter::Value<List') or
template_parameters.get(parameter).startswith('List')):
return True
if parameter in list_params:
return True
return False
def _is_getatt_a_list(self, parameter, get_atts):
""" Is a GetAtt a List """
for resource, attributes in get_atts.items():
for attribute_name, attribute_values in attributes.items():
if resource == parameter[0] and attribute_name == '*':
if attribute_values.get('PrimitiveItemType'):
return 'FALSE'
if attribute_values.get('Type') == 'List':
return 'TRUE'
return 'UNKNOWN'
if resource == parameter[0] and attribute_name == parameter[1]:
if attribute_values.get('Type') == 'List':
return 'TRUE'
return 'FALSE'
def _match_string_objs(self, join_string_objs, cfn, path):
""" Check join list """
matches = []
template_parameters = self._get_parameters(cfn)
get_atts = cfn.get_valid_getatts()
if isinstance(join_string_objs, dict):
if len(join_string_objs) == 1:
for key, value in join_string_objs.items():
if key not in self.list_supported_functions:
message = 'Fn::Join unsupported function for {0}'
matches.append(RuleMatch(
path, message.format('/'.join(map(str, path)))))
elif key in ['Ref']:
if not self._is_ref_a_list(value, template_parameters):
message = 'Fn::Join must use a list at {0}'
matches.append(RuleMatch(
path, message.format('/'.join(map(str, path)))))
elif key in ['Fn::GetAtt']:
if self._is_getatt_a_list(self._normalize_getatt(value), get_atts) == 'FALSE':
message = 'Fn::Join must use a list at {0}'
matches.append(RuleMatch(
path, message.format('/'.join(map(str, path)))))
else:
message = 'Join list of values should be singular for {0}'
matches.append(RuleMatch(
path, message.format('/'.join(map(str, path)))))
elif not isinstance(join_string_objs, list):
message = 'Join list of values for {0}'
matches.append(RuleMatch(
path, message.format('/'.join(map(str, path)))))
else:
for string_obj in join_string_objs:
if isinstance(string_obj, dict):
if len(string_obj) == 1:
for key, value in string_obj.items():
if key not in self.singular_supported_functions:
message = 'Join unsupported function for {0}'
matches.append(RuleMatch(
path, message.format('/'.join(map(str, path)))))
elif key in ['Ref']:
if self._is_ref_a_list(value, template_parameters):
message = 'Fn::Join must not be a list at {0}'
matches.append(RuleMatch(
path, message.format('/'.join(map(str, path)))))
elif key in ['Fn::GetAtt']:
if self._is_getatt_a_list(self._normalize_getatt(value), get_atts) == 'TRUE':
message = 'Fn::Join must not be a list at {0}'
matches.append(RuleMatch(
path, message.format('/'.join(map(str, path)))))
else:
message = 'Join list of values should be singular for {0}'
matches.append(RuleMatch(
path, message.format('/'.join(map(str, path)))))
elif not isinstance(string_obj, six.string_types):
message = 'Join list of singular function or string for {0}'
matches.append(RuleMatch(
path, message.format('/'.join(map(str, path)))))
return matches
def match(self, cfn):
matches = []
join_objs = cfn.search_deep_keys('Fn::Join')
for join_obj in join_objs:
join_value_obj = join_obj[-1]
path = join_obj[:-1]
if isinstance(join_value_obj, list):
if len(join_value_obj) == 2:
join_string = join_value_obj[0]
join_string_objs = join_value_obj[1]
if not isinstance(join_string, six.string_types):
message = 'Join string has to be of type string for {0}'
matches.append(RuleMatch(
path, message.format('/'.join(map(str, path)))))
matches.extend(self._match_string_objs(join_string_objs, cfn, path))
else:
message = 'Join should be an array of 2 for {0}'
matches.append(RuleMatch(
path, message.format('/'.join(map(str, path)))))
else:
message = 'Join should be an array of 2 for {0}'
matches.append(RuleMatch(
path, message.format('/'.join(map(str, path)))))
return matches
|
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef GrAtlasTextBatch_DEFINED
#define GrAtlasTextBatch_DEFINED
#include "batches/GrVertexBatch.h"
#include "GrAtlasTextContext.h"
class GrAtlasTextBatch : public GrVertexBatch {
public:
DEFINE_BATCH_CLASS_ID
static const size_t kLCDTextVASize = sizeof(SkPoint) + sizeof(SkIPoint16);
// position + local coord
static const size_t kColorTextVASize = sizeof(SkPoint) + sizeof(SkIPoint16);
static const size_t kGrayTextVASize = sizeof(SkPoint) + sizeof(GrColor) + sizeof(SkIPoint16);
static const int kVerticesPerGlyph = 4;
static const int kIndicesPerGlyph = 6;
typedef GrAtlasTextContext::DistanceAdjustTable DistanceAdjustTable;
typedef GrAtlasTextBlob Blob;
typedef Blob::Run Run;
typedef Run::SubRunInfo TextInfo;
struct Geometry {
Blob* fBlob;
int fRun;
int fSubRun;
GrColor fColor;
SkScalar fTransX;
SkScalar fTransY;
};
static GrAtlasTextBatch* CreateBitmap(GrMaskFormat maskFormat, int glyphCount,
GrBatchFontCache* fontCache) {
GrAtlasTextBatch* batch = new GrAtlasTextBatch;
batch->fFontCache = fontCache;
switch (maskFormat) {
case kA8_GrMaskFormat:
batch->fMaskType = kGrayscaleCoverageMask_MaskType;
break;
case kA565_GrMaskFormat:
batch->fMaskType = kLCDCoverageMask_MaskType;
break;
case kARGB_GrMaskFormat:
batch->fMaskType = kColorBitmapMask_MaskType;
break;
}
batch->fBatch.fNumGlyphs = glyphCount;
batch->fGeoCount = 1;
batch->fFilteredColor = 0;
batch->fFontCache = fontCache;
batch->fUseBGR = false;
return batch;
}
static GrAtlasTextBatch* CreateDistanceField(int glyphCount, GrBatchFontCache* fontCache,
const DistanceAdjustTable* distanceAdjustTable,
SkColor filteredColor, bool isLCD,
bool useBGR) {
GrAtlasTextBatch* batch = new GrAtlasTextBatch;
batch->fFontCache = fontCache;
batch->fMaskType = isLCD ? kLCDDistanceField_MaskType : kGrayscaleDistanceField_MaskType;
batch->fDistanceAdjustTable.reset(SkRef(distanceAdjustTable));
batch->fFilteredColor = filteredColor;
batch->fUseBGR = useBGR;
batch->fBatch.fNumGlyphs = glyphCount;
batch->fGeoCount = 1;
return batch;
}
// to avoid even the initial copy of the struct, we have a getter for the first item which
// is used to seed the batch with its initial geometry. After seeding, the client should call
// init() so the Batch can initialize itself
Geometry& geometry() { return fGeoData[0]; }
void init() {
const Geometry& geo = fGeoData[0];
fBatch.fColor = geo.fColor;
fBatch.fViewMatrix = geo.fBlob->fViewMatrix;
// We don't yet position distance field text on the cpu, so we have to map the vertex bounds
// into device space
const Run& run = geo.fBlob->fRuns[geo.fRun];
if (run.fSubRunInfo[geo.fSubRun].fDrawAsDistanceFields) {
SkRect bounds = run.fVertexBounds;
fBatch.fViewMatrix.mapRect(&bounds);
this->setBounds(bounds);
} else {
this->setBounds(run.fVertexBounds);
}
}
const char* name() const override { return "TextBatch"; }
SkString dumpInfo() const override;
static size_t GetVertexStride(GrMaskFormat maskFormat) {
switch (maskFormat) {
case kA8_GrMaskFormat:
return kGrayTextVASize;
case kARGB_GrMaskFormat:
return kColorTextVASize;
default:
return kLCDTextVASize;
}
}
static size_t GetVertexStrideDf(GrMaskFormat maskFormat, bool useLCDText) {
SkASSERT(maskFormat == kA8_GrMaskFormat);
if (useLCDText) {
return kLCDTextVASize;
} else {
return kGrayTextVASize;
}
}
protected:
void computePipelineOptimizations(GrInitInvariantOutput* color,
GrInitInvariantOutput* coverage,
GrBatchToXPOverrides* overrides) const override;
private:
void initBatchTracker(const GrXPOverridesForBatch& overrides) override;
struct FlushInfo {
SkAutoTUnref<const GrVertexBuffer> fVertexBuffer;
SkAutoTUnref<const GrIndexBuffer> fIndexBuffer;
int fGlyphsToFlush;
int fVertexOffset;
};
void onPrepareDraws(Target* target) const override;
GrAtlasTextBatch() : INHERITED(ClassID()) {} // initialized in factory functions.
~GrAtlasTextBatch() {
for (int i = 0; i < fGeoCount; i++) {
fGeoData[i].fBlob->unref();
}
}
GrMaskFormat maskFormat() const {
switch (fMaskType) {
case kLCDCoverageMask_MaskType:
return kA565_GrMaskFormat;
case kColorBitmapMask_MaskType:
return kARGB_GrMaskFormat;
case kGrayscaleCoverageMask_MaskType:
case kGrayscaleDistanceField_MaskType:
case kLCDDistanceField_MaskType:
return kA8_GrMaskFormat;
}
return kA8_GrMaskFormat; // suppress warning
}
bool usesDistanceFields() const {
return kGrayscaleDistanceField_MaskType == fMaskType ||
kLCDDistanceField_MaskType == fMaskType;
}
bool isLCD() const {
return kLCDCoverageMask_MaskType == fMaskType ||
kLCDDistanceField_MaskType == fMaskType;
}
template <bool regenTexCoords, bool regenPos, bool regenCol, bool regenGlyphs>
inline void regenBlob(Target* target, FlushInfo* flushInfo, Blob* blob, Run* run,
TextInfo* info, SkGlyphCache** cache,
SkTypeface** typeface, GrFontScaler** scaler, const SkDescriptor** desc,
const GrGeometryProcessor* gp, int glyphCount, size_t vertexStride,
GrColor color, SkScalar transX, SkScalar transY) const;
inline void flush(GrVertexBatch::Target* target, FlushInfo* flushInfo) const;
GrColor color() const { return fBatch.fColor; }
const SkMatrix& viewMatrix() const { return fBatch.fViewMatrix; }
bool usesLocalCoords() const { return fBatch.fUsesLocalCoords; }
int numGlyphs() const { return fBatch.fNumGlyphs; }
bool onCombineIfPossible(GrBatch* t, const GrCaps& caps) override;
// TODO just use class params
// TODO trying to figure out why lcd is so whack
GrGeometryProcessor* setupDfProcessor(const SkMatrix& viewMatrix, SkColor filteredColor,
GrColor color, GrTexture* texture) const;
struct BatchTracker {
GrColor fColor;
SkMatrix fViewMatrix;
bool fUsesLocalCoords;
bool fColorIgnored;
bool fCoverageIgnored;
int fNumGlyphs;
};
BatchTracker fBatch;
// The minimum number of Geometry we will try to allocate.
enum { kMinGeometryAllocated = 4 };
SkAutoSTMalloc<kMinGeometryAllocated, Geometry> fGeoData;
int fGeoCount;
enum MaskType {
kGrayscaleCoverageMask_MaskType,
kLCDCoverageMask_MaskType,
kColorBitmapMask_MaskType,
kGrayscaleDistanceField_MaskType,
kLCDDistanceField_MaskType,
} fMaskType;
bool fUseBGR; // fold this into the enum?
GrBatchFontCache* fFontCache;
// Distance field properties
SkAutoTUnref<const DistanceAdjustTable> fDistanceAdjustTable;
SkColor fFilteredColor;
typedef GrVertexBatch INHERITED;
};
#endif
|
'use strict';
/* Module for UserAccount */
var userAccountModule = angular.module('userAccount.module', ['myApp']);
/**
* Module for userAccount
*/
userAccountModule.config(['$routeProvider', function($routeProvider) {
// Pages routes
$routeProvider.when('/userAccount', {templateUrl: 'partials/useraccount/useraccount_list.html', controller: 'UserAccountCtrl'});
$routeProvider.when('/userAccount/new', {templateUrl: 'partials/useraccount/useraccount_form.html', controller: 'UserAccountCtrl'});
$routeProvider.when('/userAccount/:id', {templateUrl: 'partials/useraccount/useraccount_form.html', controller: 'UserAccountCtrl'});
}]);
|
import get from 'lodash/get';
angular.module('App').controller(
'HostingUpgradeOfferCtrl',
class HostingUpgradeOfferCtrl {
constructor(
$scope,
$rootScope,
$state,
$stateParams,
$translate,
$window,
Alerter,
apiTranslator,
atInternet,
Hosting,
WucUser,
) {
this.$scope = $scope;
this.$rootScope = $rootScope;
this.$state = $state;
this.$stateParams = $stateParams;
this.$translate = $translate;
this.$window = $window;
this.Alerter = Alerter;
this.apiTranslator = apiTranslator;
this.atInternet = atInternet;
this.Hosting = Hosting;
this.WucUser = WucUser;
}
$onInit() {
this.productId = this.$stateParams.productId;
this.availableOffers = [];
this.durations = null;
this.loading = {
availableOffers: true,
durations: false,
validation: false,
};
this.model = {
offer: null,
startTime: '12:00',
duration: null,
agree: false,
downgradeAgree: false,
};
this.WucUser.getUser().then((user) => {
this.ovhSubsidiary = user.ovhSubsidiary;
});
this.Hosting.getSelected(this.productId)
.then((hosting) => {
this.hosting = hosting;
return this.Hosting.getAvailableOffer(this.productId);
})
.then((availableOffers) => {
this.availableOffers = availableOffers.map((offer) => ({
name: this.$translate.instant(
`hosting_dashboard_service_offer_${offer}`,
),
value: offer,
}));
})
.catch(() => {
this.availableOffers = [];
})
.finally(() => {
this.loading.availableOffers = false;
});
}
getDurations() {
this.durations = {
available: [],
details: {},
};
this.loading.durations = true;
return this.Hosting.getUpgradePrices(
get(this.hosting, 'serviceName', this.$stateParams.productId),
this.model.offer.value,
)
.then((durations) => {
this.durations.available = durations;
if (durations.length === 1) {
[this.model.duration] = this.durations.available;
}
})
.catch((err) => {
this.Alerter.alertFromSWS(
this.$translate.instant('hosting_order_upgrade_error'),
this.apiTranslator.translate(err),
this.$scope.alerts.page,
);
this.$state.go('^');
})
.finally(() => {
this.loading.durations = false;
});
}
formatTime(startTime) {
const now = moment();
const time = moment(startTime, 'HH:mm:ss');
const isToday = time.diff(now) > 0;
return this.$translate.instant(
isToday
? 'hosting_order_upgrade_start_time_summary_today'
: 'hosting_order_upgrade_start_time_summary_tomorrow',
{ time: time.format('LT (UTCZ)') },
);
}
formatPrice(price) {
return price.value === 0
? this.$translate.instant('price_free')
: this.$translate.instant('price_ht_label', { price: price.text });
}
orderUpgrade() {
this.atInternet.trackClick({
name: 'web::hosting::upgrade::confirm',
type: 'action',
});
this.loading.validation = true;
const win = this.$window.open('', '_blank');
win.referrer = null;
win.opener = null;
const startTime = moment(this.model.startTime, 'HH:mm:ss')
.utc()
.format('HH:mm:ss');
return this.Hosting.orderUpgrade(
get(this.hosting, 'serviceName', this.$stateParams.productId),
this.model.offer.value,
this.model.duration.duration,
this.hosting.isCloudWeb ? startTime : null,
)
.then((order) => {
this.Alerter.success(
this.$translate.instant('hosting_order_upgrade_success', {
t0: order.url,
t1: order.orderId,
}),
this.$scope.alerts.page,
);
this.atInternet.trackOrder({
name: `[hosting]::${this.model.offer.value}[${this.model.offer.value}]`,
page: 'web::payment-pending',
orderId: order.orderId,
priceTaxFree: order.prices.withoutTax.value,
price: order.prices.withTax.value,
status: 1,
});
win.location = order.url;
})
.catch((err) => {
this.Alerter.alertFromSWS(
this.$translate.instant('hosting_order_upgrade_error'),
err,
this.$scope.alerts.page,
);
win.close();
})
.finally(() => {
this.loading.validation = false;
this.$state.go('^');
});
}
static isProrataDuration({ duration }) {
return /^upto/.test(duration);
}
},
);
|
function searchresultlocator(resultpos){
$$(".page-content").scrollTop(0);
topd = $$("#"+resultpos).offset();
tops = topd.top;
$$(".page-content").scrollTop(tops - 50, 1000);
resultparagraph = $$("#"+resultpos).css('font-weight', 'bold');
boldSearch($$("#"+resultpos).html());
$$("#"+resultpos).html(newword);
};
function boldSearch(editedstring){
for (b = 0; b<aresult.length; b++){
var regword = new RegExp(aresult[b], "gi");
newword = editedstring.replace(regword, aresult[b].toUpperCase());
editedstring = newword;
}
return newword;
}
$$('.opensearch').on('click', function(){
myApp.prompt('enter search keyword(s)', 'MANUAL SEARCH', function(value){
searchkeywords(value);
}, function(){
$$('.secs').removeClass('paddedsecs');
});
}
);
function searchkeywords(keywords){
a = keywords;
if (a.replace(/^\s+|\s+$/g, "").length != 0)
myApp.openPanel('right');
a = a.replace(/^\s+|\s+$/g, "");
aresult = [];
aresult = a.split(" ");
searchquery = "%";
searchquery += aresult.join("%");
searchquery += "%";
bresult = [];
for (xx=0; xx<aresult.length; xx++)
bresult[xx] = '%' + aresult[xx] + '%';
queryconstrct(bresult);
function queryconstrct(thearray){
myquery = "SELECT * FROM manual WHERE chapter = "+ currentChapter +" and content like '" + thearray[0] +"'";
for (o=1; o<thearray.length; o++)
myquery += " or content like '" + thearray[o] +"' and chapter = "+ currentChapter;
return myquery;
}
db.transaction(function(tx) {tx.executeSql(""+myquery+"", [],
function (tx, results){
var resultContent = "";
sec = 0;
for(i=0; i<results.rows.length; i++){
item = results.rows.item(i);
if (!(item.section == sec)){
sec = item.section;
subsectitleEd = subsectitle[sec - 1];
boldSearch(subsectitleEd);
resultContent += '<a href="#section'+sec+'"class="external panellinks"><p class="secs">' + newword + '</p></a>';
}
boldSearch(item.content);
trimOutput(newword, aresult);
function trimOutput(tobetrimmed, searchq){
tobetrimmedupper = tobetrimmed.toUpperCase();
pos1 = tobetrimmed.length;
pos2 = 0;
for (z=0; z<searchq.length; z++){
regword = searchq[z].toUpperCase();
postest = tobetrimmedupper.indexOf(regword);
if (postest<pos1 && postest!=-1)
pos1 = postest;
postest = tobetrimmedupper.lastIndexOf(regword) + searchq[z].length;
if (postest > pos2)
pos2 = postest;
}
if (pos2 > 60){
if ((pos2 - pos1)> 60){
if (pos1 > 20){
newword = '...'+tobetrimmed.substr(pos1 - 15, 30)+'...';
newword += '...'+tobetrimmed.substr(pos2 - 15, 30)+'...';
return newword;
}
newword = '...'+tobetrimmed.substr(0, 30)+'...';
newword += '...'+tobetrimmed.substr(pos2 - 15, 30)+'...';
return newword;
}
newword = '...'+tobetrimmed.substr(pos1, 60)+'...';
return newword;
}
newword = '...'+tobetrimmed.substr(0, 60)+'...';
return newword;
}
pagepara = ""+item.page + item.paragraph;
resultContent = resultContent + '<a href="#" class="searchresultlink panellinks" onclick=searchresultlocator('+pagepara+');><p>'+ newword + '</p></a>';
}
if (resultContent.length == 0){
boldSearch(a);
resultContent = "no results found matching "+newword+" try another keyword";
}
$$('#results-content').html(resultContent);
$$('.panellinks').on('click', function(e){
myApp.closePanel();
});
}
);});
};
|
'''
lua_call - a Redis + Lua scripting namespace and calling library for Python
Copyright 2014 Josiah Carlson
This library released under the MIT license.
What is lua_call?
=================
This library implements a script transformation function along with some
useful utilities to allow you to call Lua scripts from other Lua scripts
in Redis. There are also some Python-side wrappers to aid in calling Lua from
Python, but that's just a bonus.
Generally speaking, it adds an internal calling semantic that allows you to
pass `KEYS` and `ARGV` between your internal Lua scripts in a sane manner.
This allows you, as a developer, to to develop your Lua scripts using better
practices than copying/pasting similar code between scripts.
Limitations
===========
Due to the way we handle calling conventions, you must be careful in how you
use `KEYS` and `ARGV`. Because we are not using a full-on parser for the Lua
language, we use a regular expression to discover uses of `KEYS` and `ARGV` to
alter. More specifically, we take examples like the following::
local passed_keys = KEYS
local source = KEYS[1]
local arg = ARGV[1]
local z = redis.call('KEYS', ...)
... and translate them into::
local passed_keys = _KEYS
local source = _KEYS[1]
local arg = _ARGV[1]
local z = redis.call('KEYS', ...)
Note that we didn't mangle the `KEYS` in `redis.call()`, but if you were to
have the following::
local string = 'this is a string with KEYS and ARGV, oops!'
... we will mangle the string into::
local string = 'this is a string with _KEYS and _ARGV, oops!'
There are other potential corner cases where our name mangling might be
incorrect, and you are advised to keep your usage of `KEYS` and `ARGV` to
reading or writing to `KEYS` and `ARGV` or to the simple literal strings of
`'KEYS'` and `'ARGV'` as in `redis.call('KEYS', ...)`.
Defining scripts using lua_call
===============================
You have a Redis connection during script definition
----------------------------------------------------
If you have your Redis connection available while defining your Lua scripts,
you can use the following calls to automatically define and register the
function wrappers in the Python module, automatically load the script into
Redis, and register the function for internal calling inside Redis::
# contents of example.py
from redis import Redis
from lua_call import function
conn = Redis(...)
function .return_args("""
return ARGV
""", conn)
function .call_return("""
CALL.return_args({}, {1, 2, 3, ARGV})
""", conn)
We describe how to use these functions just past the next section.
You don't have a Redis connection during script definition
----------------------------------------------------------
If you don't have a connection during script definition, you can omit the
connection argument during definition. In this case, the scripts will not be
registered, so you must later call `load_scripts()` to register them. The
following is more or less equivalent to the 'have a connection' section
above::
# contents of example.py
from redis import Redis
from lua_call import function, load_scripts
function .return_args("""
return ARGV
""")
function .call_return("""
CALL.return_args({}, {1, 2, 3, ARGV})
""")
load_scripts(Redis(), __name__)
Calling scripts defined with lua_call
=====================================
Assuming that you have defined your scripts using one of the two methods
outlined above, the `example` module will have functions defined in the module
namespace called `return_args()` and `call_return()`. These wrappers around
the script take exactly 3 arguments: a Redis connection, then a list of `KEYS`
and a list of `ARGV` that are passed to the called scripts.
An example of their use can be seen below::
>>> from redis import Redis
>>> conn = Redis()
>>> import example
>>> example.return_args(conn, [], [1, 2, 3])
['1', '2', '3']
>>> example.call_return(conn, [], [4, 5, 6])
[1, 2, 3, ['4', '5', '6']]
Note that while KEYS and ARGV passed from outside Redis are translated into
strings as part of the calling process, internal calls do not change the types
of arguments passed.
How it works
============
This library takes scripts that you define, possibly including other Lua
script calls, and changes the source code to allow you to actually perform
those calls. Generally speaking, you can think of this as introducing a new
global value in Redis by the name of `CALL`, which allows you to both register
functions and call those functions. Now, the truth is that there is no new
global value available in Redis Lua scripting, but your scripts will act as
though that is the case.
As an example of what actually goes on, let's say that we start out with a Lua
script defined as the below, which is from the included `example.py`::
return CALL.return_args({}, {1, 2, 3, _ARGV})
After our transformation (and applying some source code formatting and extra
comments so you can understand what is going on easier), we get the following
script::
-- We reference either the externally-called KEYS/ARGV or the internally
-- called KEYS/ARGV in locals called _KEYS and _ARGV
local _KEYS, _ARGV;
if #ARGV == 0 or type(ARGV[#ARGV]) == 'string' then
-- Use the standard KEYS and ARGV as passed from the external caller
_KEYS = KEYS;
_ARGV = ARGV;
else
-- Pull the KEYS and ARGV from the table appended to ARGV
_KEYS = ARGV[#ARGV][1];
_ARGV = ARGV[#ARGV][2];
-- We remove the pushed reference to prevent circular references,
-- which can crash Redis if you aren't careful
table.remove(ARGV);
end;
-- push the arguments onto the ARGV table as call stack arguments
table.insert(ARGV, {{}, {1, 2, 3, _ARGV}});
-- fetch the script hash from the name and call the function
return _G[redis.call('HGET', ':registry', 'example.return_args')]();
Generally, there is some header code prepended to your source, KEYS and ARGV
references are changed to _KEYS and _ARGV, and any time you want to make a
call to another script, we append your arguments to the end of the ARGV table,
and pull the destination script name from a Redis-backed function registry.
Early versions of this library required assigning the result of a call to a
local variable before returning, but this is no longer necessary.
Licensing and source code mangling
==================================
Technically speaking, this library will alter the Lua script source code that
you pass in order to insert the code that handles internal calls. I do not
consider this purposeful alteration to result in your code being in any way
derived from or related to this library. Your source code remains your source
code, and this library is a utility to aid in your development and maintenance
processes.
'''
from hashlib import sha1
import re
import sys
__all__ = ['dummy', 'function', 'load_scripts']
VERSION = '0.10.0'
REGISTRY = {}
#------------------------ our dummy Redis connection -------------------------
@apply
class dummy(object):
'''A fake Redis connection you can use to defer script registration.'''
def __getattr__(self, name):
return self
def __call__(self, *args, **kwargs):
return self
#------------------ This handles the script fixing/mangling ------------------
# This handles/fixes arguments to be consistent whether you are calling from
# outside or inside Redis.
CALL_HEADER = '''
local _KEYS, _ARGV;
if #ARGV == 0 or type(ARGV[#ARGV]) == 'string' then
_KEYS = KEYS;
_ARGV = ARGV;
else
_KEYS = ARGV[#ARGV][1];
_ARGV = ARGV[#ARGV][2];
table.remove(ARGV);
end;'''.replace('\r', '').replace('\n', ' ')
# We need to mangle our KEYS and ARGV references because we are using locals
# for it, as we are using the globals for alternate argument passing
KEYS_RE = re.compile('(?<!["\'])((?:KEYS)|(?:ARGV))(?!["\'])')
# Function calls is where we really start to gain some benefit. We're going to
# use the ARGV table to carry the KEYS and ARGV to the called function, with
# the header that we inserted above automatically handling external/internal
# calls and unpacking our passed KEYS and ARGV.
CALL_RE = re.compile(
'^(.*?)CALL[.]([a-zA-Z_][a-zA-Z0-9_]*(?:[.][a-zA-Z_][a-zA-Z0-9_]*)*)[(]([^()]+)[)]\s*?$', re.MULTILINE)
PUSH_STACK_CALL_FCN = '''table.insert(ARGV, {%s});%s_G[redis.call('HGET', ':registry', '%s')]();'''
def _fix_calls(script, module):
'''
This injects are function call handling header, fixes references to KEYS
and ARGV, and translates "Y = CALL.<name>(...)" function calls into the
Lua code necessary to make it all happen.
You shouldn't need to call this directly, but you can use this to
transform your Lua scripts if you don't want to use the rest of the
module.
'''
script = KEYS_RE.sub(r'_\1', script)
def fix_calls(match):
left, full, args = match.groups()
if '.' not in full:
full = (module + '.' + full).lstrip('.')
return PUSH_STACK_CALL_FCN%(args, left, full)
script = CALL_RE.sub(fix_calls, script)
return CALL_HEADER + script
#------------------ This handles the function registration -------------------
def load_scripts(conn, prefix=''):
'''
When given a Redis connection, this will register all known scripts in
Redis with their names included for subsequent calling. If you passed a
non-dummy Redis connection in your `function .fcn_name(..., conn)`
registry call, then you shouldn't need to call this.
If you only want to load a subset of known scripts, you can pass an
optional prefix to load. As an example, say that you have a module defined
like::
from lw import dummy, function, load_scripts
function .new('return 1', dummy)
def register(conn):
load_scripts(conn, __name__)
By calling the `register()` function you have defined with the Redis
connection, you will *only* register those scripts that were defined in
the module or submodules.
'''
prefix = '' if prefix == '__main__' else prefix
prefix = (prefix.rstrip('.') + '.') if prefix else ''
pipe = conn.pipeline(True)
added = 0
for full, (hash, fixed) in REGISTRY.iteritems():
if full.startswith(prefix):
pipe.script_load(fixed)
pipe.hset(':registry', full, hash)
added += 1
pipe.execute()
return added
@apply
class function(object):
'''
Use me to register your Lua functions like::
function .script_name('script contents', conn)
This tool will perform several operations:
* Transform your Lua script to allow for internal calls from other scripts
* Transform your Lua script to make any calls according to the rules
outlined in the documentation
* Register the wrapped Lua script in the globals of your calling module
to allow for easy calling
* If a valid Redis connection is passed, this will also register the
function inside Redis to be available for calling at any time
.. Note: omitting the Redis connection requires a later
`load_scipts(conn)` call
'''
def __getattr__(self, name):
return _register(name)
def _register(name):
'''Internal implementation detail, you can ignore me.'''
if '.' in name:
raise ValueError("Cannot define a function name with an included period")
def call(script, conn=dummy):
gl = sys._getframe(1).f_globals
module = gl['__name__']
if module == '__main__':
module = ''
full = (module + '.' + name).lstrip('.')
# fix/mangle the script
fixed = _fix_calls(script, module)
hash = sha1(fixed).hexdigest()
# register the function in Redis
hash2 = conn.pipeline(True) \
.script_load(fixed) \
.hset(':registry', full, 'f_' + hash) \
.execute()
# keep a local copy
REGISTRY[full] = ('f_' + hash, fixed)
# register the name in the namespace
gl[name] = f = _caller(hash)
return f
return call
def _caller(hash):
'''Internal implementation detail, you can ignore me.'''
def call(conn, keys, argv):
return conn.evalsha(hash, len(keys), *(list(keys) + list(argv)))
return call
|