text
stringlengths
65
6.05M
lang
stringclasses
8 values
type
stringclasses
2 values
id
stringlengths
64
64
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var objmap = require('object-map'); var objkeysmap = require('object-keys-map'); var deepEqual = require('deep-equal'); var extend = typeof Object.assign === 'function' ? Object.assign : require('node-extend'); function addDesign(s) { return '_design/' + s; } function normalizeDoc(doc, id) { function normalize(doc) { doc = extend({}, doc); Object.keys(doc).forEach(function(prop) { var type = typeof doc[prop]; if(type === 'object') { doc[prop] = normalize(doc[prop]); } else if(type === 'function') { doc[prop] = doc[prop].toString(); } }); return doc; } var output = normalize(doc); output._id = id || doc._id; output._rev = doc._rev; return output; } function docEqual(local, remote) { if(!remote) return false; return deepEqual(local, remote, {strict: true}); } var pouchSeed = module.exports = function (db, design, cb) { if (!db || !design) { throw new TypeError('`db` and `design` are required'); } var local = objmap(objkeysmap(design, addDesign), normalizeDoc); var seedPromise = db.allDocs({ include_docs: true, keys: Object.keys(local) }) .then(function (docs) { var remote = {}; docs.rows.forEach(function (doc) { if (doc.doc) { remote[doc.key] = doc.doc; } }); var update = Object.keys(local).filter(function(key) { if(!remote[key]) return true; local[key]._rev = remote[key]._rev; return !docEqual(local[key], remote[key]); }).map(function(key) { return local[key]; }); if (update.length > 0) { return db.bulkDocs({ docs: update }); } else { return Promise.resolve(false); } }) .then(function(result) { if(typeof cb === 'function') { cb(null, result); } return Promise.resolve(result); }) .catch(function(err) { if(typeof cb === 'function') { cb(err, null); } console.log(err); return Promise.reject(err); }); return seedPromise; }; if(typeof window === 'object') { window.pouchSeed = pouchSeed; } },{"deep-equal":2,"node-extend":6,"object-keys-map":8,"object-map":9}],2:[function(require,module,exports){ var pSlice = Array.prototype.slice; var objectKeys = require('./lib/keys.js'); var isArguments = require('./lib/is_arguments.js'); var deepEqual = module.exports = function (actual, expected, opts) { if (!opts) opts = {}; // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (actual instanceof Date && expected instanceof Date) { return actual.getTime() === expected.getTime(); // 7.3. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if (!actual || !expected || typeof actual != 'object' && typeof expected != 'object') { return opts.strict ? actual === expected : actual == expected; // 7.4. For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else { return objEquiv(actual, expected, opts); } } function isUndefinedOrNull(value) { return value === null || value === undefined; } function isBuffer (x) { if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false; if (typeof x.copy !== 'function' || typeof x.slice !== 'function') { return false; } if (x.length > 0 && typeof x[0] !== 'number') return false; return true; } function objEquiv(a, b, opts) { var i, key; if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; //~~~I've managed to break Object.keys through screwy arguments passing. // Converting to array solves the problem. if (isArguments(a)) { if (!isArguments(b)) { return false; } a = pSlice.call(a); b = pSlice.call(b); return deepEqual(a, b, opts); } if (isBuffer(a)) { if (!isBuffer(b)) { return false; } if (a.length !== b.length) return false; for (i = 0; i < a.length; i++) { if (a[i] !== b[i]) return false; } return true; } try { var ka = objectKeys(a), kb = objectKeys(b); } catch (e) {//happens when one is a string literal and the other isn't return false; } // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!deepEqual(a[key], b[key], opts)) return false; } return typeof a === typeof b; } },{"./lib/is_arguments.js":3,"./lib/keys.js":4}],3:[function(require,module,exports){ var supportsArgumentsClass = (function(){ return Object.prototype.toString.call(arguments) })() == '[object Arguments]'; exports = module.exports = supportsArgumentsClass ? supported : unsupported; exports.supported = supported; function supported(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; }; exports.unsupported = unsupported; function unsupported(object){ return object && typeof object == 'object' && typeof object.length == 'number' && Object.prototype.hasOwnProperty.call(object, 'callee') && !Object.prototype.propertyIsEnumerable.call(object, 'callee') || false; }; },{}],4:[function(require,module,exports){ exports = module.exports = typeof Object.keys === 'function' ? Object.keys : shim; exports.shim = shim; function shim (obj) { var keys = []; for (var key in obj) keys.push(key); return keys; } },{}],5:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],6:[function(require,module,exports){ module.exports = require('./lib/extend'); },{"./lib/extend":7}],7:[function(require,module,exports){ var util = require('util'); module.exports = extend; function extend(A,B,as,isAargs){ var ___A___ = A; var ___B___ = B; if(arguments.length < 2){ throw new Error('arguments is error!'); } var args = ""; if(arguments.length > 2){ if(isAargs){ }else{ args = 'var args = '+JSON.stringify(as)+';'; } } var s = A.toString(); var footer = '}' var header = s.match(/^(function)(.)*{/gi); var e = ''; if(isAargs){e += '___B___.apply(this,arguments);'}else{e += '___B___.apply(this);';} e+='___A___.apply(this,arguments)'; var ss = header+e+footer console.log(args) var nn = eval('('+ss+')'); var ap = A.prototype; util.inherits(nn,B); for(var k in B){ nn[k] = B[k]; } for(var k in A){ nn[k] = A[k]; } for(var k in ap){ nn.prototype[k] = ap[k]; } return nn; } },{"util":12}],8:[function(require,module,exports){ module.exports = function objectKeysMap(o, f, t) { var ret = {}; if (typeof f !== 'function') { throw new TypeError('`f` has to be a function'); } Object.keys(o).forEach(function (k) { ret[f.call(t || this, k, o[k], o)] = o[k]; }); return ret; }; },{}],9:[function(require,module,exports){ module.exports = function (object, cb, context) { var newObject = {} for (key in object) { if (!object.hasOwnProperty(key)) continue; newObject[key] = cb.call(context, object[key], key, object); } return newObject; } },{}],10:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],11:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } },{}],12:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // 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. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = require('inherits'); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./support/isBuffer":11,"_process":10,"inherits":5}]},{},[1]);
JavaScript
CL
447eba1981150b9cd94ea870329639d69ad71fbdc6f4c3e850450225b40b6ab1
import React from "react"; import { HashRouter as Router, Switch, Route } from "react-router-dom"; import { Container, Box, Breadcrumbs, Typography } from "@material-ui/core"; import Menu from "./Layout/Menu"; import CustomAppBar from "./Layout/CustomAppBar"; import Home from "./views/Home"; import HeapSort from "./views/HeapSort"; import MaxHeapInsert from "views/MaxHeapInsert"; import MaxHeapify from "views/MaxHeapify"; import FCFS from "views/FCFS"; import RoundRobin from "views/RoundRobin"; import LUDecomposition from "views/LUDecomposition"; import FFT from "views/FFT"; export default function App() { const [drawer, setDrawerState] = React.useState(false); const toggleDrawer = open => event => { if ( event.type === "keydown" && (event.key === "Tab" || event.key === "Shift") ) { return; } setDrawerState(open); }; function getBreadcrumbs(props) { let routeNames = props.match.url .substring(1) .replace(/-/g, " ") .split("/"); return ( <Breadcrumbs aria-label="breadcrumb"> {routeNames.map(x => ( <Typography key={x} variant={6}> {x} </Typography> ))} </Breadcrumbs> ); } return ( <Router basename="/"> <Menu drawer={drawer} onClose={toggleDrawer(false)} /> <CustomAppBar onClick={toggleDrawer(true)} /> <Box pt={2} pl={2}> {<Route path="*" component={getBreadcrumbs} />} </Box> <Container> <Box pt={1}> <Switch> <Route path="/Advanced-OperatingSystem/FCFS"> <FCFS /> </Route> <Route path="/Advanced-OperatingSystem/Round-Robin"> <RoundRobin /> </Route> <Route path="/Advanced-Algorithms/Max-Heap-Insert"> <MaxHeapInsert /> </Route> <Route path="/Advanced-Algorithms/Max-Heapify"> <MaxHeapify /> </Route> <Route path="/Advanced-Algorithms/Heap-Sort"> <HeapSort /> </Route> <Route path="/Advanced-Algorithms/LU-Decomposition"> <LUDecomposition /> </Route> <Route path="/Advanced-Algorithms/FFT"> <FFT /> </Route> <Route path="/"> <Home /> </Route> </Switch> </Box> </Container> </Router> ); }
JavaScript
CL
12a1773ff8b9ec0969ea50dd5790422af63b3ddc5627ecba9abcd311177c0458
import Vue from "vue"; import Router from "vue-router"; import Home from "./Home"; import uploadBD from "./uploadBD"; import Login from "./Login"; import Signup from "./Signup"; import { checkUser } from "@/api/auth"; import AddMaster from "./addMaster"; import AddPublisher from "./AddPublisher"; import AddArtist from "./AddArtist"; import AddSeries from "./AddSeries"; import AddRelease from "./AddRelease"; import Master from "./Master"; import Artist from "./Artist"; import Publisher from "./Publisher"; import Browse from "./Browse"; import BrowseArtists from "./BrowseArtists"; import BrowsePublishers from "./BrowsePublishers"; Vue.use(Router); const router = new Router({ mode: "history", routes: [ { path: "/", component: Home }, { path: "/add-master", component: AddMaster, meta: { requiresAuth: true } }, { path: "/add-publisher", component: AddPublisher, meta: { requiresAuth: true } }, { path: "/add-release", component: AddRelease, meta: { requiresAuth: true } }, { path: "/add-series", component: AddSeries, meta: { requiresAuth: true } }, { path: "/add-artist", component: AddArtist, meta: { requiresAuth: true } }, { path: "/login", component: Login, meta: { // the meta object can contain any information // about the route that you may want to use // elsewhere, like in beforeEach requiresNonAuth: true } }, { path: "/signup", component: Signup, meta: { // It's also reusable! requiresNonAuth: true } }, { path: "/uploadBD", component: uploadBD, meta: { requiresNonAuth: true } }, { path: "/browse", component: Browse }, { path: "/browseArtists", component: BrowseArtists }, { path: "/browsePublishers", component: BrowsePublishers }, { path: "/masters/:id", component: Master }, { path: "/artists/:id", component: Artist }, { path: "/publisher", component: Publisher } ] }); // The callback passed to beforeEach will // get executed every time we try to navigate // There we can check the meta attribute router.beforeEach((to, from, next) => { // Warning: This doesn't work for nested routes! // If you have nested routes use the version at // https://router.vuejs.org/en/advanced/meta.html if (to.meta.requiresAuth) { // The navigation may happen before the root (new Vue in main.js) // is created (hook where we call checkUser), to prevent that, // we call it here checkUser(router.app.$root); if (!router.app.$root.user) { // we return because we can only call next once // next with a parameter allows us to control // where we redirect the user return next({ path: "/login", query: { // URL queries cannot contain specific characters // like / or ?, so we use encodeURIComponent // to transform it into a valide query value // We will have to use the complementary function // decodeURIComponent to get the orginial value redirect: encodeURIComponent(to.fullPath) } }); } } // we must always call next to let the // navigation happen next(); }); // This one is pretty much the opposite // We only want guests to access login and // signup pages. It's probably an error on // their end if they try to go to login or // signup while logged in, so we redirect // them to a more welcoming place :) router.beforeEach((to, from, next) => { if (to.meta.requiresNonAuth) { checkUser(router.app.$root); if (router.app.$root.user) return next("/"); } next(); }); export default router;
JavaScript
CL
bfad1ab2f56f10044c833f0d48d1c89c4ed6104536f147170a175ac31241e597
import React from 'react'; import { Field, reduxForm } from 'redux-form'; //Field is a Component, reduxForm is a function class StreamForm extends React.Component { renderInput = formProps => { // formProps object which was senf by redux form // console.log(formProps); // {input: {…}, meta: {…}} // !input object on formProps // input: // name: "title" // onBlur: ƒ (event) // onChange: ƒ (event) // onDragStart: ƒ (event) // onDrop: ƒ (event) // onFocus: ƒ (event) // value: "" //__;proto__: Object const className = `field ${ formProps.meta.touched && formProps.meta.error ? 'error' : '' }`; return ( <div className={className}> <label>{formProps.label}</label> <input {...formProps.input} /> {this.renderError(formProps.meta)} </div> ); }; renderError = meta => { if (meta.touched && meta.error) { //If user some touched the input once then touched will be true return ( <div className="ui error message"> <div className="header">{meta.error}</div> </div> ); } }; onSubmit = formValues => { //e.preventDefault(); => Redux form will do for us // console.log(formValues); {title: "reactsj crash course", description: "silver in color"} this.props.onSubmit(formValues); }; render() { return ( <form //handleSubmit will be provided by redux-form to us. onSubmit={this.props.handleSubmit(this.onSubmit)} className="ui form error" > <Field name="title" label="Enter Title" component={this.renderInput} /> <Field name="description" label="Enter Description" component={this.renderInput} /> <button className="ui button primary">Submit</button> </form> ); } } const validate = formValues => { const errors = {}; if (!formValues.title) { errors.title = 'you must enter a title'; } if (!formValues.description) { errors.description = 'you must include a description'; } return errors; }; export default reduxForm({ form: 'streamForm', validate: validate })(StreamForm);
JavaScript
CL
33c36aedee6a684abace7ce02a5d6c9b37f96396fef482449c5ebef9f7fef38d
import { GET_BUSINESSES } from "@gql/getBusinesses"; import { initializeApollo } from "../libs/apolloClient"; import BusinessesContainer from "@components/Containers/BusinessesContainer"; import { Box, Text } from "@chakra-ui/react"; import Error from "next/error"; import { initializeStore } from "libs/redux"; const Search = ({ businesses, statusCode }) => { if (statusCode !== 200) { return <Error statusCode={statusCode} />; } return ( <> <Box as="h1" mb="4"> Resultados de la busqueda: </Box> {businesses.length < 1 ? ( <Text as="h3" color="blue.600"> No se encontro ningun resultado. </Text> ) : ( <BusinessesContainer businesses={businesses} /> )} </> ); }; export default Search; export async function getServerSideProps(ctx) { const apolloClient = initializeApollo(); const reduxStore = initializeStore(); let businesses = []; const { dispatch } = reduxStore; if (ctx.query.location && ctx.query.term) { try { const { term, location } = ctx.query; const { data } = await apolloClient.query({ query: GET_BUSINESSES, variables: { term, location }, }); businesses = data.search.business; dispatch({ type: "UPDATE", payload: data.search.business, }); return { props: { initialReduxState: reduxStore.getState(), businesses, statusCode: 200, }, }; } catch (e) { ctx.statusCode = 503; return { props: { businesses, statusCode: 503 } }; } } else { return { redirect: { destination: "/", permanent: false, }, }; } }
JavaScript
CL
f55a1b2b9fbaff87922e1c121deb89432c8298c8797419617d40fe9ca47f3a06
/*! * @namespace BAT * @element bat.keep * @homepage batjs.github.io * * @status beta * @version 0.0.1 * @author Jo Santana * @license Released under the MIT license * * @usage: * * Bat.keep.set('batman', 'hero', 7); * Bat.keep.get('batman'); // Returns "hero". * Bat.keep.delete('batman'); // Goodbye, Bruce. */ (function() { 'use strict'; // Declare root variable - window in the browser, global on the server // Get already define BAT object (if available) or create a new object var root = this, Bat = root.Bat || {}; /* * BAT keep */ Bat.keep = (function () { return { /* * Return the supported storage type * * @attribute remaining * @type object */ storageType: function () { return ('localStorage' in window && window.localStorage !== null) ? 'localStorage' : 'cookie'; }, /* * Return string in timestamp format * * @attribute remaining * @type object */ timestamper: function (days, format) { days = (typeof days !== 'undefined') ? days : 0; format = (typeof format !== 'undefined') ? format : false; var date = new Date(), milliseconds = (24 * 60 * 60 * 1000); date.setTime(date.getTime() + (days * milliseconds)); if (format) { date = date.toUTCString(); } return date; }, /* * Remaining time till data expires * * @attribute remaining * @type object */ remaining: { years : 0, days: 0, hours: 0 }, /* * Set a new data to be kept * * @attribute name * @type string * * @attribute value * @type string/number * * @attribute days * @type int */ set: function (name, value, days) { if (value) { this[this.storageType()].set(name, value, days); } else { Bat.log.info('BAT keep: Can\'t store empty data'); return false; } }, /* * Return the data value * * @attribute name * @type string */ get: function (name) { var data = this[this.storageType()].get(name) || this['cookie'].get(name); if (data) { var expirationInfo = [ ('BAT keep: "' + name + '" will expire in '), ((this.remaining.years > 0) ? [this.remaining.years, ' year'].join('') : ''), ((this.remaining.years > 1) ? 's ' : ' '), ((this.remaining.days > 0) ? [this.remaining.days, ' day'].join('') : ''), ((this.remaining.days > 1) ? 's' : ''), ((this.remaining.days > 0 && this.remaining.hours > 0) ? ' and ' : ''), ((this.remaining.hours > 0) ? [this.remaining.hours, ' hour'].join('') : 'few minutes'), ((this.remaining.hours > 1) ? 's' : ''), ' from ' + this.storageType() ].join(''); Bat.log.info(expirationInfo); return data; } else { return null; } }, /* * Delete data * * @attribute name * @type string */ delete: function (name) { this[this.storageType()].delete(name); }, cookie: { /* * Set a new data to be kept * * @attribute name * @type string * * @attribute value * @type string/number * * @attribute days * @type int */ set: function (name, value, days, customDomain) { var value = '=' + value + ';', expiresValue = Bat.keep.timestamper(days, true), expires = days ? ('expires=' + expiresValue + ';') : '', path = 'path=/;', domain = 'domain=' + customDomain || ('.' + Bat.url.subdomain() + '.' + Bat.url.domain() + '.' + Bat.url.tld()) + ';'; expiresValue = '=' + expiresValue + ';', document.cookie = name + value + expires + path + domain; document.cookie = name + '-expires' + expiresValue + expires + path + domain; console.log('keep-cookie-set', name, domain); if (days !== -1) { Bat.log.info('BAT keep: ' + name + ' [CREATED with cookies]'); } }, /* * Return the cookie value * * @attribute name * @type string */ get: function (name) { var i, nameXP = name + "-expires=", nameEQ = name + "=", cookies = document.cookie.split(';'); for (i = 0; i < cookies.length; i++) { var cookie = cookies[i]; while (cookie.charAt(0) === ' ') { cookie = cookie.substring(1, cookie.length); } if (cookie.indexOf(nameXP) === 0) { var difference = new Date(cookie.substring(nameXP.length, cookie.length) - Bat.keep.timestamper()); Bat.keep.remaining.days = difference.getUTCDate() - 1; Bat.keep.remaining.hours = difference.getUTCHours(); Bat.keep.remaining.years = difference.getUTCFullYear(); } if (cookie.indexOf(nameEQ) === 0) { return cookie.substring(nameEQ.length, cookie.length); } } return null; }, /* * Detele a cookie * * @attribute name * @type string */ delete: function (name) { this.set(name, '', -1); Bat.log.info('BAT keep: ' + name + ' [DELETED from cookies]'); } }, localStorage: { /* * Set a new data on localStorage * * @attribute name * @type string * * @attribute value * @type string/number * * @attribute days * @type int */ set: function (name, value, days) { try { window.localStorage.setItem(name, JSON.stringify({ 'value': value, 'timestamp': Bat.keep.timestamper(days) })); } catch(exception) { } Bat.log.info('BAT keep: ' + name + ' [CREATED with localStorage]'); }, /* * Return localStorage value * * @attribute name * @type string */ get: function (name) { var data = window.localStorage.getItem(name); if (data) { data = JSON.parse(data); var now = new Date(Bat.keep.timestamper()), exp = new Date(data.timestamp); if (now < exp) { var difference = new Date(Math.abs(now.getTime() - exp.getTime())); Bat.keep.remaining.days = difference.getUTCDate() - 1; Bat.keep.remaining.hours = difference.getUTCHours(); Bat.keep.remaining.years = new Date(exp).getFullYear() - new Date(now).getFullYear(); // Bat.log.trace('-------'); // Bat.log.trace('localStorage get'); // Bat.log.trace(data); // Bat.log.trace(now); // Bat.log.trace(exp); // Bat.log.trace(difference); // Bat.log.trace(Bat.keep.remaining); // Bat.log.trace('-------'); return data.value; } else { this.delete(name); return null; } } else { return null; } }, /* * Detele localStorage data * * @attribute name * @type string */ delete: function (name) { window.localStorage.removeItem(name); Bat.log.info('BAT keep: ' + name + ' [DELETED from localStorage]'); } } }; })(); // Return a new element to BAT object root.Bat = Bat; }).call(this);
JavaScript
CL
29dfca2e09f4bcf3e4337db66d8e217e9b6478ae9e3672035837b75b31b6a61e
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. import { parseKeyVaultKeyIdentifier } from "./identifier"; /** * @internal * Shapes the exposed {@link KeyVaultKey} based on either a received key bundle or deleted key bundle. */ export function getKeyFromKeyBundle(bundle) { const keyBundle = bundle; const deletedKeyBundle = bundle; const parsedId = parseKeyVaultKeyIdentifier(keyBundle.key.kid); const attributes = keyBundle.attributes || {}; delete keyBundle.attributes; const resultObject = { key: keyBundle.key, id: keyBundle.key ? keyBundle.key.kid : undefined, name: parsedId.name, keyOperations: keyBundle.key ? keyBundle.key.keyOps : undefined, keyType: keyBundle.key ? keyBundle.key.kty : undefined, properties: { tags: keyBundle.tags, enabled: attributes.enabled, notBefore: attributes.notBefore, expiresOn: attributes.expires, createdOn: attributes.created, updatedOn: attributes.updated, recoverableDays: attributes.recoverableDays, recoveryLevel: attributes.recoveryLevel, exportable: attributes.exportable, releasePolicy: keyBundle.releasePolicy, vaultUrl: parsedId.vaultUrl, version: parsedId.version, name: parsedId.name, managed: keyBundle.managed, id: keyBundle.key ? keyBundle.key.kid : undefined, }, }; if (deletedKeyBundle.recoveryId) { resultObject.properties.recoveryId = deletedKeyBundle.recoveryId; resultObject.properties.scheduledPurgeDate = deletedKeyBundle.scheduledPurgeDate; resultObject.properties.deletedOn = deletedKeyBundle.deletedDate; } return resultObject; } /** * @internal * Shapes the exposed {@link DeletedKey} based on a received KeyItem. */ export function getDeletedKeyFromDeletedKeyItem(keyItem) { const commonProperties = getKeyPropertiesFromKeyItem(keyItem); return { key: { kid: keyItem.kid, }, id: keyItem.kid, name: commonProperties.name, properties: Object.assign(Object.assign({}, commonProperties), { recoveryId: keyItem.recoveryId, scheduledPurgeDate: keyItem.scheduledPurgeDate, deletedOn: keyItem.deletedDate }), }; } /** * @internal * Shapes the exposed {@link KeyProperties} based on a received KeyItem. */ export function getKeyPropertiesFromKeyItem(keyItem) { const parsedId = parseKeyVaultKeyIdentifier(keyItem.kid); const attributes = keyItem.attributes || {}; const resultObject = { createdOn: attributes.created, enabled: attributes === null || attributes === void 0 ? void 0 : attributes.enabled, expiresOn: attributes === null || attributes === void 0 ? void 0 : attributes.expires, id: keyItem.kid, managed: keyItem.managed, name: parsedId.name, notBefore: attributes === null || attributes === void 0 ? void 0 : attributes.notBefore, recoverableDays: attributes === null || attributes === void 0 ? void 0 : attributes.recoverableDays, recoveryLevel: attributes === null || attributes === void 0 ? void 0 : attributes.recoveryLevel, tags: keyItem.tags, updatedOn: attributes.updated, vaultUrl: parsedId.vaultUrl, version: parsedId.version, }; return resultObject; } /** * @internal */ export const keyRotationTransformations = { propertiesToGenerated: function (parameters) { var _a; const policy = { attributes: { expiryTime: parameters.expiresIn, }, lifetimeActions: (_a = parameters.lifetimeActions) === null || _a === void 0 ? void 0 : _a.map((action) => { const generatedAction = { action: { type: action.action }, trigger: {}, }; if (action.timeAfterCreate) { generatedAction.trigger.timeAfterCreate = action.timeAfterCreate; } if (action.timeBeforeExpiry) { generatedAction.trigger.timeBeforeExpiry = action.timeBeforeExpiry; } return generatedAction; }), }; return policy; }, generatedToPublic(generated) { var _a, _b, _c, _d; const policy = { id: generated.id, createdOn: (_a = generated.attributes) === null || _a === void 0 ? void 0 : _a.created, updatedOn: (_b = generated.attributes) === null || _b === void 0 ? void 0 : _b.updated, expiresIn: (_c = generated.attributes) === null || _c === void 0 ? void 0 : _c.expiryTime, lifetimeActions: (_d = generated.lifetimeActions) === null || _d === void 0 ? void 0 : _d.map((action) => { var _a, _b; return { action: action.action.type, timeAfterCreate: (_a = action.trigger) === null || _a === void 0 ? void 0 : _a.timeAfterCreate, timeBeforeExpiry: (_b = action.trigger) === null || _b === void 0 ? void 0 : _b.timeBeforeExpiry, }; }), }; return policy; }, }; //# sourceMappingURL=transformations.js.map
JavaScript
CL
93988900f2d691655de5149e73b71be4b8f13b5052f39d3a2a86f35a9e4aff7a
const { authenticate } = require('@feathersjs/authentication').hooks; const { setField } = require('feathers-authentication-hooks'); const { iff, isProvider, preventChanges } = require('feathers-hooks-common'); const { setDefaultSort, getFullModel, protectUserFields } = require('../common_hooks.js'); const {buildHtmlEmail, renderButton} = require('../mailer/htmlEmail'); const includeAssociations = (context) => { const sequelize = context.app.get('sequelizeClient'); const { users } = sequelize.models; context.params.sequelize = { ...context.params.sequelize, include: ["author"] } return context; } const mustBeOwnerOrAdmin = (options) => { return iff( isProvider('external'), async (context) => { const issueComment = await context.service.get(context.id); const tldr = await context.service('tldrs').get(issueComment.tldrId); const issueCommentFields = Object.keys(context.service.Model.rawAttributes); if(context.params.user.id == issueComment.authorId){ // owner of issue // block all fields except status (others?) preventChanges(subtractFromArray(issueCommentFields, ["status"])); } else if(context.params.user.id !== tldr.authorId){ // owner of tldr // block all fields except status (others?) preventChanges(subtractFromArray(issueCommentFields, ["status"])); } else{ throw new Forbidden('You are not allowed to access this'); } return context; } ); } // COMMENTS COUNT const updateCommentsCount = async (context) => { const comments = await context.service.find({ query: { issueId: context.data.issueId, $limit: 0 // count } }); const issue = await context.app.service('issues').patch(context.data.issueId, { commentCount: comments.total }); return context; } // SEND COMMENT NOTIFICATION const sendIssueCommentEmail = async (context) => { // config const serverUrl = context.app.get('clientServer'); const fromEmail = context.app.get('fromEmail'); const issue = await context.app.service('issues').get(context.dispatch.issueId); const tldr = await context.app.service('tldrs').get(issue.tldrId); // get recipients to notify // maybe there's a feathers way to do this but for now // just custom query this stuff const sequelize = context.app.get('sequelizeClient'); const [result, metadata] = await sequelize.query(` SELECT DISTINCT users.email AS email FROM issue_comments INNER JOIN users ON issue_comments."authorId" = users.id WHERE issue_comments."issueId" = ${context.dispatch.issueId} AND users."notifyParticipatedIssues" = true UNION SELECT DISTINCT users.email AS email FROM issues INNER JOIN users ON issues."authorId" = users.id WHERE issues.id = ${context.dispatch.issueId} AND users."notifyOwnedIssues" = true `); const bccEmails = result.map( r => r.email); // build email const linkBack = `${serverUrl}/tldr/issue?issueId=${context.dispatch.issueId}`; const truncate = (input, length) => input.length > length ? `${input.substring(0, length)}...` : input; const bodyContent = ` <p><b>@${context.dispatch.author.urlKey}</b> posted:<br/> ${truncate(context.dispatch.body, 140)}</p> ${renderButton('See the full issue', linkBack)} `.trim(); const email = { from: `"@${context.dispatch.author.urlKey}" ${fromEmail}`, to: fromEmail, bcc: bccEmails, subject: `Re: [${tldr.urlKey}] ${issue.title}`, html: buildHtmlEmail({}, bodyContent) }; // send context.app.service('mailer').create(email).then(function (result) { console.log('Sent email', result) }).catch(err => { console.log('Error sending email', err) }); return context; } module.exports = { before: { all: [], find: [ setDefaultSort({ field: 'createdAt', order: 1 }), includeAssociations, ], get: [ includeAssociations, ], create: [ authenticate('jwt'), setField({ from: 'params.user.id', as: 'data.authorId' }) ], update: [ authenticate('jwt'), mustBeOwnerOrAdmin() ], patch: [ authenticate('jwt'), mustBeOwnerOrAdmin() ], remove: [ authenticate('jwt'), mustBeOwnerOrAdmin() ] }, after: { all: [], find: [ protectUserFields('author.') ], get: [ protectUserFields('author.') ], create: [ updateCommentsCount, getFullModel(), sendIssueCommentEmail, protectUserFields('author.') ], update: [ protectUserFields('author.') ], patch: [ protectUserFields('author.') ], remove: [ updateCommentsCount, protectUserFields('author.') ] }, error: { all: [], find: [], get: [], create: [], update: [], patch: [], remove: [] } };
JavaScript
CL
896311e40211f7e0aab3839cadc1777f28eb69cadc5a4097fd42293be98702ed
const express = require("express"); const request = require("request"); const fs = require('fs'); const fsPromises = fs.promises; var cors = require('cors'); const axios = require('axios') const {PythonShell} =require('python-shell'); const router = express.Router(); router.get("/", cors(),(req, res) => { res.render("index"); }); //|| itemsList[k].title.includes(".pptx") router.post("/search", cors(), async (req, res) => { const {token} = req.body; var userDir; if (!token) { return res.redirect("/"); } let url = "https://canvas.pitt.edu/api/v1/users/self/profile?access_token=" + token; try { let response = await axios.get(url) if (response.status !== 200) { return res.status(404).send("Error Invalid Canvas user"); } let body = response.data let userProfile = body; userDir = "./public/" + userProfile.id; if (fs.existsSync(userDir)) { console.log("already fetched user") } else{ if(!fs.existsSync(userDir)) fs.mkdirSync(userDir); let courseUrl = "https://canvas.pitt.edu/api/v1/users/self/courses?access_token=" + token; response = await axios.get(courseUrl); if(response.status !== 200) { return res.status(404).send("Error cannot retrieve Courses for User ID" + userProfile.id); } body = response.data; let courseList = body; for(let i in courseList) { let moduleUrl = "https://canvas.pitt.edu/api/v1/courses/" + courseList[i].id + "/modules?access_token=" + token + "&per_page=20 "; response = await axios.get(moduleUrl); if(response.status !== 200) { return res.status(404).send("Error cannot retrieve Modules for Course " + courseList[i].name); } body = response.data; let moduleList = body; if(moduleList.length > 0) { for(let j in moduleList) { let itemsUrl = moduleList[j].items_url + "?access_token=" + token; let response = await axios.get(itemsUrl); if(response.status !== 200) { return res.status(404).send("Error cannot retrieve Modules items for Course "); } body = response.data; let itemsList = body; for(let k in itemsList) { if(itemsList[k].title.includes(".pdf")) { let fileUrl = itemsList[k].url + "?access_token=" + token; response = await axios.get(fileUrl); if(response.status !== 200) { return res.status(404).send("Error accessing files in Module Items"); } body = response.data; let files = body; let downloadPath = userDir + "/" + files.filename; if(!fs.existsSync(downloadPath)) { console.log(downloadPath); axios.get(files.url, {responseType: "stream"}).then((response) => { response.data.pipe(fs.createWriteStream(downloadPath)); }); } } } } } } } res.render("search", {user: userProfile.id}); } catch (error) { return res.status(404).send("Error accessing Canvas user"); } }); router.get("/generate", (req, res) => { // console.log("from generate request",req.query.path); console.log("coming in generate"); let options = { mode: 'text', pythonOptions: ['-u'], // get print results in real-time //If you are having python_test.py script in same folder, then it's optional. args: ['public/'+req.query.path] //An argument which can be accessed in the script using sys.argv[1] }; PythonShell.run('index_run.py', options, function (err, result){ if (err) throw err; // result is an array consisting of messages collected //during execution of script. console.log('result: ', result.toString()); res.status(200).send({status:"200"}); }); }); router.get("/search", (req, res) => { let query = req.query.searchQuery; let userId = req.query.userId; let options = { mode: 'text', pythonOptions: ['-u'], // get print results in real-time //If you are having python_test.py script in same folder, then it's optional. args: [userId,query] //An argument which can be accessed in the script using sys.argv[1] }; PythonShell.run('query_run.py', options, function (err, result){ if (err) throw err; // result is an array consisting of messages collected //during execution of script. console.log('result: ', result.toString()); let r = JSON.parse(result) console.log(r) res.status(200).send({q: query, result:r}); }); // The userId here will give you which folder to actually use to search for the query // Use that and then after that send a JSON object containing the top results }); module.exports = router;
JavaScript
CL
70cab11afabb808b540239c7a57b812fcbba9f07303ae2a6be152404342795d7
/**文档相关接口*/ import $axios from "@/service/httpServer"; // 获取文档列表 export const getDocsList = p => $axios.get('/inkwash/dos/list', p); // 获取文档详情 export const getDocumentDetail = p => $axios.get('/inkwash/dos/detail', p); // 创建文件夹 export const newFolder = p => $axios.post('/inkwash/docs/newFolder', p); // 新增文档 export const createDocument = p => $axios.post('/inkwash/docs/add', p); // 删除文档 export const delDocument = p => $axios.post('/inkwash/docs/del', p); // 文档重命名 export const documentRename = p => $axios.post('/inkwash/docs/rename', p); // 获取文档路径 export const getDocumentPathById = p => $axios.get('/inkwash/docs/path', p) // 点赞 export const starDocument = p => $axios.get('/inkwash/docs/star', p) // 收藏 export const collectDocument = p => $axios.get('/inkwash/docs/collect', p) /** * 我的文档 * */ // 我的文档列表 export const getMyDocumentList = () => $axios.get('/inkwash/docs/myDocument') /** * 我的收藏 * */ // 我的文档列表 export const getMyCollectDocumentList = () => $axios.get('/inkwash/docs/myCollectDocument') /** * 我的协作 * */ // 我的文档列表 export const getMyCooperationDocumentList = () => $axios.get('/inkwash/docs/myCooperationDocument') // 按小组添加协作人 export const addCooperationUser = p => $axios.post('/inkwash/docs/addCooperation/userIds', p) // 按userIds添加协作人 export const addCooperationUserByGroup = p => $axios.post('/inkwash/docs/addCooperation/groupId', p) // 获取协作人列表 export const getCooperationUserListByDocumentId = p => $axios.get('/inkwash/docs/getCooperation/userList', p) // 删除协作人 export const removeCooperationUser = p => $axios.post('/inkwash/delCooperation/user', p) /** * 我的浏览历史 * */ // 我的文档列表 export const getMyVisitHistoryDocumentList = () => $axios.get('/inkwash/docs/myVisitHistoryDocument') /** * 我的回收站 * */ // 我的文档列表 export const getMyRecycleBinDocumentList = () => $axios.get('/inkwash/docs/myRecycleBin') // 恢复文档 export const recoveryDocument = p => $axios.post('/inkwash/docs/recovery', p) // 彻底删除文档 export const destroyDocument = p => $axios.post('/inkwash/docs/distory', p) /** * 上传axure压缩包 */ export const docsUplaodAxure = p => $axios.post('/inkwash/docs/axure/upload', p) /** * 设置访问方式 */ export const getMembersByDocumentId = p => $axios.get('/inkwash/docs/getDocMembers', p) export const setDocumentVisitTeam = p => $axios.post('/inkwash/docs/visit/setAsTeam', p) export const setDocumentOpen = p => $axios.post('/inkwash/docs/visit/setAsOpen', p) export const setDocumentPrivate = p => $axios.post('/inkwash/docs/visit/setAsPrivate', p) export const documentCheckPass = p => $axios.post('/inkwash/docs/checkPass', p) /** * 我的模板 */ export const getMyTemplate = p => $axios.get('/inkwash/docs/myTemplate', p);
JavaScript
CL
0ab91acdc6963fe8208d596de8dec1d246ea3c744d496f132e8aa86fed330403
import React from 'react'; import Button from '@material-ui/core/Button'; import TextField from '@material-ui/core/TextField'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogTitle from '@material-ui/core/DialogTitle'; import { CircularProgress, Snackbar } from '@material-ui/core'; import axios from 'axios'; import MuiAlert from '@material-ui/lab/Alert'; export default function CreateHotelComponent(props) { const [openDialog, setOpenDialog] = React.useState(false); const [name, setName] = React.useState(''); const [address, setAddress] = React.useState(''); const [open, setOpen] = React.useState(false); const [message, setMessage] = React.useState(''); const [severity, setSeverity] = React.useState('success'); const [disabled, setDisabled] = React.useState(false); const handleClickOpen = () => { setOpenDialog(true); }; const handleCloseDialog = () => { setOpenDialog(false); }; const handleClose = (event, reason) => { if (reason === 'clickaway') { return; } setOpen(false); }; const Alert = ((props) => { return <MuiAlert elevation={6} variant="filled" {...props} />; }); const createHotel = async (e) => { setDisabled(true); e.preventDefault(); try { const response = await axios.post(`${process.env.REACT_APP_API_URL}/hotel`, { name, address }); if (response) { setMessage(response.data.message); props.updateHotelList(response.data.data); setOpen(true); setSeverity('success'); setDisabled(false); handleCloseDialog(); } } catch (error) { console.log(error, 'error'); setDisabled(false); (error.response.data.message) ? setMessage(error.response.data.message) : setMessage('Something went wrong'); setSeverity('error'); setOpen(true); handleCloseDialog(); } setName(''); setAddress(''); } return ( <div> <Snackbar onClose={handleClose} open={open} autoHideDuration={2000} > <Alert onClose={handleClose} severity={severity}> {message} </Alert> </Snackbar> <Button style={{margin: '0px 8px'}} variant="contained" color="secondary" onClick={handleClickOpen}> Create Hotel </Button> <Dialog open={openDialog} onClose={handleCloseDialog} aria-labelledby="form-dialog-title"> <form onSubmit={createHotel}> <DialogTitle id="form-dialog-title">Create Hotel</DialogTitle> <DialogContent> <DialogContentText> You can Create a hotel with basic details </DialogContentText> <TextField autoFocus variant="outlined" margin="normal" id="name" disabled={disabled} color="secondary" label="Name" value={name} onChange={(e) => setName(e.target.value)} type="text" required fullWidth /> <TextField variant="outlined" margin="normal" id="address" disabled={disabled} color="secondary" label="Address" value={address} onChange={(e) => setAddress(e.target.value)} type="text" required fullWidth /> </DialogContent> <DialogActions> <Button variant="contained" type="submit" color="secondary"> <span style={{ marginRight: '8px' }}> {(disabled) ? <CircularProgress size={20} /> : null} </span> Create </Button> <Button variant="contained" onClick={handleCloseDialog} color="primary"> Cancel </Button> </DialogActions> </form> </Dialog> </div> ); }
JavaScript
CL
118b445fc0fd63065ee836f0cc6f56b2dade7cad28acc06763693213247f3cbb
export default class alap { alapConfig; alapElem = null; curTimerID = 0; theBody = null; listType = "ol"; mode = "vanilla"; // vanilla, vue, react, etc menuTimeout = 5000; ESC_KEYCODE = 27; constructor(config = undefined, mode = "vanilla") { if (config && Object.keys(config).length) { this.configure(config, mode); } } // only use this with plain vanilla js // wrappers such as vue, react, svelte, etc // should manage <div id="alapelem"> resetAlapElem() { this.theBody = document.querySelector("body"); // is there an existing alap elenent? this.alapElem = document.getElementById("alapelem"); if (this.alapElem) { document.removeChild(this.alapElem); } // start fresh this.alapElem = document.createElement("div"); this.alapElem.setAttribute("id", "alapelem"); document.body.append(this.alapElem); } resetEvents() { // in case of a stray this.theBody.removeEventListener("click", this.bodyClickHandler); this.theBody.addEventListener("click", this.bodyClickHandler.bind(this)); // in case we have any strays... this.theBody.removeEventListener("keydown", this.bodyKeyHandler); this.theBody.addEventListener("keydown", this.bodyKeyHandler.bind(this)); // strays? this.alapElem.removeEventListener("mouseleave", this.menuMouseLeaveHandler); this.alapElem.removeEventListener("mouseenter", this.menuMouseEnterHandler); // add event handler on our menu for mouseouts... this.alapElem.addEventListener( "mouseleave", this.menuMouseLeaveHandler.bind(this) ); this.alapElem.addEventListener( "mouseenter", this.menuMouseEnterHandler.bind(this) ); } configure(config = {}, mode = "vanilla") { if (Object.keys(config).length === 0) { return; } this.mode = mode; this.alapConfig = Object.assign({}, config); this.listType = this.getSetting("listType", "ul"); this.menuTimeout = +this.getSetting("menuTimeout", 5000); // if we are calling alap from plain js, we do some extra // setup.. otherwise, we leave it to the calling wrapper // to handle events (such as Vue and React) if (mode === "vanilla") { this.resetAlapElem(); // any element with the class of 'alap'... does not have to be an anchor element let myLinks = Array.from(document.getElementsByClassName("alap")); for (const curLink of myLinks) { // dont allow more than one listener for a given signature // init may be called more than once (when elements are dynamically added // or updated). It's safe to call this when there is no listener bound curLink.removeEventListener("click", this.doClick); // ok, now we're good to bind curLink.addEventListener("click", this.doClick.bind(this), false); } this.resetEvents(); } } getSetting(settingName, defaultValue = "") { let retVal = defaultValue; if (this.alapConfig && this.alapConfig.settings) { if (this.alapConfig.settings[settingName]) { retVal = this.alapConfig.settings[settingName]; } } return retVal; } setSetting(settingName, value) { if (this.alapConfig && this.alapConfig.settings) { this.alapConfig.settings[settingName] = value; } } dumpConfig() { console.dir(this.alapConfig); } removeMenu() { this.alapElem = document.getElementById("alapelem"); this.alapElem.style.display = "none"; this.stopTimer(); } bodyClickHandler(event) { let inMenu = event.target.closest("#alapelem"); if (!inMenu) { this.removeMenu(); } } bodyKeyHandler(event) { if (event.keyCode == this.ESC_KEYCODE) { this.removeMenu(); } } menuMouseLeaveHandler() { this.startTimer(); } menuMouseEnterHandler() { this.stopTimer(); } startTimer() { if (this.curTimerID) { clearTimeout(this.curTimerID); } this.curTimerID = setTimeout(this.removeMenu.bind(this), this.menuTimeout); } stopTimer() { clearTimeout(this.curTimerID); this.curTimerID = 0; } cleanMyData(theStr) { let myData = ""; // if we need to split for tag intersections and diffs later, // we provide a consistent space separated string myData = theStr.replace(/\s+|["']+/g, ""); myData = myData.replace(/\-{1,}/g, " - "); myData = myData.replace(/\+{1,}/g, " + "); myData = myData.replace(/\|{1,}/g, " | "); myData = myData.replace(/,{1,}/g, ","); myData = myData.replace(/\.{1,}/g, "."); myData = myData.replace(/\@{1,}/g, "@"); // future use myData = myData.replace(/\#{1,}/g, "#"); myData = myData.replace(/\*{1,}/g, "*"); myData = myData.replace(/\%{1,}/g, "%"); return myData; } parseLine(theStr) { let knownWords = []; let myData = ""; if (!theStr) return []; myData = this.cleanMyData(theStr); let dataElem = myData.split(/[,]/); for (const curDataElem of dataElem) { let curWord = curDataElem.toString(); curWord = curWord.trim(); // too short? dont bother if (curWord.length < 2) { continue; } knownWords.push(curWord); } return knownWords; } searchTags(searchStr) { let resultSet = []; if (searchStr.charAt(0) == ".") { searchStr = searchStr.slice(1); } for (const key in this.alapConfig.allLinks) { let theTags = this.cleanArgList(this.alapConfig.allLinks[key].tags); let foundMatch = 0; const numTags = theTags.length; for (let i = 0; i < numTags && foundMatch == 0; i++) { if (theTags[i] == searchStr) { foundMatch++; resultSet.push(key); } } } return resultSet; } cleanArgList(aList = []) { const allElems = []; // may need to test here for an object... const theElems = aList.toString().split(","); theElems.map((curElem) => { allElems.push(curElem.replace(/\s+|["']+/g, "")); }); return allElems; } parseElem(theElem) { let resultSet = []; let curResultSet = []; let tokens = theElem.split(" "); // are we looking for an 'AND'? let needIntersection = 0; // are we looking to remove items? let needWithout = 0; // are we looking for an 'OR'? let needUnion = 0; for (const curToken of tokens) { const firstChar = curToken.charAt(0); switch (firstChar) { // intersection case "+": if (curToken.length == 1) { needIntersection = 1; } break; // without .. subtraction case "-": if (curToken.length == 1) { needWithout = 1; } break; // "OR" case "|": if (curToken.length == 1) { needUnion = 1; } break; // we're looking for a tag case ".": curResultSet = this.searchTags(curToken); if (needWithout) { resultSet = resultSet.filter((x) => !curResultSet.includes(x)); } else if (needIntersection) { resultSet = resultSet.filter((x) => curResultSet.includes(x)); } else if (needUnion) { resultSet = [...new Set([...resultSet, ...curResultSet])]; } else { resultSet.push.apply(resultSet, curResultSet); } needWithout = 0; needIntersection = 0; needUnion = 0; break; // this is a no-op for now, reserving '@' for future use as macro case "@": break; // the normal case of getting data from an id default: if (this.alapConfig.allLinks[curToken] !== undefined) { resultSet.push(curToken.toString()); } break; } } return resultSet; } offset(el) { const rect = el.getBoundingClientRect(), scrollLeft = window.pageXOffset || document.documentElement.scrollLeft, scrollTop = window.pageYOffset || document.documentElement.scrollTop; return { top: rect.top + scrollTop, left: rect.left + scrollLeft }; } // this is used when we have an event in vue, react, or some // other framework.. we just come here to gather info, and // bundle it up in an object. It is up to the framework to // handle the Render and Event side of the menu processEvent(eventProperties, config = null) { const eventTarget = eventProperties.target; // in case the wrapper needs to override config.. if (config != null) { this.alapConfig = config; } const myEventData = { valid: false, theData: null, theTargets: [], listType: this.listType, menuTimeout: this.menuTimeout, tagType: null, anchorID: "", cssAttr: "", anchorCSS: "", anchorCSSNormal: "", offset: {}, left: 0, top: 0, // pointers config: this.alapConfig, allLinks: this.alapConfig.allLinks }; myEventData.theData = eventTarget.getAttribute("data-alap-linkitems"); if (!myEventData.theData) { return myEventData; } // check for a macro expansion... myEventData.theData = this.checkMacro(myEventData.theData); if (!myEventData.theData) { return myEventData; } myEventData.theTargets = this.getTargets(myEventData.theData); myEventData.tagType = eventTarget.tagName.toLowerCase(); myEventData.anchorID = eventTarget.id || ""; myEventData.anchorCSS = getComputedStyle(eventTarget, ":link"); myEventData.anchorCSSNormal = getComputedStyle(eventTarget); if (myEventData.anchorID) { myEventData.cssAttr = `alap_${myEventData.anchorID}`; } // we use an absolute offset here, but in our css rules, // we should define in .alapelem: // margin-top: 1.5rem; // this gives a consistent offset based on rem myEventData.offset = this.offset(eventTarget); // our offset is fixed here, you can set margin-top // and margin-left in .alapelem to adjust as you wish // position: fixed; myEventData.left = myEventData.offset.left; myEventData.top = myEventData.offset.top; if (myEventData.tagType === "img") { myEventData.left = eventProperties.pageX; myEventData.top = eventProperties.pageY; } myEventData.valid = true; return myEventData; } // do we have a macro? checkMacro(theData) { if (theData.charAt(0) === "@") { let checkMacroName = null; // a bare '@'? Ok, we will use the DOM ID if (theData.length === 1) { if (anchorID) { checkMacroName = anchorID; } } else { checkMacroName = theData.slice(1); } if ( checkMacroName && this.alapConfig.macros && this.alapConfig.macros[checkMacroName] && this.alapConfig.macros[checkMacroName].linkItems ) { theData = this.alapConfig.macros[checkMacroName].linkItems; } } return theData; } getTargets(theData) { let allDataElem = this.parseLine(theData); let localTargets = []; for (const curElem of allDataElem) { localTargets = [...localTargets, ...this.parseElem(curElem)]; } // remove duplicates if (localTargets.length) { localTargets = [...new Set([...localTargets])]; } return localTargets; } getEntryByID(id) { if (this.alapConfig.allLinks && this.alapConfig.allLinks[id]) { return this.alapConfig.allLinks[id]; } else { return null; //test } } // the event and DOM portions of this still need to be // split out, so that all of the functionality can be // accessed from the API. doClick(event) { event.preventDefault(); event.stopPropagation(); const eventData = this.processEvent({ target: event.target, pageX: event.pageX, pageY: event.pageY }); if (!eventData.valid) return; let divCSS = {}; divCSS.zIndex = 10; if (eventData.anchorCSS.zIndex && eventData.anchorCSS.zIndex !== "auto") { divCSS.zIndex = eventData.anchorCSS.zIndex + 10; } this.alapElem.style.display = "block"; this.alapElem.style.cssText = ` position: absolute; z-index: 10; left: ${eventData.left}px; top: ${eventData.top}px; `; // clear out any classes from our existing alapElem this.alapElem.removeAttribute("class"); // ...and, if we have a specific css attribute to add, // the element is ready for a fresh class specifier this.alapElem.classList.add("alapelem"); if (eventData.cssAttr) { this.alapElem.classList.add(eventData.cssAttr); } let menuHTML = `<${this.listType}>`; eventData.theTargets.map((curTarget) => { let curInfo = this.alapConfig.allLinks[curTarget]; let cssClass = "alapListElem"; if (curInfo.cssClass) { cssClass += ` ${curInfo.cssClass}`; } let listItemContent = curInfo.label; // however .. if we have an image... if (curInfo.image) { let altText = `image for ${curTarget}`; if (curInfo.altText) { altText = curInfo.altText; } listItemContent = ` <img alt="${altText}" src="${curInfo.image}"> `; } let targetWindow = "fromAlap"; // however .. if we have a specific target if (curInfo.targetWindow) { targetWindow = curInfo.targetWindow; } menuHTML += ` <li class="${cssClass}"><a target="${targetWindow}" href=${curInfo.url}>${listItemContent}</a></li> `; }); menuHTML += `</${this.listType}>`; this.alapElem.innerHTML = menuHTML; // exit any existing timer... this.stopTimer(); this.startTimer(); } }
JavaScript
CL
8ace7566c6616dd25cb75c444262be76c1a60fe3d00252bda2a15e027817d9b9
require('dotenv').config() module.exports = { /* ** Nuxt rendering mode ** See https://nuxtjs.org/api/configuration-mode */ mode: 'universal', /* ** Nuxt target ** See https://nuxtjs.org/api/configuration-target */ target: 'server', /* ** Headers of the page ** See https://nuxtjs.org/api/configuration-head */ head: { title: process.env.npm_package_name || '', meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width, initial-scale=1, viewport-fit=cover' }, { hid: 'description', name: 'description', content: process.env.npm_package_description || '' } ], script: [ { src: '/js/facebook.js' }, { src: '/js/common.js' }, { src: '/js/wx.js' }, { src: 'https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js'} ], link: [ { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' } ] }, /* ** Global CSS */ css: [ // 'ant-design-vue/lib/button/style/css', 'ant-design-vue/dist/antd.less', 'quill/dist/quill.core.css', // for snow theme 'quill/dist/quill.snow.css', // for bubble theme 'quill/dist/quill.bubble.css', '~/assets/main.css', 'swiper/css/swiper.css' ], /* ** Plugins to load before mounting the App ** https://nuxtjs.org/guide/plugins */ plugins: [ '@/plugins/antd-ui', '@/plugins/vant-ui', '@/plugins/axios', { src: '@/plugins/vue-quill-editor', ssr: false }, { src: '@/plugins/vue-infinite-scroll.js', ssr: false }, { src: '@/plugins/avatar.js', ssr: false }, { src: '@/plugins/vue-swiper', ssr: false }, ], /* ** 客户端和服务端共享的环境变量 */ env: { host_env: process.env.CODE_ENV }, router: { middleware: 'user-agent' }, axios: { proxy: false, }, proxy: { '/': { target: '//ashago-api-dev.cc2dbe1fd91f042528f96dc27c2dba5fe.cn-zhangjiakou.alicontainer.com' }, '/api': { target: '//ashago-api-dev.cc2dbe1fd91f042528f96dc27c2dba5fe.cn-zhangjiakou.alicontainer.com' }, '/user': { target: '//ashago-api-dev.cc2dbe1fd91f042528f96dc27c2dba5fe.cn-zhangjiakou.alicontainer.com' }, }, /* ** Auto import components ** See https://nuxtjs.org/api/configuration-components */ components: true, /* ** Nuxt.js dev-modules */ buildModules: [ ], /* ** Nuxt.js modules */ modules: [ '@nuxtjs/axios', '@nuxtjs/dotenv' ], /* ** Build configuration ** See https://nuxtjs.org/api/configuration-build/ */ build: { extend (config, { isClient }) { // 客户端打包配置 if (isClient) { } }, loaders: { // 定制ant-design-vue全局主题 less: { lessOptions: { javascriptEnabled: true, modifyVars: { 'primary-color': '#8D050B', } } } }, vendor: ['axios'] } }
JavaScript
CL
fd29057dd2723975751eb60088416d8aff5ee2ac30016214548b1ba4731f0dab
/* * eIDPluginHelper * * Copyright (c) 2014 The Third Research Institute of The Ministry of Public Security * * Version 3.7.5.154 */ var eID = null; var onPluginLoad = null; eID = new eIDPluginHelper(); function eIDPluginHelper() { //控件对象 var eIDpuginObject = null; //是否插件已加载 var isPluginLoad = false; //函数索引 var funcIndex = 0; //缓存回调函数列表 var funcIDBindList = []; //是否正在检测设备拔插 var isDetecting = false; //检测设备回调函数 var onDeviceDetect = null; //开始检测设备回调函数 var onBeginDeviceDetect = null; //终止检测设备回调函数 var onEndDeviceDetect = null; //当前读卡器和银行尾号列表 var currentReaderSerialList = []; //本对象 var self = this; //控件基准版本 var basePlugInVersion = 154; //加载控件 this.load = function(loadCallback) { if (typeof (loadCallback) != 'function') { return; } if (isPluginLoad) { loadCallback(true); return; } isPluginLoad = true; //插件加载错误 function onPluginError() { isPluginLoad = false; loadCallback(false, 'http://update.cneid.net.cn/update/eIDSetup.exe'); } onPluginLoad = function() { if (isInterfaceFull() == true) { //绑定插件事件 attach(eIDpuginObject, 'GetVersionCompleted', getVersionCompleted); attach(eIDpuginObject, 'GetReaderListCompleted', getReaderListCompleted); attach(eIDpuginObject, 'DetectCardBeginCompleted', detectCardBeginCompleted); attach(eIDpuginObject, 'DetectCardEndCompleted', detectCardEndCompleted); attach(eIDpuginObject, 'DeviceInsertCompleted', deviceInsertCompleted); attach(eIDpuginObject, 'DeviceRemoveCompleted', deviceRemoveCompleted); attach(eIDpuginObject, 'HashCompleted', hashCompleted); attach(eIDpuginObject, 'SignCompleted', signCompleted); attach(eIDpuginObject, 'VerifyPinCompleted', verifyPinCompleted); attach(eIDpuginObject, 'SignNoInputPinCompleted', signNoInputPinCompleted); self.getVersion(function(rv, version) { if (rv == 0) { var funcID = addFuncIDBind(function(rv, version) { if (rv != 0) { onPluginError(); return; } var plugInVersion = version; for (var i = 0; i < 3; i++) { var index = version.indexOf("."); plugInVersion = plugInVersion.substring(index + 1, plugInVersion.length - index + 1); } if (plugInVersion < basePlugInVersion) { onPluginError(); return; } loadCallback(true); }); eIDpuginObject.eID_GetVersion(funcID); } else { onPluginError(); } }); } else { onPluginError(); } }; var objectHtml = '<object id="eIDPlugin" type="application/x-eidpluginhelper" width="0" height="0" style="visibility: visible">'; objectHtml += '<param name="onload" value="onPluginLoad" />'; objectHtml += '</object>'; document.body.innerHTML += objectHtml; eIDpuginObject = document.getElementById('eIDPlugin'); if (isInterfaceFull() == false) { onPluginError(); } } //转换返回值为中文提示信息 this.getMessage = function(rv) { if (typeof (rv) != 'number') { return ''; } if (eIDpuginObject.eID_GetMessage == null || rv == 0xE017003D) { return '未安装控件。'; } return eIDpuginObject.eID_GetMessage(rv); } //获取接口版本号 this.getVersion = function(getVersionCallback) { if (typeof (getVersionCallback) != 'function') { return; } if (eIDpuginObject.eID_GetVersion == null) { getVersionCallback(0xE017003D); return; } var funcID = addFuncIDBind(getVersionCallback); eIDpuginObject.eID_GetVersion(funcID); } //开始检测设备插拔 this.detectDeviceBegin = function(detectDeviceCallback) { if (typeof (detectDeviceCallback) != 'function') { return; } if ( eIDpuginObject.eID_GetReaderList == null || eIDpuginObject.eID_DetectCardBegin == null) { detectDeviceCallback(0xE017003D); return; } if (isDetecting == true) { onDeviceDetect = detectDeviceCallback; detectDeviceCallback(0, currentReaderSerialList); return; } isDetecting = true; onBeginDeviceDetect = function(rv, readerSerialList) { onDeviceDetect = detectDeviceCallback; if (rv == 0) { eIDpuginObject.eID_DetectCardBegin(0); } }; eIDpuginObject.eID_GetReaderList(0); } //结束检测设备插拔 this.detectDeviceEnd = function(detectDeviceEndCallback) { if (typeof (detectDeviceEndCallback) != 'function') { return; } if (eIDpuginObject.eID_DetectCardEnd == null) { detectDeviceEndCallback(0xE017003D); return; } if (isDetecting == false) { detectDeviceEndCallback(0); return; } isDetecting = false; onEndDeviceDetect = detectDeviceEndCallback; eIDpuginObject.eID_DetectCardEnd(0); } //杂凑数据 this.hash = function(hashCallback, reader, data, type, alg) { if (typeof (hashCallback) != 'function') { return; } if (typeof (reader) != 'string' || typeof (data) != 'string' || typeof (type) != 'number') { hashCallback(0xE0170005); return; } var aAlg = alg; if (alg == undefined) { aAlg = 1; } else if (typeof (aAlg) != 'number') { hashCallback(0xE0170005); return; } if (eIDpuginObject.eID_Hash == null) { hashCallback(0xE017003D); return; } var funcID = addFuncIDBind(hashCallback); eIDpuginObject.eID_Hash(funcID, reader, data, type, aAlg); } //签名数据 this.sign = function(signCallback, reader, data, type) { if (typeof (signCallback) != 'function') { return; } if (typeof (reader) != 'string' || typeof (data) != 'string' || typeof (type) != 'number') { signCallback(0xE0170005); return; } if (eIDpuginObject.eID_Sign == null) { signCallback(0xE017003D); return; } var funcID = addFuncIDBind(signCallback); eIDpuginObject.eID_Sign(funcID, reader, data, type); } //校验PIN码 this.verifyPin = function(verifyPinCallback, reader, type, pin) { if (typeof (verifyPinCallback) != 'function') { return; } if (typeof (reader) != 'string' || typeof (type) != 'number' || typeof (pin) != 'string') { verifyPinCallback(0xE0170005); return; } if (eIDpuginObject.eID_VerifyPin == null) { verifyPinCallback(0xE017003D); return; } var funcID = addFuncIDBind(verifyPinCallback); eIDpuginObject.eID_VerifyPin(funcID, reader, type, pin); } //签名数据而不校验PIN码 this.signNoInputPin = function(signNoInputPinCallback, reader, data, type) { if (typeof (signNoInputPinCallback) != 'function') { return; } if (typeof (reader) != 'string' || typeof (data) != 'string' || typeof (type) != 'number') { signNoInputPinCallback(0xE0170005); return; } if (eIDpuginObject.eID_Sign == null) { signNoInputPinCallback(0xE017003D); return; } var funcID = addFuncIDBind(signNoInputPinCallback); eIDpuginObject.eID_SignNoInputPin(funcID, reader, data, type); } //检测更新事件处理 function getVersionCompleted(param) { var funcID = param[0]; var rv = parseInt(param[1], 10); var version = param[2]; var func = getFuncIDBind(funcID); if (func != null) { func(rv, version); } } //开始检测设备插拔事件处理 function getReaderListCompleted(param) { var funcID = param[0]; var rv = parseInt(param[1], 10); if (rv != 0) { onBeginDeviceDetect(rv); isDetecting = false; return; } currentReaderSerialList = []; for (var i = 2; i < param.length; i++) { var readerSerial = param[i]; if (readerSerial[1].length > 0) { if (readerSerial[1].indexOf('尾号') == -1) { readerSerial[1] = '尾号:' + readerSerial[1]; } } else { readerSerial[1] = ' eID通用载体'; } var isExist = false; for (var j = 0; j < currentReaderSerialList.length; j++) { if (param[i][0] == currentReaderSerialList[j][0]) { isExist = true; break; } } if (isExist == false) { currentReaderSerialList.push(readerSerial); } } onBeginDeviceDetect(rv); } //开始检测设备插拔事件处理 function detectCardBeginCompleted(param) { var funcID = param[0]; var rv = parseInt(param[1], 10); if (rv != 0) { isDetecting = false; } onDeviceDetect(rv, currentReaderSerialList); } //结束检测设备插拔事件处理 function detectCardEndCompleted(param) { var funcID = param[0]; var rv = parseInt(param[1], 10); if (rv != 0) { isDetecting = true; } onEndDeviceDetect(rv); } //设备插入事件处理 function deviceInsertCompleted(param) { var rv = parseInt(param[0], 10); var readerSerial = param[1]; if (readerSerial[1].length > 0) { if (readerSerial[1].indexOf('尾号') == -1) { readerSerial[1] = '尾号:' + readerSerial[1]; } } else { readerSerial[1] = ' eID通用载体'; } if (rv == 0) { var isExist = false; for (var j = 0; j < currentReaderSerialList.length; j++) { if (readerSerial[0] == currentReaderSerialList[j][0]) { isExist = true; break; } } if (isExist == false) { currentReaderSerialList.push(readerSerial); } } onDeviceDetect(rv, currentReaderSerialList); } //设备拔出事件处理 function deviceRemoveCompleted(param) { var rv = parseInt(param[0], 10); if (rv == 0) { var readerSerial = param[1]; for (var i = 0; i < currentReaderSerialList.length; i++) { if (readerSerial[0] == currentReaderSerialList[i][0]) { currentReaderSerialList.splice(i, 1); break; } } } onDeviceDetect(rv, currentReaderSerialList); } //杂凑数据完成事件处理 function hashCompleted(param) { var funcID = param[0]; var rv = parseInt(param[1], 10); var result = param[2]; var idCarrier = param[3]; var alg = param[4]; var func = null; if (rv == 0xE0170031) { func = getFuncIDBind(funcID, false); } else { func = getFuncIDBind(funcID, true); } if (func != null) { func(rv, result, idCarrier, alg); } } //签名数据完成事件处理 function signCompleted(param) { var funcID = param[0]; var rv = parseInt(param[1], 10); var result = param[2]; var idCarrier = param[3]; var issuer = param[4]; var subject = param[5]; var certSn = param[6]; var issuerSn = param[7]; var serial = param[8]; var alg = param[9]; var func = null; if (rv == 0xE0170031) { func = getFuncIDBind(funcID, false); } else { func = getFuncIDBind(funcID, true); } if (func != null) { func(rv, result, idCarrier, issuer, subject, certSn, issuerSn, serial, alg); } } //校验PIN码完成事件处理 function verifyPinCompleted(param) { var funcID = param[0]; var rv = parseInt(param[1], 10); var func = null; if (rv == 0xE0170031) { func = getFuncIDBind(funcID, false); } else { func = getFuncIDBind(funcID, true); } if (func != null) { func(rv); } } //签名数据不输入PIN码完成事件处理 function signNoInputPinCompleted(param) { var funcID = param[0]; var rv = parseInt(param[1], 10); var result = param[2]; var idCarrier = param[3]; var issuer = param[4]; var subject = param[5]; var certSn = param[6]; var issuerSn = param[7]; var serial = param[8]; var alg = param[9]; var func = null; if (rv == 0xE0170031) { func = getFuncIDBind(funcID, false); } else { func = getFuncIDBind(funcID, true); } if (func != null) { func(rv, result, idCarrier, issuer, subject, certSn, issuerSn, serial, alg); } } //函数索引和函数绑定 function funcIDBind(vid, vfunc) { this.id = vid; this.func = vfunc; } //添加回调函数绑定 function addFuncIDBind(func) { funcIndex++; var newFuncIDBind = new funcIDBind(funcIndex, func); funcIDBindList.push(newFuncIDBind); return funcIndex; } //获取并移除回调函数绑定 function getFuncIDBind(funcID, isRemove) { if (funcID == null) { return; } var index = null; for (var i = 0; i < funcIDBindList.length; i++) { if (funcIDBindList[i].id == funcID) { if (isRemove == true) { return funcIDBindList.splice(i, 1)[0].func; } else { return funcIDBindList[i].func; } } } } //绑定事件 function attach(elem, eventName, func) { if (elem.attachEvent != null) { elem.attachEvent('on' + eventName, func); } else if (elem.addEventListener != null) { elem.addEventListener(eventName, func, false); } } //判断接口是否完整 function isInterfaceFull() { if (eIDpuginObject == null || eIDpuginObject.eID_GetVersion == null || eIDpuginObject.eID_GetMessage == null || eIDpuginObject.eID_GetReaderList == null || eIDpuginObject.eID_DetectCardBegin == null || eIDpuginObject.eID_DetectCardEnd == null || eIDpuginObject.eID_Hash == null || eIDpuginObject.eID_Sign == null || eIDpuginObject.eID_VerifyPin == null || eIDpuginObject.eID_SignNoInputPin == null) { return false; } return true; } }
JavaScript
CL
7c4535efdf9f520413bb1715090dbe1c7c61b36494b4a07d795e62c30ed51619
(function () { 'use strict'; angular.module('app.setting').config(config); /** @ngInject */ function config($stateProvider) { $stateProvider.state( 'settingList', { parent: 'root', url: '/setting/capDo-list', templateUrl: 'app/setting/capDo/capDo-list.tpl.html', controller: 'capDoListCtr', controllerAs: 'capDoListVm', data: { pageTitle: 'Cài Đặt', module: 'setting', icon: 'icon-settings', permission: 'Setting' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } } ).state('capDo-list', { parent: 'root', url: '/setting/capDo-list', templateUrl: 'app/setting/capDo/capDo-list.tpl.html', controller: 'capDoListCtr', controllerAs: 'capDoListVm', data: { pageTitle: 'Quản lý Cấp Độ', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } } ).state('capDo-add', { parent: 'root', url: '/setting/capDo-add', templateUrl: 'app/setting/capDo/capDo-add.tpl.html', controller: 'capDoAddCtr', controllerAs: 'capDoAddVm', data: { pageTitle: 'Thêm Loại Cấp Độ', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }) .state('capDo-edit', { parent: 'root', url: '/setting/capDo-edit/:id', templateUrl: 'app/setting/capDo/capDo-edit.tpl.html', controller: 'capDoEditCtr', controllerAs: 'capDoEditVm', data: { pageTitle: 'Sửa Loại Cấp Độ', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }) .state('loaiNoiThat-list', { parent: 'root', url: '/setting/loaiNoiThat-list', templateUrl: 'app/setting/loaiNoiThat/loaiNoiThat-list.tpl.html', controller: 'loaiNoiThatListCtr', controllerAs: 'loaiNoiThatListVm', data: { pageTitle: 'Quản Lý Loại Nội Thất', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('loaiNoiThat-add', { parent: 'root', url: '/setting/loaiNoiThat-add', templateUrl: 'app/setting/loaiNoiThat/loaiNoiThat-add.tpl.html', controller: 'loaiNoiThatAddCtr', controllerAs: 'loaiNoiThatAddVm', data: { pageTitle: 'Thêm Loại Nội Thất', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('loaiNoiThat-edit', { parent: 'root', url: '/setting/loaiNoiThat-edit/:id', templateUrl: 'app/setting/loaiNoiThat/loaiNoiThat-edit.tpl.html', controller: 'loaiNoiThatEditCtr', controllerAs: 'loaiNoiThatEditVm', data: { pageTitle: 'Sửa Loại Nội Thất', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('loaiTacNghiep-list', { parent: 'root', url: '/setting/loaiTacNghiep-list', templateUrl: 'app/setting/loaiTacNghiep/loaiTacNghiep-list.tpl.html', controller: 'loaiTacNghiepListCtr', controllerAs: 'loaiTacNghiepListVm', data: { pageTitle: 'Quản Lý Loại Tác Nghiệp', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('loaiTacNghiep-add', { parent: 'root', url: '/setting/loaiTacNghiep-mod', templateUrl: 'app/setting/loaiTacNghiep/loaiTacNghiep-mod.tpl.html', controller: 'loaiTacNghiepModCtr', controllerAs: 'loaiTacNghiepModVm', data: { pageTitle: 'Thêm Loại Tác Nghiệp', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('loaiTacNghiep-edit', { parent: 'root', url: '/setting/loaiTacNghiep-mod/:idLoai', templateUrl: 'app/setting/loaiTacNghiep/loaiTacNghiep-mod.tpl.html', controller: 'loaiTacNghiepModCtr', controllerAs: 'loaiTacNghiepModVm', data: { pageTitle: 'Sửa Loại Tác Nghiệp', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('tacNghiep-list', { parent: 'root', url: '/setting/tacNghiep-list', templateUrl: 'app/setting/tacNghiep/tacNghiep-list.tpl.html', controller: 'tacNghiepListCtr', controllerAs: 'tacNghiepListVm', data: { pageTitle: 'Quản Lý Tác Nghiệp', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] // , // deps: ['$ocLazyLoad', function($ocLazyLoad){ // return $ocLazyLoad.load({ // cache: true, // files: [ // './app/bds/tacNghiep.service.js' // ] // }); // }] } }).state('tacNghiep-edit', { parent: 'root', url: '/setting/tacNghiep-mod/:id', templateUrl: 'app/setting/tacNghiep/tacNghiep-mod.tpl.html', controller: 'tacNghiepModCtr', controllerAs: 'tacNghiepModVm', data: { pageTitle: 'Sửa Tác Nghiệp', module: 'setting', parent: 'settingList', hide: true }, params: { id: null, bdsId: null, text: null }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('hanhChinh-list', { parent: 'root', url: '/setting/hanhChinh-list', templateUrl: 'app/setting/hanhChinh/hanhChinh-list.tpl.html', controller: 'hanhChinhListCtr', controllerAs: 'hanhChinhListVm', data: { pageTitle: 'Quản Lý Hành Chính', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] // , // deps: ['$ocLazyLoad', function($ocLazyLoad){ // return $ocLazyLoad.load({ // cache: true, // files: [ // './app/common/utils/mark-removal.service.js' // ] // }); // }] } }).state('viTri-list', { parent: 'root', url: '/setting/viTri-list', templateUrl: 'app/setting/viTri/viTri-list.tpl.html', controller: 'viTriListCtr', controllerAs: 'viTriListVm', data: { pageTitle: 'Quản Lý Loại Vị Trí', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('viTri-add', { parent: 'root', url: '/setting/viTri-mod', templateUrl: 'app/setting/viTri/viTri-mod.tpl.html', controller: 'viTriModCtr', controllerAs: 'viTriModVm', data: { pageTitle: 'Thêm Loại Vị Trí', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('viTri-edit', { parent: 'root', url: '/setting/viTri-mod/:idLoai', templateUrl: 'app/setting/viTri/viTri-mod.tpl.html', controller: 'viTriModCtr', controllerAs: 'viTriModVm', data: { pageTitle: 'Sửa Loại Vị Trí', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('duAn-list', { parent: 'root', url: '/setting/duAn-list', templateUrl: 'app/setting/duAn/duAn-list.tpl.html', controller: 'duAnListCtr', controllerAs: 'duAnListVm', data: { pageTitle: 'Quản Lý Dự Án', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('duAn-add', { parent: 'root', url: '/setting/duAn-mod', templateUrl: 'app/setting/duAn/duAn-mod.tpl.html', controller: 'duAnModCtr', controllerAs: 'duAnModVm', data: { pageTitle: 'Thêm Loại Dự Án', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('duAn-edit', { parent: 'root', url: '/setting/duAn-mod/:idLoai', templateUrl: 'app/setting/duAn/duAn-mod.tpl.html', controller: 'duAnModCtr', controllerAs: 'duAnModVm', data: { pageTitle: 'Sửa Loại Dự Án', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('bDS-list', { parent: 'root', url: '/setting/bDS-list', templateUrl: 'app/setting/bDS/bDS-list.tpl.html', controller: 'bDSListCtr', controllerAs: 'bDSListVm', data: { pageTitle: 'Quản Lý Loại BĐS', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('bDS-add', { parent: 'root', url: '/setting/bDS-mod', templateUrl: 'app/setting/bDS/bDS-mod.tpl.html', controller: 'bDSModCtr', controllerAs: 'bDSModVm', data: { pageTitle: 'Thêm Loại Bất Động Sản', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('bDS-edit', { parent: 'root', url: '/setting/bDS-mod/:idLoai', templateUrl: 'app/setting/bDS/bDS-mod.tpl.html', controller: 'bDSModCtr', controllerAs: 'bDSModVm', data: { pageTitle: 'Chi Tiết Loại Bất Động Sản', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('duong-list', { parent: 'root', url: '/setting/duong-list', templateUrl: 'app/setting/duong/duong-list.tpl.html', controller: 'duongListCtr', controllerAs: 'duongListVm', data: { pageTitle: 'Quản Lý Loại Đường', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('duong-add', { parent: 'root', url: '/setting/duong-mod', templateUrl: 'app/setting/duong/duong-mod.tpl.html', controller: 'duongModCtr', controllerAs: 'duongModVm', data: { pageTitle: 'Thêm Loại Đường', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('duong-edit', { parent: 'root', url: '/setting/duong-mod/:idLoai', templateUrl: 'app/setting/duong/duong-mod.tpl.html', controller: 'duongModCtr', controllerAs: 'duongModVm', data: { pageTitle: 'Sửa Loại Đường', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('giamGia-list', { parent: 'root', url: '/setting/giamGia-list', templateUrl: 'app/setting/giamGia/giamGia-list.tpl.html', controller: 'giamGiaListCtr', controllerAs: 'giamGiaListVm', data: { pageTitle: 'Quản Lý Loại Giảm Giá', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('giamGia-add', { parent: 'root', url: '/setting/giamGia-mod', templateUrl: 'app/setting/giamGia/giamGia-mod.tpl.html', controller: 'giamGiaModCtr', controllerAs: 'giamGiaModVm', data: { pageTitle: 'Thêm Loại Giảm Giá', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('giamGia-edit', { parent: 'root', url: '/setting/giamGia-mod/:idLoai', templateUrl: 'app/setting/giamGia/giamGia-mod.tpl.html', controller: 'giamGiaModCtr', controllerAs: 'giamGiaModVm', data: { pageTitle: 'Sửa Loại Giảm Giá', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('hau-list', { parent: 'root', url: '/setting/hau-list', templateUrl: 'app/setting/hau/hau-list.tpl.html', controller: 'hauListCtr', controllerAs: 'hauListVm', data: { pageTitle: 'Quản Lý Loại Hậu', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('hau-add', { parent: 'root', url: '/setting/hau-mod', templateUrl: 'app/setting/hau/hau-mod.tpl.html', controller: 'hauModCtr', controllerAs: 'hauModVm', data: { pageTitle: 'Thêm Loại Hậu', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('hau-edit', { parent: 'root', url: '/setting/hau-mod/:idLoai', templateUrl: 'app/setting/hau/hau-mod.tpl.html', controller: 'hauModCtr', controllerAs: 'hauModVm', data: { pageTitle: 'Sửa Loại Hậu', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('huong-list', { parent: 'root', url: '/setting/huong-list', templateUrl: 'app/setting/huong/huong-list.tpl.html', controller: 'huongListCtr', controllerAs: 'huongListVm', data: { pageTitle: 'Quản Lý Loại Hướng', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('huong-add', { parent: 'root', url: '/setting/huong-mod', templateUrl: 'app/setting/huong/huong-mod.tpl.html', controller: 'huongModCtr', controllerAs: 'huongModVm', data: { pageTitle: 'Thêm Loại Hướng', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('huong-edit', { parent: 'root', url: '/setting/huong-mod/:idLoai', templateUrl: 'app/setting/huong/huong-mod.tpl.html', controller: 'huongModCtr', controllerAs: 'huongModVm', data: { pageTitle: 'Sửa Loại Hướng', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('lienKetUser-list', { parent: 'root', url: '/setting/lienKetUser-list', templateUrl: 'app/setting/lienKetUser/lienKetUser-list.tpl.html', controller: 'lienKetUserListCtr', controllerAs: 'lienKetUserListVm', data: { pageTitle: 'Quản Lý Loại Liên Kết User', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('lienKetUser-add', { parent: 'root', url: '/setting/lienKetUser-mod', templateUrl: 'app/setting/lienKetUser/lienKetUser-mod.tpl.html', controller: 'lienKetUserModCtr', controllerAs: 'lienKetUserModVm', data: { pageTitle: 'Thêm Loại Liên Kết User', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('lienKetUser-edit', { parent: 'root', url: '/setting/lienKetUser-mod/:idLoai', templateUrl: 'app/setting/lienKetUser/lienKetUser-mod.tpl.html', controller: 'lienKetUserModCtr', controllerAs: 'lienKetUserModVm', data: { pageTitle: 'Sửa Loại Liên Kết User', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('nguonBDS-list', { parent: 'root', url: '/setting/nguonBDS-list', templateUrl: 'app/setting/nguonBDS/nguonBDS-list.tpl.html', controller: 'nguonBDSListCtr', controllerAs: 'nguonBDSListVm', data: { pageTitle: 'Quản Lý Loại Nguồn BDS', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('nguonBDS-add', { parent: 'root', url: '/setting/nguonBDS-mod', templateUrl: 'app/setting/nguonBDS/nguonBDS-mod.tpl.html', controller: 'nguonBDSModCtr', controllerAs: 'nguonBDSModVm', data: { pageTitle: 'Thêm Loại Nguồn BDS', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('nguonBDS-edit', { parent: 'root', url: '/setting/nguonBDS-mod/:idLoai', templateUrl: 'app/setting/nguonBDS/nguonBDS-mod.tpl.html', controller: 'nguonBDSModCtr', controllerAs: 'nguonBDSModVm', data: { pageTitle: 'Sửa Loại Nguồn BDS', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('mucDich-list', { parent: 'root', url: '/setting/mucDich-list', templateUrl: 'app/setting/mucDich/mucDich-list.tpl.html', controller: 'mucDichListCtr', controllerAs: 'mucDichListVm', data: { pageTitle: 'Quản Lý Loại Mục Đích', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('mucDich-add', { parent: 'root', url: '/setting/mucDich-mod', templateUrl: 'app/setting/mucDich/mucDich-mod.tpl.html', controller: 'mucDichModCtr', controllerAs: 'mucDichModVm', data: { pageTitle: 'Thêm Loại Mục Đích', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('mucDich-edit', { parent: 'root', url: '/setting/mucDich-mod/:idLoai', templateUrl: 'app/setting/mucDich/mucDich-mod.tpl.html', controller: 'mucDichModCtr', controllerAs: 'mucDichModVm', data: { pageTitle: 'Sửa Loại Mục Đích', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('user-list', { parent: 'root', url: '/setting/user-list', templateUrl: 'app/setting/user/user-list.tpl.html', controller: 'settingUserListCtr', controllerAs: 'userListVm', data: { pageTitle: 'Quản Lý Loại User', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('user-add', { parent: 'root', url: '/setting/user-mod', templateUrl: 'app/setting/user/user-mod.tpl.html', controller: 'userModCtr', controllerAs: 'userModVm', data: { pageTitle: 'Thêm Loại User', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('user-edit', { parent: 'root', url: '/setting/user-mod/:idLoai', templateUrl: 'app/setting/user/user-mod.tpl.html', controller: 'userModCtr', controllerAs: 'userModVm', data: { pageTitle: 'Sửa Loại User', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('danhMucBDS-list', { parent: 'root', url: '/setting/danhMucBDS-list', templateUrl: 'app/setting/danhMucBDS/danhMucBDS-list.tpl.html', controller: 'danhMucBDSListCtr', controllerAs: 'danhMucBDSListVm', data: { pageTitle: 'Quản Lý Kho BĐS', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('danhMucBDS-add', { parent: 'root', url: '/setting/danhMucBDS-mod', templateUrl: 'app/setting/danhMucBDS/danhMucBDS-mod.tpl.html', controller: 'danhMucBDSModCtr', controllerAs: 'danhMucBDSModVm', data: { pageTitle: 'Thêm Kho BĐS', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('danhMucBDS-edit', { parent: 'root', url: '/setting/danhMucBDS-mod/:idLoai', templateUrl: 'app/setting/danhMucBDS/danhMucBDS-mod.tpl.html', controller: 'danhMucBDSModCtr', controllerAs: 'danhMucBDSModVm', data: { pageTitle: 'Sửa Kho BĐS', module: 'setting', parent: 'settingList', hide: true }, params: { item: null }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('nhuCau-list', { parent: 'root', url: '/setting/nhuCau-list', templateUrl: 'app/setting/nhuCau/nhuCau-list.tpl.html', controller: 'settingNhuCauListCtr', controllerAs: 'nhuCauListVm', data: { pageTitle: 'Quản Lý Loại Nhu Cầu', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('nhuCau-add', { parent: 'root', url: '/setting/nhuCau-mod', templateUrl: 'app/setting/nhuCau/nhuCau-mod.tpl.html', controller: 'nhuCauModCtr', controllerAs: 'nhuCauModVm', data: { pageTitle: 'Thêm Loại Nhu Cầu', module: 'setting', parent: 'settingList', icon: 'icon-settings', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('nhuCau-edit', { parent: 'root', url: '/setting/nhuCau-mod/:idLoai', templateUrl: 'app/setting/nhuCau/nhuCau-mod.tpl.html', controller: 'nhuCauModCtr', controllerAs: 'nhuCauModVm', data: { pageTitle: 'Sửa Loại Nhu Cầu', module: 'setting', parent: 'settingList', hide: true }, params: { item: null, }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('duLieuTho', { parent: 'root', url: '/duLieuTho', templateUrl: 'app/setting/duLieuTho/duLieuTho.tpl.html', controller: 'duLieuThoCtr', controllerAs: 'duLieuThoVm', data: { pageTitle: 'Dữ Liệu Thô', module: 'setting', parent: 'settingList', hide: false }, params: { item: null, }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }], deps: ['$ocLazyLoad', function ($ocLazyLoad) { return $ocLazyLoad.load({ cache: true, name: 'app.user', files: [ './app/user/user.service.js' ] }); }] } }).state('khoanGia', { parent: 'root', url: '/setting/khoanGia', templateUrl: 'app/setting/khoanGia/list.tpl.html', controller: 'listCtr', controllerAs: 'listVm', data: { pageTitle: 'Quản lý Khoản giá', module: 'setting', icon: 'icon-settings', parent: 'settingList' }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }).state('khoanGia.chiTiet', { parent: 'root', url: '/setting/khoanGia/chiTiet/:id', templateUrl: 'app/setting/khoanGia/chiTiet.tpl.html', controller: 'chiTietCtr', controllerAs: 'chiTietVm', data: { pageTitle: '', module: 'setting', parent: 'settingList', hide: true }, resolve: { "currentAuth": ["authService", function (authService) { return authService.requireSignIn(); }] } }) ; //---- } })();
JavaScript
CL
b07b233342d151e71cf821ec254aae9d246079a2d2813e1cc335687a876fe697
//模块化思想 //1 启动server webpack-dev-server //2 模块化开发commonjs //3 版本号控制 hash或者chunkhash //4 css,sass引入 //5 html自定义模板 //6 抽离css //7 压缩合并JS //8 用babel编译es6,需要创建.babelrc文件 //9 mock数据(npm i json-server -g 搭建虚拟服务器) //10 external外部配置文件(开发依赖),例如项目用到jQuery var webpack=require('webpack'); //4 配置HTML 模板 ,插件 var HtmlWebpackPlugin = require('html-webpack-plugin'); //6 把css抽离 const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports={ //1 配置入口 //entry:'./src/js/index.js', entry:'./src/js/entry.js', // 1.1 如果有多个入口 //entry: ['./src/js/serch.js','./src/index.js'], //1.2 入口以对象的话,称为chunks, // 对象行形式 filename不能是一个了 //entry:{ // app:'./src/js/index.js', // serch:'./src/js/serch.js' //}, //output:{ // path:__dirname+'/build', // //3.1 如何配置版本号,清除缓存 // //filename:'[name]_[hash].js' // filename:'[name]_[chunkhash].js' //}, //2 配置出口(打包的输出路径) output:{ path:__dirname+'/build', //filename:'bundle.js', filename:'app_[hash].js' }, //3 配置服务器 devServer:{ contentBase:'./build', inline: true, port:8000, //9.1配置后台接口 proxy:{ //路由映射 "/api":{ target:'http://localhost:9000/', pathRewrite: {"^/api":""} } } }, //5 引入loaders module:{ loaders:[ //5.1 解析css,css-loader { test:/\.css$/, //loader:'style-loader!css-loader' // 6.2 想抽离出来得 loader:ExtractTextPlugin.extract({ fallback:'style-loader', use:'css-loader' }) }, { //5.2.SASS的.scss 文件使用 style-loader、css-loader 和 sass-loader 来编译处理 test: /\.scss$/, //loader: 'style-loader!css-loader!sass-loader' // 6.2 想抽离出来得 loader:ExtractTextPlugin.extract({ fallback:'style-loader', use:'css-loader!sass-loader' }) }, //8 编译es6 { test:'/\.js$/', exclude:/node_modules/, loader:'babel-loader' //8.2在根目录创建.babelrc文件,并输入配置 } ] }, //4 配置HTML模板插件 // 这样 webpack 编译的时候回自动在output目录下生成index.html plugins:[ new HtmlWebpackPlugin({ //4.1配置参数,html的title title:'正在热映[豆瓣]', abc:'自定义输出', // 4.2 输出后html的名字,可以自定义 filename:'index.html', //4.3 html的模板 template:'webpack.tem.ejs' }), //7 代码优化:合并以及压缩代码 // 开发环境暂时不需要 new webpack.optimize.UglifyJsPlugin({ //7.1输出不显示警告 compress:{ warnings:false }, //7.2 输出去掉注释 output:{ comments:false } }), //6.1 css抽离 new ExtractTextPlugin({ filename:'app_[hash].css', disable:false, allChunks:true }) ], //10 项目依赖,如JQ externals: { jquery: 'window.jQuery' } };
JavaScript
CL
dbac61c27c26748946061bde4b33e8623b9d4ca353beed2c4a53b7409ed1a200
import { LEAGUE_REQUEST_BY_ID, LEAGUE_RECEIVE_BY_ID, REQUEST_FIXTURES_BY_LEAGUE, RECEIVE_FIXTURES_BY_LEAGUE, LEAGUE_REQUEST_TEAMS, LEAGUE_RECEIVE_TEAMS, LEAGUE_RECEIVE_MULTIPLE_LEAGUES, } from '../types/leagues' import { getAllSeasonsForLeague } from '../../fetch/League' import { getTeamsByLeagueID } from '../../fetch/Team' import { receiveMultipleTeams } from './teams' import { initFixtures } from './fixtures' /** * @module Redux Creators leagues */ /** * Sets the fetchingLeague property of the specified league in leaguesByID store to true. * @method requestLeagueByID * @param {Integer} leagueID A league ID * @return {Action} type: LEAGUE_REQUEST_BY_ID */ export function requestLeagueByID(leagueID){ return { type: LEAGUE_REQUEST_BY_ID, leagueID: leagueID, }; } /** * Sets the fetchingLeague property of the specified league in leaguesByID store to false. * Stores a league name. * Stores a country code. * Stores a uri address for a logo. * @method receiveLeagueByID * @param {Object} league (league : properties) * @return {Action} type: LEAGUE_RECEIVE_BY_ID */ export function receiveLeagueByID(league){ return { type: LEAGUE_RECEIVE_BY_ID, leagueID: league.leagueID, name: league.name, countryCode: league.countryCode, logo: league.logo, seasonStart: league.seasonStart, seasonEnd: league.seasonEnd, }; } /** * Should Fetch test for a league. * @method shouldFetchLeague * @param {Object} league (league : properties) * @return {Boolean} True if !null false otherwise. */ function shouldFetchLeague(league){ if(!league){ return true; }else if(league.fetchingLeague){ return false; } } /** * Fetch sequence for a league. * @method fetchLeagues * @param {Array} leagueIDs A set of league IDs * @return {Function} */ export function fetchLeagues(leagueIDs){ return (dispatch, getState) => { if(leagueIDs.length){ let counter = leagueIDs.length leagueIDs.map( leagueID => { if(shouldFetchLeague(getState().leaguesByID[leagueID])){ dispatch(requestLeagueByID(leagueID)) return getAllSeasonsForLeague(leagueID) // get latest season .then( data => processLeague(data)) .then( processedData => { dispatch( receiveLeagueByID(processedData)); counter-=1; if(counter == 0){ dispatch(initFixtures()) } }) } }); }else{ dispatch(initFixtures()) } } } /** * Converts the received API date string to a ms timestamp. * @method dateToTimeStamp * @param {String} date A date in dd-mm-yyyy format * @return {Integer} A ms timestamp */ function dateToTimeStamp(date){ pieces = date.trim().split('-'); timeStamp = Date.UTC(parseInt(pieces[0]), parseInt(pieces[1], 10)-1, parseInt(pieces[2], 10)); return timeStamp } /** * Processes league data into a league Object. * @method processLeague * @param {Object} data An formatted Object containing league data. * @return {Object} (propertyName : property) */ function processLeague(data){ data = data.api; leagues = data.leagues; league = leagues[leagues.length-1] return { leagueID: league.league_id, name: league.country + " " + league.name, countryCode: league.country_code, logo: league.logo, seasonStart: dateToTimeStamp(league.season_start), seasonEnd: dateToTimeStamp(league.season_end), }; } /** * Sets the fetchingTeams property in the leaguesByID store to true. * @method requestTeamsByID * @param {Integer} leagueID A league ID * @return {Action} type: LEAGUE_REQUEST_TEAMS */ export function requestTeamsByID(leagueID){ return { type: LEAGUE_REQUEST_TEAMS, leagueID: leagueID, }; } /** * Sets the fetchingTeams property in the leaguesByID store to false. * Stores the passed teamIDs into the store for the specified league. * @method receiveTeamsByID * @param {Array} teamIDs A set of team IDs * @param {Integer} leagueID A league ID * @return {Action} type: LEAGUE_RECEIVE_TEAMS */ export function receiveTeamsByID(teamIDs, leagueID){ return { type: LEAGUE_RECEIVE_TEAMS, teamIDs: teamIDs, leagueID: leagueID, }; } /** * Should fetch test for a team. * @method shouldFetchTeams * @param {Object} league A league Object * @return {Boolean} */ function shouldFetchTeams(league){ if(!league.teamIDs){ return true; }else if(league.fetchingTeams){ return false; } } /** * Fetch sequence for teams of a league. * Fetches all teams belonging to the specified league. * @method fetchTeams * @param {Integer} leagueID A league ID * @return {Function} */ export function fetchTeams(leagueID){ return (dispatch, getState) => { if(shouldFetchTeams(getState().leaguesByID[leagueID])){ dispatch(requestTeamsByID(leagueID)) return getTeamsByLeagueID(leagueID) .then( data => processTeams(data)) .then( processedData => { dispatch(receiveMultipleTeams(processedData)); dispatch(receiveTeamsByID(Object.keys(processedData), leagueID)); }) } } } /** * Since teams are grouped in a single object initialization parameters such as * fetch flags must be included as well. * @method processTeams * @param {Object} data A parsed JSON Object * @return {Object} (teamID : data) */ export function processTeams(data){ collect = {}; ids = []; data = data.api; teams = data.teams; teams.forEach( team => { collect[team.team_id] = { fetchingTeam: false, fetchingLeagues: false, fetchingPast: false, fetchingPlayers: false, fetchingFuture: false, teamID: team.team_id, name: team.name, logo: team.logo, country: team.country, } }) return collect; } /** * Processes a set of teams for a League. * @method processLeagues * @param {Object} data A parsed JSON Object * @return {Array} [ * 0 : [Array] A set of ids belonging to the processed teams. * 2 : [Object] (teamID : data) * ] */ export function processLeagues(data){ collect = {}; ids = []; data = data.api; leagues = data.leagues; count = 0 for (leagueID in leagues){ league = leagues[leagueID]; if(league.is_current){ count++; ids.push(league.league_id); collect[league.league_id] = { fetchingLeague: false, fetchingFixtures: false, fetchingTeams: false, leagueID: league.league_id, name: league.country + " " + league.name, countryCode: league.country_code, logo: league.logo, // returns timestamp of dates in UTC seasonStart: dateToTimeStamp(league.season_start), seasonEnd: dateToTimeStamp(league.season_end), }; } if(count == 9){ break; } } return [ids,collect]; } /** * Adds a set of leagues into the leaguesByID store. * @method receiveMultipleLeagues * @param {Object} leagues (leagueID : Object(propertyName : property)) * @return {Action} type: LEAGUE_RECEIVE_MULTIPLE_LEAGUES */ export function receiveMultipleLeagues(leagues){ return { type: LEAGUE_RECEIVE_MULTIPLE_LEAGUES, leagues: leagues, }; }
JavaScript
CL
92a7833d3c7726f8cebbc55a0da5a12e9c709977cf9eee1fd776c3b035e8c1b7
'use strict'; // const child_process = require('child_process'); const aws = require('aws-sdk'); const s3 = new aws.S3(); const lambda = new aws.Lambda({ region: 'us-east-1' //change to your region }); const exec = require('child_process').execSync; const fs = require('fs'); function systemSync(cmd) { return exec(cmd).toString(); }; exports.handler = (event, context, callback) => { console.log(event.Records[0].s3); // If not invoked directly then treat as coming from S3 if (!event.sourceBucket) { if (event.Records[0].s3.bucket.name) { var sourceBucket = event.Records[0].s3.bucket.name; var sourceKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); } else { console.error ('no source bucket defined'); } } else { var sourceBucket = event.sourceBucket; var sourceKey = event.sourceKey; } // in case of s3 event triggered by a new overview file (which it should if // wired correctly) we need to point at the intermediate tif file not ovr if (sourceKey.includes(".ovr")) { sourceKey = sourceKey.replace('.ovr',''); console.log ('Stripped .ovr from key'); } // escape if s3 event triggered by upload not in georef subdirectory var deepDirectory = 'georef/' + process.env.georefSubDir; if (!sourceKey.includes(deepDirectory)) { console.log("error: key doesn't include '" + deepDirectory + "'. exiting..."); console.log(sourceKey); return } else { console.log('Source Bucket: ' + sourceBucket); console.log('Source Key: ' + sourceKey); console.log('NC GDAL Args: ' + process.env.ncGdalArgs); console.log('BW GDAL Args: ' + process.env.bwGdalArgs); console.log('Upload Bucket: ' + process.env.uploadBucket); console.log('Upload Key ACL: ' + process.env.uploadKeyAcl); console.log('Upload Georef Sub Directory: ' + process.env.georefSubDir); // choose gdal command for number of bands in raster. if not bw or nc, just escape var gdalCmd; if (sourceKey.includes('bw/')) { gdalCmd = process.env.bwGdalArgs; } else if (sourceKey.includes('nc/')) { gdalCmd = process.env.ncGdalArgs; } else { console.log("error: key doesn't include 'bw/' or 'nc/'. exiting..."); return } // the AWS access keys will not be neccessary in gdal ver 2.3 due to IAM Role support const cmd = 'AWS_REQUEST_PAYER=requester' + ' GDAL_DISABLE_READDIR_ON_OPEN=YES CPL_VSIL_CURL_ALLOWED_EXTENSIONS=.tif ./bin/gdal_translate ' + gdalCmd + ' /vsis3/' + sourceBucket + '/' + sourceKey + ' /tmp/output.tif'; console.log('Command to run: ' + cmd); // clear contents of tmp dir in case of reuse console.log(systemSync('rm -fv /tmp/*')); // run command here should have some error checking console.log(systemSync(cmd)); console.log(systemSync('ls -alh /tmp')); // upload key is source key swapped with georef & sub swapped for COG var uploadKey = sourceKey.replace(deepDirectory, 'cog/'); console.log('uploadKey: ' + uploadKey); var body = fs.createReadStream('/tmp/output.tif'); var s3obj = new aws.S3({params: {Bucket: process.env.uploadBucket, Key: uploadKey, ACL: process.env.uploadKeyAcl, ContentType: 'image/tiff' }}); // upload output of the gdal util to S3 s3obj.upload({Body: body}) .on('httpUploadProgress', function(evt) { //console.log(evt); }) .send(function(err, data) { console.log(data); const payload = {sourceBucket: process.env.uploadBucket,sourceKey: uploadKey} lambda.invoke({ ClientContext: "ls4-03", FunctionName: "ls4-04-shp_index", InvocationType: "Event", Payload: JSON.stringify(payload) // pass params }, function(error, data) { if (error) { context.done('error', error); } if(data.Payload){ console.log("ls4-04-shp_index invoked!") context.succeed(data.Payload) } }); callback(err, 'Process complete!');} ) } };
JavaScript
CL
c672c3634f32427f63f84c6d3bc3ed14d89eb337232cdf01398b8a61f0b73edc
import { connect } from "react-redux"; import { compose } from "redux"; import { createStructuredSelector } from "reselect"; import { collectionsFetchingSelector } from "../../redux/shop/shop.selectors"; import { WithSpinner } from "../../components/with-spinner/with-spinner.component"; import CollectionPage from "../collection/collection.component"; const mapStateToProps = createStructuredSelector({ isLoading: collectionsFetchingSelector, }); const CollectionsPageContainer = compose( connect(mapStateToProps), WithSpinner )(CollectionPage); export default CollectionsPageContainer;
JavaScript
CL
dd517b7ed05bc08f0c3c08633870d68c5f9f7a1fafe973aa246819774b292589
/* eslint-disable import/no-unresolved, import/extensions */ import Entypo from 'react-native-vector-icons/Entypo'; import EvilIcons from 'react-native-vector-icons/EvilIcons'; import Feather from 'react-native-vector-icons/Feather'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import Foundation from 'react-native-vector-icons/Foundation'; import Ionicons from 'react-native-vector-icons/Ionicons'; import MaterialIcons from 'react-native-vector-icons/MaterialIcons'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; import Octicons from 'react-native-vector-icons/Octicons'; import Zocial from 'react-native-vector-icons/Zocial'; import SimpleLineIcons from 'react-native-vector-icons/SimpleLineIcons'; import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import {spacing, Styles} from "../assets/style/Styles"; import {Alert, Text, View} from "react-native"; import {withPanierContext} from "../routes/PanierProvider"; const propTypes = { isBadge: PropTypes.bool, name: PropTypes.string.isRequired, style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), size: PropTypes.number, color: PropTypes.string, /** * Name of Icon set that should be use. From react-native-vector-icons */ iconSet: PropTypes.string, /** * banner */ banner: PropTypes.any, }; const defaultProps = { isBadge:false, size: null, color: null, style: null, iconSet: null, }; const getIconComponent = iconSet => { switch (iconSet) { case 'Entypo': return Entypo; case 'EvilIcons': return EvilIcons; case 'Feather': return Feather; case 'FontAwesome': return FontAwesome; case 'Foundation': return Foundation; case 'Ionicons': return Ionicons; case 'MaterialIcons': return MaterialIcons; case 'MaterialCommunityIcons': return MaterialCommunityIcons; case 'Octicons': return Octicons; case 'Zocial': return Zocial; case 'SimpleLineIcons': return SimpleLineIcons; default: return MaterialIcons; } }; class Icon extends PureComponent { render() { const { isBadge, name, style, size, color, iconSet, context} = this.props; const badgeValue = context.banner || 0; const iconColor = color || Styles.Palette.text.secondary; const iconSize = size || spacing.iconSize; const VectorIcon = getIconComponent(iconSet); if (isBadge){ const showBadge = (badgeValue && badgeValue > 0 ) ? <View style={Styles.badge.container}> <Text style={Styles.badge.content}> {badgeValue < 10 ? badgeValue: '9+'} </Text> </View> :null; return (<View style={{flexDirection:'row'}}> <VectorIcon iconSet={iconSet} name={name} color={color} size={iconSize} /> {showBadge} </View>); } return ( <VectorIcon name={name} size={iconSize} color={iconColor} style={style} /> ); } } Icon.propTypes = propTypes; Icon.defaultProps = defaultProps; export default withPanierContext(Icon);
JavaScript
CL
e78b91f32698eaacf64b0879ebdbf87f0a88c39341eeff03c6f22cde63f470d8
'use strict';var Vue=require('vue');function _interopDefaultLegacy(e){return e&&typeof e==='object'&&'default'in e?e:{'default':e}}var Vue__default=/*#__PURE__*/_interopDefaultLegacy(Vue);function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }var script$4 = Vue__default['default'].extend({ inject: ['data'], computed: { publisher: function publisher() { return this.data.publisher || {}; } } });function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier /* server only */, shadowMode, createInjector, createInjectorSSR, createInjectorShadow) { if (typeof shadowMode !== 'boolean') { createInjectorSSR = createInjector; createInjector = shadowMode; shadowMode = false; } // Vue.extend constructor export interop. const options = typeof script === 'function' ? script.options : script; // render functions if (template && template.render) { options.render = template.render; options.staticRenderFns = template.staticRenderFns; options._compiled = true; // functional template if (isFunctionalTemplate) { options.functional = true; } } // scopedId if (scopeId) { options._scopeId = scopeId; } let hook; if (moduleIdentifier) { // server build hook = function (context) { // 2.3 injection context = context || // cached call (this.$vnode && this.$vnode.ssrContext) || // stateful (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext); // functional // 2.2 with runInNewContext: true if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { context = __VUE_SSR_CONTEXT__; } // inject component styles if (style) { style.call(this, createInjectorSSR(context)); } // register component module identifier for async chunk inference if (context && context._registeredComponents) { context._registeredComponents.add(moduleIdentifier); } }; // used by ssr in case component is cached and beforeCreate // never gets called options._ssrRegister = hook; } else if (style) { hook = shadowMode ? function (context) { style.call(this, createInjectorShadow(context, this.$root.$options.shadowRoot)); } : function (context) { style.call(this, createInjector(context)); }; } if (hook) { if (options.functional) { // register for functional component in vue file const originalRender = options.render; options.render = function renderWithStyleInjection(h, context) { hook.call(context); return originalRender(h, context); }; } else { // inject component registration as beforeCreate hook const existing = options.beforeCreate; options.beforeCreate = existing ? [].concat(existing, hook) : [hook]; } } return script; }/* script */ var __vue_script__$4 = script$4; /* template */ var __vue_render__$4 = function __vue_render__() { var _vm = this; var _h = _vm.$createElement; var _c = _vm._self._c || _h; return _c('div', { staticClass: "shadow-md p-5 rounded-lg bg-white" }, [_vm._ssrNode("<div class=\"flex\"><div>" + (_vm.publisher.image ? "<img" + _vm._ssrAttr("src", _vm.publisher.image) + _vm._ssrAttr("alt", _vm.publisher.username) + " class=\"rounded mr-4\" style=\"min-width: 75px; min-height: 75px; width: 75px; height: 75px\">" : "<!---->") + "</div> <div class=\"flex flex-col justify-center\"><h4 class=\"font-semibold text-xl text-blue-500\">" + _vm._ssrEscape("\n " + _vm._s(_vm.publisher.username) + "\n ") + "</h4> <p class=\"text-sm mb-2\">" + _vm._ssrEscape("\n " + _vm._s(_vm.publisher.info) + "\n ") + "</p></div></div>")]); }; var __vue_staticRenderFns__$4 = []; /* style */ var __vue_inject_styles__$4 = undefined; /* scoped */ var __vue_scope_id__$4 = undefined; /* module identifier */ var __vue_module_identifier__$4 = "data-v-2753a560"; /* functional template */ var __vue_is_functional_template__$4 = false; /* style inject */ /* style inject SSR */ /* style inject shadow dom */ var __vue_component__$4 = /*#__PURE__*/normalizeComponent({ render: __vue_render__$4, staticRenderFns: __vue_staticRenderFns__$4 }, __vue_inject_styles__$4, __vue_script__$4, __vue_scope_id__$4, __vue_is_functional_template__$4, __vue_module_identifier__$4, false, undefined, undefined, undefined);var script$3 = Vue__default['default'].extend({ inject: ['data', 'emitEvent'], computed: { subTotal: function subTotal() { var vm = this; var _vm$data = vm.data, _vm$data$deliveryItem = _vm$data.deliveryItems, deliveryItems = _vm$data$deliveryItem === void 0 ? [] : _vm$data$deliveryItem, _vm$data$pickupItems = _vm$data.pickupItems, pickupItems = _vm$data$pickupItems === void 0 ? [] : _vm$data$pickupItems; var deliveryItemsTotal = vm.getTotal(deliveryItems); var pickupItemsTotal = vm.getTotal(pickupItems); return deliveryItemsTotal + pickupItemsTotal; }, taxes: function taxes() { var vm = this; return vm.subTotal * (vm.data.tax || 0); }, total: function total() { var vm = this; return vm.subTotal + vm.taxes; } }, methods: { getTotal: function getTotal(items) { return (items || []).reduce(function (total, item) { total += +item.quantity * +item.price; return total; }, 0); } } });/* script */ var __vue_script__$3 = script$3; /* template */ var __vue_render__$3 = function __vue_render__() { var _vm = this; var _h = _vm.$createElement; var _c = _vm._self._c || _h; return _c('div', { staticClass: "checkout-cart__order-summary shadow-md rounded-lg bg-white" }, [_vm._ssrNode("<h4 class=\"text-lg font-medium text-gray-600 mb-4\">Order Summary</h4> <p class=\"flex justify-between mb-1 text-gray-400\"><span>Subtotal:</span> <span>" + _vm._ssrEscape("$" + _vm._s(_vm.subTotal.toFixed(2))) + "</span></p> <p class=\"flex justify-between mb-1 text-gray-400\"><span>Taxes:</span> <span>" + _vm._ssrEscape("$" + _vm._s(_vm.taxes.toFixed(2))) + "</span></p> <hr class=\"my-4\"> <p class=\"flex justify-between mb-1\"><span>Total:</span> <span>" + _vm._ssrEscape("$" + _vm._s(_vm.total.toFixed(2))) + "</span></p> <button class=\"p-2 border border-blue-500 bg-blue-500 rounded text-white focus:outline-none hover:bg-blue-700 hover:border-blue-700 text-sm w-full mt-4\">\n Checkout\n </button>")]); }; var __vue_staticRenderFns__$3 = []; /* style */ var __vue_inject_styles__$3 = undefined; /* scoped */ var __vue_scope_id__$3 = undefined; /* module identifier */ var __vue_module_identifier__$3 = "data-v-455fa9d4"; /* functional template */ var __vue_is_functional_template__$3 = false; /* style inject */ /* style inject SSR */ /* style inject shadow dom */ var __vue_component__$3 = /*#__PURE__*/normalizeComponent({ render: __vue_render__$3, staticRenderFns: __vue_staticRenderFns__$3 }, __vue_inject_styles__$3, __vue_script__$3, __vue_scope_id__$3, __vue_is_functional_template__$3, __vue_module_identifier__$3, false, undefined, undefined, undefined);var monthsNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];function formatDateWithLeadTime(leadTime) { var currentDateInSecs = Math.round(new Date().getTime() / 1000); return formatDate(new Date((currentDateInSecs + leadTime * 60) * 1000)); } function formatDate(date) { return { base: date, formatted: "".concat(monthsNames[date.getMonth()], " ").concat(date.getDate(), ", ").concat(date.getFullYear()) }; }var script$2 = Vue__default['default'].extend({ inject: ['data', 'emitEvent'], computed: { address: function address() { return this.data.deliveryLocation; }, deliveryDate: function deliveryDate() { return formatDateWithLeadTime(this.data.deliveryLeadTime).formatted; } } });/* script */ var __vue_script__$2 = script$2; /* template */ var __vue_render__$2 = function __vue_render__() { var _vm = this; var _h = _vm.$createElement; var _c = _vm._self._c || _h; return _c('div', { staticClass: "orders--delivery shadow-md rounded-lg bg-white mb-4" }, [_vm._ssrNode("<div class=\"p-4 font-semibold\">Delivery Information</div> <hr> <div class=\"p-4\"><div class=\"flex flex-col lg:flex-row mb-4\"><div class=\"delivery__address w-full lg:w-1/2 pr-4 mb-2 lg:mb-0\"><label class=\"text-sm text-gray-400 font-semibold mb-2 inline-block\">\n Items to be delivered to\n </label> <p>" + _vm._ssrEscape(_vm._s(_vm.address.name)) + "</p> <p>" + _vm._ssrEscape(_vm._s(_vm.address.street)) + "</p> <p>" + _vm._ssrEscape(_vm._s(_vm.address.city) + ", " + _vm._s(_vm.address.state) + ", " + _vm._s(_vm.address.zip)) + "</p> <a href=\"javascript:void(0)\" class=\"text-xs text-blue-500 cursor-pointer hover:text-blue-700\">\n Change\n </a></div> <div class=\"delivery__schedule w-full lg:w-1/2 pr-4\"><label class=\"text-sm text-gray-400 font-semibold mb-2 inline-block\">\n Estimated Delivery Date\n </label> <p>" + _vm._ssrEscape("\n " + _vm._s(_vm.deliveryDate) + "\n ") + "</p></div></div> <div class=\"delivery__items mb-4\"><div class=\"flex justify-between\"><label class=\"text-sm text-gray-400 font-semibold mb-2\">\n Delivery Items\n </label></div> " + _vm._ssrList(_vm.data.deliveryItems, function (item, i) { return "<div" + _vm._ssrClass("border p-2", [{ 'rounded-t-lg': i === 0 }, { 'rounded-b-lg': i === _vm.data.deliveryItems.length - 1 }, i < _vm.data.deliveryItems.length - 1 ? 'border-b-0' : 'border-b']) + "><div class=\"flex flex-col lg:flex-row items-center\"><div class=\"mr-2 text-center\"><img" + _vm._ssrAttr("src", item.image) + _vm._ssrAttr("alt", item.name) + " class=\"object-contain bg-no-repeat\" style=\"\\n min-width: 100px;\\n width: 100px;\\n min-height: 100px;\\n height: 100px;\\n \"></div> <div class=\"flex-grow text-center lg:text-left\"><p>" + _vm._ssrEscape(_vm._s(item.name)) + "</p> <small class=\"text-gray-400\">" + _vm._ssrEscape(_vm._s(item.selectedOptions)) + "</small></div> <div class=\"py-2 lg:p-4 text-right\"><p class=\"text-blue-500 font-semibold\">" + _vm._ssrEscape("\n " + _vm._s(item.quantity) + " @ $" + _vm._s(item.price.toFixed(2)) + "\n ") + "</p></div></div> <div class=\"text-center lg:text-left\"><a href=\"javascript:void(0)\" class=\"text-xs text-green-500 cursor-pointer mr-2 hover:text-green-700\">\n Update\n </a> <a href=\"javascript:void(0)\" class=\"text-xs text-red-500 cursor-pointer hover:text-red-700\">\n Remove\n </a></div></div>"; }) + "</div></div>")]); }; var __vue_staticRenderFns__$2 = []; /* style */ var __vue_inject_styles__$2 = undefined; /* scoped */ var __vue_scope_id__$2 = undefined; /* module identifier */ var __vue_module_identifier__$2 = "data-v-a8d6c2d8"; /* functional template */ var __vue_is_functional_template__$2 = false; /* style inject */ /* style inject SSR */ /* style inject shadow dom */ var __vue_component__$2 = /*#__PURE__*/normalizeComponent({ render: __vue_render__$2, staticRenderFns: __vue_staticRenderFns__$2 }, __vue_inject_styles__$2, __vue_script__$2, __vue_scope_id__$2, __vue_is_functional_template__$2, __vue_module_identifier__$2, false, undefined, undefined, undefined);var script$1 = Vue__default['default'].extend({ inject: ['data', 'emitEvent'], computed: { address: function address() { return this.data.pickupLocation; }, suggestedDate: function suggestedDate() { return formatDateWithLeadTime(this.data.pickupLeadTime).base; }, selectedPickupDate: function selectedPickupDate() { var vm = this; if (!vm.data.selectedPickupDate) { return null; } return formatDate(new Date(vm.data.selectedPickupDate)).formatted; } } });/* script */ var __vue_script__$1 = script$1; /* template */ var __vue_render__$1 = function __vue_render__() { var _vm = this; var _h = _vm.$createElement; var _c = _vm._self._c || _h; return _c('div', { staticClass: "orders--pickup shadow-md rounded-lg bg-white mb-4" }, [_vm._ssrNode("<div class=\"p-4 font-semibold\">Pickup Information</div> <hr> <div class=\"p-4\"><div class=\"flex flex-col lg:flex-row mb-4\"><div class=\"pickup__address w-full lg:w-1/2 pr-4 mb-2 lg:mb-0\"><label class=\"text-sm text-gray-400 font-semibold mb-2 inline-block\">\n Items to be picked up at\n </label> <p>" + _vm._ssrEscape(_vm._s(_vm.address.name)) + "</p> <p>" + _vm._ssrEscape(_vm._s(_vm.address.street)) + "</p> <p>" + _vm._ssrEscape(_vm._s(_vm.address.city) + ", " + _vm._s(_vm.address.state) + ", " + _vm._s(_vm.address.zip)) + "</p> <a href=\"javascript:void(0)\" class=\"text-xs text-blue-500 cursor-pointer hover:text-blue-700\">\n Change\n </a></div> <div class=\"pickup__schedule w-full lg:w-1/2 pr-4\"><label class=\"text-sm text-gray-400 font-semibold mb-2 inline-block\">\n Selected Pickup Date\n </label> " + (_vm.selectedPickupDate ? "<p>" + _vm._ssrEscape("\n " + _vm._s(_vm.selectedPickupDate) + "\n ") + "</p> <a href=\"javascript:void(0)\" class=\"text-xs text-blue-500 cursor-pointer hover:text-blue-700\">\n Change\n </a>" : "<div><button class=\"p-2 border border-blue-500 rounded text-blue-500 focus:outline-none hover:bg-blue-100 text-sm\">\n Schedule Pickup\n </button></div>") + "</div></div> <div class=\"pickup__items mb-4\"><div class=\"flex justify-between\"><label class=\"text-sm text-gray-400 font-semibold mb-2\">\n Pickup Items\n </label></div> " + _vm._ssrList(_vm.data.pickupItems, function (item, i) { return "<div" + _vm._ssrClass("border p-2", [{ 'rounded-t-lg': i === 0 }, { 'rounded-b-lg': i === _vm.data.pickupItems.length - 1 }, i < _vm.data.pickupItems.length - 1 ? 'border-b-0' : 'border-b']) + "><div class=\"flex flex-col lg:flex-row items-center\"><div class=\"mr-2 text-center\"><img" + _vm._ssrAttr("src", item.image) + _vm._ssrAttr("alt", item.name) + " class=\"object-contain bg-no-repeat\" style=\"\\n min-width: 100px;\\n width: 100px;\\n min-height: 100px;\\n height: 100px;\\n \"></div> <div class=\"flex-grow text-center lg:text-left\"><p>" + _vm._ssrEscape(_vm._s(item.name)) + "</p> <small class=\"text-gray-400\">" + _vm._ssrEscape(_vm._s(item.selectedOptions)) + "</small></div> <div class=\"py-2 lg:p-4 text-right\"><p class=\"text-blue-500 font-semibold\">" + _vm._ssrEscape("\n " + _vm._s(item.quantity) + " @ $" + _vm._s(item.price.toFixed(2)) + "\n ") + "</p></div></div> <div class=\"text-center lg:text-left\"><a href=\"javascript:void(0)\" class=\"text-xs text-green-500 cursor-pointer mr-2 hover:text-green-700\">\n Update\n </a> <a href=\"javascript:void(0)\" class=\"text-xs text-red-500 cursor-pointer hover:text-red-700\">\n Remove\n </a></div></div>"; }) + "</div></div>")]); }; var __vue_staticRenderFns__$1 = []; /* style */ var __vue_inject_styles__$1 = undefined; /* scoped */ var __vue_scope_id__$1 = undefined; /* module identifier */ var __vue_module_identifier__$1 = "data-v-3abdaf61"; /* functional template */ var __vue_is_functional_template__$1 = false; /* style inject */ /* style inject SSR */ /* style inject shadow dom */ var __vue_component__$1 = /*#__PURE__*/normalizeComponent({ render: __vue_render__$1, staticRenderFns: __vue_staticRenderFns__$1 }, __vue_inject_styles__$1, __vue_script__$1, __vue_scope_id__$1, __vue_is_functional_template__$1, __vue_module_identifier__$1, false, undefined, undefined, undefined);var script = /*#__PURE__*/Vue__default['default'].extend({ name: 'VueTailwindCheckoutCart', provide: function provide() { var vm = this; return { data: vm.data, emitEvent: vm.emitEvent }; }, components: { CheckoutCartPublisher: __vue_component__$4, CheckoutCartSummary: __vue_component__$3, CheckoutCartDeliveryItems: __vue_component__$2, CheckoutCartPickupItems: __vue_component__$1 }, props: { twBgColor: { type: String, default: 'bg-gray-100' }, data: { type: Object, required: true } }, computed: { deliveryItems: function deliveryItems() { return this.data.deliveryItems || []; }, pickupItems: function pickupItems() { return this.data.pickupItems || []; } }, methods: { emitEvent: function emitEvent(eventName, data) { this.$emit(eventName, data); } } });function createInjectorSSR(context) { if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { context = __VUE_SSR_CONTEXT__; } if (!context) return () => { }; if (!('styles' in context)) { context._styles = context._styles || {}; Object.defineProperty(context, 'styles', { enumerable: true, get: () => context._renderStyles(context._styles) }); context._renderStyles = context._renderStyles || renderStyles; } return (id, style) => addStyle(id, style, context); } function addStyle(id, css, context) { const group = css.media || 'default' ; const style = context._styles[group] || (context._styles[group] = { ids: [], css: '' }); if (!style.ids.includes(id)) { style.media = css.media; style.ids.push(id); let code = css.source; style.css += code + '\n'; } } function renderStyles(styles) { let css = ''; for (const key in styles) { const style = styles[key]; css += '<style data-vue-ssr-id="' + Array.from(style.ids).join(' ') + '"' + (style.media ? ' media="' + style.media + '"' : '') + '>' + style.css + '</style>'; } return css; }/* script */ var __vue_script__ = script; /* template */ var __vue_render__ = function __vue_render__() { var _vm = this; var _h = _vm.$createElement; var _c = _vm._self._c || _h; return _c('div', { staticClass: "vue-tw-checkout-cart p-2", class: _vm.twBgColor }, [_vm.data.publisher ? _c('CheckoutCartPublisher', { staticClass: "mb-4" }) : _vm._e(), _vm._ssrNode(" "), _vm._ssrNode("<div class=\"flex flex-col md:flex-row\" data-v-a96ee62c>", "</div>", [_vm._ssrNode("<div class=\"checkout-cart__orders flex flex-col flex-grow\" data-v-a96ee62c>", "</div>", [_vm.deliveryItems.length || _vm.pickupItems.length ? [_vm.deliveryItems.length ? _c('CheckoutCartDeliveryItems') : _vm._e(), _vm._ssrNode(" "), _vm.pickupItems.length ? _c('CheckoutCartPickupItems') : _vm._e()] : _vm._ssrNode("<div class=\"shadow-md rounded-lg bg-white mb-4 p-4\" data-v-a96ee62c>\n No orders to show.\n </div>")], 2), _vm._ssrNode(" "), _vm._ssrNode("<div class=\"md:ml-4\" data-v-a96ee62c>", "</div>", [_c('CheckoutCartSummary', { staticClass: "p-5 sticky top-4" })], 1)], 2)], 2); }; var __vue_staticRenderFns__ = []; /* style */ var __vue_inject_styles__ = function __vue_inject_styles__(inject) { if (!inject) return; inject("data-v-a96ee62c_0", { source: ".checkout-cart__order-summary[data-v-a96ee62c]{min-width:320px}", map: undefined, media: undefined }); }; /* scoped */ var __vue_scope_id__ = "data-v-a96ee62c"; /* module identifier */ var __vue_module_identifier__ = "data-v-a96ee62c"; /* functional template */ var __vue_is_functional_template__ = false; /* style inject shadow dom */ var __vue_component__ = /*#__PURE__*/normalizeComponent({ render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ }, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, false, undefined, createInjectorSSR, undefined);// Import vue component // Default export is installable instance of component. // IIFE injects install function into component, allowing component // to be registered via Vue.use() as well as Vue.component(), var component = /*#__PURE__*/(function () { // Assign InstallableComponent type var installable = __vue_component__; // Attach install function executed by Vue.use() installable.install = function (Vue) { Vue.component('VueCheckoutCart', installable); }; return installable; })(); // It's possible to expose named exports when writing components that can // also be used as directives, etc. - eg. import { RollupDemoDirective } from 'rollup-demo'; // export const RollupDemoDirective = directive; var namedExports=/*#__PURE__*/Object.freeze({__proto__:null,'default': component});// only expose one global var, with named exports exposed as properties of // that global var (eg. plugin.namedExport) Object.entries(namedExports).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), exportName = _ref2[0], exported = _ref2[1]; if (exportName !== 'default') component[exportName] = exported; });module.exports=component;
JavaScript
CL
868fab039ce6cb75fd2ab35e07fbab04921e7fbef0251ed95b3dceb95c9f1226
let util = require("util"); let Room = require("./Room.js").Room; let ProtoID = require("../../../net/CSProto.js").ProtoID; let CommFuc = require("../../../util/CommonFuc.js"); /////////////////////////////////////////////////////////////////////////////// //>> 斗地主 function SubGame() { this.protoMap = {}; // 协议表 this.roomCnt = 0; this.rooms = {}; this.init(); } SubGame.prototype = { // 初始化 init: function () { this.initProtoMap(); }, // 初始化协议表 initProtoMap: function () { this.onProto(ProtoID.CLIENT_GAME_GRAB, this.onPlayerReqGrab); this.onProto(ProtoID.CLIENT_GAME_CUE, this.onPlayerCue); this.onProto(ProtoID.CLIENT_GAME_DO_PLAY_DDZ, this.onPlayerReqPlay); this.onProto(ProtoID.CLIENT_GAME_DO_PASS_DDZ, this.onPlayerReqPass); this.onProto(ProtoID.CLIENT_GAME_SELECT_CARDS, this.onPlayerSelectCardReq); this.onProto(ProtoID.CLIENT_GAME_TG_DDZ, this.onPlayerHosted); this.onProto(ProtoID.CLIENT_GAME_DOUBLE_DDZ, this.onPlayerDouble); }, onProto: function (opCode, handler) { this.protoMap[opCode] = handler; }, /** * 创建房间 * @param cArgs * @returns {*} */ createRoom: function (cArgs) { let newRoom = new Room(cArgs); if (newRoom.init(cArgs)) { this.roomCnt += 1; this.rooms[cArgs.roomId] = newRoom; return newRoom; } return null; }, // 销毁房间 destroyRoom: function (room) { ERROR("销毁了 房间: " + room.roomId); delete this.rooms[room.roomId]; this.roomCnt -= 1; room = null; }, // 关闭 shutdown: function () { for (let rId in this.rooms) { if (!this.rooms.hasOwnProperty(rId)) { continue; } this.rooms[rId].shutdown(); } }, /** * 请求销毁房间 * @param wsConn * @param rState * @param rArgs */ client_game_destory_room:function(wsConn, rState, rArgs) { let uid = +rArgs.uid; let roomId = +rArgs.roomId; let wantRoom = this.rooms[roomId]; if (!wantRoom) { DEBUG(util.format("Room %d not exists", roomId)); return; } DEBUG(util.format("Player %d request DestroyRoom", uid)); wantRoom.client_game_destory_room(uid); }, /** * 发起解散房间 * @param wsConn * @param rState * @param rArgs */ client_game_launch_restory_room:function (wsConn,rState,rArgs) { let uid = +rArgs.uid; let roomId = +rArgs.roomId; let wantRoom = this.rooms[roomId]; if (!wantRoom) { DEBUG(util.format("Room %d not exists", roomId)); return; } DEBUG(util.format("Player %d request DestroyRoom", uid)); wantRoom.client_game_launch_restory_room(uid); }, /** * 发起投票解散房间 * @param wsConn * @param rState * @param rArgs */ client_game_vote_room:function(wsConn, rState, rArgs) { let uid = +rArgs.uid; let roomId = +rArgs.roomId; let agree = rArgs.ok; let wantRoom = this.rooms[roomId]; if (!wantRoom) { DEBUG(util.format("Room %d not exists", roomId)); return; } DEBUG(util.format("Player %d request SelectDestroyRoom", uid)); wantRoom.onPlayerJSRoom(uid, agree); }, // 查找协议处理程序 findProtoHandler: function (rCode) { return this.protoMap[rCode]; }, //游戏逻辑部分------------------------------------------------------------------------------- //抢地主 onPlayerReqGrab: function (wsConn, rState, rArgs) { let roomId = +rArgs.roomId; let uid = +rArgs.uid; let ok = rArgs.ok; let wantRoom = this.rooms[roomId]; if (!wantRoom) { DEBUG(util.format("Room %d not exists", roomId)); return false; } let playerIndex = wantRoom.getPlayerIndex(uid); wantRoom.startGrab(playerIndex, ok); }, //请求出牌 onPlayerReqPlay: function (wsConn, rState, rArgs) { let roomId = rArgs.roomId; let uid = rArgs.uid; let cards = rArgs.cards; let wantRoom = this.rooms[roomId]; if (!wantRoom) { DEBUG(util.format("Room %d not exists", roomId)); return false; } wantRoom.onPlayerReqPlay(uid, cards); }, //玩家出牌 onPlayerDoPlay: function (wsConn, rState, rArgs) { let roomId = rArgs.roomId; let uid = rArgs.uid; let doShape = {isBomb: rArgs.isBomb, finaType: rArgs.finaType, cards: rArgs.cards, conCard: rArgs.conCard} let wantRoom = this.rooms[roomId]; if (!wantRoom) { DEBUG(util.format("Room %d not exists", roomId)); return false; } wantRoom.onPlayerDoPlay(uid, doShape); }, /** * 玩家过牌 * @param wsConn * @param rState * @param rArgs * @returns {boolean} */ onPlayerReqPass: function (wsConn, rState, rArgs) { let roomId = rArgs.roomId; let uid = rArgs.uid; let wantRoom = this.rooms[roomId]; if (!wantRoom) { DEBUG(util.format("Room %d not exists", roomId)); return false; } wantRoom.onPlayerReqPass(uid); }, /** * 选牌 * @param wsConn * @param rState * @param rArgs */ onPlayerSelectCardReq:function (wsConn, rState, rArgs) { let roomId = rArgs.roomId; let uid = rArgs.uid; let wantRoom = this.rooms[roomId]; let cards = rArgs.cards; if (!wantRoom) { DEBUG(util.format("Room %d not exists", roomId)); return false; } wantRoom.selectCard(uid, cards); }, /** * 请求托管 * @param wsConn * @param rState * @param rArgs */ onPlayerHosted:function (wsConn, rState, rArgs) { let uid = +rArgs.uid; let roomId = +rArgs.roomId; let wantRoom = this.rooms[roomId]; let isT = JSON.parse(rArgs.isT); if(!wantRoom){ DEBUG(util.format("Room %d not exists", roomId)); return; } wantRoom.onPlayerHosted(uid,isT); }, //房主申请解散房间 onPlayerFZDestroyRoom: function (wsConn, rState, rArgs) { let roomId = rArgs.roomId; let uid = rArgs.uid; let wantRoom = this.rooms[roomId]; if (!wantRoom) { DEBUG(util.format("Room %d not exists", roomId)); return false; } wantRoom.client_game_destory_room(uid); }, //非房主申请解散房间 onPlayerWJDestroyRoom: function (wsConn, rState, rArgs) { let roomId = rArgs.roomId; let uid = rArgs.uid; let wantRoom = this.rooms[roomId]; if (!wantRoom) { DEBUG(util.format("Room %d not exists", roomId)); return false; } wantRoom.client_game_launch_restory_room(uid); }, //客户端选择解散房间 onPlayerDestoryYesNo: function (wsConn, rState, rArgs) { let uid = +rArgs.uid; let roomId = +rArgs.roomId; let agree = JSON.parse(rArgs.agree); let wantRoom = this.rooms[roomId]; if (!wantRoom) { DEBUG(util.format("Room %d not exists", roomId)); return; } DEBUG(util.format("Player %d request SelectDestroyRoom", uid)); wantRoom.onPlayerJSRoom(uid, agree); }, // 客户端请求提示 onPlayerCue: function (wsConn, rState, rArgs) { let uid = +rArgs.uid; let roomId = +rArgs.roomId; let wantRoom = this.rooms[roomId]; if (!wantRoom) { DEBUG(util.format("Room %d not exists", roomId)); return; } DEBUG(util.format("Player %d request onPlayerCue", uid)); wantRoom.onPlayerCue(uid); }, /** * 请求加倍 * @param wsConn * @param rState * @param rArgs */ onPlayerDouble:function (wsConn, rState, rArgs) { let uid = +rArgs.uid; let roomId = +rArgs.roomId; let double = +rArgs.double; let wantRoom = this.rooms[roomId]; if (!wantRoom) { DEBUG(util.format("Room %d not exists", roomId)); return; } DEBUG(util.format("Player %d request double", uid)); let index = wantRoom.getPlayerIndex(uid); wantRoom.onPlayerDouble(index, double); }, //聊天 onPlayerReqSay: function (wsConn, rState, rArgs) { let uid = +rArgs.uid; let roomId = +rArgs.roomId; let wantRoom = this.rooms[roomId]; if (!wantRoom) { DEBUG(util.format("Room %d not exists", roomId)); return; } wantRoom.onPlayerReqSay(uid, rArgs); }, /** * 白盒测试用 * @param room */ startRoom(room){ let count = Object.keys(this.rooms).length; ERROR("正在进行的总局数" + count); }, /** * 白盒测试用 * @param room */ endRoom(room){ let count = Object.keys(this.rooms).length; ERROR("剩余总局数" + count); }, } exports = module.exports = new SubGame();
JavaScript
CL
74c88a9786452cd9ad4df5a3fd4e9e9c144898714fb48a15a3ac97a742238b3b
/** * jKif - 2015 * conjunctionnode.js * @file AST ConjunctionNode constructor for representing conjunctions * @author Clark Feusier - cfeusier@gmail.com * @copyright Copyright (C) Clark Feusier - All Rights Reserved */ var BaseNode = require('./ast_constructor_base'); /** * * @param {Object} locationData * @param {Array} conjuncts * @constructor */ function ConjunctionNode(locationData, conjuncts) { BaseNode.call(this, 'ConjunctionNode', locationData); this.conjuncts = this.conjuncts || []; this.conjuncts = this.conjuncts.concat(conjuncts); } /** * * @type {ConjunctionNode} */ module.exports = ConjunctionNode;
JavaScript
CL
5c4c1f03073ef272930fb9462830266b750b9d20df53d7526f97bf708eaa2c12
import { graphqlKoa, graphiqlKoa } from 'graphql-server-koa'; import schema from '../../data/schema'; import { authJwt, vertifyToken } from '../../auth'; export default (router) => { router.post('/graphql', authJwt(), vertifyToken, graphqlKoa(ctx => ({ schema, context: { user: ctx.req.user, headers: ctx.req.headers } }))); router.get('/graphql', graphqlKoa({ schema: schema })); // Tool for test your queries: localhost:3000/graphiql router.get('/graphiql', graphiqlKoa({ endpointURL: '/graphql' })); };
JavaScript
CL
55c3a7d0559f5ef29cf6efdbf3b2dbc99c17367cfe62415705833b71a5337372
let createError = require('http-errors'), express = require('express'), child_process = require('child_process'), path = require('path'), cookieParser = require('cookie-parser'), logger = require('morgan'), debug = require('debug')('server-media-server:server'), http = require('http'), indexRouter = require('./routes/index'), usersRouter = require('./routes/users'), port = normalizePort(process.env.PORT || '4000'), app = express(), cors = require('cors'), server = http.createServer(app), WebSocketServer = require('ws').Server, pathToFfmpeg = require('ffmpeg-static'), wss = new WebSocketServer({ server: server }), shell = require('any-shell-escape'), NodeMediaServer = require('node-media-server'); app.set('port', port); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(cors()); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'browser'))); app.use('/', indexRouter); app.use('/media-server', express.static(path.join(__dirname, 'browser'))); app.use('/users', usersRouter); app.use(function( req, res, next) { next(createError(404)); }); app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); startMediaServer(); wss.on('connection', (ws, req) => { //Запуск команд командной оболочкой сервера /* const makeMp3 = shell([ 'ffmpeg', '-y', '-v', 'error', '-i', path.join(process.cwd(), src), '-acodec', 'mp3', '-format', 'mp3', path.join(process.cwd(), 'media-shell') ]) child_process.exec(makeMp3, (err) => { if (err) { console.error(err) process.exit(1) } else { console.info('done!') } }) */ // Ensure that the URL starts with '/rtmp/', and extract the target RTMP URL. /* let match; if ( !(match = req.url.match(/^\/rtmp\/(.*)$/)) ) { ws.terminate(); // No match, reject the connection. return; } const rtmpUrl = decodeURIComponent(match[1]); console.log('Target RTMP URL:', rtmpUrl);*/ // Launch FFmpeg to handle all appropriate transcoding, muxing, and RTMP. // If 'ffmpeg' isn't in your path, specify the full path to the ffmpeg binary. const ffmpeg = child_process.spawn( pathToFfmpeg, [ // Facebook requires an audio track, so we create a silent one here. // Remove this line, as well as `-shortest`, if you send audio from the browser. '-f', 'lavfi', '-i', 'anullsrc', // FFmpeg will read input video from STDIN '-i', '-', // If we're encoding H.264 in-browser, we can set the video codec to 'copy' // so that we don't waste any CPU and quality with unnecessary transcoding. // If the browser doesn't support H.264, set the video codec to 'libx264' // or similar to transcode it to H.264 here on the server. '-vcodec', 'copy', // AAC audio is required for Facebook Live. No browser currently supports // encoding AAC, so we must transcode the audio to AAC here on the server. '-acodec', 'aac', // FLV is the container format used in conjunction with RTMP '-f', 'flv', // The output RTMP URL. // For debugging, you could set this to a filename like 'test.flv', and play // the resulting file with VLC. Please also read the security considerations // later on in this tutorial. 'rtmp://127.0.0.1:1935/life' ]); // If FFmpeg stops for any reason, close the WebSocket connection. ffmpeg.on('close', (code, signal) => { console.log('FFmpeg child process closed, code ' + code + ', signal ' + signal); ws.terminate(); }); // Handle STDIN pipe errors by logging to the console. // These errors most commonly occur when FFmpeg closes and there is still // data to write. If left unhandled, the server will crash. ffmpeg.stdin.on('error', (e) => { console.log('FFmpeg STDIN Error', e); }); // FFmpeg outputs all of its messages to STDERR. Let's log them to the console. ffmpeg.stderr.on('data', (data) => { console.log('FFmpeg Data Transfer:', data.toString()); }); // When data comes in from the WebSocket, write it to FFmpeg's STDIN. ws.on('message', (msg) => { console.log('Ws DATA', msg); ffmpeg.stdin.write(msg); }); // If the client disconnects, stop FFmpeg. ws.on('close', (e) => { ffmpeg.kill('SIGINT'); }); }); server.listen(port); server.on('error', onError); server.on('listening', onListening); //Запуск медиа сервиса function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } function onError(error) { if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } } /** * Event listener for HTTP server "listening" event. */ function onListening() { var addr = server.address(); var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; debug('http application server istening on ' + bind); } function startMediaServer(){ const config = { rtmp: { port: 1935, chunk_size: 60000, gop_cache: true, ping: 30, ping_timeout: 60 }, http: { port: 7000, allow_origin: '*' }, relay: { ffmpeg: pathToFfmpeg, tasks: [ { app: 'live', mode: 'static', edge: 'rtmp://127.0.0.1/hls',//rtsp name: 'technology', rtsp_transport : 'tcp', //['udp', 'tcp', 'udp_multicast', 'http'] } ] }, trans: { // Here, the parameter is a trans parameter, not a relay parameter. The hls configuration in the relay parameter is invalid ffmpeg: pathToFfmpeg, tasks: [ { app: 'live', ac: 'acc', vc: 'libx264', hls: true, hlsFlags: '[hls_time=2:hls_list_size=3:hls_flags=delete_segments]', dash: true, dashFlags: '[f=dash:window_size=3:extra_window_size=5]' } ] } }; let nms = new NodeMediaServer(config) nms.run(); //подписки на события nms.on('preConnect', (id, args) => { console.log('[NodeEvent on preConnect]', `id=${id} args=${JSON.stringify(args)}`); let session = nms.getSession(id); //session.reject(); }); nms.on('postConnect', (id, args) => { console.log('[NodeEvent on postConnect]', `id=${id} args=${JSON.stringify(args)}`); }); nms.on('doneConnect', (id, args) => { console.log('[NodeEvent on doneConnect]', `id=${id} args=${JSON.stringify(args)}`); }); nms.on('prePublish', (id, StreamPath, args) => { console.log('[NodeEvent on prePublish]', `id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`); // let session = nms.getSession(id); // session.reject(); }); nms.on('postPublish', (id, StreamPath, args) => { console.log('[NodeEvent on postPublish]', `id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`); }); nms.on('donePublish', (id, StreamPath, args) => { console.log('[NodeEvent on donePublish]', `id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`); }); nms.on('prePlay', (id, StreamPath, args) => { console.log('[NodeEvent on prePlay]', `id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`); // let session = nms.getSession(id); // session.reject(); }); nms.on('postPlay', (id, StreamPath, args) => { console.log('[NodeEvent on postPlay]', `id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`); }); nms.on('donePlay', (id, StreamPath, args) => { console.log('[NodeEvent on donePlay]', `id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`); }); }
JavaScript
CL
a7447325f2b5bc2f6a85c96f10fdaa070af8268e953cb4eeb2b0786ff6ce2905
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["main"],{ /***/ "./$$_lazy_route_resource lazy recursive": /*!******************************************************!*\ !*** ./$$_lazy_route_resource lazy namespace object ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function webpackEmptyAsyncContext(req) { // Here Promise.resolve().then() is used instead of new Promise() to prevent // uncaught exception popping up in devtools return Promise.resolve().then(function() { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; }); } webpackEmptyAsyncContext.keys = function() { return []; }; webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; module.exports = webpackEmptyAsyncContext; webpackEmptyAsyncContext.id = "./$$_lazy_route_resource lazy recursive"; /***/ }), /***/ "./src/app/app-routing.module.ts": /*!***************************************!*\ !*** ./src/app/app-routing.module.ts ***! \***************************************/ /*! exports provided: AppRoutingModule */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppRoutingModule", function() { return AppRoutingModule; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js"); /* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/router */ "./node_modules/@angular/router/__ivy_ngcc__/fesm2015/router.js"); /* harmony import */ var _fruit_fruit_component__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fruit/fruit.component */ "./src/app/fruit/fruit.component.ts"); /* harmony import */ var _home_home_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./home/home.component */ "./src/app/home/home.component.ts"); const routes = [ { path: ':dir', component: _fruit_fruit_component__WEBPACK_IMPORTED_MODULE_2__["FruitComponent"] }, { path: '', component: _home_home_component__WEBPACK_IMPORTED_MODULE_3__["HomeComponent"] }, { path: '**', component: _home_home_component__WEBPACK_IMPORTED_MODULE_3__["HomeComponent"] } ]; class AppRoutingModule { } AppRoutingModule.ɵmod = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineNgModule"]({ type: AppRoutingModule }); AppRoutingModule.ɵinj = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjector"]({ factory: function AppRoutingModule_Factory(t) { return new (t || AppRoutingModule)(); }, imports: [[_angular_router__WEBPACK_IMPORTED_MODULE_1__["RouterModule"].forRoot(routes)], _angular_router__WEBPACK_IMPORTED_MODULE_1__["RouterModule"]] }); (function () { (typeof ngJitMode === "undefined" || ngJitMode) && _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵsetNgModuleScope"](AppRoutingModule, { imports: [_angular_router__WEBPACK_IMPORTED_MODULE_1__["RouterModule"]], exports: [_angular_router__WEBPACK_IMPORTED_MODULE_1__["RouterModule"]] }); })(); /*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](AppRoutingModule, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["NgModule"], args: [{ imports: [_angular_router__WEBPACK_IMPORTED_MODULE_1__["RouterModule"].forRoot(routes)], exports: [_angular_router__WEBPACK_IMPORTED_MODULE_1__["RouterModule"]] }] }], null, null); })(); /***/ }), /***/ "./src/app/app.component.ts": /*!**********************************!*\ !*** ./src/app/app.component.ts ***! \**********************************/ /*! exports provided: AppComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppComponent", function() { return AppComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js"); /* harmony import */ var _nav_nav_component__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./nav/nav.component */ "./src/app/nav/nav.component.ts"); /* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/router */ "./node_modules/@angular/router/__ivy_ngcc__/fesm2015/router.js"); class AppComponent { constructor() { this.title = 'zeenbee'; } } AppComponent.ɵfac = function AppComponent_Factory(t) { return new (t || AppComponent)(); }; AppComponent.ɵcmp = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineComponent"]({ type: AppComponent, selectors: [["app-root"]], decls: 3, vars: 0, consts: [[1, "container-fluid"]], template: function AppComponent_Template(rf, ctx) { if (rf & 1) { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](0, "app-nav"); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](1, "div", 0); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](2, "router-outlet"); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); } }, directives: [_nav_nav_component__WEBPACK_IMPORTED_MODULE_1__["NavComponent"], _angular_router__WEBPACK_IMPORTED_MODULE_2__["RouterOutlet"]], styles: ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL2FwcC5jb21wb25lbnQuc2NzcyJ9 */"] }); /*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](AppComponent, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Component"], args: [{ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }] }], null, null); })(); /***/ }), /***/ "./src/app/app.module.ts": /*!*******************************!*\ !*** ./src/app/app.module.ts ***! \*******************************/ /*! exports provided: AppModule */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppModule", function() { return AppModule; }); /* harmony import */ var _angular_platform_browser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/platform-browser */ "./node_modules/@angular/platform-browser/__ivy_ngcc__/fesm2015/platform-browser.js"); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js"); /* harmony import */ var _app_routing_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./app-routing.module */ "./src/app/app-routing.module.ts"); /* harmony import */ var _app_component__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./app.component */ "./src/app/app.component.ts"); /* harmony import */ var _ng_bootstrap_ng_bootstrap__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @ng-bootstrap/ng-bootstrap */ "./node_modules/@ng-bootstrap/ng-bootstrap/__ivy_ngcc__/fesm2015/ng-bootstrap.js"); /* harmony import */ var _nav_nav_component__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./nav/nav.component */ "./src/app/nav/nav.component.ts"); /* harmony import */ var _angular_common_http__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @angular/common/http */ "./node_modules/@angular/common/__ivy_ngcc__/fesm2015/http.js"); /* harmony import */ var _what_pipe__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./what.pipe */ "./src/app/what.pipe.ts"); /* harmony import */ var _home_home_component__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./home/home.component */ "./src/app/home/home.component.ts"); /* harmony import */ var _fruit_fruit_component__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./fruit/fruit.component */ "./src/app/fruit/fruit.component.ts"); class AppModule { } AppModule.ɵmod = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineNgModule"]({ type: AppModule, bootstrap: [_app_component__WEBPACK_IMPORTED_MODULE_3__["AppComponent"]] }); AppModule.ɵinj = _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵdefineInjector"]({ factory: function AppModule_Factory(t) { return new (t || AppModule)(); }, providers: [], imports: [[ _angular_platform_browser__WEBPACK_IMPORTED_MODULE_0__["BrowserModule"], _app_routing_module__WEBPACK_IMPORTED_MODULE_2__["AppRoutingModule"], _ng_bootstrap_ng_bootstrap__WEBPACK_IMPORTED_MODULE_4__["NgbModule"], _angular_common_http__WEBPACK_IMPORTED_MODULE_6__["HttpClientModule"] ]] }); (function () { (typeof ngJitMode === "undefined" || ngJitMode) && _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵɵsetNgModuleScope"](AppModule, { declarations: [_app_component__WEBPACK_IMPORTED_MODULE_3__["AppComponent"], _nav_nav_component__WEBPACK_IMPORTED_MODULE_5__["NavComponent"], _what_pipe__WEBPACK_IMPORTED_MODULE_7__["WhatPipe"], _home_home_component__WEBPACK_IMPORTED_MODULE_8__["HomeComponent"], _fruit_fruit_component__WEBPACK_IMPORTED_MODULE_9__["FruitComponent"]], imports: [_angular_platform_browser__WEBPACK_IMPORTED_MODULE_0__["BrowserModule"], _app_routing_module__WEBPACK_IMPORTED_MODULE_2__["AppRoutingModule"], _ng_bootstrap_ng_bootstrap__WEBPACK_IMPORTED_MODULE_4__["NgbModule"], _angular_common_http__WEBPACK_IMPORTED_MODULE_6__["HttpClientModule"]] }); })(); /*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_1__["ɵsetClassMetadata"](AppModule, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_1__["NgModule"], args: [{ declarations: [ _app_component__WEBPACK_IMPORTED_MODULE_3__["AppComponent"], _nav_nav_component__WEBPACK_IMPORTED_MODULE_5__["NavComponent"], _what_pipe__WEBPACK_IMPORTED_MODULE_7__["WhatPipe"], _home_home_component__WEBPACK_IMPORTED_MODULE_8__["HomeComponent"], _fruit_fruit_component__WEBPACK_IMPORTED_MODULE_9__["FruitComponent"] ], imports: [ _angular_platform_browser__WEBPACK_IMPORTED_MODULE_0__["BrowserModule"], _app_routing_module__WEBPACK_IMPORTED_MODULE_2__["AppRoutingModule"], _ng_bootstrap_ng_bootstrap__WEBPACK_IMPORTED_MODULE_4__["NgbModule"], _angular_common_http__WEBPACK_IMPORTED_MODULE_6__["HttpClientModule"] ], providers: [], bootstrap: [_app_component__WEBPACK_IMPORTED_MODULE_3__["AppComponent"]] }] }], null, null); })(); /***/ }), /***/ "./src/app/fruit/fruit.component.ts": /*!******************************************!*\ !*** ./src/app/fruit/fruit.component.ts ***! \******************************************/ /*! exports provided: FruitComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FruitComponent", function() { return FruitComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js"); /* harmony import */ var _what_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../what.service */ "./src/app/what.service.ts"); /* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/router */ "./node_modules/@angular/router/__ivy_ngcc__/fesm2015/router.js"); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/__ivy_ngcc__/fesm2015/common.js"); /* harmony import */ var _ng_bootstrap_ng_bootstrap__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @ng-bootstrap/ng-bootstrap */ "./node_modules/@ng-bootstrap/ng-bootstrap/__ivy_ngcc__/fesm2015/ng-bootstrap.js"); /* harmony import */ var _what_pipe__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../what.pipe */ "./src/app/what.pipe.ts"); function FruitComponent_ngb_alert_0_Template(rf, ctx) { if (rf & 1) { const _r3 = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵgetCurrentView"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](0, "ngb-alert", 2); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵlistener"]("close", function FruitComponent_ngb_alert_0_Template_ngb_alert_close_0_listener() { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵrestoreView"](_r3); const ctx_r2 = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵnextContext"](); return ctx_r2.staticAlertClosed = true; }); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](1); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); } if (rf & 2) { const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵnextContext"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](1); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtextInterpolate"](ctx_r0.instructs); } } function FruitComponent_div_1_div_2_Template(rf, ctx) { if (rf & 1) { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](0, "div"); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](1, "img", 6); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵpipe"](2, "what"); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); } if (rf & 2) { const what_r5 = ctx.$implicit; const ctx_r4 = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵnextContext"](2); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](1); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵproperty"]("src", _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵpipeBind2"](2, 1, what_r5, ctx_r4.whatUrl), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵsanitizeUrl"]); } } function FruitComponent_div_1_Template(rf, ctx) { if (rf & 1) { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](0, "div", 3); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](1, "div", 4); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtemplate"](2, FruitComponent_div_1_div_2_Template, 3, 4, "div", 5); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); } if (rf & 2) { const ctx_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵnextContext"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](2); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵproperty"]("ngForOf", ctx_r1.whatList); } } class FruitComponent { constructor(route, whatService) { this.route = route; this.whatService = whatService; this.instructs = 'Scroll downnnnnnnnn!'; //self-closing alert this.staticAlertClosed = false; } ngOnInit() { this.route.params.forEach((params) => { this.directory = params['dir']; this.whatList = []; this.getWhat(); }); //self-closing alert setTimeout(() => this.staticAlertClosed = true, 10000); } getWhat() { this.whatService.getWhat(this.directory).subscribe(resp => { this.whatList = resp.body; this.whatUrl = resp.url; }); } } FruitComponent.ɵfac = function FruitComponent_Factory(t) { return new (t || FruitComponent)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_angular_router__WEBPACK_IMPORTED_MODULE_2__["ActivatedRoute"]), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_what_service__WEBPACK_IMPORTED_MODULE_1__["WhatService"])); }; FruitComponent.ɵcmp = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineComponent"]({ type: FruitComponent, selectors: [["app-fruit"]], features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([_what_service__WEBPACK_IMPORTED_MODULE_1__["WhatService"]])], decls: 2, vars: 2, consts: [[3, "close", 4, "ngIf"], ["class", "row", 4, "ngIf"], [3, "close"], [1, "row"], [1, "col-12", "text-center", "pl-0", "pr-0"], [4, "ngFor", "ngForOf"], [1, "img-fluid", "rounded", 3, "src"]], template: function FruitComponent_Template(rf, ctx) { if (rf & 1) { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtemplate"](0, FruitComponent_ngb_alert_0_Template, 2, 1, "ngb-alert", 0); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtemplate"](1, FruitComponent_div_1_Template, 3, 1, "div", 1); } if (rf & 2) { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵproperty"]("ngIf", !ctx.staticAlertClosed); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](1); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵproperty"]("ngIf", ctx.whatList); } }, directives: [_angular_common__WEBPACK_IMPORTED_MODULE_3__["NgIf"], _ng_bootstrap_ng_bootstrap__WEBPACK_IMPORTED_MODULE_4__["NgbAlert"], _angular_common__WEBPACK_IMPORTED_MODULE_3__["NgForOf"]], pipes: [_what_pipe__WEBPACK_IMPORTED_MODULE_5__["WhatPipe"]], styles: ["img[_ngcontent-%COMP%] {\n -o-object-fit: contain;\n object-fit: contain;\n max-height: 100vh;\n}\n\ncdk-virtual-scroll-viewport[_ngcontent-%COMP%] {\n height: 100vh;\n width: 100vw;\n}\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi9ob21lL2JpbmdvL0RldmVsb3BtZW50L3plZW5iZWUvc3JjL2FwcC9mcnVpdC9mcnVpdC5jb21wb25lbnQuc2NzcyIsInNyYy9hcHAvZnJ1aXQvZnJ1aXQuY29tcG9uZW50LnNjc3MiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7RUFDSSxzQkFBQTtLQUFBLG1CQUFBO0VBQ0EsaUJBQUE7QUNDSjs7QURDQTtFQUNDLGFBQUE7RUFDQSxZQUFBO0FDRUQiLCJmaWxlIjoic3JjL2FwcC9mcnVpdC9mcnVpdC5jb21wb25lbnQuc2NzcyIsInNvdXJjZXNDb250ZW50IjpbImltZyB7XG4gICAgb2JqZWN0LWZpdDogY29udGFpbjtcbiAgICBtYXgtaGVpZ2h0OjEwMHZoO1xufVxuY2RrLXZpcnR1YWwtc2Nyb2xsLXZpZXdwb3J0IHtcblx0aGVpZ2h0OjEwMHZoO1xuXHR3aWR0aDoxMDB2dztcbn1cblxuIiwiaW1nIHtcbiAgb2JqZWN0LWZpdDogY29udGFpbjtcbiAgbWF4LWhlaWdodDogMTAwdmg7XG59XG5cbmNkay12aXJ0dWFsLXNjcm9sbC12aWV3cG9ydCB7XG4gIGhlaWdodDogMTAwdmg7XG4gIHdpZHRoOiAxMDB2dztcbn0iXX0= */"] }); /*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](FruitComponent, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Component"], args: [{ selector: 'app-fruit', templateUrl: './fruit.component.html', styleUrls: ['./fruit.component.scss'], providers: [_what_service__WEBPACK_IMPORTED_MODULE_1__["WhatService"]] }] }], function () { return [{ type: _angular_router__WEBPACK_IMPORTED_MODULE_2__["ActivatedRoute"] }, { type: _what_service__WEBPACK_IMPORTED_MODULE_1__["WhatService"] }]; }, null); })(); /***/ }), /***/ "./src/app/home/home.component.ts": /*!****************************************!*\ !*** ./src/app/home/home.component.ts ***! \****************************************/ /*! exports provided: HomeComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HomeComponent", function() { return HomeComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js"); /* harmony import */ var _what_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../what.service */ "./src/app/what.service.ts"); /* harmony import */ var _ng_bootstrap_ng_bootstrap__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @ng-bootstrap/ng-bootstrap */ "./node_modules/@ng-bootstrap/ng-bootstrap/__ivy_ngcc__/fesm2015/ng-bootstrap.js"); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/__ivy_ngcc__/fesm2015/common.js"); /* harmony import */ var _what_pipe__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../what.pipe */ "./src/app/what.pipe.ts"); function HomeComponent_div_1_div_1_Template(rf, ctx) { if (rf & 1) { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](0, "div", 14); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](1, "video", 15); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵpipe"](2, "what"); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](3, " loading video! boop... beep. "); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); } if (rf & 2) { const what_r1 = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵnextContext"]().$implicit; const ctx_r2 = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵnextContext"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](1); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵproperty"]("src", _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵpipeBind2"](2, 1, what_r1, ctx_r2.whatUrl), _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵsanitizeUrl"]); } } function HomeComponent_div_1_Template(rf, ctx) { if (rf & 1) { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](0, "div", 2); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtemplate"](1, HomeComponent_div_1_div_1_Template, 4, 4, "div", 13); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵpipe"](2, "what"); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); } if (rf & 2) { const what_r1 = ctx.$implicit; const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵnextContext"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](1); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵproperty"]("ngIf", _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵpipeBind2"](2, 1, what_r1, ctx_r0.whatUrl)); } } class HomeComponent { constructor(whatService) { this.whatService = whatService; this.blurb = `Hey friends and fam! Sienna & I ran off and got married in Joshua Tree on October 15th 2016. We wanted to celebrate our love and figured that marriage was just the thing. Friends rallied down to the desert (in style) and helped make this event into a masterpiece. We built our own furniture, collected decorations from flea markets, bought a case of champagne and headed into Joshua Tree National Park for a photoshoot. We parked the Volkswagen on an old lake bed and unfolded a brilliant dining table. Solar panels lit the scene where we feasted and spoke aloud under the full moon. Our dear ordained Josh led the ceremonies as we stood in between the van and the table-of-plenty. This was a safe space that set the stage for true bonding. All of you brought us to this very place in our lives, we thank you directly. This website is our product to share. It is the finest culmination of our combined skills, fueled with love. We hope that this can transport you to that far away place where something special once began.`; this.tooltip = 'Peeks are out here!'; this.blurb2 = `We returned home to plan a big family wedding. On October 15th 2017, we had the ceremony at the Brazilian Room in Berkeley. We built a photo booth, decorated the tables with protea, and gathered all who have been part of our relationship. Twas a treat to have you all. Please, enjoy the photos. Hope you find a good one or two of yourself :)`; this.claim = 'site made from scratch by Austin Zee, photos curated & edited by Sienna Bee'; this.spotify = '~playlist~'; } ngOnInit() { this.whatList = []; this.getWhat(); } getWhat() { this.whatService.getWhat().subscribe(resp => { this.whatList = resp.body; this.whatUrl = resp.url; }, error => { this.handleError(error); }); } handleError(error) { if (error.error instanceof ErrorEvent) { console.error("error occurred"); } else { console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`); } } bottomImgClicked() { window.scrollTo(0, 0); } } HomeComponent.ɵfac = function HomeComponent_Factory(t) { return new (t || HomeComponent)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_what_service__WEBPACK_IMPORTED_MODULE_1__["WhatService"])); }; HomeComponent.ɵcmp = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineComponent"]({ type: HomeComponent, selectors: [["app-home"]], features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([_what_service__WEBPACK_IMPORTED_MODULE_1__["WhatService"]])], decls: 18, vars: 7, consts: [["id", "homeComponent", "triggers", "click:blur", 1, "row", 3, "ngbTooltip"], ["class", "col-12", 4, "ngFor", "ngForOf"], [1, "col-12"], ["src", "../../assets/invite.jpg", 1, "img-fluid", "mx-auto", "rounded"], [1, "mt-1", "lead"], [1, "col-12", "media", "mb-3"], ["href", "https://open.spotify.com/user/adamzuffi/playlist/3uNOYdks1hAp7GjjB0gCDq", "target", "_blank", "placement", "top", 1, "d-flex", 3, "ngbTooltip"], ["src", "../../assets/spotify.jpg", "srcset", "../../assets/spotify-2x.jpg 2x", 1, "d-flex", "align-self-center", "mr-3", 3, "alt"], [1, "media-body"], [1, "lead"], [1, "col-md-6"], ["src", "../../assets/invite-front.jpg", 1, "img-fluid", "rounded", 3, "click"], ["src", "../../assets/invite-back.jpg", 1, "img-fluid", "rounded", 3, "click"], ["class", "col-12 embed-responsive embed-responsive-16by9", 4, "ngIf"], [1, "col-12", "embed-responsive", "embed-responsive-16by9"], ["width", "872", "controls", "", "type", "video/mp4", 1, "d-block", "mx-auto", "embed-responsive-item", 3, "src"]], template: function HomeComponent_Template(rf, ctx) { if (rf & 1) { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](0, "div", 0); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtemplate"](1, HomeComponent_div_1_Template, 3, 4, "div", 1); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](2, "div", 2); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](3, "img", 3); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](4, "p", 4); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](5); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](6, "p", 4); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](7); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](8, "div", 5); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](9, "a", 6); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](10, "img", 7); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](11, "div", 8); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](12, "p", 9); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](13); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](14, "div", 10); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](15, "img", 11); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵlistener"]("click", function HomeComponent_Template_img_click_15_listener() { return ctx.bottomImgClicked(); }); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](16, "div", 10); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](17, "img", 12); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵlistener"]("click", function HomeComponent_Template_img_click_17_listener() { return ctx.bottomImgClicked(); }); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); } if (rf & 2) { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵpropertyInterpolate"]("ngbTooltip", ctx.tooltip); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](1); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵproperty"]("ngForOf", ctx.whatList); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](4); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtextInterpolate"](ctx.blurb); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](2); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtextInterpolate"](ctx.blurb2); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](2); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵpropertyInterpolate"]("ngbTooltip", ctx.spotify); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](1); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵpropertyInterpolate"]("alt", ctx.spotify); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](3); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtextInterpolate"](ctx.claim); } }, directives: [_ng_bootstrap_ng_bootstrap__WEBPACK_IMPORTED_MODULE_2__["NgbTooltip"], _angular_common__WEBPACK_IMPORTED_MODULE_3__["NgForOf"], _angular_common__WEBPACK_IMPORTED_MODULE_3__["NgIf"]], pipes: [_what_pipe__WEBPACK_IMPORTED_MODULE_4__["WhatPipe"]], styles: ["#homeComponent[_ngcontent-%COMP%] {\n margin-left: auto;\n margin-right: auto;\n}\n@media (min-width: 768px) {\n #homeComponent[_ngcontent-%COMP%] {\n max-width: 872px;\n }\n}\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi9ob21lL2JpbmdvL0RldmVsb3BtZW50L3plZW5iZWUvc3JjL2FwcC9ob21lL2hvbWUuY29tcG9uZW50LnNjc3MiLCJzcmMvYXBwL2hvbWUvaG9tZS5jb21wb25lbnQuc2NzcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtFQUFBO0FBRUE7RUFDQyxpQkFBQTtFQUNBLGtCQUFBO0FDQ0Q7QURDQTtFQUNDO0lBQ0MsZ0JBQUE7RUNFQTtBQUNGIiwiZmlsZSI6InNyYy9hcHAvaG9tZS9ob21lLmNvbXBvbmVudC5zY3NzIiwic291cmNlc0NvbnRlbnQiOlsiLyogTWVkaXVtIGRldmljZXMgKHRhYmxldHMsIDc2OHB4IGFuZCB1cClcbiAqL1xuI2hvbWVDb21wb25lbnQge1xuXHRtYXJnaW4tbGVmdDogYXV0bztcblx0bWFyZ2luLXJpZ2h0OiBhdXRvO1xufVxuQG1lZGlhIChtaW4td2lkdGg6IDc2OHB4KSB7XG5cdCNob21lQ29tcG9uZW50IHtcblx0XHRtYXgtd2lkdGg6IDg3MnB4O1xuXHR9XG59XG5cbiIsIi8qIE1lZGl1bSBkZXZpY2VzICh0YWJsZXRzLCA3NjhweCBhbmQgdXApXG4gKi9cbiNob21lQ29tcG9uZW50IHtcbiAgbWFyZ2luLWxlZnQ6IGF1dG87XG4gIG1hcmdpbi1yaWdodDogYXV0bztcbn1cblxuQG1lZGlhIChtaW4td2lkdGg6IDc2OHB4KSB7XG4gICNob21lQ29tcG9uZW50IHtcbiAgICBtYXgtd2lkdGg6IDg3MnB4O1xuICB9XG59Il19 */"] }); /*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](HomeComponent, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Component"], args: [{ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'], providers: [_what_service__WEBPACK_IMPORTED_MODULE_1__["WhatService"]] }] }], function () { return [{ type: _what_service__WEBPACK_IMPORTED_MODULE_1__["WhatService"] }]; }, null); })(); /***/ }), /***/ "./src/app/nav/nav.component.ts": /*!**************************************!*\ !*** ./src/app/nav/nav.component.ts ***! \**************************************/ /*! exports provided: NavComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NavComponent", function() { return NavComponent; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js"); /* harmony import */ var _what_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../what.service */ "./src/app/what.service.ts"); /* harmony import */ var _ng_bootstrap_ng_bootstrap__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @ng-bootstrap/ng-bootstrap */ "./node_modules/@ng-bootstrap/ng-bootstrap/__ivy_ngcc__/fesm2015/ng-bootstrap.js"); /* harmony import */ var _angular_router__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/router */ "./node_modules/@angular/router/__ivy_ngcc__/fesm2015/router.js"); /* harmony import */ var _angular_common__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @angular/common */ "./node_modules/@angular/common/__ivy_ngcc__/fesm2015/common.js"); /* harmony import */ var _what_pipe__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../what.pipe */ "./src/app/what.pipe.ts"); function NavComponent_ul_6_li_1_Template(rf, ctx) { if (rf & 1) { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](0, "li", 9); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](1, "a", 10); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵpipe"](2, "what"); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtext"](3); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵpipe"](4, "what"); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); } if (rf & 2) { const key_r2 = ctx.$implicit; _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](1); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵpropertyInterpolate1"]("routerLink", "/", _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵpipeBind1"](2, 2, key_r2), ""); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](2); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtextInterpolate"](_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵpipeBind1"](4, 4, key_r2)); } } function NavComponent_ul_6_Template(rf, ctx) { if (rf & 1) { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](0, "ul", 7); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtemplate"](1, NavComponent_ul_6_li_1_Template, 5, 6, "li", 8); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); } if (rf & 2) { const ctx_r0 = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵnextContext"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](1); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵproperty"]("ngForOf", ctx_r0.whatKeys); } } class NavComponent { constructor(whatService) { this.whatService = whatService; this.isCollapsed = true; } ngOnInit() { this.getWhat(); } /* Uses action methods */ getWhat(dir) { this.whatService.getWhat(dir).subscribe(resp => { this.unsortedKeys = resp.body; this.unfilteredKeys = this.unsortedKeys.sort((left, right) => { let l = new Date(left.mtime); let r = new Date(right.mtime); if (l < r) return -1; if (l > r) return 1; return 0; }); this.whatKeys = this.unfilteredKeys.filter((key) => key.type === 'directory'); }, error => { this.errorMessage = 'not connected to my photo site, is your browser blocking?'; this.handleError(error); }); } handleError(error) { if (error.error instanceof ErrorEvent) { console.error("error occurred"); } else { console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`); } } } NavComponent.ɵfac = function NavComponent_Factory(t) { return new (t || NavComponent)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdirectiveInject"](_what_service__WEBPACK_IMPORTED_MODULE_1__["WhatService"])); }; NavComponent.ɵcmp = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineComponent"]({ type: NavComponent, selectors: [["app-nav"]], features: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵProvidersFeature"]([_what_service__WEBPACK_IMPORTED_MODULE_1__["WhatService"]])], decls: 7, vars: 3, consts: [[1, "navbar", "sticky-top", "navbar-expand-lg", "navbar-light", "bg-light"], ["routerLink", "/", 1, "navbar-brand", "d-md-block"], ["src", "../../assets/icon.png", "srcset", "../../assets/icon-2x.png 2x", "alt", "", 1, "d-inline-block", "align-top"], ["type", "button", "data-toggle", "collapse", "data-target", "#navbarSupportedContent", "aria-controls", "navbarSupportedContent", "aria-expanded", "false", "aria-label", "Toggle navigation", 1, "navbar-toggler", 3, "click"], [1, "navbar-toggler-icon"], ["id", "navbarSupportedContent", 1, "collapse", "navbar-collapse", 3, "ngbCollapse", "click"], ["class", "navbar-nav mr-auto", 4, "ngIf"], [1, "navbar-nav", "mr-auto"], ["class", "nav-item ", 4, "ngFor", "ngForOf"], [1, "nav-item"], ["routerLinkActive", "active", 1, "nav-link", 3, "routerLink"]], template: function NavComponent_Template(rf, ctx) { if (rf & 1) { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](0, "nav", 0); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](1, "a", 1); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](2, "img", 2); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](3, "button", 3); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵlistener"]("click", function NavComponent_Template_button_click_3_listener() { return ctx.isCollapsed = !ctx.isCollapsed; }); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelement"](4, "span", 4); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementStart"](5, "div", 5); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵlistener"]("click", function NavComponent_Template_div_click_5_listener() { return ctx.isCollapsed = true; }); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵtemplate"](6, NavComponent_ul_6_Template, 2, 1, "ul", 6); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵelementEnd"](); } if (rf & 2) { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](3); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵattribute"]("aria-expanded", !ctx.isCollapsed); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](2); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵproperty"]("ngbCollapse", ctx.isCollapsed); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵadvance"](1); _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵproperty"]("ngIf", ctx.whatKeys); } }, directives: [_ng_bootstrap_ng_bootstrap__WEBPACK_IMPORTED_MODULE_2__["NgbNavbar"], _angular_router__WEBPACK_IMPORTED_MODULE_3__["RouterLinkWithHref"], _ng_bootstrap_ng_bootstrap__WEBPACK_IMPORTED_MODULE_2__["NgbCollapse"], _angular_common__WEBPACK_IMPORTED_MODULE_4__["NgIf"], _angular_common__WEBPACK_IMPORTED_MODULE_4__["NgForOf"], _angular_router__WEBPACK_IMPORTED_MODULE_3__["RouterLinkActive"]], pipes: [_what_pipe__WEBPACK_IMPORTED_MODULE_5__["WhatPipe"]], styles: ["\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzcmMvYXBwL25hdi9uYXYuY29tcG9uZW50LnNjc3MifQ== */"] }); /*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](NavComponent, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Component"], args: [{ selector: 'app-nav', templateUrl: './nav.component.html', styleUrls: ['./nav.component.scss'], providers: [_what_service__WEBPACK_IMPORTED_MODULE_1__["WhatService"]] }] }], function () { return [{ type: _what_service__WEBPACK_IMPORTED_MODULE_1__["WhatService"] }]; }, null); })(); /***/ }), /***/ "./src/app/what.pipe.ts": /*!******************************!*\ !*** ./src/app/what.pipe.ts ***! \******************************/ /*! exports provided: WhatPipe */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WhatPipe", function() { return WhatPipe; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js"); class WhatPipe { transform(value, args) { /** means we want a full url */ if (args) { /** return top-level files but not folders */ if (value.type == "file") return args + value.name; } else if (value.type == "directory") return value.name; } } WhatPipe.ɵfac = function WhatPipe_Factory(t) { return new (t || WhatPipe)(); }; WhatPipe.ɵpipe = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefinePipe"]({ name: "what", type: WhatPipe, pure: true }); /*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](WhatPipe, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"], args: [{ name: 'what' }] }], null, null); })(); /***/ }), /***/ "./src/app/what.service.ts": /*!*********************************!*\ !*** ./src/app/what.service.ts ***! \*********************************/ /*! exports provided: WhatService */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WhatService", function() { return WhatService; }); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js"); /* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/_esm2015/index.js"); /* harmony import */ var _angular_common_http__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @angular/common/http */ "./node_modules/@angular/common/__ivy_ngcc__/fesm2015/http.js"); class WhatService { constructor(http) { this.http = http; this.whatUrl = 'http://mariner.whatbox.ca:11720/jtree/'; } getWhat(dir) { let whatUrl = this.whatUrl; if (dir) { whatUrl = this.whatUrl + dir + '/'; } return this.http.get(whatUrl, { observe: 'response' }); /** .pipe( catchError( this.handleError(new HttpResponse<string[]>()) ) ); */ } /** * from angular.io http tutorial * Handle Http operation that failed. * Let the app continue. * @param result - optional value to return as the observable result */ handleError(result) { return (error) => { console.error(error); return Object(rxjs__WEBPACK_IMPORTED_MODULE_1__["of"])(result); }; } } WhatService.ɵfac = function WhatService_Factory(t) { return new (t || WhatService)(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵinject"](_angular_common_http__WEBPACK_IMPORTED_MODULE_2__["HttpClient"])); }; WhatService.ɵprov = _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵɵdefineInjectable"]({ token: WhatService, factory: WhatService.ɵfac, providedIn: 'root' }); /*@__PURE__*/ (function () { _angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵsetClassMetadata"](WhatService, [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Injectable"], args: [{ providedIn: 'root' }] }], function () { return [{ type: _angular_common_http__WEBPACK_IMPORTED_MODULE_2__["HttpClient"] }]; }, null); })(); /***/ }), /***/ "./src/environments/environment.ts": /*!*****************************************!*\ !*** ./src/environments/environment.ts ***! \*****************************************/ /*! exports provided: environment */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "environment", function() { return environment; }); // This file can be replaced during build by using the `fileReplacements` array. // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. // The list of file replacements can be found in `angular.json`. const environment = { production: false }; /* * For easier debugging in development mode, you can import the following file * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. * * This import should be commented out in production mode because it will have a negative impact * on performance if an error is thrown. */ // import 'zone.js/dist/zone-error'; // Included with Angular CLI. /***/ }), /***/ "./src/main.ts": /*!*********************!*\ !*** ./src/main.ts ***! \*********************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _angular_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/core */ "./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js"); /* harmony import */ var _environments_environment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./environments/environment */ "./src/environments/environment.ts"); /* harmony import */ var _app_app_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./app/app.module */ "./src/app/app.module.ts"); /* harmony import */ var _angular_platform_browser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @angular/platform-browser */ "./node_modules/@angular/platform-browser/__ivy_ngcc__/fesm2015/platform-browser.js"); if (_environments_environment__WEBPACK_IMPORTED_MODULE_1__["environment"].production) { Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["enableProdMode"])(); } _angular_platform_browser__WEBPACK_IMPORTED_MODULE_3__["platformBrowser"]().bootstrapModule(_app_app_module__WEBPACK_IMPORTED_MODULE_2__["AppModule"]) .catch(err => console.error(err)); /***/ }), /***/ 0: /*!***************************!*\ !*** multi ./src/main.ts ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! /home/bingo/Development/zeenbee/src/main.ts */"./src/main.ts"); /***/ }) },[[0,"runtime","vendor"]]]); //# sourceMappingURL=main-es2015.js.map
JavaScript
CL
c0e3a73ebd56dfedcde94c77c3371a22bf2667d1c52b71ba29e105f7647f12c6
/** * Getting telemetry data of the Crazyflie */ const { Crazyradio } = require('../dist/index'); // Because you can only use `await` within an async function... main(); async function main() { const radio = new Crazyradio(); try { await radio.init(); radio.on('console line', console.log); radio.on('error', err => { console.log('Radio error!', err); }); const drones = await radio.findDrones(); console.log(`Nearby drones: ${drones}`); if (drones.length < 1) { throw 'Could not find any drones!'; } const drone = await radio.connect(drones[0]); drone.on('error', err => { console.log('Drone error!', err); }); console.log('******************************'); console.log('Retrieving Crazyflie Table of Contents'); console.log('******************************'); const telemetryStart = new Date(); const toc = await drone.logging.getTOC(); console.log('******************************'); console.log(`Telemetry ready! After ${(Date.now() - telemetryStart) / 1000}s`); console.log(`TOC is of length ${drone.logging.tocFetcher.length} and has a checksum of ${drone.logging.tocFetcher.crc}`); console.log('Initializing gyroscope data now.'); console.log('******************************'); // Invoke getting of gyroscope data await drone.logging.start([ toc.getItem('gyro', 'x'), toc.getItem('gyro', 'y'), toc.getItem('gyro', 'z') ], 100); console.log('******************************'); console.log('Telemetry initialization finished!'); console.log('******************************'); /** * You can use any of the 3 types of events to get the logging data. * You can use: * * 1) Global `*` event - This will emit all data received in the format `{ group: { name: value } }` * 2) Group event - This will emit data received for the group in the format `{ name: value }` * 3) Full name event (`group.name`) - This will emit the value received. */ drone.logging.data.on('*', data => { console.log('Logging data:', data); }); drone.logging.data.on('gyro', data => { console.log('Gyro data:', data); }); drone.logging.data.on('gyro.x', data => { console.log('Gyro X data:', data); }); drone.logging.data.on('gyro.y', data => { console.log('Gyro Y data:', data); }); drone.logging.data.on('gyro.z', data => { console.log('Gyro Z data:', data); }); } catch (err) { console.log('Uh oh!', err); await radio.close(); } }
JavaScript
CL
cb3ecfb76b67fa3ff3af7396c8e8cd95aa8d5a8110a07108505a0c7ed95bf725
module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "fb15"); /******/ }) /************************************************************************/ /******/ ({ /***/ "014b": /***/ (function(module, exports, __webpack_require__) { "use strict"; // ECMAScript 6 symbols shim var global = __webpack_require__("e53d"); var has = __webpack_require__("07e3"); var DESCRIPTORS = __webpack_require__("8e60"); var $export = __webpack_require__("63b6"); var redefine = __webpack_require__("9138"); var META = __webpack_require__("ebfd").KEY; var $fails = __webpack_require__("294c"); var shared = __webpack_require__("dbdb"); var setToStringTag = __webpack_require__("45f2"); var uid = __webpack_require__("62a0"); var wks = __webpack_require__("5168"); var wksExt = __webpack_require__("ccb9"); var wksDefine = __webpack_require__("6718"); var enumKeys = __webpack_require__("47ee"); var isArray = __webpack_require__("9003"); var anObject = __webpack_require__("e4ae"); var isObject = __webpack_require__("f772"); var toObject = __webpack_require__("241e"); var toIObject = __webpack_require__("36c3"); var toPrimitive = __webpack_require__("1bc3"); var createDesc = __webpack_require__("aebd"); var _create = __webpack_require__("a159"); var gOPNExt = __webpack_require__("0395"); var $GOPD = __webpack_require__("bf0b"); var $GOPS = __webpack_require__("9aa9"); var $DP = __webpack_require__("d9f6"); var $keys = __webpack_require__("c3a1"); var gOPD = $GOPD.f; var dP = $DP.f; var gOPN = gOPNExt.f; var $Symbol = global.Symbol; var $JSON = global.JSON; var _stringify = $JSON && $JSON.stringify; var PROTOTYPE = 'prototype'; var HIDDEN = wks('_hidden'); var TO_PRIMITIVE = wks('toPrimitive'); var isEnum = {}.propertyIsEnumerable; var SymbolRegistry = shared('symbol-registry'); var AllSymbols = shared('symbols'); var OPSymbols = shared('op-symbols'); var ObjectProto = Object[PROTOTYPE]; var USE_NATIVE = typeof $Symbol == 'function' && !!$GOPS.f; var QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function () { return _create(dP({}, 'a', { get: function () { return dP(this, 'a', { value: 7 }).a; } })).a != 7; }) ? function (it, key, D) { var protoDesc = gOPD(ObjectProto, key); if (protoDesc) delete ObjectProto[key]; dP(it, key, D); if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); } : dP; var wrap = function (tag) { var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { return typeof it == 'symbol'; } : function (it) { return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D) { if (it === ObjectProto) $defineProperty(OPSymbols, key, D); anObject(it); key = toPrimitive(key, true); anObject(D); if (has(AllSymbols, key)) { if (!D.enumerable) { if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; D = _create(D, { enumerable: createDesc(0, false) }); } return setSymbolDesc(it, key, D); } return dP(it, key, D); }; var $defineProperties = function defineProperties(it, P) { anObject(it); var keys = enumKeys(P = toIObject(P)); var i = 0; var l = keys.length; var key; while (l > i) $defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P) { return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key) { var E = isEnum.call(this, key = toPrimitive(key, true)); if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { it = toIObject(it); key = toPrimitive(key, true); if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; var D = gOPD(it, key); if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it) { var names = gOPN(toIObject(it)); var result = []; var i = 0; var key; while (names.length > i) { if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { var IS_OP = it === ObjectProto; var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); var result = []; var i = 0; var key; while (names.length > i) { if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if (!USE_NATIVE) { $Symbol = function Symbol() { if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); var tag = uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function (value) { if (this === ObjectProto) $set.call(OPSymbols, value); if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); }; if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); return wrap(tag); }; redefine($Symbol[PROTOTYPE], 'toString', function toString() { return this._k; }); $GOPD.f = $getOwnPropertyDescriptor; $DP.f = $defineProperty; __webpack_require__("6abf").f = gOPNExt.f = $getOwnPropertyNames; __webpack_require__("355d").f = $propertyIsEnumerable; $GOPS.f = $getOwnPropertySymbols; if (DESCRIPTORS && !__webpack_require__("b8e3")) { redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } wksExt.f = function (name) { return wrap(wks(name)); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); for (var es6Symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function (key) { return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(sym) { if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; }, useSetter: function () { setter = true; }, useSimple: function () { setter = false; } }); $export($export.S + $export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives // https://bugs.chromium.org/p/v8/issues/detail?id=3443 var FAILS_ON_PRIMITIVES = $fails(function () { $GOPS.f(1); }); $export($export.S + $export.F * FAILS_ON_PRIMITIVES, 'Object', { getOwnPropertySymbols: function getOwnPropertySymbols(it) { return $GOPS.f(toObject(it)); } }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it) { var args = [it]; var i = 1; var replacer, $replacer; while (arguments.length > i) args.push(arguments[i++]); $replacer = replacer = args[1]; if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined if (!isArray(replacer)) replacer = function (key, value) { if (typeof $replacer == 'function') value = $replacer.call(this, key, value); if (!isSymbol(value)) return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__("35e8")($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); /***/ }), /***/ "01f9": /***/ (function(module, exports, __webpack_require__) { "use strict"; var LIBRARY = __webpack_require__("2d00"); var $export = __webpack_require__("5ca1"); var redefine = __webpack_require__("2aba"); var hide = __webpack_require__("32e9"); var Iterators = __webpack_require__("84f2"); var $iterCreate = __webpack_require__("41a0"); var setToStringTag = __webpack_require__("7f20"); var getPrototypeOf = __webpack_require__("38fd"); var ITERATOR = __webpack_require__("2b4c")('iterator'); var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` var FF_ITERATOR = '@@iterator'; var KEYS = 'keys'; var VALUES = 'values'; var returnThis = function () { return this; }; module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { $iterCreate(Constructor, NAME, next); var getMethod = function (kind) { if (!BUGGY && kind in proto) return proto[kind]; switch (kind) { case KEYS: return function keys() { return new Constructor(this, kind); }; case VALUES: return function values() { return new Constructor(this, kind); }; } return function entries() { return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator'; var DEF_VALUES = DEFAULT == VALUES; var VALUES_BUG = false; var proto = Base.prototype; var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; var $default = $native || getMethod(DEFAULT); var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; var methods, key, IteratorPrototype; // Fix native if ($anyNative) { IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if (DEF_VALUES && $native && $native.name !== VALUES) { VALUES_BUG = true; $default = function values() { return $native.call(this); }; } // Define iterator if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if (DEFAULT) { methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if (FORCED) for (key in methods) { if (!(key in proto)) redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }), /***/ "0293": /***/ (function(module, exports, __webpack_require__) { // 19.1.2.9 Object.getPrototypeOf(O) var toObject = __webpack_require__("241e"); var $getPrototypeOf = __webpack_require__("53e2"); __webpack_require__("ce7e")('getPrototypeOf', function () { return function getPrototypeOf(it) { return $getPrototypeOf(toObject(it)); }; }); /***/ }), /***/ "0395": /***/ (function(module, exports, __webpack_require__) { // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = __webpack_require__("36c3"); var gOPN = __webpack_require__("6abf").f; var toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function (it) { try { return gOPN(it); } catch (e) { return windowNames.slice(); } }; module.exports.f = function getOwnPropertyNames(it) { return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; /***/ }), /***/ "061b": /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("fa99"); /***/ }), /***/ "07e3": /***/ (function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function (it, key) { return hasOwnProperty.call(it, key); }; /***/ }), /***/ "0d58": /***/ (function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __webpack_require__("ce10"); var enumBugKeys = __webpack_require__("e11e"); module.exports = Object.keys || function keys(O) { return $keys(O, enumBugKeys); }; /***/ }), /***/ "0fc9": /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__("3a38"); var max = Math.max; var min = Math.min; module.exports = function (index, length) { index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }), /***/ "1136": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyFormItem_vue_vue_type_style_index_0_id_fa83a2d8_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("ad2a"); /* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyFormItem_vue_vue_type_style_index_0_id_fa83a2d8_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyFormItem_vue_vue_type_style_index_0_id_fa83a2d8_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0__); /* unused harmony reexport * */ /* unused harmony default export */ var _unused_webpack_default_export = (_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyFormItem_vue_vue_type_style_index_0_id_fa83a2d8_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default.a); /***/ }), /***/ "1495": /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__("86cc"); var anObject = __webpack_require__("cb7c"); var getKeys = __webpack_require__("0d58"); module.exports = __webpack_require__("9e1e") ? Object.defineProperties : function defineProperties(O, Properties) { anObject(O); var keys = getKeys(Properties); var length = keys.length; var i = 0; var P; while (length > i) dP.f(O, P = keys[i++], Properties[P]); return O; }; /***/ }), /***/ "1654": /***/ (function(module, exports, __webpack_require__) { "use strict"; var $at = __webpack_require__("71c1")(true); // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__("30f1")(String, 'String', function (iterated) { this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function () { var O = this._t; var index = this._i; var point; if (index >= O.length) return { value: undefined, done: true }; point = $at(O, index); this._i += point.length; return { value: point, done: false }; }); /***/ }), /***/ "1691": /***/ (function(module, exports) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); /***/ }), /***/ "1af6": /***/ (function(module, exports, __webpack_require__) { // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) var $export = __webpack_require__("63b6"); $export($export.S, 'Array', { isArray: __webpack_require__("9003") }); /***/ }), /***/ "1bc3": /***/ (function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = __webpack_require__("f772"); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function (it, S) { if (!isObject(it)) return it; var fn, val; if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; throw TypeError("Can't convert object to primitive value"); }; /***/ }), /***/ "1ca4": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyCheckboxGroup_vue_vue_type_style_index_0_id_1cbe62ae_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("d0cb"); /* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyCheckboxGroup_vue_vue_type_style_index_0_id_1cbe62ae_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyCheckboxGroup_vue_vue_type_style_index_0_id_1cbe62ae_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0__); /* unused harmony reexport * */ /* unused harmony default export */ var _unused_webpack_default_export = (_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyCheckboxGroup_vue_vue_type_style_index_0_id_1cbe62ae_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default.a); /***/ }), /***/ "1df8": /***/ (function(module, exports, __webpack_require__) { // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = __webpack_require__("63b6"); $export($export.S, 'Object', { setPrototypeOf: __webpack_require__("ead6").set }); /***/ }), /***/ "1ec9": /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__("f772"); var document = __webpack_require__("e53d").document; // typeof document.createElement is 'object' in old IE var is = isObject(document) && isObject(document.createElement); module.exports = function (it) { return is ? document.createElement(it) : {}; }; /***/ }), /***/ "20fd": /***/ (function(module, exports, __webpack_require__) { "use strict"; var $defineProperty = __webpack_require__("d9f6"); var createDesc = __webpack_require__("aebd"); module.exports = function (object, index, value) { if (index in object) $defineProperty.f(object, index, createDesc(0, value)); else object[index] = value; }; /***/ }), /***/ "230e": /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__("d3f4"); var document = __webpack_require__("7726").document; // typeof document.createElement is 'object' in old IE var is = isObject(document) && isObject(document.createElement); module.exports = function (it) { return is ? document.createElement(it) : {}; }; /***/ }), /***/ "241e": /***/ (function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__("25eb"); module.exports = function (it) { return Object(defined(it)); }; /***/ }), /***/ "25b0": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("1df8"); module.exports = __webpack_require__("584a").Object.setPrototypeOf; /***/ }), /***/ "25eb": /***/ (function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; /***/ }), /***/ "294c": /***/ (function(module, exports) { module.exports = function (exec) { try { return !!exec(); } catch (e) { return true; } }; /***/ }), /***/ "2aba": /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__("7726"); var hide = __webpack_require__("32e9"); var has = __webpack_require__("69a8"); var SRC = __webpack_require__("ca5a")('src'); var $toString = __webpack_require__("fa5b"); var TO_STRING = 'toString'; var TPL = ('' + $toString).split(TO_STRING); __webpack_require__("8378").inspectSource = function (it) { return $toString.call(it); }; (module.exports = function (O, key, val, safe) { var isFunction = typeof val == 'function'; if (isFunction) has(val, 'name') || hide(val, 'name', key); if (O[key] === val) return; if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); if (O === global) { O[key] = val; } else if (!safe) { delete O[key]; hide(O, key, val); } else if (O[key]) { O[key] = val; } else { hide(O, key, val); } // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, TO_STRING, function toString() { return typeof this == 'function' && this[SRC] || $toString.call(this); }); /***/ }), /***/ "2aeb": /***/ (function(module, exports, __webpack_require__) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = __webpack_require__("cb7c"); var dPs = __webpack_require__("1495"); var enumBugKeys = __webpack_require__("e11e"); var IE_PROTO = __webpack_require__("613b")('IE_PROTO'); var Empty = function () { /* empty */ }; var PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function () { // Thrash, waste and sodomy: IE GC bug var iframe = __webpack_require__("230e")('iframe'); var i = enumBugKeys.length; var lt = '<'; var gt = '>'; var iframeDocument; iframe.style.display = 'none'; __webpack_require__("fab2").appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties) { var result; if (O !== null) { Empty[PROTOTYPE] = anObject(O); result = new Empty(); Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; /***/ }), /***/ "2b4c": /***/ (function(module, exports, __webpack_require__) { var store = __webpack_require__("5537")('wks'); var uid = __webpack_require__("ca5a"); var Symbol = __webpack_require__("7726").Symbol; var USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function (name) { return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; /***/ }), /***/ "2d00": /***/ (function(module, exports) { module.exports = false; /***/ }), /***/ "2d95": /***/ (function(module, exports) { var toString = {}.toString; module.exports = function (it) { return toString.call(it).slice(8, -1); }; /***/ }), /***/ "2fdd": /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin /***/ }), /***/ "3041": /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin /***/ }), /***/ "30f1": /***/ (function(module, exports, __webpack_require__) { "use strict"; var LIBRARY = __webpack_require__("b8e3"); var $export = __webpack_require__("63b6"); var redefine = __webpack_require__("9138"); var hide = __webpack_require__("35e8"); var Iterators = __webpack_require__("481b"); var $iterCreate = __webpack_require__("8f60"); var setToStringTag = __webpack_require__("45f2"); var getPrototypeOf = __webpack_require__("53e2"); var ITERATOR = __webpack_require__("5168")('iterator'); var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` var FF_ITERATOR = '@@iterator'; var KEYS = 'keys'; var VALUES = 'values'; var returnThis = function () { return this; }; module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { $iterCreate(Constructor, NAME, next); var getMethod = function (kind) { if (!BUGGY && kind in proto) return proto[kind]; switch (kind) { case KEYS: return function keys() { return new Constructor(this, kind); }; case VALUES: return function values() { return new Constructor(this, kind); }; } return function entries() { return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator'; var DEF_VALUES = DEFAULT == VALUES; var VALUES_BUG = false; var proto = Base.prototype; var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; var $default = $native || getMethod(DEFAULT); var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; var methods, key, IteratorPrototype; // Fix native if ($anyNative) { IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if (DEF_VALUES && $native && $native.name !== VALUES) { VALUES_BUG = true; $default = function values() { return $native.call(this); }; } // Define iterator if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if (DEFAULT) { methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if (FORCED) for (key in methods) { if (!(key in proto)) redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }), /***/ "32e9": /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__("86cc"); var createDesc = __webpack_require__("4630"); module.exports = __webpack_require__("9e1e") ? function (object, key, value) { return dP.f(object, key, createDesc(1, value)); } : function (object, key, value) { object[key] = value; return object; }; /***/ }), /***/ "32fc": /***/ (function(module, exports, __webpack_require__) { var document = __webpack_require__("e53d").document; module.exports = document && document.documentElement; /***/ }), /***/ "335c": /***/ (function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__("6b4c"); // eslint-disable-next-line no-prototype-builtins module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }), /***/ "355d": /***/ (function(module, exports) { exports.f = {}.propertyIsEnumerable; /***/ }), /***/ "35e8": /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__("d9f6"); var createDesc = __webpack_require__("aebd"); module.exports = __webpack_require__("8e60") ? function (object, key, value) { return dP.f(object, key, createDesc(1, value)); } : function (object, key, value) { object[key] = value; return object; }; /***/ }), /***/ "36c3": /***/ (function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__("335c"); var defined = __webpack_require__("25eb"); module.exports = function (it) { return IObject(defined(it)); }; /***/ }), /***/ "3702": /***/ (function(module, exports, __webpack_require__) { // check on default Array iterator var Iterators = __webpack_require__("481b"); var ITERATOR = __webpack_require__("5168")('iterator'); var ArrayProto = Array.prototype; module.exports = function (it) { return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }), /***/ "385e": /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin /***/ }), /***/ "38fd": /***/ (function(module, exports, __webpack_require__) { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = __webpack_require__("69a8"); var toObject = __webpack_require__("4bf8"); var IE_PROTO = __webpack_require__("613b")('IE_PROTO'); var ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function (O) { O = toObject(O); if (has(O, IE_PROTO)) return O[IE_PROTO]; if (typeof O.constructor == 'function' && O instanceof O.constructor) { return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; /***/ }), /***/ "3a38": /***/ (function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil; var floor = Math.floor; module.exports = function (it) { return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }), /***/ "40c3": /***/ (function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = __webpack_require__("6b4c"); var TAG = __webpack_require__("5168")('toStringTag'); // ES3 wrong here var ARG = cof(function () { return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function (it, key) { try { return it[key]; } catch (e) { /* empty */ } }; module.exports = function (it) { var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; /***/ }), /***/ "41a0": /***/ (function(module, exports, __webpack_require__) { "use strict"; var create = __webpack_require__("2aeb"); var descriptor = __webpack_require__("4630"); var setToStringTag = __webpack_require__("7f20"); var IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__("32e9")(IteratorPrototype, __webpack_require__("2b4c")('iterator'), function () { return this; }); module.exports = function (Constructor, NAME, next) { Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }), /***/ "454f": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("46a7"); var $Object = __webpack_require__("584a").Object; module.exports = function defineProperty(it, key, desc) { return $Object.defineProperty(it, key, desc); }; /***/ }), /***/ "4588": /***/ (function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil; var floor = Math.floor; module.exports = function (it) { return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }), /***/ "45f2": /***/ (function(module, exports, __webpack_require__) { var def = __webpack_require__("d9f6").f; var has = __webpack_require__("07e3"); var TAG = __webpack_require__("5168")('toStringTag'); module.exports = function (it, tag, stat) { if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); }; /***/ }), /***/ "4630": /***/ (function(module, exports) { module.exports = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; /***/ }), /***/ "46a7": /***/ (function(module, exports, __webpack_require__) { var $export = __webpack_require__("63b6"); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) $export($export.S + $export.F * !__webpack_require__("8e60"), 'Object', { defineProperty: __webpack_require__("d9f6").f }); /***/ }), /***/ "47ee": /***/ (function(module, exports, __webpack_require__) { // all enumerable object keys, includes symbols var getKeys = __webpack_require__("c3a1"); var gOPS = __webpack_require__("9aa9"); var pIE = __webpack_require__("355d"); module.exports = function (it) { var result = getKeys(it); var getSymbols = gOPS.f; if (getSymbols) { var symbols = getSymbols(it); var isEnum = pIE.f; var i = 0; var key; while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); } return result; }; /***/ }), /***/ "481b": /***/ (function(module, exports) { module.exports = {}; /***/ }), /***/ "4aa6": /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("dc62"); /***/ }), /***/ "4b4d": /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin /***/ }), /***/ "4bf8": /***/ (function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__("be13"); module.exports = function (it) { return Object(defined(it)); }; /***/ }), /***/ "4d16": /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("25b0"); /***/ }), /***/ "4ee1": /***/ (function(module, exports, __webpack_require__) { var ITERATOR = __webpack_require__("5168")('iterator'); var SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function () { SAFE_CLOSING = true; }; // eslint-disable-next-line no-throw-literal Array.from(riter, function () { throw 2; }); } catch (e) { /* empty */ } module.exports = function (exec, skipClosing) { if (!skipClosing && !SAFE_CLOSING) return false; var safe = false; try { var arr = [7]; var iter = arr[ITERATOR](); iter.next = function () { return { done: safe = true }; }; arr[ITERATOR] = function () { return iter; }; exec(arr); } catch (e) { /* empty */ } return safe; }; /***/ }), /***/ "50ed": /***/ (function(module, exports) { module.exports = function (done, value) { return { value: value, done: !!done }; }; /***/ }), /***/ "5168": /***/ (function(module, exports, __webpack_require__) { var store = __webpack_require__("dbdb")('wks'); var uid = __webpack_require__("62a0"); var Symbol = __webpack_require__("e53d").Symbol; var USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function (name) { return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; /***/ }), /***/ "53e2": /***/ (function(module, exports, __webpack_require__) { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = __webpack_require__("07e3"); var toObject = __webpack_require__("241e"); var IE_PROTO = __webpack_require__("5559")('IE_PROTO'); var ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function (O) { O = toObject(O); if (has(O, IE_PROTO)) return O[IE_PROTO]; if (typeof O.constructor == 'function' && O instanceof O.constructor) { return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; /***/ }), /***/ "549b": /***/ (function(module, exports, __webpack_require__) { "use strict"; var ctx = __webpack_require__("d864"); var $export = __webpack_require__("63b6"); var toObject = __webpack_require__("241e"); var call = __webpack_require__("b0dc"); var isArrayIter = __webpack_require__("3702"); var toLength = __webpack_require__("b447"); var createProperty = __webpack_require__("20fd"); var getIterFn = __webpack_require__("7cd6"); $export($export.S + $export.F * !__webpack_require__("4ee1")(function (iter) { Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { var O = toObject(arrayLike); var C = typeof this == 'function' ? this : Array; var aLen = arguments.length; var mapfn = aLen > 1 ? arguments[1] : undefined; var mapping = mapfn !== undefined; var index = 0; var iterFn = getIterFn(O); var length, result, step, iterator; if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); // if object isn't iterable or it's array with default iterator - use simple case if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); } } else { length = toLength(O.length); for (result = new C(length); length > index; index++) { createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); } } result.length = index; return result; } }); /***/ }), /***/ "54a1": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("6c1c"); __webpack_require__("1654"); module.exports = __webpack_require__("95d5"); /***/ }), /***/ "5537": /***/ (function(module, exports, __webpack_require__) { var core = __webpack_require__("8378"); var global = __webpack_require__("7726"); var SHARED = '__core-js_shared__'; var store = global[SHARED] || (global[SHARED] = {}); (module.exports = function (key, value) { return store[key] || (store[key] = value !== undefined ? value : {}); })('versions', []).push({ version: core.version, mode: __webpack_require__("2d00") ? 'pure' : 'global', copyright: '© 2019 Denis Pushkarev (zloirock.ru)' }); /***/ }), /***/ "5559": /***/ (function(module, exports, __webpack_require__) { var shared = __webpack_require__("dbdb")('keys'); var uid = __webpack_require__("62a0"); module.exports = function (key) { return shared[key] || (shared[key] = uid(key)); }; /***/ }), /***/ "584a": /***/ (function(module, exports) { var core = module.exports = { version: '2.6.9' }; if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef /***/ }), /***/ "5b4e": /***/ (function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__("36c3"); var toLength = __webpack_require__("b447"); var toAbsoluteIndex = __webpack_require__("0fc9"); module.exports = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) if (IS_INCLUDES || index in O) { if (O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; /***/ }), /***/ "5ca1": /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__("7726"); var core = __webpack_require__("8378"); var hide = __webpack_require__("32e9"); var redefine = __webpack_require__("2aba"); var ctx = __webpack_require__("9b43"); var PROTOTYPE = 'prototype'; var $export = function (type, name, source) { var IS_FORCED = type & $export.F; var IS_GLOBAL = type & $export.G; var IS_STATIC = type & $export.S; var IS_PROTO = type & $export.P; var IS_BIND = type & $export.B; var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]; var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); var key, own, out, exp; if (IS_GLOBAL) source = name; for (key in source) { // contains in native own = !IS_FORCED && target && target[key] !== undefined; // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // extend global if (target) redefine(target, key, out, type & $export.U); // export if (exports[key] != out) hide(exports, key, exp); if (IS_PROTO && expProto[key] != out) expProto[key] = out; } }; global.core = core; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; /***/ }), /***/ "5d58": /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("d8d6"); /***/ }), /***/ "613b": /***/ (function(module, exports, __webpack_require__) { var shared = __webpack_require__("5537")('keys'); var uid = __webpack_require__("ca5a"); module.exports = function (key) { return shared[key] || (shared[key] = uid(key)); }; /***/ }), /***/ "626a": /***/ (function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__("2d95"); // eslint-disable-next-line no-prototype-builtins module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }), /***/ "62a0": /***/ (function(module, exports) { var id = 0; var px = Math.random(); module.exports = function (key) { return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }), /***/ "63b6": /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__("e53d"); var core = __webpack_require__("584a"); var ctx = __webpack_require__("d864"); var hide = __webpack_require__("35e8"); var has = __webpack_require__("07e3"); var PROTOTYPE = 'prototype'; var $export = function (type, name, source) { var IS_FORCED = type & $export.F; var IS_GLOBAL = type & $export.G; var IS_STATIC = type & $export.S; var IS_PROTO = type & $export.P; var IS_BIND = type & $export.B; var IS_WRAP = type & $export.W; var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); var expProto = exports[PROTOTYPE]; var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]; var key, own, out; if (IS_GLOBAL) source = name; for (key in source) { // contains in native own = !IS_FORCED && target && target[key] !== undefined; if (own && has(exports, key)) continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function (C) { var F = function (a, b, c) { if (this instanceof C) { switch (arguments.length) { case 0: return new C(); case 1: return new C(a); case 2: return new C(a, b); } return new C(a, b, c); } return C.apply(this, arguments); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% if (IS_PROTO) { (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out); } } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; /***/ }), /***/ "6718": /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__("e53d"); var core = __webpack_require__("584a"); var LIBRARY = __webpack_require__("b8e3"); var wksExt = __webpack_require__("ccb9"); var defineProperty = __webpack_require__("d9f6").f; module.exports = function (name) { var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); }; /***/ }), /***/ "67bb": /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("f921"); /***/ }), /***/ "6821": /***/ (function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__("626a"); var defined = __webpack_require__("be13"); module.exports = function (it) { return IObject(defined(it)); }; /***/ }), /***/ "69a8": /***/ (function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function (it, key) { return hasOwnProperty.call(it, key); }; /***/ }), /***/ "69d3": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("6718")('asyncIterator'); /***/ }), /***/ "6a99": /***/ (function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = __webpack_require__("d3f4"); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function (it, S) { if (!isObject(it)) return it; var fn, val; if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; throw TypeError("Can't convert object to primitive value"); }; /***/ }), /***/ "6abf": /***/ (function(module, exports, __webpack_require__) { // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = __webpack_require__("e6f3"); var hiddenKeys = __webpack_require__("1691").concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return $keys(O, hiddenKeys); }; /***/ }), /***/ "6b4c": /***/ (function(module, exports) { var toString = {}.toString; module.exports = function (it) { return toString.call(it).slice(8, -1); }; /***/ }), /***/ "6c1c": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("c367"); var global = __webpack_require__("e53d"); var hide = __webpack_require__("35e8"); var Iterators = __webpack_require__("481b"); var TO_STRING_TAG = __webpack_require__("5168")('toStringTag'); var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' + 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' + 'TextTrackList,TouchList').split(','); for (var i = 0; i < DOMIterables.length; i++) { var NAME = DOMIterables[i]; var Collection = global[NAME]; var proto = Collection && Collection.prototype; if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = Iterators.Array; } /***/ }), /***/ "71c1": /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__("3a38"); var defined = __webpack_require__("25eb"); // true -> String#at // false -> String#codePointAt module.exports = function (TO_STRING) { return function (that, pos) { var s = String(defined(that)); var i = toInteger(pos); var l = s.length; var a, b; if (i < 0 || i >= l) return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }), /***/ "765d": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("6718")('observable'); /***/ }), /***/ "7726": /***/ (function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self // eslint-disable-next-line no-new-func : Function('return this')(); if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef /***/ }), /***/ "774e": /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("d2d5"); /***/ }), /***/ "77f1": /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__("4588"); var max = Math.max; var min = Math.min; module.exports = function (index, length) { index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }), /***/ "794b": /***/ (function(module, exports, __webpack_require__) { module.exports = !__webpack_require__("8e60") && !__webpack_require__("294c")(function () { return Object.defineProperty(__webpack_require__("1ec9")('div'), 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /***/ "79aa": /***/ (function(module, exports) { module.exports = function (it) { if (typeof it != 'function') throw TypeError(it + ' is not a function!'); return it; }; /***/ }), /***/ "79e5": /***/ (function(module, exports) { module.exports = function (exec) { try { return !!exec(); } catch (e) { return true; } }; /***/ }), /***/ "7cd6": /***/ (function(module, exports, __webpack_require__) { var classof = __webpack_require__("40c3"); var ITERATOR = __webpack_require__("5168")('iterator'); var Iterators = __webpack_require__("481b"); module.exports = __webpack_require__("584a").getIteratorMethod = function (it) { if (it != undefined) return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }), /***/ "7e90": /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__("d9f6"); var anObject = __webpack_require__("e4ae"); var getKeys = __webpack_require__("c3a1"); module.exports = __webpack_require__("8e60") ? Object.defineProperties : function defineProperties(O, Properties) { anObject(O); var keys = getKeys(Properties); var length = keys.length; var i = 0; var P; while (length > i) dP.f(O, P = keys[i++], Properties[P]); return O; }; /***/ }), /***/ "7f20": /***/ (function(module, exports, __webpack_require__) { var def = __webpack_require__("86cc").f; var has = __webpack_require__("69a8"); var TAG = __webpack_require__("2b4c")('toStringTag'); module.exports = function (it, tag, stat) { if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); }; /***/ }), /***/ "7f7f": /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__("86cc").f; var FProto = Function.prototype; var nameRE = /^\s*function ([^ (]*)/; var NAME = 'name'; // 19.2.4.2 name NAME in FProto || __webpack_require__("9e1e") && dP(FProto, NAME, { configurable: true, get: function () { try { return ('' + this).match(nameRE)[1]; } catch (e) { return ''; } } }); /***/ }), /***/ "8378": /***/ (function(module, exports) { var core = module.exports = { version: '2.6.9' }; if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef /***/ }), /***/ "8436": /***/ (function(module, exports) { module.exports = function () { /* empty */ }; /***/ }), /***/ "84f2": /***/ (function(module, exports) { module.exports = {}; /***/ }), /***/ "85f2": /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("454f"); /***/ }), /***/ "86cc": /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__("cb7c"); var IE8_DOM_DEFINE = __webpack_require__("c69a"); var toPrimitive = __webpack_require__("6a99"); var dP = Object.defineProperty; exports.f = __webpack_require__("9e1e") ? Object.defineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (IE8_DOM_DEFINE) try { return dP(O, P, Attributes); } catch (e) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; /***/ }), /***/ "8bbf": /***/ (function(module, exports) { module.exports = require("vue"); /***/ }), /***/ "8e60": /***/ (function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__("294c")(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /***/ "8f60": /***/ (function(module, exports, __webpack_require__) { "use strict"; var create = __webpack_require__("a159"); var descriptor = __webpack_require__("aebd"); var setToStringTag = __webpack_require__("45f2"); var IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__("35e8")(IteratorPrototype, __webpack_require__("5168")('iterator'), function () { return this; }); module.exports = function (Constructor, NAME, next) { Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }), /***/ "9003": /***/ (function(module, exports, __webpack_require__) { // 7.2.2 IsArray(argument) var cof = __webpack_require__("6b4c"); module.exports = Array.isArray || function isArray(arg) { return cof(arg) == 'Array'; }; /***/ }), /***/ "9138": /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("35e8"); /***/ }), /***/ "9427": /***/ (function(module, exports, __webpack_require__) { var $export = __webpack_require__("63b6"); // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) $export($export.S, 'Object', { create: __webpack_require__("a159") }); /***/ }), /***/ "95d5": /***/ (function(module, exports, __webpack_require__) { var classof = __webpack_require__("40c3"); var ITERATOR = __webpack_require__("5168")('iterator'); var Iterators = __webpack_require__("481b"); module.exports = __webpack_require__("584a").isIterable = function (it) { var O = Object(it); return O[ITERATOR] !== undefined || '@@iterator' in O // eslint-disable-next-line no-prototype-builtins || Iterators.hasOwnProperty(classof(O)); }; /***/ }), /***/ "9aa9": /***/ (function(module, exports) { exports.f = Object.getOwnPropertySymbols; /***/ }), /***/ "9b43": /***/ (function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__("d8e8"); module.exports = function (fn, that, length) { aFunction(fn); if (that === undefined) return fn; switch (length) { case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function (/* ...args */) { return fn.apply(that, arguments); }; }; /***/ }), /***/ "9c6c": /***/ (function(module, exports, __webpack_require__) { // 22.1.3.31 Array.prototype[@@unscopables] var UNSCOPABLES = __webpack_require__("2b4c")('unscopables'); var ArrayProto = Array.prototype; if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__("32e9")(ArrayProto, UNSCOPABLES, {}); module.exports = function (key) { ArrayProto[UNSCOPABLES][key] = true; }; /***/ }), /***/ "9def": /***/ (function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__("4588"); var min = Math.min; module.exports = function (it) { return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }), /***/ "9e1e": /***/ (function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__("79e5")(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /***/ "a159": /***/ (function(module, exports, __webpack_require__) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = __webpack_require__("e4ae"); var dPs = __webpack_require__("7e90"); var enumBugKeys = __webpack_require__("1691"); var IE_PROTO = __webpack_require__("5559")('IE_PROTO'); var Empty = function () { /* empty */ }; var PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function () { // Thrash, waste and sodomy: IE GC bug var iframe = __webpack_require__("1ec9")('iframe'); var i = enumBugKeys.length; var lt = '<'; var gt = '>'; var iframeDocument; iframe.style.display = 'none'; __webpack_require__("32fc").appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties) { var result; if (O !== null) { Empty[PROTOTYPE] = anObject(O); result = new Empty(); Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; /***/ }), /***/ "a45b": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyInput_vue_vue_type_style_index_0_id_16661b44_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("3041"); /* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyInput_vue_vue_type_style_index_0_id_16661b44_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyInput_vue_vue_type_style_index_0_id_16661b44_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0__); /* unused harmony reexport * */ /* unused harmony default export */ var _unused_webpack_default_export = (_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyInput_vue_vue_type_style_index_0_id_16661b44_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default.a); /***/ }), /***/ "a4fd": /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin /***/ }), /***/ "a745": /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("f410"); /***/ }), /***/ "ac6a": /***/ (function(module, exports, __webpack_require__) { var $iterators = __webpack_require__("cadf"); var getKeys = __webpack_require__("0d58"); var redefine = __webpack_require__("2aba"); var global = __webpack_require__("7726"); var hide = __webpack_require__("32e9"); var Iterators = __webpack_require__("84f2"); var wks = __webpack_require__("2b4c"); var ITERATOR = wks('iterator'); var TO_STRING_TAG = wks('toStringTag'); var ArrayValues = Iterators.Array; var DOMIterables = { CSSRuleList: true, // TODO: Not spec compliant, should be false. CSSStyleDeclaration: false, CSSValueList: false, ClientRectList: false, DOMRectList: false, DOMStringList: false, DOMTokenList: true, DataTransferItemList: false, FileList: false, HTMLAllCollection: false, HTMLCollection: false, HTMLFormElement: false, HTMLSelectElement: false, MediaList: true, // TODO: Not spec compliant, should be false. MimeTypeArray: false, NamedNodeMap: false, NodeList: true, PaintRequestList: false, Plugin: false, PluginArray: false, SVGLengthList: false, SVGNumberList: false, SVGPathSegList: false, SVGPointList: false, SVGStringList: false, SVGTransformList: false, SourceBufferList: false, StyleSheetList: true, // TODO: Not spec compliant, should be false. TextTrackCueList: false, TextTrackList: false, TouchList: false }; for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) { var NAME = collections[i]; var explicit = DOMIterables[NAME]; var Collection = global[NAME]; var proto = Collection && Collection.prototype; var key; if (proto) { if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues); if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = ArrayValues; if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true); } } /***/ }), /***/ "ad2a": /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin /***/ }), /***/ "aebd": /***/ (function(module, exports) { module.exports = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; /***/ }), /***/ "aee8": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyRadioGroup_vue_vue_type_style_index_0_id_07f8ba8a_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("4b4d"); /* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyRadioGroup_vue_vue_type_style_index_0_id_07f8ba8a_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyRadioGroup_vue_vue_type_style_index_0_id_07f8ba8a_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0__); /* unused harmony reexport * */ /* unused harmony default export */ var _unused_webpack_default_export = (_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyRadioGroup_vue_vue_type_style_index_0_id_07f8ba8a_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default.a); /***/ }), /***/ "b0dc": /***/ (function(module, exports, __webpack_require__) { // call something on iterator step with safe closing on error var anObject = __webpack_require__("e4ae"); module.exports = function (iterator, fn, value, entries) { try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch (e) { var ret = iterator['return']; if (ret !== undefined) anObject(ret.call(iterator)); throw e; } }; /***/ }), /***/ "b447": /***/ (function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__("3a38"); var min = Math.min; module.exports = function (it) { return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }), /***/ "b8e3": /***/ (function(module, exports) { module.exports = true; /***/ }), /***/ "be13": /***/ (function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; /***/ }), /***/ "bf0b": /***/ (function(module, exports, __webpack_require__) { var pIE = __webpack_require__("355d"); var createDesc = __webpack_require__("aebd"); var toIObject = __webpack_require__("36c3"); var toPrimitive = __webpack_require__("1bc3"); var has = __webpack_require__("07e3"); var IE8_DOM_DEFINE = __webpack_require__("794b"); var gOPD = Object.getOwnPropertyDescriptor; exports.f = __webpack_require__("8e60") ? gOPD : function getOwnPropertyDescriptor(O, P) { O = toIObject(O); P = toPrimitive(P, true); if (IE8_DOM_DEFINE) try { return gOPD(O, P); } catch (e) { /* empty */ } if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); }; /***/ }), /***/ "bffd": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyCheckbox_vue_vue_type_style_index_0_id_a767d046_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("a4fd"); /* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyCheckbox_vue_vue_type_style_index_0_id_a767d046_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyCheckbox_vue_vue_type_style_index_0_id_a767d046_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0__); /* unused harmony reexport * */ /* unused harmony default export */ var _unused_webpack_default_export = (_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyCheckbox_vue_vue_type_style_index_0_id_a767d046_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default.a); /***/ }), /***/ "c207": /***/ (function(module, exports) { /***/ }), /***/ "c22d": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyRadio_vue_vue_type_style_index_0_id_0eb575c5_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("2fdd"); /* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyRadio_vue_vue_type_style_index_0_id_0eb575c5_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyRadio_vue_vue_type_style_index_0_id_0eb575c5_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0__); /* unused harmony reexport * */ /* unused harmony default export */ var _unused_webpack_default_export = (_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyRadio_vue_vue_type_style_index_0_id_0eb575c5_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default.a); /***/ }), /***/ "c366": /***/ (function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__("6821"); var toLength = __webpack_require__("9def"); var toAbsoluteIndex = __webpack_require__("77f1"); module.exports = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) if (IS_INCLUDES || index in O) { if (O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; /***/ }), /***/ "c367": /***/ (function(module, exports, __webpack_require__) { "use strict"; var addToUnscopables = __webpack_require__("8436"); var step = __webpack_require__("50ed"); var Iterators = __webpack_require__("481b"); var toIObject = __webpack_require__("36c3"); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = __webpack_require__("30f1")(Array, 'Array', function (iterated, kind) { this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function () { var O = this._t; var kind = this._k; var index = this._i++; if (!O || index >= O.length) { this._t = undefined; return step(1); } if (kind == 'keys') return step(0, index); if (kind == 'values') return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }), /***/ "c3a1": /***/ (function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __webpack_require__("e6f3"); var enumBugKeys = __webpack_require__("1691"); module.exports = Object.keys || function keys(O) { return $keys(O, enumBugKeys); }; /***/ }), /***/ "c69a": /***/ (function(module, exports, __webpack_require__) { module.exports = !__webpack_require__("9e1e") && !__webpack_require__("79e5")(function () { return Object.defineProperty(__webpack_require__("230e")('div'), 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /***/ "c8bb": /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("54a1"); /***/ }), /***/ "ca5a": /***/ (function(module, exports) { var id = 0; var px = Math.random(); module.exports = function (key) { return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }), /***/ "cadf": /***/ (function(module, exports, __webpack_require__) { "use strict"; var addToUnscopables = __webpack_require__("9c6c"); var step = __webpack_require__("d53b"); var Iterators = __webpack_require__("84f2"); var toIObject = __webpack_require__("6821"); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = __webpack_require__("01f9")(Array, 'Array', function (iterated, kind) { this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function () { var O = this._t; var kind = this._k; var index = this._i++; if (!O || index >= O.length) { this._t = undefined; return step(1); } if (kind == 'keys') return step(0, index); if (kind == 'values') return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }), /***/ "cb7c": /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__("d3f4"); module.exports = function (it) { if (!isObject(it)) throw TypeError(it + ' is not an object!'); return it; }; /***/ }), /***/ "ccb9": /***/ (function(module, exports, __webpack_require__) { exports.f = __webpack_require__("5168"); /***/ }), /***/ "ccf2": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyButton_vue_vue_type_style_index_0_id_7664fdda_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("385e"); /* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyButton_vue_vue_type_style_index_0_id_7664fdda_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyButton_vue_vue_type_style_index_0_id_7664fdda_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0__); /* unused harmony reexport * */ /* unused harmony default export */ var _unused_webpack_default_export = (_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_lib_loader_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MyButton_vue_vue_type_style_index_0_id_7664fdda_lang_scss_rel_stylesheet_2Fscss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default.a); /***/ }), /***/ "ce10": /***/ (function(module, exports, __webpack_require__) { var has = __webpack_require__("69a8"); var toIObject = __webpack_require__("6821"); var arrayIndexOf = __webpack_require__("c366")(false); var IE_PROTO = __webpack_require__("613b")('IE_PROTO'); module.exports = function (object, names) { var O = toIObject(object); var i = 0; var result = []; var key; for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); // Don't enum bug & hidden keys while (names.length > i) if (has(O, key = names[i++])) { ~arrayIndexOf(result, key) || result.push(key); } return result; }; /***/ }), /***/ "ce7e": /***/ (function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives var $export = __webpack_require__("63b6"); var core = __webpack_require__("584a"); var fails = __webpack_require__("294c"); module.exports = function (KEY, exec) { var fn = (core.Object || {})[KEY] || Object[KEY]; var exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); }; /***/ }), /***/ "d0cb": /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin /***/ }), /***/ "d2d5": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("1654"); __webpack_require__("549b"); module.exports = __webpack_require__("584a").Array.from; /***/ }), /***/ "d3f4": /***/ (function(module, exports) { module.exports = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }), /***/ "d53b": /***/ (function(module, exports) { module.exports = function (done, value) { return { value: value, done: !!done }; }; /***/ }), /***/ "d864": /***/ (function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__("79aa"); module.exports = function (fn, that, length) { aFunction(fn); if (that === undefined) return fn; switch (length) { case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function (/* ...args */) { return fn.apply(that, arguments); }; }; /***/ }), /***/ "d8d6": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("1654"); __webpack_require__("6c1c"); module.exports = __webpack_require__("ccb9").f('iterator'); /***/ }), /***/ "d8e8": /***/ (function(module, exports) { module.exports = function (it) { if (typeof it != 'function') throw TypeError(it + ' is not a function!'); return it; }; /***/ }), /***/ "d9f6": /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__("e4ae"); var IE8_DOM_DEFINE = __webpack_require__("794b"); var toPrimitive = __webpack_require__("1bc3"); var dP = Object.defineProperty; exports.f = __webpack_require__("8e60") ? Object.defineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (IE8_DOM_DEFINE) try { return dP(O, P, Attributes); } catch (e) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; /***/ }), /***/ "dbdb": /***/ (function(module, exports, __webpack_require__) { var core = __webpack_require__("584a"); var global = __webpack_require__("e53d"); var SHARED = '__core-js_shared__'; var store = global[SHARED] || (global[SHARED] = {}); (module.exports = function (key, value) { return store[key] || (store[key] = value !== undefined ? value : {}); })('versions', []).push({ version: core.version, mode: __webpack_require__("b8e3") ? 'pure' : 'global', copyright: '© 2019 Denis Pushkarev (zloirock.ru)' }); /***/ }), /***/ "dc62": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("9427"); var $Object = __webpack_require__("584a").Object; module.exports = function create(P, D) { return $Object.create(P, D); }; /***/ }), /***/ "e11e": /***/ (function(module, exports) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); /***/ }), /***/ "e4ae": /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__("f772"); module.exports = function (it) { if (!isObject(it)) throw TypeError(it + ' is not an object!'); return it; }; /***/ }), /***/ "e53d": /***/ (function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self // eslint-disable-next-line no-new-func : Function('return this')(); if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef /***/ }), /***/ "e6f3": /***/ (function(module, exports, __webpack_require__) { var has = __webpack_require__("07e3"); var toIObject = __webpack_require__("36c3"); var arrayIndexOf = __webpack_require__("5b4e")(false); var IE_PROTO = __webpack_require__("5559")('IE_PROTO'); module.exports = function (object, names) { var O = toIObject(object); var i = 0; var result = []; var key; for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); // Don't enum bug & hidden keys while (names.length > i) if (has(O, key = names[i++])) { ~arrayIndexOf(result, key) || result.push(key); } return result; }; /***/ }), /***/ "ead6": /***/ (function(module, exports, __webpack_require__) { // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var isObject = __webpack_require__("f772"); var anObject = __webpack_require__("e4ae"); var check = function (O, proto) { anObject(O); if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); }; module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line function (test, buggy, set) { try { set = __webpack_require__("d864")(Function.call, __webpack_require__("bf0b").f(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch (e) { buggy = true; } return function setPrototypeOf(O, proto) { check(O, proto); if (buggy) O.__proto__ = proto; else set(O, proto); return O; }; }({}, false) : undefined), check: check }; /***/ }), /***/ "ebfd": /***/ (function(module, exports, __webpack_require__) { var META = __webpack_require__("62a0")('meta'); var isObject = __webpack_require__("f772"); var has = __webpack_require__("07e3"); var setDesc = __webpack_require__("d9f6").f; var id = 0; var isExtensible = Object.isExtensible || function () { return true; }; var FREEZE = !__webpack_require__("294c")(function () { return isExtensible(Object.preventExtensions({})); }); var setMeta = function (it) { setDesc(it, META, { value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs } }); }; var fastKey = function (it, create) { // return primitive with prefix if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if (!has(it, META)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return 'F'; // not necessary to add metadata if (!create) return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function (it, create) { if (!has(it, META)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return true; // not necessary to add metadata if (!create) return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function (it) { if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; /***/ }), /***/ "f410": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("1af6"); module.exports = __webpack_require__("584a").Array.isArray; /***/ }), /***/ "f6fd": /***/ (function(module, exports) { // document.currentScript polyfill by Adam Miller // MIT license (function(document){ var currentScript = "currentScript", scripts = document.getElementsByTagName('script'); // Live NodeList collection // If browser needs currentScript polyfill, add get currentScript() to the document object if (!(currentScript in document)) { Object.defineProperty(document, currentScript, { get: function(){ // IE 6-10 supports script readyState // IE 10+ support stack trace try { throw new Error(); } catch (err) { // Find the second match for the "at" string to get file src url from stack. // Specifically works with the format of stack traces in IE. var i, res = ((/.*at [^\(]*\((.*):.+:.+\)$/ig).exec(err.stack) || [false])[1]; // For all scripts on the page, if src matches or if ready state is interactive, return the script tag for(i in scripts){ if(scripts[i].src == res || scripts[i].readyState == "interactive"){ return scripts[i]; } } // If no match, return null return null; } } }); } })(document); /***/ }), /***/ "f772": /***/ (function(module, exports) { module.exports = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }), /***/ "f921": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("014b"); __webpack_require__("c207"); __webpack_require__("69d3"); __webpack_require__("765d"); module.exports = __webpack_require__("584a").Symbol; /***/ }), /***/ "fa5b": /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("5537")('native-function-to-string', Function.toString); /***/ }), /***/ "fa99": /***/ (function(module, exports, __webpack_require__) { __webpack_require__("0293"); module.exports = __webpack_require__("584a").Object.getPrototypeOf; /***/ }), /***/ "fab2": /***/ (function(module, exports, __webpack_require__) { var document = __webpack_require__("7726").document; module.exports = document && document.documentElement; /***/ }), /***/ "fb15": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); // CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/setPublicPath.js // This file is imported into lib/wc client bundles. if (typeof window !== 'undefined') { if (true) { __webpack_require__("f6fd") } var setPublicPath_i if ((setPublicPath_i = window.document.currentScript) && (setPublicPath_i = setPublicPath_i.src.match(/(.+\/)[^/]+\.js(\?.*)?$/))) { __webpack_require__.p = setPublicPath_i[1] // eslint-disable-line } } // Indicate to webpack that this file can be concatenated /* harmony default export */ var setPublicPath = (null); // EXTERNAL MODULE: ./node_modules/core-js/modules/web.dom.iterable.js var web_dom_iterable = __webpack_require__("ac6a"); // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"1ab05c31-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-checkbox/src/MyCheckbox.vue?vue&type=template&id=a767d046&scoped=true& var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('label',{staticClass:"checkbox-container",class:[{'is-checked': _vm.isChecked}, {'is-disabled': _vm.isDisabled}, {'is-switch': _vm.isSwitch}]},[_c('input',{directives:[{name:"model",rawName:"v-model",value:(_vm.selfValue),expression:"selfValue"}],staticClass:"checkbox-base",attrs:{"type":"checkbox","disabled":_vm.isDisabled},domProps:{"value":_vm.val,"checked":Array.isArray(_vm.selfValue)?_vm._i(_vm.selfValue,_vm.val)>-1:(_vm.selfValue)},on:{"click":_vm.handleClick,"change":function($event){var $$a=_vm.selfValue,$$el=$event.target,$$c=$$el.checked?(true):(false);if(Array.isArray($$a)){var $$v=_vm.val,$$i=_vm._i($$a,$$v);if($$el.checked){$$i<0&&(_vm.selfValue=$$a.concat([$$v]))}else{$$i>-1&&(_vm.selfValue=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}}else{_vm.selfValue=$$c}}}}),_vm._m(0),_c('span',{staticClass:"checkbox-label"},[_vm._v(_vm._s(_vm.isChecked))]),_vm._t("default")],2)} var staticRenderFns = [function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('span',{staticClass:"checkbox-box"},[_c('span',{staticClass:"checkbox-inner"})])}] // CONCATENATED MODULE: ./packages/my-checkbox/src/MyCheckbox.vue?vue&type=template&id=a767d046&scoped=true& // CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/classCallCheck.js function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // EXTERNAL MODULE: ./node_modules/@babel/runtime-corejs2/core-js/object/define-property.js var define_property = __webpack_require__("85f2"); var define_property_default = /*#__PURE__*/__webpack_require__.n(define_property); // CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/createClass.js function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; define_property_default()(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } // EXTERNAL MODULE: ./node_modules/@babel/runtime-corejs2/core-js/symbol/iterator.js var iterator = __webpack_require__("5d58"); var iterator_default = /*#__PURE__*/__webpack_require__.n(iterator); // EXTERNAL MODULE: ./node_modules/@babel/runtime-corejs2/core-js/symbol.js var symbol = __webpack_require__("67bb"); var symbol_default = /*#__PURE__*/__webpack_require__.n(symbol); // CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/typeof.js function typeof_typeof2(obj) { if (typeof symbol_default.a === "function" && typeof iterator_default.a === "symbol") { typeof_typeof2 = function _typeof2(obj) { return typeof obj; }; } else { typeof_typeof2 = function _typeof2(obj) { return obj && typeof symbol_default.a === "function" && obj.constructor === symbol_default.a && obj !== symbol_default.a.prototype ? "symbol" : typeof obj; }; } return typeof_typeof2(obj); } function typeof_typeof(obj) { if (typeof symbol_default.a === "function" && typeof_typeof2(iterator_default.a) === "symbol") { typeof_typeof = function _typeof(obj) { return typeof_typeof2(obj); }; } else { typeof_typeof = function _typeof(obj) { return obj && typeof symbol_default.a === "function" && obj.constructor === symbol_default.a && obj !== symbol_default.a.prototype ? "symbol" : typeof_typeof2(obj); }; } return typeof_typeof(obj); } // CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/assertThisInitialized.js function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } // CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/possibleConstructorReturn.js function _possibleConstructorReturn(self, call) { if (call && (typeof_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } // EXTERNAL MODULE: ./node_modules/@babel/runtime-corejs2/core-js/object/get-prototype-of.js var get_prototype_of = __webpack_require__("061b"); var get_prototype_of_default = /*#__PURE__*/__webpack_require__.n(get_prototype_of); // EXTERNAL MODULE: ./node_modules/@babel/runtime-corejs2/core-js/object/set-prototype-of.js var set_prototype_of = __webpack_require__("4d16"); var set_prototype_of_default = /*#__PURE__*/__webpack_require__.n(set_prototype_of); // CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/getPrototypeOf.js function getPrototypeOf_getPrototypeOf(o) { getPrototypeOf_getPrototypeOf = set_prototype_of_default.a ? get_prototype_of_default.a : function _getPrototypeOf(o) { return o.__proto__ || get_prototype_of_default()(o); }; return getPrototypeOf_getPrototypeOf(o); } // EXTERNAL MODULE: ./node_modules/@babel/runtime-corejs2/core-js/object/create.js var create = __webpack_require__("4aa6"); var create_default = /*#__PURE__*/__webpack_require__.n(create); // CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/setPrototypeOf.js function _setPrototypeOf(o, p) { _setPrototypeOf = set_prototype_of_default.a || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } // CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/inherits.js function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = create_default()(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } // CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.js /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; } return __assign.apply(this, arguments); } function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __exportStar(m, exports) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } function __values(o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result.default = mod; return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } // EXTERNAL MODULE: external {"commonjs":"vue","commonjs2":"vue","root":"Vue"} var external_commonjs_vue_commonjs2_vue_root_Vue_ = __webpack_require__("8bbf"); var external_commonjs_vue_commonjs2_vue_root_Vue_default = /*#__PURE__*/__webpack_require__.n(external_commonjs_vue_commonjs2_vue_root_Vue_); // CONCATENATED MODULE: ./node_modules/vue-class-component/dist/vue-class-component.esm.js /** * vue-class-component v7.1.0 * (c) 2015-present Evan You * @license MIT */ // The rational behind the verbose Reflect-feature check below is the fact that there are polyfills // which add an implementation for Reflect.defineMetadata but not for Reflect.getOwnMetadataKeys. // Without this check consumers will encounter hard to track down runtime errors. var reflectionIsSupported = typeof Reflect !== 'undefined' && Reflect.defineMetadata && Reflect.getOwnMetadataKeys; function copyReflectionMetadata(to, from) { forwardMetadata(to, from); Object.getOwnPropertyNames(from.prototype).forEach(function (key) { forwardMetadata(to.prototype, from.prototype, key); }); Object.getOwnPropertyNames(from).forEach(function (key) { forwardMetadata(to, from, key); }); } function forwardMetadata(to, from, propertyKey) { var metaKeys = propertyKey ? Reflect.getOwnMetadataKeys(from, propertyKey) : Reflect.getOwnMetadataKeys(from); metaKeys.forEach(function (metaKey) { var metadata = propertyKey ? Reflect.getOwnMetadata(metaKey, from, propertyKey) : Reflect.getOwnMetadata(metaKey, from); if (propertyKey) { Reflect.defineMetadata(metaKey, metadata, to, propertyKey); } else { Reflect.defineMetadata(metaKey, metadata, to); } }); } var fakeArray = { __proto__: [] }; var hasProto = fakeArray instanceof Array; function createDecorator(factory) { return function (target, key, index) { var Ctor = typeof target === 'function' ? target : target.constructor; if (!Ctor.__decorators__) { Ctor.__decorators__ = []; } if (typeof index !== 'number') { index = undefined; } Ctor.__decorators__.push(function (options) { return factory(options, key, index); }); }; } function mixins() { var Ctors = []; for (var _i = 0; _i < arguments.length; _i++) { Ctors[_i] = arguments[_i]; } return external_commonjs_vue_commonjs2_vue_root_Vue_default.a.extend({ mixins: Ctors }); } function isPrimitive(value) { var type = typeof value; return value == null || (type !== 'object' && type !== 'function'); } function warn(message) { if (typeof console !== 'undefined') { console.warn('[vue-class-component] ' + message); } } function collectDataFromConstructor(vm, Component) { // override _init to prevent to init as Vue instance var originalInit = Component.prototype._init; Component.prototype._init = function () { var _this = this; // proxy to actual vm var keys = Object.getOwnPropertyNames(vm); // 2.2.0 compat (props are no longer exposed as self properties) if (vm.$options.props) { for (var key in vm.$options.props) { if (!vm.hasOwnProperty(key)) { keys.push(key); } } } keys.forEach(function (key) { if (key.charAt(0) !== '_') { Object.defineProperty(_this, key, { get: function () { return vm[key]; }, set: function (value) { vm[key] = value; }, configurable: true }); } }); }; // should be acquired class property values var data = new Component(); // restore original _init to avoid memory leak (#209) Component.prototype._init = originalInit; // create plain data object var plainData = {}; Object.keys(data).forEach(function (key) { if (data[key] !== undefined) { plainData[key] = data[key]; } }); if (false) {} return plainData; } var $internalHooks = [ 'data', 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeDestroy', 'destroyed', 'beforeUpdate', 'updated', 'activated', 'deactivated', 'render', 'errorCaptured', 'serverPrefetch' // 2.6 ]; function componentFactory(Component, options) { if (options === void 0) { options = {}; } options.name = options.name || Component._componentTag || Component.name; // prototype props. var proto = Component.prototype; Object.getOwnPropertyNames(proto).forEach(function (key) { if (key === 'constructor') { return; } // hooks if ($internalHooks.indexOf(key) > -1) { options[key] = proto[key]; return; } var descriptor = Object.getOwnPropertyDescriptor(proto, key); if (descriptor.value !== void 0) { // methods if (typeof descriptor.value === 'function') { (options.methods || (options.methods = {}))[key] = descriptor.value; } else { // typescript decorated data (options.mixins || (options.mixins = [])).push({ data: function () { var _a; return _a = {}, _a[key] = descriptor.value, _a; } }); } } else if (descriptor.get || descriptor.set) { // computed properties (options.computed || (options.computed = {}))[key] = { get: descriptor.get, set: descriptor.set }; } }); (options.mixins || (options.mixins = [])).push({ data: function () { return collectDataFromConstructor(this, Component); } }); // decorate options var decorators = Component.__decorators__; if (decorators) { decorators.forEach(function (fn) { return fn(options); }); delete Component.__decorators__; } // find super var superProto = Object.getPrototypeOf(Component.prototype); var Super = superProto instanceof external_commonjs_vue_commonjs2_vue_root_Vue_default.a ? superProto.constructor : external_commonjs_vue_commonjs2_vue_root_Vue_default.a; var Extended = Super.extend(options); forwardStaticMembers(Extended, Component, Super); if (reflectionIsSupported) { copyReflectionMetadata(Extended, Component); } return Extended; } var reservedPropertyNames = [ // Unique id 'cid', // Super Vue constructor 'super', // Component options that will be used by the component 'options', 'superOptions', 'extendOptions', 'sealedOptions', // Private assets 'component', 'directive', 'filter' ]; var shouldIgnore = { prototype: true, arguments: true, callee: true, caller: true }; function forwardStaticMembers(Extended, Original, Super) { // We have to use getOwnPropertyNames since Babel registers methods as non-enumerable Object.getOwnPropertyNames(Original).forEach(function (key) { // Skip the properties that should not be overwritten if (shouldIgnore[key]) { return; } // Some browsers does not allow reconfigure built-in properties var extendedDescriptor = Object.getOwnPropertyDescriptor(Extended, key); if (extendedDescriptor && !extendedDescriptor.configurable) { return; } var descriptor = Object.getOwnPropertyDescriptor(Original, key); // If the user agent does not support `__proto__` or its family (IE <= 10), // the sub class properties may be inherited properties from the super class in TypeScript. // We need to exclude such properties to prevent to overwrite // the component options object which stored on the extended constructor (See #192). // If the value is a referenced value (object or function), // we can check equality of them and exclude it if they have the same reference. // If it is a primitive value, it will be forwarded for safety. if (!hasProto) { // Only `cid` is explicitly exluded from property forwarding // because we cannot detect whether it is a inherited property or not // on the no `__proto__` environment even though the property is reserved. if (key === 'cid') { return; } var superDescriptor = Object.getOwnPropertyDescriptor(Super, key); if (!isPrimitive(descriptor.value) && superDescriptor && superDescriptor.value === descriptor.value) { return; } } // Warn if the users manually declare reserved properties if (false) {} Object.defineProperty(Extended, key, descriptor); }); } function vue_class_component_esm_Component(options) { if (typeof options === 'function') { return componentFactory(options); } return function (Component) { return componentFactory(Component, options); }; } vue_class_component_esm_Component.registerHooks = function registerHooks(keys) { $internalHooks.push.apply($internalHooks, keys); }; /* harmony default export */ var vue_class_component_esm = (vue_class_component_esm_Component); // CONCATENATED MODULE: ./node_modules/vue-property-decorator/lib/vue-property-decorator.js /** vue-property-decorator verson 8.2.1 MIT LICENSE copyright 2019 kaorun343 */ /// <reference types='reflect-metadata'/> /** Used for keying reactive provide/inject properties */ var reactiveInjectKey = '__reactiveInject__'; /** * decorator of an inject * @param from key * @return PropertyDecorator */ function Inject(options) { return createDecorator(function (componentOptions, key) { if (typeof componentOptions.inject === 'undefined') { componentOptions.inject = {}; } if (!Array.isArray(componentOptions.inject)) { componentOptions.inject[key] = options || key; } }); } /** * decorator of a reactive inject * @param from key * @return PropertyDecorator */ function InjectReactive(options) { return createDecorator(function (componentOptions, key) { if (typeof componentOptions.inject === 'undefined') { componentOptions.inject = {}; } if (!Array.isArray(componentOptions.inject)) { var fromKey_1 = !!options ? options.from || options : key; var defaultVal_1 = (!!options && options.default) || undefined; if (!componentOptions.computed) componentOptions.computed = {}; componentOptions.computed[key] = function () { var obj = this[reactiveInjectKey]; return obj ? obj[fromKey_1] : defaultVal_1; }; componentOptions.inject[reactiveInjectKey] = reactiveInjectKey; } }); } /** * decorator of a provide * @param key key * @return PropertyDecorator | void */ function Provide(key) { return createDecorator(function (componentOptions, k) { var provide = componentOptions.provide; if (typeof provide !== 'function' || !provide.managed) { var original_1 = componentOptions.provide; provide = componentOptions.provide = function () { var rv = Object.create((typeof original_1 === 'function' ? original_1.call(this) : original_1) || null); for (var i in provide.managed) rv[provide.managed[i]] = this[i]; return rv; }; provide.managed = {}; } provide.managed[k] = key || k; }); } /** * decorator of a reactive provide * @param key key * @return PropertyDecorator | void */ function ProvideReactive(key) { return createDecorator(function (componentOptions, k) { var provide = componentOptions.provide; if (typeof provide !== 'function' || !provide.managed) { var original_2 = componentOptions.provide; provide = componentOptions.provide = function () { var _this = this; var rv = Object.create((typeof original_2 === 'function' ? original_2.call(this) : original_2) || null); rv[reactiveInjectKey] = {}; var _loop_1 = function (i) { rv[provide.managed[i]] = this_1[i]; // Duplicates the behavior of `@Provide` Object.defineProperty(rv[reactiveInjectKey], provide.managed[i], { enumerable: true, get: function () { return _this[i]; }, }); }; var this_1 = this; for (var i in provide.managed) { _loop_1(i); } return rv; }; provide.managed = {}; } provide.managed[k] = key || k; }); } /** @see {@link https://github.com/vuejs/vue-class-component/blob/master/src/reflect.ts} */ var reflectMetadataIsSupported = typeof Reflect !== 'undefined' && typeof Reflect.getMetadata !== 'undefined'; function applyMetadata(options, target, key) { if (reflectMetadataIsSupported) { if (!Array.isArray(options) && typeof options !== 'function' && typeof options.type === 'undefined') { options.type = Reflect.getMetadata('design:type', target, key); } } } /** * decorator of model * @param event event name * @param options options * @return PropertyDecorator */ function Model(event, options) { if (options === void 0) { options = {}; } return function (target, key) { applyMetadata(options, target, key); createDecorator(function (componentOptions, k) { ; (componentOptions.props || (componentOptions.props = {}))[k] = options; componentOptions.model = { prop: k, event: event || k }; })(target, key); }; } /** * decorator of a prop * @param options the options for the prop * @return PropertyDecorator | void */ function Prop(options) { if (options === void 0) { options = {}; } return function (target, key) { applyMetadata(options, target, key); createDecorator(function (componentOptions, k) { ; (componentOptions.props || (componentOptions.props = {}))[k] = options; })(target, key); }; } /** * decorator of a synced prop * @param propName the name to interface with from outside, must be different from decorated property * @param options the options for the synced prop * @return PropertyDecorator | void */ function PropSync(propName, options) { if (options === void 0) { options = {}; } // @ts-ignore return function (target, key) { applyMetadata(options, target, key); createDecorator(function (componentOptions, k) { ; (componentOptions.props || (componentOptions.props = {}))[propName] = options; (componentOptions.computed || (componentOptions.computed = {}))[k] = { get: function () { return this[propName]; }, set: function (value) { // @ts-ignore this.$emit("update:" + propName, value); }, }; })(target, key); }; } /** * decorator of a watch function * @param path the path or the expression to observe * @param WatchOption * @return MethodDecorator */ function Watch(path, options) { if (options === void 0) { options = {}; } var _a = options.deep, deep = _a === void 0 ? false : _a, _b = options.immediate, immediate = _b === void 0 ? false : _b; return createDecorator(function (componentOptions, handler) { if (typeof componentOptions.watch !== 'object') { componentOptions.watch = Object.create(null); } var watch = componentOptions.watch; if (typeof watch[path] === 'object' && !Array.isArray(watch[path])) { watch[path] = [watch[path]]; } else if (typeof watch[path] === 'undefined') { watch[path] = []; } watch[path].push({ handler: handler, deep: deep, immediate: immediate }); }); } // Code copied from Vue/src/shared/util.js var hyphenateRE = /\B([A-Z])/g; var hyphenate = function (str) { return str.replace(hyphenateRE, '-$1').toLowerCase(); }; /** * decorator of an event-emitter function * @param event The name of the event * @return MethodDecorator */ function Emit(event) { return function (_target, key, descriptor) { key = hyphenate(key); var original = descriptor.value; descriptor.value = function emitter() { var _this = this; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var emit = function (returnValue) { if (returnValue !== undefined) args.unshift(returnValue); _this.$emit.apply(_this, [event || key].concat(args)); }; var returnValue = original.apply(this, args); if (isPromise(returnValue)) { returnValue.then(function (returnValue) { emit(returnValue); }); } else { emit(returnValue); } return returnValue; }; }; } /** * decorator of a ref prop * @param refKey the ref key defined in template */ function Ref(refKey) { return createDecorator(function (options, key) { options.computed = options.computed || {}; options.computed[key] = { cache: false, get: function () { return this.$refs[refKey || key]; }, }; }); } function isPromise(obj) { return obj instanceof Promise || (obj && typeof obj.then === 'function'); } // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/ts-loader??ref--13-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-checkbox/src/MyCheckbox.vue?vue&type=script&lang=ts& var MyCheckboxvue_type_script_lang_ts_MyCheckbox = /*#__PURE__*/ function (_Vue) { _inherits(MyCheckbox, _Vue); function MyCheckbox() { _classCallCheck(this, MyCheckbox); return _possibleConstructorReturn(this, getPrototypeOf_getPrototypeOf(MyCheckbox).apply(this, arguments)); } _createClass(MyCheckbox, [{ key: "handleClick", /* 判断是否在组内 1. 在组内的话,将绑定值设置为当前按钮的值,执行set方法,将新值传递给组。 2. 单独使用,直接将绑定值取反即可。 */ value: function handleClick() { var isDisabled = this.isDisabled, isGroup = this.isGroup, selfValue = this.selfValue, val = this.val; if (!isDisabled) { this.selfValue = isGroup ? val : !selfValue; } } // 只在 isGroup 为 false 起作用 }, { key: "emitChange", value: function emitChange(newValue) { console.log(newValue); } }, { key: "isGroup", /* 动态属性 */ get: function get() { return this.$parent.$options['_componentTag'] === 'MyCheckboxGroup'; } }, { key: "isDisabled", get: function get() { return this.$parent.disabled || this.disabled; } }, { key: "isChecked", get: function get() { var isGroup = this.isGroup, propValue = this.propValue; if (!isGroup) { return propValue; } else { var val = this.val, selectItems = this.$parent.propValueArr; return selectItems.some(function (item) { return item === val; }); } } /* 判断当前值是否在组内 1. 是,返回最外层的数组 2. 否,返回父组件传过来的值 */ }, { key: "selfValue", get: function get() { return this.isGroup ? this.$parent.propValueArr : this.propValue; } /* 判断当前值是否在组内 1. 是,判断是否已经选中 1) 是,则调用组的方法,将当前值从数组中删除 2)否,则调用组的方法,将当前值添加到数组中 2. 否,将新值返回给组 */ , set: function set(newValue) { var isGroup = this.isGroup, isChecked = this.isChecked; if (isGroup) { isChecked ? this.$parent.deleteItem(newValue) : this.$parent.selectItem(newValue); } else { this.emitChange(newValue); } } }]); return MyCheckbox; }(external_commonjs_vue_commonjs2_vue_root_Vue_default.a); __decorate([Prop()], MyCheckboxvue_type_script_lang_ts_MyCheckbox.prototype, "label", void 0); __decorate([Prop({ default: true })], MyCheckboxvue_type_script_lang_ts_MyCheckbox.prototype, "val", void 0); __decorate([Prop({ default: false })], MyCheckboxvue_type_script_lang_ts_MyCheckbox.prototype, "disabled", void 0); __decorate([Prop({ default: false })], MyCheckboxvue_type_script_lang_ts_MyCheckbox.prototype, "isSwitch", void 0); __decorate([Model('change')], MyCheckboxvue_type_script_lang_ts_MyCheckbox.prototype, "propValue", void 0); __decorate([Emit('change')], MyCheckboxvue_type_script_lang_ts_MyCheckbox.prototype, "emitChange", null); MyCheckboxvue_type_script_lang_ts_MyCheckbox = __decorate([vue_class_component_esm({ name: 'MyCheckbox', mounted: function mounted() {} })], MyCheckboxvue_type_script_lang_ts_MyCheckbox); /* harmony default export */ var MyCheckboxvue_type_script_lang_ts_ = (MyCheckboxvue_type_script_lang_ts_MyCheckbox); // CONCATENATED MODULE: ./packages/my-checkbox/src/MyCheckbox.vue?vue&type=script&lang=ts& /* harmony default export */ var src_MyCheckboxvue_type_script_lang_ts_ = (MyCheckboxvue_type_script_lang_ts_); // EXTERNAL MODULE: ./packages/my-checkbox/src/MyCheckbox.vue?vue&type=style&index=0&id=a767d046&lang=scss&rel=stylesheet%2Fscss&scoped=true& var MyCheckboxvue_type_style_index_0_id_a767d046_lang_scss_rel_stylesheet_2Fscss_scoped_true_ = __webpack_require__("bffd"); // CONCATENATED MODULE: ./node_modules/vue-loader/lib/runtime/componentNormalizer.js /* globals __VUE_SSR_CONTEXT__ */ // IMPORTANT: Do NOT use ES2015 features in this file (except for modules). // This module is a runtime utility for cleaner component module output and will // be included in the final webpack user bundle. function normalizeComponent ( scriptExports, render, staticRenderFns, functionalTemplate, injectStyles, scopeId, moduleIdentifier, /* server only */ shadowMode /* vue-cli only */ ) { // Vue.extend constructor export interop var options = typeof scriptExports === 'function' ? scriptExports.options : scriptExports // render functions if (render) { options.render = render options.staticRenderFns = staticRenderFns options._compiled = true } // functional template if (functionalTemplate) { options.functional = true } // scopedId if (scopeId) { options._scopeId = 'data-v-' + scopeId } var hook if (moduleIdentifier) { // server build hook = function (context) { // 2.3 injection context = context || // cached call (this.$vnode && this.$vnode.ssrContext) || // stateful (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional // 2.2 with runInNewContext: true if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { context = __VUE_SSR_CONTEXT__ } // inject component styles if (injectStyles) { injectStyles.call(this, context) } // register component module identifier for async chunk inferrence if (context && context._registeredComponents) { context._registeredComponents.add(moduleIdentifier) } } // used by ssr in case component is cached and beforeCreate // never gets called options._ssrRegister = hook } else if (injectStyles) { hook = shadowMode ? function () { injectStyles.call(this, this.$root.$options.shadowRoot) } : injectStyles } if (hook) { if (options.functional) { // for template-only hot-reload because in that case the render fn doesn't // go through the normalizer options._injectStyles = hook // register for functioal component in vue file var originalRender = options.render options.render = function renderWithStyleInjection (h, context) { hook.call(context) return originalRender(h, context) } } else { // inject component registration as beforeCreate hook var existing = options.beforeCreate options.beforeCreate = existing ? [].concat(existing, hook) : [hook] } } return { exports: scriptExports, options: options } } // CONCATENATED MODULE: ./packages/my-checkbox/src/MyCheckbox.vue /* normalize component */ var component = normalizeComponent( src_MyCheckboxvue_type_script_lang_ts_, render, staticRenderFns, false, null, "a767d046", null ) /* harmony default export */ var src_MyCheckbox = (component.exports); // CONCATENATED MODULE: ./packages/my-checkbox/index.ts // 导入组件,组件必须声明name // 为组件提供install安装方法,供按需引入 src_MyCheckbox.install = function (Vue) { Vue.component('MyCheckbox', src_MyCheckbox); }; // 默认导出组件 /* harmony default export */ var my_checkbox = (src_MyCheckbox); // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"1ab05c31-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-checkbox-group/src/MyCheckboxGroup.vue?vue&type=template&id=1cbe62ae&scoped=true& var MyCheckboxGroupvue_type_template_id_1cbe62ae_scoped_true_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"checkbox-group-container",class:{'is-disabled': _vm.disabled},attrs:{"name":"checkbox-group"}},[_vm._t("default")],2)} var MyCheckboxGroupvue_type_template_id_1cbe62ae_scoped_true_staticRenderFns = [] // CONCATENATED MODULE: ./packages/my-checkbox-group/src/MyCheckboxGroup.vue?vue&type=template&id=1cbe62ae&scoped=true& // EXTERNAL MODULE: ./node_modules/@babel/runtime-corejs2/core-js/array/is-array.js var is_array = __webpack_require__("a745"); var is_array_default = /*#__PURE__*/__webpack_require__.n(is_array); // CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/arrayWithoutHoles.js function _arrayWithoutHoles(arr) { if (is_array_default()(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } // EXTERNAL MODULE: ./node_modules/@babel/runtime-corejs2/core-js/array/from.js var from = __webpack_require__("774e"); var from_default = /*#__PURE__*/__webpack_require__.n(from); // EXTERNAL MODULE: ./node_modules/@babel/runtime-corejs2/core-js/is-iterable.js var is_iterable = __webpack_require__("c8bb"); var is_iterable_default = /*#__PURE__*/__webpack_require__.n(is_iterable); // CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/iterableToArray.js function _iterableToArray(iter) { if (is_iterable_default()(Object(iter)) || Object.prototype.toString.call(iter) === "[object Arguments]") return from_default()(iter); } // CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/nonIterableSpread.js function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } // CONCATENATED MODULE: ./node_modules/@babel/runtime-corejs2/helpers/esm/toConsumableArray.js function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/ts-loader??ref--13-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-checkbox-group/src/MyCheckboxGroup.vue?vue&type=script&lang=ts& var MyCheckboxGroupvue_type_script_lang_ts_MyCheckboxGroup = /*#__PURE__*/ function (_Vue) { _inherits(MyCheckboxGroup, _Vue); function MyCheckboxGroup() { _classCallCheck(this, MyCheckboxGroup); return _possibleConstructorReturn(this, getPrototypeOf_getPrototypeOf(MyCheckboxGroup).apply(this, arguments)); } _createClass(MyCheckboxGroup, [{ key: "onChangePropValueArr", value: function onChangePropValueArr(newValue) { this.emitInput(newValue); } // 将新值添加到数组中 }, { key: "selectItem", value: function selectItem(item) { var propValueArr = this.propValueArr; this.emitInput([].concat(_toConsumableArray(propValueArr), [item])); } // 将新值从数组中删除 }, { key: "deleteItem", value: function deleteItem(item) { var propValueArr = this.propValueArr; this.emitInput(propValueArr.filter(function (selectItem) { return selectItem !== item; })); } }, { key: "emitInput", value: function emitInput(realArr) { console.log(realArr); } }]); return MyCheckboxGroup; }(external_commonjs_vue_commonjs2_vue_root_Vue_default.a); __decorate([Prop()], MyCheckboxGroupvue_type_script_lang_ts_MyCheckboxGroup.prototype, "labelArr", void 0); __decorate([Prop()], MyCheckboxGroupvue_type_script_lang_ts_MyCheckboxGroup.prototype, "valArr", void 0); __decorate([Prop({ default: false })], MyCheckboxGroupvue_type_script_lang_ts_MyCheckboxGroup.prototype, "disabled", void 0); __decorate([Model('change', {})], MyCheckboxGroupvue_type_script_lang_ts_MyCheckboxGroup.prototype, "propValueArr", void 0); __decorate([Watch('propValueArr')], MyCheckboxGroupvue_type_script_lang_ts_MyCheckboxGroup.prototype, "onChangePropValueArr", null); __decorate([Emit('change')], MyCheckboxGroupvue_type_script_lang_ts_MyCheckboxGroup.prototype, "emitInput", null); MyCheckboxGroupvue_type_script_lang_ts_MyCheckboxGroup = __decorate([vue_class_component_esm({ name: 'MyCheckboxGroup', mounted: function mounted() {} })], MyCheckboxGroupvue_type_script_lang_ts_MyCheckboxGroup); /* harmony default export */ var MyCheckboxGroupvue_type_script_lang_ts_ = (MyCheckboxGroupvue_type_script_lang_ts_MyCheckboxGroup); // CONCATENATED MODULE: ./packages/my-checkbox-group/src/MyCheckboxGroup.vue?vue&type=script&lang=ts& /* harmony default export */ var src_MyCheckboxGroupvue_type_script_lang_ts_ = (MyCheckboxGroupvue_type_script_lang_ts_); // EXTERNAL MODULE: ./packages/my-checkbox-group/src/MyCheckboxGroup.vue?vue&type=style&index=0&id=1cbe62ae&lang=scss&rel=stylesheet%2Fscss&scoped=true& var MyCheckboxGroupvue_type_style_index_0_id_1cbe62ae_lang_scss_rel_stylesheet_2Fscss_scoped_true_ = __webpack_require__("1ca4"); // CONCATENATED MODULE: ./packages/my-checkbox-group/src/MyCheckboxGroup.vue /* normalize component */ var MyCheckboxGroup_component = normalizeComponent( src_MyCheckboxGroupvue_type_script_lang_ts_, MyCheckboxGroupvue_type_template_id_1cbe62ae_scoped_true_render, MyCheckboxGroupvue_type_template_id_1cbe62ae_scoped_true_staticRenderFns, false, null, "1cbe62ae", null ) /* harmony default export */ var src_MyCheckboxGroup = (MyCheckboxGroup_component.exports); // CONCATENATED MODULE: ./packages/my-checkbox-group/index.ts // 导入组件,组件必须声明name // 为组件提供install安装方法,供按需引入 src_MyCheckboxGroup.install = function (Vue) { Vue.component('MyCheckboxGroup', src_MyCheckboxGroup); }; // 默认导出组件 /* harmony default export */ var my_checkbox_group = (src_MyCheckboxGroup); // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"1ab05c31-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-button/src/MyButton.vue?vue&type=template&id=7664fdda&scoped=true& var MyButtonvue_type_template_id_7664fdda_scoped_true_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"btn-container",class:[{'is-loading':_vm.isLoading},{'is-disabled': _vm.disabled}]},[_c('button',{staticClass:"btn",attrs:{"disabled":_vm.disabled},on:{"click":_vm.handleClick}},[_vm._v(_vm._s(_vm.label))]),_c('span',{class:{'loading':_vm.isLoading}})])} var MyButtonvue_type_template_id_7664fdda_scoped_true_staticRenderFns = [] // CONCATENATED MODULE: ./packages/my-button/src/MyButton.vue?vue&type=template&id=7664fdda&scoped=true& // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/ts-loader??ref--13-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-button/src/MyButton.vue?vue&type=script&lang=ts& var MyButtonvue_type_script_lang_ts_MyButton = /*#__PURE__*/ function (_Vue) { _inherits(MyButton, _Vue); function MyButton() { _classCallCheck(this, MyButton); return _possibleConstructorReturn(this, getPrototypeOf_getPrototypeOf(MyButton).apply(this, arguments)); } _createClass(MyButton, [{ key: "handleClick", value: function handleClick() { this.emitClick(); } }, { key: "emitClick", value: function emitClick() {} }]); return MyButton; }(external_commonjs_vue_commonjs2_vue_root_Vue_default.a); __decorate([Prop()], MyButtonvue_type_script_lang_ts_MyButton.prototype, "label", void 0); __decorate([Prop({ default: false })], MyButtonvue_type_script_lang_ts_MyButton.prototype, "disabled", void 0); __decorate([Prop({ type: Boolean, default: false })], MyButtonvue_type_script_lang_ts_MyButton.prototype, "isLoading", void 0); __decorate([Emit("click")], MyButtonvue_type_script_lang_ts_MyButton.prototype, "emitClick", null); MyButtonvue_type_script_lang_ts_MyButton = __decorate([vue_class_component_esm({ name: "MyButton", mounted: function mounted() {} })], MyButtonvue_type_script_lang_ts_MyButton); /* harmony default export */ var MyButtonvue_type_script_lang_ts_ = (MyButtonvue_type_script_lang_ts_MyButton); // CONCATENATED MODULE: ./packages/my-button/src/MyButton.vue?vue&type=script&lang=ts& /* harmony default export */ var src_MyButtonvue_type_script_lang_ts_ = (MyButtonvue_type_script_lang_ts_); // EXTERNAL MODULE: ./packages/my-button/src/MyButton.vue?vue&type=style&index=0&id=7664fdda&lang=scss&rel=stylesheet%2Fscss&scoped=true& var MyButtonvue_type_style_index_0_id_7664fdda_lang_scss_rel_stylesheet_2Fscss_scoped_true_ = __webpack_require__("ccf2"); // CONCATENATED MODULE: ./packages/my-button/src/MyButton.vue /* normalize component */ var MyButton_component = normalizeComponent( src_MyButtonvue_type_script_lang_ts_, MyButtonvue_type_template_id_7664fdda_scoped_true_render, MyButtonvue_type_template_id_7664fdda_scoped_true_staticRenderFns, false, null, "7664fdda", null ) /* harmony default export */ var src_MyButton = (MyButton_component.exports); // CONCATENATED MODULE: ./packages/my-button/index.ts // 导入组件,组件必须声明name // 为组件提供install安装方法,供按需引入 src_MyButton.install = function (Vue) { Vue.component('MyButton', src_MyButton); }; // 默认导出组件 /* harmony default export */ var my_button = (src_MyButton); // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"1ab05c31-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-radio/src/MyRadio.vue?vue&type=template&id=0eb575c5&scoped=true& var MyRadiovue_type_template_id_0eb575c5_scoped_true_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('label',{staticClass:"radio-container",class:[{'is-disabled': _vm.isDisabled}]},[_c('input',{directives:[{name:"model",rawName:"v-model",value:(_vm.selfValue),expression:"selfValue"}],staticClass:"radio-base",attrs:{"type":"radio","disabled":_vm.isDisabled},domProps:{"value":_vm.val,"checked":_vm._q(_vm.selfValue,_vm.val)},on:{"click":_vm.handleClick,"change":function($event){_vm.selfValue=_vm.val}}}),_vm._m(0),_c('span',{staticClass:"radio-label"},[_vm._v(_vm._s(_vm.label))]),_vm._t("default")],2)} var MyRadiovue_type_template_id_0eb575c5_scoped_true_staticRenderFns = [function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('span',{staticClass:"radio-box"},[_c('span',{staticClass:"radio-inner"})])}] // CONCATENATED MODULE: ./packages/my-radio/src/MyRadio.vue?vue&type=template&id=0eb575c5&scoped=true& // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/ts-loader??ref--13-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-radio/src/MyRadio.vue?vue&type=script&lang=ts& var MyRadiovue_type_script_lang_ts_MyRadio = /*#__PURE__*/ function (_Vue) { _inherits(MyRadio, _Vue); function MyRadio() { _classCallCheck(this, MyRadio); return _possibleConstructorReturn(this, getPrototypeOf_getPrototypeOf(MyRadio).apply(this, arguments)); } _createClass(MyRadio, [{ key: "handleClick", value: function handleClick() { !this.isDisabled && (this.selfValue = this.val); } }, { key: "emitChange", value: function emitChange(newValue) {} }, { key: "isGroup", get: function get() { return this.$parent.$options['_componentTag'] === 'MyRadioGroup'; } }, { key: "isDisabled", get: function get() { return this.$parent.disabled || this.disabled; } }, { key: "selfValue", get: function get() { return this.isGroup ? this.$parent.propValueArr : this.propValue; }, set: function set(newValue) { this.isGroup ? this.$parent.emitChange(newValue) : this.emitChange(newValue); } }]); return MyRadio; }(external_commonjs_vue_commonjs2_vue_root_Vue_default.a); __decorate([Prop()], MyRadiovue_type_script_lang_ts_MyRadio.prototype, "label", void 0); __decorate([Prop()], MyRadiovue_type_script_lang_ts_MyRadio.prototype, "val", void 0); __decorate([Prop({ default: false })], MyRadiovue_type_script_lang_ts_MyRadio.prototype, "disabled", void 0); __decorate([Model('change', {})], MyRadiovue_type_script_lang_ts_MyRadio.prototype, "propValue", void 0); __decorate([Emit('change')], MyRadiovue_type_script_lang_ts_MyRadio.prototype, "emitChange", null); MyRadiovue_type_script_lang_ts_MyRadio = __decorate([vue_class_component_esm({ name: 'MyRadio', mounted: function mounted() {} })], MyRadiovue_type_script_lang_ts_MyRadio); /* harmony default export */ var MyRadiovue_type_script_lang_ts_ = (MyRadiovue_type_script_lang_ts_MyRadio); // CONCATENATED MODULE: ./packages/my-radio/src/MyRadio.vue?vue&type=script&lang=ts& /* harmony default export */ var src_MyRadiovue_type_script_lang_ts_ = (MyRadiovue_type_script_lang_ts_); // EXTERNAL MODULE: ./packages/my-radio/src/MyRadio.vue?vue&type=style&index=0&id=0eb575c5&lang=scss&rel=stylesheet%2Fscss&scoped=true& var MyRadiovue_type_style_index_0_id_0eb575c5_lang_scss_rel_stylesheet_2Fscss_scoped_true_ = __webpack_require__("c22d"); // CONCATENATED MODULE: ./packages/my-radio/src/MyRadio.vue /* normalize component */ var MyRadio_component = normalizeComponent( src_MyRadiovue_type_script_lang_ts_, MyRadiovue_type_template_id_0eb575c5_scoped_true_render, MyRadiovue_type_template_id_0eb575c5_scoped_true_staticRenderFns, false, null, "0eb575c5", null ) /* harmony default export */ var src_MyRadio = (MyRadio_component.exports); // CONCATENATED MODULE: ./packages/my-radio/index.ts // 导入组件,组件必须声明name // 为组件提供install安装方法,供按需引入 src_MyRadio.install = function (Vue) { Vue.component('MyRadio', src_MyRadio); }; // 默认导出组件 /* harmony default export */ var my_radio = (src_MyRadio); // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"1ab05c31-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-radio-group/src/MyRadioGroup.vue?vue&type=template&id=07f8ba8a&scoped=true& var MyRadioGroupvue_type_template_id_07f8ba8a_scoped_true_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"radio-group-container",class:[{'is-disabled': _vm.disabled}, {'is-btn-group': _vm.isBtnGroup}],attrs:{"name":"checkbox-group"}},[_vm._t("default")],2)} var MyRadioGroupvue_type_template_id_07f8ba8a_scoped_true_staticRenderFns = [] // CONCATENATED MODULE: ./packages/my-radio-group/src/MyRadioGroup.vue?vue&type=template&id=07f8ba8a&scoped=true& // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/ts-loader??ref--13-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-radio-group/src/MyRadioGroup.vue?vue&type=script&lang=ts& var MyRadioGroupvue_type_script_lang_ts_MyRadioGroup = /*#__PURE__*/ function (_Vue) { _inherits(MyRadioGroup, _Vue); function MyRadioGroup() { _classCallCheck(this, MyRadioGroup); return _possibleConstructorReturn(this, getPrototypeOf_getPrototypeOf(MyRadioGroup).apply(this, arguments)); } _createClass(MyRadioGroup, [{ key: "onChangePropValueArr", value: function onChangePropValueArr(newValue) { this.emitChange(newValue); } }, { key: "emitChange", value: function emitChange(newValue) {} }]); return MyRadioGroup; }(external_commonjs_vue_commonjs2_vue_root_Vue_default.a); __decorate([Prop({ default: false })], MyRadioGroupvue_type_script_lang_ts_MyRadioGroup.prototype, "disabled", void 0); __decorate([Prop({ default: false })], MyRadioGroupvue_type_script_lang_ts_MyRadioGroup.prototype, "isBtnGroup", void 0); __decorate([Model('change', {})], MyRadioGroupvue_type_script_lang_ts_MyRadioGroup.prototype, "propValueArr", void 0); __decorate([Watch('propValueArr')], MyRadioGroupvue_type_script_lang_ts_MyRadioGroup.prototype, "onChangePropValueArr", null); __decorate([Emit('change')], MyRadioGroupvue_type_script_lang_ts_MyRadioGroup.prototype, "emitChange", null); MyRadioGroupvue_type_script_lang_ts_MyRadioGroup = __decorate([vue_class_component_esm({})], MyRadioGroupvue_type_script_lang_ts_MyRadioGroup); /* harmony default export */ var MyRadioGroupvue_type_script_lang_ts_ = (MyRadioGroupvue_type_script_lang_ts_MyRadioGroup); // CONCATENATED MODULE: ./packages/my-radio-group/src/MyRadioGroup.vue?vue&type=script&lang=ts& /* harmony default export */ var src_MyRadioGroupvue_type_script_lang_ts_ = (MyRadioGroupvue_type_script_lang_ts_); // EXTERNAL MODULE: ./packages/my-radio-group/src/MyRadioGroup.vue?vue&type=style&index=0&id=07f8ba8a&lang=scss&rel=stylesheet%2Fscss&scoped=true& var MyRadioGroupvue_type_style_index_0_id_07f8ba8a_lang_scss_rel_stylesheet_2Fscss_scoped_true_ = __webpack_require__("aee8"); // CONCATENATED MODULE: ./packages/my-radio-group/src/MyRadioGroup.vue /* normalize component */ var MyRadioGroup_component = normalizeComponent( src_MyRadioGroupvue_type_script_lang_ts_, MyRadioGroupvue_type_template_id_07f8ba8a_scoped_true_render, MyRadioGroupvue_type_template_id_07f8ba8a_scoped_true_staticRenderFns, false, null, "07f8ba8a", null ) /* harmony default export */ var src_MyRadioGroup = (MyRadioGroup_component.exports); // CONCATENATED MODULE: ./packages/my-radio-group/index.ts // 导入组件,组件必须声明name // 为组件提供install安装方法,供按需引入 src_MyRadioGroup.install = function (Vue) { Vue.component('MyRadioGroup', src_MyRadioGroup); }; // 默认导出组件 /* harmony default export */ var my_radio_group = (src_MyRadioGroup); // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"1ab05c31-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-input/src/MySelect.vue?vue&type=template&id=16661b44&scoped=true& var MyInputvue_type_template_id_16661b44_scoped_true_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"input-container"},[((_vm.type)==='checkbox')?_c('input',{directives:[{name:"model",rawName:"v-model",value:(_vm.selfVal),expression:"selfVal"}],staticClass:"input",attrs:{"placeholder":_vm.placeholder,"type":"checkbox"},domProps:{"checked":Array.isArray(_vm.selfVal)?_vm._i(_vm.selfVal,null)>-1:(_vm.selfVal)},on:{"blur":_vm.handleBlur,"change":function($event){var $$a=_vm.selfVal,$$el=$event.target,$$c=$$el.checked?(true):(false);if(Array.isArray($$a)){var $$v=null,$$i=_vm._i($$a,$$v);if($$el.checked){$$i<0&&(_vm.selfVal=$$a.concat([$$v]))}else{$$i>-1&&(_vm.selfVal=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}}else{_vm.selfVal=$$c}}}}):((_vm.type)==='radio')?_c('input',{directives:[{name:"model",rawName:"v-model",value:(_vm.selfVal),expression:"selfVal"}],staticClass:"input",attrs:{"placeholder":_vm.placeholder,"type":"radio"},domProps:{"checked":_vm._q(_vm.selfVal,null)},on:{"blur":_vm.handleBlur,"change":function($event){_vm.selfVal=null}}}):_c('input',{directives:[{name:"model",rawName:"v-model",value:(_vm.selfVal),expression:"selfVal"}],staticClass:"input",attrs:{"placeholder":_vm.placeholder,"type":_vm.type},domProps:{"value":(_vm.selfVal)},on:{"blur":_vm.handleBlur,"input":function($event){if($event.target.composing){ return; }_vm.selfVal=$event.target.value}}})])} var MyInputvue_type_template_id_16661b44_scoped_true_staticRenderFns = [] // CONCATENATED MODULE: ./packages/my-input/src/MySelect.vue?vue&type=template&id=16661b44&scoped=true& // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/ts-loader??ref--13-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-input/src/MySelect.vue?vue&type=script&lang=ts& var MyInputvue_type_script_lang_ts_MyInput = /*#__PURE__*/ function (_Vue) { _inherits(MyInput, _Vue); function MyInput() { _classCallCheck(this, MyInput); return _possibleConstructorReturn(this, getPrototypeOf_getPrototypeOf(MyInput).apply(this, arguments)); } _createClass(MyInput, [{ key: "handleFocus", value: function handleFocus() { console.log('我获得了焦点'); } }, { key: "handleBlur", value: function handleBlur() { console.log('我失去了焦点'); this.emitBlur(); } }, { key: "emitChange", value: function emitChange(newValue) {} }, { key: "emitBlur", value: function emitBlur() { if (this.$parent.isNeedCheck) { this.$parent.onChangeFormResult(this.selfVal); } } }, { key: "selfVal", get: function get() { return this.propVal; }, set: function set(newValue) { this.emitChange(newValue); } }]); return MyInput; }(external_commonjs_vue_commonjs2_vue_root_Vue_default.a); __decorate([Prop()], MyInputvue_type_script_lang_ts_MyInput.prototype, "placeholder", void 0); __decorate([Prop()], MyInputvue_type_script_lang_ts_MyInput.prototype, "type", void 0); __decorate([Model('change')], MyInputvue_type_script_lang_ts_MyInput.prototype, "propVal", void 0); __decorate([Emit('change')], MyInputvue_type_script_lang_ts_MyInput.prototype, "emitChange", null); __decorate([Emit('blur')], MyInputvue_type_script_lang_ts_MyInput.prototype, "emitBlur", null); MyInputvue_type_script_lang_ts_MyInput = __decorate([vue_class_component_esm({ name: "MyInput", mounted: function mounted() {} })], MyInputvue_type_script_lang_ts_MyInput); /* harmony default export */ var MyInputvue_type_script_lang_ts_ = (MyInputvue_type_script_lang_ts_MyInput); // CONCATENATED MODULE: ./packages/my-input/src/MySelect.vue?vue&type=script&lang=ts& /* harmony default export */ var src_MyInputvue_type_script_lang_ts_ = (MyInputvue_type_script_lang_ts_); // EXTERNAL MODULE: ./packages/my-input/src/MySelect.vue?vue&type=style&index=0&id=16661b44&lang=scss&rel=stylesheet%2Fscss&scoped=true& var MyInputvue_type_style_index_0_id_16661b44_lang_scss_rel_stylesheet_2Fscss_scoped_true_ = __webpack_require__("a45b"); // CONCATENATED MODULE: ./packages/my-input/src/MySelect.vue /* normalize component */ var MyInput_component = normalizeComponent( src_MyInputvue_type_script_lang_ts_, MyInputvue_type_template_id_16661b44_scoped_true_render, MyInputvue_type_template_id_16661b44_scoped_true_staticRenderFns, false, null, "16661b44", null ) /* harmony default export */ var src_MyInput = (MyInput_component.exports); // CONCATENATED MODULE: ./packages/my-input/index.ts // 导入组件,组件必须声明name // 为组件提供install安装方法,供按需引入 src_MyInput.install = function (Vue) { Vue.component('MyInput', src_MyInput); }; // 默认导出组件 /* harmony default export */ var my_input = (src_MyInput); // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"1ab05c31-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-form-item/src/MyFormItem.vue?vue&type=template&id=fa83a2d8&scoped=true& var MyFormItemvue_type_template_id_fa83a2d8_scoped_true_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"form-item",class:[{'form-item-true': _vm.selfResult === true}, {'form-item-false': _vm.selfResult === false}]},[(_vm.label)?_c('span',{staticClass:"form-item-label"},[(_vm.isNeedCheck)?_c('i',{staticClass:"require-icon"},[_vm._v("*")]):_vm._e(),_vm._v(_vm._s(_vm.label)+"\n ")]):_vm._e(),_c('div',{staticClass:"form-item-content"},[_vm._t("default"),_c('span',{staticClass:"errorText"},[_vm._v(_vm._s(_vm.errorText))])],2)])} var MyFormItemvue_type_template_id_fa83a2d8_scoped_true_staticRenderFns = [] // CONCATENATED MODULE: ./packages/my-form-item/src/MyFormItem.vue?vue&type=template&id=fa83a2d8&scoped=true& // EXTERNAL MODULE: ./node_modules/core-js/modules/es6.function.name.js var es6_function_name = __webpack_require__("7f7f"); // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/ts-loader??ref--13-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-form-item/src/MyFormItem.vue?vue&type=script&lang=ts& var MyFormItemvue_type_script_lang_ts_MyFormItem = /*#__PURE__*/ function (_Vue) { _inherits(MyFormItem, _Vue); function MyFormItem() { var _this; _classCallCheck(this, MyFormItem); _this = _possibleConstructorReturn(this, getPrototypeOf_getPrototypeOf(MyFormItem).apply(this, arguments)); _this.selfResult = ''; _this.errorText = ''; return _this; } _createClass(MyFormItem, [{ key: "onChangeFormResult", // @Watch('selfVal') value: function onChangeFormResult(newValue) { // 校验结果,并保存在form对象上,同时判断所有校验是否正确 this.errorText = this.validFunc(newValue); this.selfResult = this.errorText === ''; this.$parent.formResult[this.name + 'Result'] = this.selfResult; this.$parent.validForm(); } }, { key: "selfVal", get: function get() { return this.$parent.formResult[this.name]; } }, { key: "isNeedCheck", get: function get() { var _this2 = this; return this.$parent.validItemArr.some(function (item) { return item === _this2.name; }); } }]); return MyFormItem; }(external_commonjs_vue_commonjs2_vue_root_Vue_default.a); __decorate([Prop()], MyFormItemvue_type_script_lang_ts_MyFormItem.prototype, "label", void 0); __decorate([Prop()], MyFormItemvue_type_script_lang_ts_MyFormItem.prototype, "validFunc", void 0); __decorate([Prop()], MyFormItemvue_type_script_lang_ts_MyFormItem.prototype, "name", void 0); MyFormItemvue_type_script_lang_ts_MyFormItem = __decorate([vue_class_component_esm({ name: "MyFormItem" })], MyFormItemvue_type_script_lang_ts_MyFormItem); /* harmony default export */ var MyFormItemvue_type_script_lang_ts_ = (MyFormItemvue_type_script_lang_ts_MyFormItem); // CONCATENATED MODULE: ./packages/my-form-item/src/MyFormItem.vue?vue&type=script&lang=ts& /* harmony default export */ var src_MyFormItemvue_type_script_lang_ts_ = (MyFormItemvue_type_script_lang_ts_); // EXTERNAL MODULE: ./packages/my-form-item/src/MyFormItem.vue?vue&type=style&index=0&id=fa83a2d8&lang=scss&rel=stylesheet%2Fscss&scoped=true& var MyFormItemvue_type_style_index_0_id_fa83a2d8_lang_scss_rel_stylesheet_2Fscss_scoped_true_ = __webpack_require__("1136"); // CONCATENATED MODULE: ./packages/my-form-item/src/MyFormItem.vue /* normalize component */ var MyFormItem_component = normalizeComponent( src_MyFormItemvue_type_script_lang_ts_, MyFormItemvue_type_template_id_fa83a2d8_scoped_true_render, MyFormItemvue_type_template_id_fa83a2d8_scoped_true_staticRenderFns, false, null, "fa83a2d8", null ) /* harmony default export */ var src_MyFormItem = (MyFormItem_component.exports); // CONCATENATED MODULE: ./packages/my-form-item/index.ts // 导入组件,组件必须声明name // 为组件提供install安装方法,供按需引入 src_MyFormItem.install = function (Vue) { Vue.component('MyFormItem', src_MyFormItem); }; // 默认导出组件 /* harmony default export */ var my_form_item = (src_MyFormItem); // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"1ab05c31-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-form/src/MyForm.vue?vue&type=template&id=69644ca8&scoped=true& var MyFormvue_type_template_id_69644ca8_scoped_true_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"form"},[_vm._t("default")],2)} var MyFormvue_type_template_id_69644ca8_scoped_true_staticRenderFns = [] // CONCATENATED MODULE: ./packages/my-form/src/MyForm.vue?vue&type=template&id=69644ca8&scoped=true& // CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/ts-loader??ref--13-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./packages/my-form/src/MyForm.vue?vue&type=script&lang=ts& var MyFormvue_type_script_lang_ts_MyForm = /*#__PURE__*/ function (_Vue) { _inherits(MyForm, _Vue); function MyForm() { _classCallCheck(this, MyForm); return _possibleConstructorReturn(this, getPrototypeOf_getPrototypeOf(MyForm).apply(this, arguments)); } _createClass(MyForm, [{ key: "onChangeFormResult", value: function onChangeFormResult(newValue) {} // 校验整个form的正确性 }, { key: "validForm", value: function validForm() { for (var i = 0; i < this.validItemArr.length; i++) { if (this.formResult[this.validItemArr[i] + 'Result'] !== true) { this.formResult.isValid = false; return; } this.formResult.isValid = true; } } }]); return MyForm; }(external_commonjs_vue_commonjs2_vue_root_Vue_default.a); __decorate([Prop()], MyFormvue_type_script_lang_ts_MyForm.prototype, "validItemArr", void 0); __decorate([Model('change', {})], MyFormvue_type_script_lang_ts_MyForm.prototype, "formResult", void 0); __decorate([Watch('formResult', { deep: true })], MyFormvue_type_script_lang_ts_MyForm.prototype, "onChangeFormResult", null); MyFormvue_type_script_lang_ts_MyForm = __decorate([vue_class_component_esm({ name: "MyForm" })], MyFormvue_type_script_lang_ts_MyForm); /* harmony default export */ var MyFormvue_type_script_lang_ts_ = (MyFormvue_type_script_lang_ts_MyForm); // CONCATENATED MODULE: ./packages/my-form/src/MyForm.vue?vue&type=script&lang=ts& /* harmony default export */ var src_MyFormvue_type_script_lang_ts_ = (MyFormvue_type_script_lang_ts_); // CONCATENATED MODULE: ./packages/my-form/src/MyForm.vue /* normalize component */ var MyForm_component = normalizeComponent( src_MyFormvue_type_script_lang_ts_, MyFormvue_type_template_id_69644ca8_scoped_true_render, MyFormvue_type_template_id_69644ca8_scoped_true_staticRenderFns, false, null, "69644ca8", null ) /* harmony default export */ var src_MyForm = (MyForm_component.exports); // CONCATENATED MODULE: ./packages/my-form/index.ts // 导入组件,组件必须声明name // 为组件提供install安装方法,供按需引入 src_MyForm.install = function (Vue) { Vue.component('MyForm', src_MyForm); }; // 默认导出组件 /* harmony default export */ var my_form = (src_MyForm); // CONCATENATED MODULE: ./src/index.ts /* 打包配置文件 */ var components = [my_checkbox, my_checkbox_group, my_button, my_radio, my_radio_group, my_input, my_form_item, my_form]; var componentsName = ['MyCheckbox', 'MyCheckboxGroup', 'MyButton', 'MyRadio', 'MyRadioGroup', 'MyInput', 'MyFormItem', 'MyForm']; var install = function install(Vue) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; components.forEach(function (component, i) { Vue.component(componentsName[i], component); }); }; if (typeof window !== 'undefined' && window.Vue) { install(window.Vue); } var API = { version: '0.0.0', install: install, MyCheckbox: my_checkbox, MyCheckboxGroup: my_checkbox_group, MyButton: my_button, MyRadio: my_radio, MyRadioGroup: my_radio_group, MyInput: my_input, MyFormItem: my_form_item, MyForm: my_form }; /* harmony default export */ var src = (API); // CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/entry-lib.js /* concated harmony reexport MyCheckbox */__webpack_require__.d(__webpack_exports__, "MyCheckbox", function() { return my_checkbox; }); /* concated harmony reexport MyCheckboxGroup */__webpack_require__.d(__webpack_exports__, "MyCheckboxGroup", function() { return my_checkbox_group; }); /* concated harmony reexport MyButton */__webpack_require__.d(__webpack_exports__, "MyButton", function() { return my_button; }); /* concated harmony reexport MyRadio */__webpack_require__.d(__webpack_exports__, "MyRadio", function() { return my_radio; }); /* concated harmony reexport MyRadioGroup */__webpack_require__.d(__webpack_exports__, "MyRadioGroup", function() { return my_radio_group; }); /* concated harmony reexport MyInput */__webpack_require__.d(__webpack_exports__, "MyInput", function() { return my_input; }); /* concated harmony reexport MyFormItem */__webpack_require__.d(__webpack_exports__, "MyFormItem", function() { return my_form_item; }); /* concated harmony reexport MyForm */__webpack_require__.d(__webpack_exports__, "MyForm", function() { return my_form; }); /* harmony default export */ var entry_lib = __webpack_exports__["default"] = (src); /***/ }) /******/ }); //# sourceMappingURL=lqs-plugin.common.js.map
JavaScript
CL
96188283dcba942eaa49a7cbfc0562bf336285e2d8f3b2bf25265ae25ac903a6
'use strict'; (function() { // Crudms Controller Spec describe('Crudms Controller Tests', function() { // Initialize global variables var CrudmsController, scope, $httpBackend, $stateParams, $location; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function() { jasmine.addMatchers({ toEqualData: function(util, customEqualityTesters) { return { compare: function(actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) { // Set a new global scope scope = $rootScope.$new(); // Point global variables to injected services $stateParams = _$stateParams_; $httpBackend = _$httpBackend_; $location = _$location_; // Initialize the Crudms controller. CrudmsController = $controller('CrudmsController', { $scope: scope }); })); it('$scope.find() should create an array with at least one Crudm object fetched from XHR', inject(function(Crudms) { // Create sample Crudm using the Crudms service var sampleCrudm = new Crudms({ name: 'New Crudm' }); // Create a sample Crudms array that includes the new Crudm var sampleCrudms = [sampleCrudm]; // Set GET response $httpBackend.expectGET('crudms').respond(sampleCrudms); // Run controller functionality scope.find(); $httpBackend.flush(); // Test scope value expect(scope.crudms).toEqualData(sampleCrudms); })); it('$scope.findOne() should create an array with one Crudm object fetched from XHR using a crudmId URL parameter', inject(function(Crudms) { // Define a sample Crudm object var sampleCrudm = new Crudms({ name: 'New Crudm' }); // Set the URL parameter $stateParams.crudmId = '525a8422f6d0f87f0e407a33'; // Set GET response $httpBackend.expectGET(/crudms\/([0-9a-fA-F]{24})$/).respond(sampleCrudm); // Run controller functionality scope.findOne(); $httpBackend.flush(); // Test scope value expect(scope.crudm).toEqualData(sampleCrudm); })); it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Crudms) { // Create a sample Crudm object var sampleCrudmPostData = new Crudms({ name: 'New Crudm' }); // Create a sample Crudm response var sampleCrudmResponse = new Crudms({ _id: '525cf20451979dea2c000001', name: 'New Crudm' }); // Fixture mock form input values scope.name = 'New Crudm'; // Set POST response $httpBackend.expectPOST('crudms', sampleCrudmPostData).respond(sampleCrudmResponse); // Run controller functionality scope.create(); $httpBackend.flush(); // Test form inputs are reset expect(scope.name).toEqual(''); // Test URL redirection after the Crudm was created expect($location.path()).toBe('/crudms/' + sampleCrudmResponse._id); })); it('$scope.update() should update a valid Crudm', inject(function(Crudms) { // Define a sample Crudm put data var sampleCrudmPutData = new Crudms({ _id: '525cf20451979dea2c000001', name: 'New Crudm' }); // Mock Crudm in scope scope.crudm = sampleCrudmPutData; // Set PUT response $httpBackend.expectPUT(/crudms\/([0-9a-fA-F]{24})$/).respond(); // Run controller functionality scope.update(); $httpBackend.flush(); // Test URL location to new object expect($location.path()).toBe('/crudms/' + sampleCrudmPutData._id); })); it('$scope.remove() should send a DELETE request with a valid crudmId and remove the Crudm from the scope', inject(function(Crudms) { // Create new Crudm object var sampleCrudm = new Crudms({ _id: '525a8422f6d0f87f0e407a33' }); // Create new Crudms array and include the Crudm scope.crudms = [sampleCrudm]; // Set expected DELETE response $httpBackend.expectDELETE(/crudms\/([0-9a-fA-F]{24})$/).respond(204); // Run controller functionality scope.remove(sampleCrudm); $httpBackend.flush(); // Test array after successful delete expect(scope.crudms.length).toBe(0); })); }); }());
JavaScript
CL
e64a3ea9b9b13ce2630803c59ead9073724e4e14fdcee8bd0cef83a0f3e949b2
import React from 'react'; import { act } from 'react-dom/test-utils'; import { fireEvent } from '@testing-library/react'; import OptionsList from '..'; const options = [ { value: 'velociraptor', label: 'Velociraptor' }, { value: 't-rex', label: 'Tyrannosaurus rex' }, { value: 'diplodocus', label: 'Diplodocus' }, { value: 'brachiosaure', label: 'Brachiosaure' }, { value: 'triceratops', label: 'Triceratops' }, ]; describe('<OptionsList />', () => { test('should render without a problem', () => { const { getByText } = render(<OptionsList options={options} values={[]} />); const trex = getByText(/tyrannosaurus/i); expect(trex).toBeInTheDocument(); }); test('should display a searchbar', () => { const { getByTestId } = render( <OptionsList options={options} searchBarPlaceholder="Are you looking for a dinosaure ?" searchMethod={() => options} values={[]} />, ); const searchBar = getByTestId('input-container'); expect(searchBar).toBeInTheDocument(); }); test('searchMethod should filter options', () => { const { getByTestId, queryByText } = render( <OptionsList options={options} searchBarPlaceholder="Are you looking for a dinosaure ?" searchMethod={() => options.filter(option => option.label !== 'Triceratops')} values={[]} />, ); const searchBarInput = getByTestId('input'); act(() => { fireEvent.change(searchBarInput, { target: { value: 'Diplo' } }); }); const triceratops = queryByText(/triceratops/i); const diplodocus = queryByText(/diplodocus/i); expect(searchBarInput).toBeInTheDocument(); expect(triceratops).not.toBeInTheDocument(); expect(diplodocus).toBeInTheDocument(); }); test('should display radio buttons if allowMultiple is false', () => { const { queryAllByTestId } = render(<OptionsList options={options} values={[]} />); const radio = queryAllByTestId('styled-radio'); const checkbox = queryAllByTestId('styled-checkBox'); expect(radio).toHaveLength(options.length); expect(checkbox).toHaveLength(0); }); test('should display checkboxes if allowMultiple is true', () => { const { queryAllByTestId } = render( <OptionsList allowMultiple options={options} values={[]} />, ); const radio = queryAllByTestId('styled-radio'); const checkbox = queryAllByTestId('styled-checkBox'); expect(radio).toHaveLength(0); expect(checkbox).toHaveLength(options.length); }); test('should call onChange method on checkbox click', () => { const onChange = jest.fn(); const { getByText } = render( <OptionsList allowMultiple onChange={onChange} options={options} values={['triceratops']} />, ); act(() => { const velociraptor = getByText(/velociraptor/i); fireEvent.click(velociraptor); }); expect(onChange.mock.calls[0][0]).toEqual(['triceratops', 'velociraptor']); }); test('should call onChange method on radio click and return last option clicked', () => { const onChange = jest.fn(); const { getByText } = render( <OptionsList onChange={onChange} options={options} values={['diplodocus']} />, ); act(() => { const velociraptor = getByText(/velociraptor/i); fireEvent.click(velociraptor); }); act(() => { const triceratops = getByText(/triceratops/i); fireEvent.click(triceratops); }); expect(onChange.mock.calls[0][0]).toEqual(['velociraptor']); expect(onChange.mock.calls[1][0]).toEqual(['triceratops']); }); test('should display custom component when no result', () => { const onChange = jest.fn(); // eslint-disable-next-line react/prop-types const NoResult = () => <div>You bred raptors ?</div>; const { getByTestId, queryByText } = render( <OptionsList onChange={onChange} options={options} values={[]} NoResult={NoResult} searchMethod={() => []} />, ); const searchBarInput = getByTestId('input'); act(() => { fireEvent.change(searchBarInput, { target: { value: 'Diplo' } }); }); const noResultMessage = queryByText(/bred raptors/i); expect(noResultMessage).toBeInTheDocument(); }); test('should display custom component for option', () => { const onChange = jest.fn(); // eslint-disable-next-line react/prop-types const Option = ({ label }) => <div>{`custom ${label}`}</div>; const { queryByText } = render( <OptionsList onChange={onChange} options={options} values={[]} OptionComponent={Option} />, ); const customOption = queryByText(/custom triceratops/i); expect(customOption).toBeInTheDocument(); }); });
JavaScript
CL
51455740c6b3e4492ebfe39019efd54fa92838f3bce4e2823d0c8af15ce6ee97
/* eslint-disable react/prop-types */ /* eslint-disable no-underscore-dangle */ import React from 'react'; import { useHistory } from 'react-router-dom'; import { useStoreState, useStoreActions } from 'easy-peasy'; import { useSnackbar } from 'notistack'; import Button from '@material-ui/core/Button'; import CardMedia from '@material-ui/core/CardMedia'; import DetailsIcon from '@material-ui/icons/Details'; import EditIcon from '@material-ui/icons/Edit'; import { makeStyles, withStyles } from '@material-ui/core/styles'; import { deepOrange } from '@material-ui/core/colors'; const useStyles = makeStyles((theme) => ({ root: { height: '100vh', }, nav: { paddingLeft: '5px', backgroundRepeat: 'no-repeat', backgroundColor: theme.palette.type === 'light' ? '#FFF' : '#FFF', backgroundSize: 'cover', backgroundPosition: 'center', }, navText: { paddingLeft: '5px', paddingBottom: '5px', marginTop: '15px', }, selectedButton: { width: '100%', minWidth: '42px', color: '#fff', backgroundColor: '#4285F4', borderBottomRightRadius: '15px', justifyContent: 'flex-start', }, label: { fontSize: '13px', }, button: { width: '100%', minWidth: '42px', color: '#000', justifyContent: 'flex-start', }, background: { backgroundColor: theme.palette.type === 'light' ? '#F9FAFD' : '#F9FAFD', }, mainSection: { padding: '0 0 0 2vw', margin: theme.spacing(7, 5), display: 'flex', flexDirection: 'column', alignItems: 'left', }, subSection: { padding: '0 0 0 0', margin: theme.spacing(7, 3), display: 'flex', flexDirection: 'column', alignItems: 'left', }, card: { backgroundColor: '#fff', padding: '12px', borderRadius: '12px', margin: theme.spacing(0, 0, 5, 0), }, productImage: { borderRadius: '12px', }, actionButton: { margin: '0 auto', marginTop: '22px', marginRight: '24px', padding: theme.spacing(0, 3, 0, 3), width: 'auto', minWidth: '42px', color: '#4285F4', backgroundColor: '#e1f5fe', borderRadius: '12px', }, profileButton: { margin: '0 auto', marginRight: '24px', padding: theme.spacing(0, 3, 0, 3), width: '100%', minWidth: '42px', color: '#4285F4', backgroundColor: '#e1f5fe', borderRadius: '12px', }, avatar: { color: theme.palette.getContrastText(deepOrange[500]), backgroundColor: deepOrange[500], margin: theme.spacing(0.5, 0, 5, 0), }, media: { height: 140, }, })); const iconStyles = { root: { width: 24, height: 24, marginTop: 12, marginBottom: 12, marginRight: 5, }, }; const IconDetails = withStyles(iconStyles)(({ classes }) => <DetailsIcon classes={classes} />); const IconEdit = withStyles(iconStyles)(({ classes }) => <EditIcon classes={classes} />); export default function ProductCard(props) { const classes = useStyles(); const history = useHistory(); const { enqueueSnackbar } = useSnackbar(); const { product } = props; const user = useStoreState((state) => state.user); const authToken = useStoreState((state) => state.authToken); const setCurrItem = useStoreActions((actions) => actions.setCurrItem); const setSeller = useStoreActions((actions) => actions.setSeller); // eslint-disable-next-line no-underscore-dangle const productUrl = `/Item/${product._id}`; // eslint-disable-next-line no-underscore-dangle const editProductUrl = `/EditItem/${product._id}`; let cardImage = <div>Image goes here</div>; async function handleViewDetails(event) { event.preventDefault(); await fetch(`/api/users/${product.sellerId}`, { method: 'GET', headers: { 'auth-token': authToken, }, }) .then((response) => response.json()) .then((data) => { setSeller(data); }) .catch((err) => { enqueueSnackbar(err, { variant: 'error', }); }); // eslint-disable-next-line no-underscore-dangle await fetch(`/api/products/${product._id}`, { method: 'GET', headers: { 'auth-token': authToken, }, }) .then((response) => response.json()) .then((data) => { setCurrItem(data); history.push(productUrl); }) .catch((err) => { enqueueSnackbar(err, { variant: 'error', }); }); } async function handleEditListing(event) { event.preventDefault(); // eslint-disable-next-line no-underscore-dangle await fetch(`/api/products/${product._id}`, { method: 'GET', headers: { 'auth-token': authToken, }, }) .then((response) => response.json()) .then((data) => { setCurrItem(data); history.push(editProductUrl); }) .catch((err) => { enqueueSnackbar(err, { variant: 'error', }); }); } if (product.photos && product.photos.length > 0) { cardImage = ( <CardMedia component="img" alt="Contemplative Reptile" className={classes.media} image={product.photos[0]} title="Contemplative Reptile" /> ); } else { cardImage = ( <CardMedia component="img" alt="Contemplative Reptile" className={classes.media} image="../../assets/noImageAvailable.jpg" title="Contemplative Reptile" /> ); } return ( <div className={classes.card}> <div className="row"> <div className="three columns"> <div className={classes.productImage}> {cardImage} </div> </div> <div className="nine columns"> <h4>{`${product.title} - $${product.price}`}</h4> <p className="no-margin">{`Category: ${product.category}`}</p> <p className="no-margin">{`Condition: ${product.condition}`}</p> <Button dense color="primary" classes={{ root: classes.actionButton, label: classes.label }} onClick={handleViewDetails} > <IconDetails /> See Detail </Button> { product.sellerId === user._id && ( <Button dense color="primary" classes={{ root: classes.actionButton, label: classes.label }} onClick={handleEditListing} > <IconEdit /> Edit Listing </Button> )} </div> </div> </div> ); }
JavaScript
CL
65018754607ad1b8cb71eae59749eeb437499dd24d69d90696cad18d33aff5d0
#!/usr/bin/env node /** * Copyright (c) 2018-present, Lmntrx Tech. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // /!\ DO NOT MODIFY THIS FILE /!\ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // mochaswagger-gen is installed globally on people's computers. This means // that it is extremely difficult to have them upgrade the version and // because there's only one global version installed, it is very prone to // breaking changes. // // If you need to add a new command, please add it to the scripts/ folder. // // The only reason to modify this file is to add more warnings and // troubleshooting information for the `mochaswagger-gen` command. // // Do not make breaking changes! We absolutely don't want to have to // tell people to update their global version of mochaswagger-gen. // // Also be careful with new language features. // This file must work on Node 0.10+. // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // /!\ DO NOT MODIFY THIS FILE /!\ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ "use strict"; const path = require("path"); const glob = require("glob"); const chalk = require("chalk"); const fs = require("fs"); const ProgressBar = require("progress"); module.exports = dir => { const root = path.resolve(dir); const testDirName = path.basename(root); const testFileFormats = ["/**/*.js", "/**/*.ts"]; let routes = []; testFileFormats.forEach(testFileFormat => { let files = glob.sync(`${testDirName}/${testFileFormat}`); if (!files || files.length <= 0) { console.warn( chalk.magenta( `${testDirName} directory does not contain files matching pattern ${testFileFormat}` ) ); return null; } console.info( chalk.cyan(`Parsing files matching pattern ${testFileFormat}`) ); var bar = new ProgressBar(" processing [:bar] :percent :etas", { complete: "=", incomplete: " ", total: files.length * 2, renderThrottle: 0 }); files.forEach(file => { processFile(fs.readFileSync(file).toString()); bar.tick(2); }); }); function processFile(data) { let blocks = data.split("it"); blocks.forEach(block => { let lines = block.split("."); let route = null; lines.forEach((line, index) => { let method = null; if (line.includes("`") && !line.includes("$")) { line = line.replace(/`/g, '"').trim(); } if (line.includes("+")) { line = line.substring(0, line.indexOf('" +')) + ":" + (lines[index + 1].includes("(") ? line.substring(line.indexOf('" +') + 3, line.length).trim() : lines[index + 1].substring(0, lines[index + 1].indexOf(")"))) + '")'; } if (line.includes("`") && line.includes("$")) { method = null; } else if (line.startsWith("get")) { method = "get"; } else if (line.startsWith("post")) { method = "post"; } else if (line.startsWith("delete")) { method = "delete"; } else if (line.startsWith("put")) { method = "put"; } else if (line.startsWith("patch")) { method = "patch"; } if (method) { let parameters = []; let path = line.substring(line.indexOf("(") + 1, line.indexOf(")")); path = path.replace(/"/g, ""); if (path.includes(":")) { path = path.replace(/:/g, "{"); path = path.replace(/{\//g, "}"); path = path + "}"; parameters = [ { in: "path", required: true, type: "string", name: path.substring(path.indexOf("{") + 1, path.indexOf("}")) } ]; } if (route) { route.method = method; route.path = path; route.parameters = parameters; } else route = { method, path, parameters }; } }); if ( route && !routes.find(r => { if (r.path === route.path && r.method === route.method) return true; }) ) { if (route.path.startsWith("/")) routes.push(route); else { let d = data.replace(/\s/g, "").split(";"); let actualPath = ""; d.find(l => { if (l.includes(route.path)) { actualPath = l.split("=")[1].replace(/"/g, ""); return true; } }); route.path = actualPath; if ( !routes.find(r => { if (r.path === route.path && r.method === route.method) return true; }) ) routes.push(route); } } }); } return routes; };
JavaScript
CL
0738559b34434b3a85b3046546c06e459fbcd41856e5fe8c273cdf89d555d1d9
import axios from 'axios'; import React, { useEffect, useState } from 'react'; import NumberFormat from 'react-number-format'; import CheckCircleIcon from '@material-ui/icons/CheckCircle'; import ArrowDownwardIcon from '@material-ui/icons/ArrowDownward'; import ArrowUpwardIcon from '@material-ui/icons/ArrowUpward'; import SearchIcon from '@material-ui/icons/Search'; import { Card, CardActionArea, CardContent, CardMedia, Typography, IconButton, Grid, InputBase } from '@material-ui/core'; import { useStyles } from '../Style/StyleOrder'; function MainProduct() { const classes = useStyles(); const [viewMainProduct, setViewMainProduct] = useState([]); const [token, setToken] = useState(localStorage.getItem("jwt")) const apiMainProduct='http://localhost:3030/product/' const fetchMainProduct = async () => { const result = await axios(apiMainProduct, { headers: { "x-access-token":token }, }); if (token === null){ props.history.push('/') } else { setViewMainProduct(result.data.data.data); } } useEffect(() => { fetchMainProduct(); }, []); return( <div> <Grid container justify="center"> <IconButton fontSize="medium"> <SearchIcon /> </IconButton> &nbsp; <InputBase placeholder = " Search Name..." inputProps={{ 'aria-label': 'naked' }} name= "search" /> &emsp; <IconButton size="medium"> <ArrowUpwardIcon /> </IconButton> <IconButton size="medium"> <ArrowDownwardIcon /> </IconButton> </Grid><br /> <Grid container className={classes.grid} spacing={0}> <Grid item xs={11}> <Grid container justify="center" spacing={4}> {viewMainProduct.map((data, index) => { return( <Grid key={index} item justify="center"> <Card className={classes.card}> <CardActionArea> <CardMedia component="img" alt="Contemplative Reptile" height="140" image={data.image} title={data.name} /> <CardContent> <Typography gutterBottom variant="h6" component="h6"> {data.name} </Typography> <Typography variant="body2" color="textSecondary" component="p"> {data.description} </Typography> <Grid container direction="row" alignItems="center"> <Grid item> <h3 className={classes.h3}><NumberFormat value={data.price} displayType={'text'} thousandSeparator={true} prefix={'Rp.'} /></h3> </Grid> <Grid item> <CheckCircleIcon className={classes.circleIconColor}/> </Grid> </Grid> </CardContent> </CardActionArea> </Card> </Grid> ) })} </Grid> </Grid> </Grid> </div> ) } export default MainProduct
JavaScript
CL
0102dda88a48591a17d31175efcf9ac61f20ed8b44a48d28ccf9a517e7fe9516
LineChart.prototype = new DexComponent(); LineChart.constructor = LineChart; function LineChart(userConfig) { DexComponent.call(this, userConfig, { 'parent' : null, 'csv' : { 'header' : [ "X", "Y" ], 'data' : [[0,0],[1,1],[2,4],[3,9],[4,16]] }, 'width' : 600, 'height' : 400, 'xi' : 0, 'yi' : [1], 'xoffset' : 0, 'yoffset' : 0, 'pointColors' : d3.scale.category20(), 'lineColors' : d3.scale.category20() }); // Ugly, but my JavaScript is weak. When in handler functions // this seems to be the only way to get linked back to the // this.x variables. this.chart = this; } LineChart.prototype.render = function() { this.update(); }; LineChart.prototype.update = function() { // If we need to call super: //DexComponent.prototype.update.call(this); var chart = this.chart; var config = this.config; var csv = config.csv; //console.dir(config); // Use a linear scale for x, map the value range to the pixel range. var x = d3.scale.linear() .domain(d3.extent(csv.data, function(d) { return +d[config.xi]; })) .range([0, config.width]); // Use a linear scale for y, map the value range to the pixel range. var y = d3.scale.linear() .domain(d3.extent( dex.matrix.flatten(dex.matrix.slice(csv.data, config.yi)))) .range([config.height, 0]); // I hate this kind of stuff, but it's necessary to share // with mouseOver function. There's probably a better way to do // it but I don't feel like blowing a couple hours figuring it out. this.x = x; this.y = y; // Create the x axis at the bottom. var xAxis = d3.svg.axis() .scale(x) .orient("bottom"); // Create the y axis to the left. var yAxis = d3.svg.axis() .scale(y) .orient("left"); var lines = []; for(var i=0; i<config.yi.length; i++) { // Define a function to draw the line. var line = d3.svg.line() .x(function(d) { return x(+d[config.xi]); }) .y(function(d) { return y(+d[config.yi[i]]); }); lines.push(line); } // Append a graphics node to the parent, all drawing will be relative // to the supplied offsets. This encapsulating transform simplifies // the offsets within the child nodes. //config.parent.select("#lineChartContainer").remove(); var chartContainer = config.parent.append("g") .attr("id", "lineChartContainer") .attr("transform", "translate(" + config.xoffset + "," + config.yoffset + ")"); // Draw the x axis. chartContainer.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + config.height + ")") .call(xAxis); // Draw the y axis. chartContainer.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text(dex.array.slice(csv.header, config.yi).join(" ")); // Draw each of the lines. for (var i=0; i<lines.length; i++) { chartContainer.append("path") .datum(csv.data) .attr("class", "line") .attr("d", lines[i]) .style("stroke", config.lineColors(i)); } // We handle mouseover with transparent rectangles. This will calculate // the width of each rectangle. var rectalWidth = (csv.data.length > 1) ? x(csv.data[1][config.xi]) - x(csv.data[0][config.xi]) : 0; // Add the transparent rectangles for our mouseover events. chartContainer.selectAll("rect") .data(csv.data.map(function(d) { return d; })) .enter().append("rect") .attr("class", "overlay") .attr("transform", function(d,i) { return "translate(" + x(d[config.xi]) + ",0)"; }) .attr("opacity", 0.0) .attr("width", rectalWidth) .attr("height", config.height) .on("mouseover", function(d) { var chartEvent = { type: "mouseover", data: d }; chart.mouseOverHandler(chartEvent); chart.notify(chartEvent); }); this.chartContainer = chartContainer; }; LineChart.prototype.mouseOverHandler = function(chartEvent, targetChart) { var chart; if (arguments.length === 2) { chart = targetChart; } else { chart = this.chart; } var config = chart.config; var x = chart.x; var y = chart.y; var chartContainer = chart.chartContainer; //console.log("Chart Container: " + typeof chart); //console.dir(chart); // Remove any old circles. chartContainer.selectAll("circle").remove(); chartContainer.selectAll("#circleLabel").remove(); // Draw a small red circle over the mouseover point. for (var i=0; i<config.yi.length; i++) { //console.log("I: " + y); var circle = chartContainer.append("circle") .attr("fill", config.pointColors(i)) .attr("r", 4) .attr("cx", x(chartEvent.data[config.xi])) .attr("cy", y(chartEvent.data[config.yi[i]])); chartContainer.append("text") .attr("id", "circleLabel") .attr("x", x(chartEvent.data[config.xi])) .attr("y", y(chartEvent.data[config.yi[i]]) - 10) .attr("dy", ".35m") .style("font-size", 14) .attr("text-anchor", "top") .attr("fill", "black") .text(function(d) { return chartEvent.data[config.yi[i]];}); } };
JavaScript
CL
4f0c45f268ae664f9b98113175166824ea8f119c48aca848f98d1a034e2124ea
; (function (ng) { 'use strict'; ng.module('grastin', []) .controller('GrastinCtrl', ['$scope', 'modalService', function ($scope, modalService) { var ctrl = this; ctrl.init = function () { if (!window.isGrastinLoaded) { jQuery.getScript((window.location.protocol === "https:" ? "https:" : "http:") + "//grastin.ru/js/gWidget.js", function () { var divgWidgetContainer = $('<div id="gWidget" style="height:500px;"></div>'); Object.keys(ctrl.grastinWidgetConfigData).map(function (objectKey) { divgWidgetContainer.attr(objectKey, ctrl.grastinWidgetConfigData[objectKey]); }); modalService.renderModal( "modalGrastinWidget", null, divgWidgetContainer.prop('outerHTML'), null, { modalClass: 'grastin-widget-dialog', callbackInit: 'grastin.GrastinWidgetInitModal()' }, { grastin: { GrastinWidgetInitModal: function () { gwClient.createWidgets(); } } }); window.grastinPvzWidgetCallback = ctrl.setGrastinPvz; gwClient.onMessage = function(event) { if (event.origin.indexOf(this.o.host) != -1) { var i = "object" == typeof event.data ? event.data : JSON.parse(event.data), a = Object.keys(i)[0]; switch (a) { case "delivery": "function" == typeof window[this.o.callbackName] && window[this.o.callbackName](i[a]); } } }; window.isGrastinLoaded = true; }); } else { } } ctrl.setGrastinPvz = function (delivery) { if (typeof (delivery) === 'string') { delivery = (new Function("return " + delivery))(); } var closeModal = true; // Если почта, то не обязательно данные по точке самовыова (их нет) if (delivery.cost <= 0 || !delivery.partnerId || (delivery.partnerId !== 'post' && delivery.deliveryType === 'pvz' && (!delivery.currentId || !delivery.pvzData))) return; var deliveryClone = JSON.parse(JSON.stringify(delivery)); if (delivery.deliveryType === 'courier') { deliveryClone.deliveryType = 1; } else if (delivery.deliveryType === 'pvz') { deliveryClone.deliveryType = 2; } var company = ''; if (delivery.partnerId === 'grastin') { company = 'Grastin'; deliveryClone.partner = 1; } else if (delivery.partnerId === 'dpd') { company = 'DPD'; deliveryClone.partner = 5; } else if (delivery.partnerId === 'hermes') { company = 'Hermes'; deliveryClone.partner = 2; } else if (delivery.partnerId === 'boxberry') { company = 'BoxBerry'; deliveryClone.partner = 4; } else if (delivery.partnerId === 'post') { company = 'Почта РФ'; deliveryClone.partner = 3; } else if (delivery.partnerId) { company = delivery.partnerId; } if (delivery.partnerId === 'post') { // Особый случай с почтой ctrl.grastinShipping.PickpointId = delivery.partnerId; ctrl.grastinShipping.PickpointAddress = delivery.cityTo; ctrl.grastinShipping.PickpointAdditionalData = JSON.stringify(deliveryClone); ctrl.grastinShipping.NameRate = 'Самовывоз ' + company; ctrl.grastinShipping.Rate = delivery.cost; ctrl.grastinShipping.DeliveryTime = '';//(delivery.time && delivery.time > 0 ? delivery.time + " д." : ""); } else if (delivery.deliveryType === 'pvz') { ctrl.grastinShipping.PickpointId = delivery.currentId; ctrl.grastinShipping.PickpointAddress = delivery.pvzData.name; ctrl.grastinShipping.PickpointAdditionalData = JSON.stringify(deliveryClone); ctrl.grastinShipping.NameRate = 'Самовывоз ' + company; ctrl.grastinShipping.Rate = delivery.cost; ctrl.grastinShipping.DeliveryTime = '';//(delivery.time && delivery.time > 0 ? delivery.time + " д." : ""); } else { ctrl.grastinShipping.PickpointId = delivery.partnerId; ctrl.grastinShipping.PickpointAddress = delivery.cityTo; ctrl.grastinShipping.PickpointAdditionalData = JSON.stringify(deliveryClone); ctrl.grastinShipping.NameRate = 'Курьерская доставка ' + company; ctrl.grastinShipping.Rate = delivery.cost; ctrl.grastinShipping.DeliveryTime = '';//(delivery.time && delivery.time > 0 ? delivery.time + " д." : ""); } ctrl.grastinCallback({ event: 'grastinWidget', field: ctrl.grastinShipping.PickpointId || 0 }); if (closeModal) { modalService.close("modalGrastinWidget"); } $scope.$digest(); } }]) .directive('grastin', ['urlHelper', function (urlHelper) { return { scope: { grastinShipping: '=', grastinCallback: '&', grastinWidgetConfigData: '=', grastinIsSelected: '=', grastinContact: '=' }, controller: 'GrastinCtrl', controllerAs: 'grastin', bindToController: true, templateUrl: function () { return 'scripts/_partials/shipping/extend/grastin/grastin.tpl.html'; }, link: function (scope, element, attrs, ctrl) { ctrl.init(); } } }]) })(window.angular);
JavaScript
CL
6e240400f90e4e9680871cc7dd1a75190688d4ab5fce6f3dc7ca4457cc2bbf7b
/** * checkbox group component define * @author fengpeng */ import controller from './checkbox.group'; import template from './template.html'; /** * @type {Object} * @property {Boolean} disabled - binding symbol is <, 禁用状态, 在组上禁用则全部禁用, 实际上是对ng-disabled的包装 * @property {Array.<Object>} model - binding symbol is =?, 数据源, 由于是双向绑定的逻辑会去修改数据源上的checked属性 * @property {Boolean} inline - binding symbol is @, 是否横着排 */ let CheckboxGroupComponentDefine = { template, controller, controllerAs: 'controller', bindings: { disabled: '<', model: '=?model', inline: '@' } } export default CheckboxGroupComponentDefine;
JavaScript
CL
a42552a55431d0fa072713fcfefc9d1156da725baf8b27bc0356f3056cba7286
const _ = require('lodash'); const DEBUG = process.env.DEBUG || 0; // many to many function makeAgg(knex, k, field) { return knex.raw('json_agg(x' + k + ') AS "' + field + '"'); } // Many to many select field with only _id field function makeAggId(knex, k, field) { return knex.raw('json_agg(x' + k + '._id) AS "' + field + '"'); } // one to many function makeRow(knex, k, field) { return knex.raw('row_to_json(x' + k + ') AS "' + field + '"'); } let i = 0; // keep global query operation id // Chain operations on find() and findjustOne module.exports = class Query { constructor(model, params, justOne, _knex) { this.knex = _knex; this.model = model; this.schema = model._schema; // sugar this.params = params; // || {}; this.populateFields = []; this.ops = []; this.justOne = justOne; this._i = ++i; this.excludeFields = []; } findOne(params) { if (!isNaN(parseFloat(this.params))) this.params = params; else if (params && this.params) this.params = _.merge(this.params, params); this.justOne = true; return this; } findByID(params) { return this.findOne(params); } findById(params) { return this.findByID(params); } find(params) { this.findOne(params); this.justOne = false; return this; } sort(field) { // TODO: POPULATE if (field.charAt(0) !== '-') this.ops.push(q => q.orderBy(this.schema.table + '.' + field)); //'desc' else { field = field.substring(1); this.ops.push(q => q.orderBy(this.schema.table + '.' + field, 'desc')); } return this; } select(field) { if (field.charAt(0) === '-') this.excludeFields.push(field.substring(1)); else throw new Error('additional select field', field); return this; // TODO: secondary select } populate(model1, model2) { if (Array.isArray(model1)) this.populateFields.push(...model1); else { if(model1.indexOf('-') === 0) this.excludeFields.push(model1.substring(1)); else this.populateFields.push(model1); } if (model2) { if(model2.indexOf('-') === 0) this.excludeFields.push(model2.substring(1)); else this.populateFields.push(model2); } return this; } exec(cb) { // if (DEBUG) console.log('exec', this.method); const _schema = this.schema; if (!_schema) throw new Error('missing schema state'); const many = makeAgg.bind(null, this.knex); const manyID = makeAggId.bind(null, this.knex); const one = makeRow.bind(null, this.knex); // aggregate fields with any needed join table columns let fields = ['*'] if(this.excludeFields.length > 0) { fields = _.without(_.keys(_schema.props), ...this.populateFields, ...this.excludeFields); fields.push('_id'); } const fieldsToTable = _.map(fields, f => _schema.table + '.' + f); const linkedRefs = _(this.schema.refs) .map((f, K) => { const fullJoin = _.includes(this.populateFields, f); if (_schema.joins[f]) { if (fullJoin) return many(K, f); else return manyID(K, f); } if (fullJoin && _schema.props[f]) return one(K, f); return null; /* Validate invalid populate fields else if(!_schema.joins[f] && _schema.props[f]) { console.log( f); throw new Error('unlisted field ' + f); }*/ }) .filter(null); const extra = [ ...fieldsToTable, ...linkedRefs, ]; // Select fields let q = this.knex.select(...extra).from(_schema.table); // Ordering _.forEach(this.ops, op => q = op(q)); // Where clauses if (_.isObject(this.params)) { // Fixes where fields that are ambiguous to the table this.params = _.mapKeys( this.params, (v, k) => this.schema.table + '.' + k ); q = q.where(this.params); } else if (!isNaN(parseFloat(this.params))) q = q.where(this.schema.table + '._id', parseFloat(this.params)); // == Nested many-many group _.forEach(this.schema.refs, (f, K) => { const prop = _schema.joins[f]; if (!prop) return; //if(!prop) throw new Error('field not found '+f); const key = 'x' + K; q = q .leftOuterJoin( prop.ltable + ' AS L', _schema.table + '._id', 'L.' + _schema.table ) .leftOuterJoin(prop.refTable + ' AS ' + key, 'L.' + f, key + '._id'); }); // == Nested one-many group const extraOrders = []; // order fix for row_to_json selection _.forEach(this.schema.refs, (f, K) => { const prop = _schema.props[f]; if (!prop) return; //if(!prop) throw new Error('field not found '+f); const key = 'x' + K; extraOrders.push(key); q = q.leftOuterJoin( prop.refTable + ' AS ' + key, _schema.table + '.' + f, key + '._id' ); }); if (this.populateFields.length) q = q.groupBy(_schema.table + '._id', ...extraOrders); else q = q.groupBy(_schema.table + '._id'); //console.log( this._i, q.toString() ); return q.then(x => { //console.log(this._i, 'returned') // extract single element if (this.justOne) { x = x.length > 0 ? x[0] : null; if (x) x = this.model.create(x); // convert to ModelInstance } else { x = _.map(x, y => this.model.create(y)); } if (cb) cb(null, x); return x; }); } };
JavaScript
CL
c686f0b98e65b461f6b3b2059221849e7a6ba0daa666933df50840802502e886
import React from 'react'; import PropTypes from 'prop-types'; import { Redirect } from 'react-router-dom'; import DashboardPanel from './dashboardPanel.js'; import Map from './map.js'; import Profile from './profile.js'; // The Dashboard component lays out the bootstrap containers for its children // components. It includes the Dashboard Panel and either the Profile or Map // component depending on which page is selected from the dropdown in the Nav // component. const Dashboard = (props) => { let loadComponent; if (props.load === 'Map') { // If Dashboard is selected from the dropdown in the Nav component. loadComponent = <Map updateUser={props.updateUser} stateObj={props.stateObj} />; } else if (props.load === 'Profile') { // If Profile is selected from the dropdown in the Nav component. loadComponent = <Profile updateUser={props.updateUser} stateObj={props.stateObj} />; } if (props.stateObj.loggedIn) { // The Dashboard component will only return the 'dashboard' if the loggedIn state of App.js is true. return ( <div className="container-fluid"> <div className="row h-100 set-row d-flex align-items-stretch"> <div className="col-12 col-sm-3 bg-dark text-white"> <DashboardPanel pageNum={props.pageNum} paging={props.paging} getSearches={props.getSearches} updateUser={props.updateUser} stateObj={props.stateObj} /> </div> <div className="col-12 col-sm-9"> {loadComponent} </div> </div> </div> ); } else { // If the loggedIn state of App.js is false, the user will be redirected to the home route when attempting to access /dashboard. return ( <Redirect to={'/'} /> ); } }; Dashboard.proptypes = { stateObj: PropTypes.object, load: PropTypes.string, updateUser: PropTypes.func, getSearches: PropTypes.func, paging: PropTypes.func, pageNum: PropTypes.number } export default Dashboard;
JavaScript
CL
862b03bbdff671ab897903b61919f7d86c02e70b81e613a5e73762c9b81c6121
// Import the ORM to create functions that will interact with the database. var orm = require("../config/orm.js"); var Sequelize = require("sequelize"); var sequelize = require("../config/connection.js"); var burger = sequelize.define("buger", { burger_name: Sequelize.STRING, devoured: Sequelize.BOOLEAN }); // The variables cols and vals are arrays. burger.sync(); // Export the database functions for the controller (catsController.js). module.exports = burger;
JavaScript
CL
9670705fadb3082a353ff548ae752fc785e9fc158b289f5bf90fc3d1105c385e
import { PropTypes } from 'react'; import Helmet from 'react-helmet'; import NotFoundHandler from '../routes/not_found_handler'; import ProjectsList from '../projects/list'; import BreadcrumbsList from '../breadcrumbs/list'; import { getAllProjects, getTechnology } from '../data/store'; import { getPositionText } from '../positions/utils'; import { getPortfolioPath } from '../url_utils'; const PARENT_BREADCRUMBS = { workProject: { routeName: getPortfolioPath('/work'), text: 'Work', }, sideProject: { routeName: getPortfolioPath('/side-projects'), text: 'Side Projects', }, communityProject: { routeName: getPortfolioPath('/in-community'), text: 'Efforts in Community', }, }; const PROJECT_TYPE_LOOKUP = {}; Object.keys(PARENT_BREADCRUMBS).forEach((type) => { PROJECT_TYPE_LOOKUP[PARENT_BREADCRUMBS[type].routeName] = type; }); const getFragmentText = (fragment) => ( fragment.text ? fragment.text : fragment ); function getProjectDescriptionText(description) { return Array.isArray(description) ? description.reduce((prev, curr) => prev + getFragmentText(curr), '') : description; } function getMetaDescription({ createdFor, name, positions, description, technologies, }) { const points = []; if (positions) { points.push(`${getPositionText(positions[0] || positions)}.`); } if (createdFor) { points.push(`For ${createdFor}.`); } points.push(`${name} — ${getProjectDescriptionText(description)}`); if (technologies) { const technologiesString = technologies.map((id) => getTechnology(id)) .join(', '); points.push(`Uses ${technologiesString}.`); } return points.join(' '); } function getMetaData(project) { return { title: project.name, meta: [{ name: 'description', content: getMetaDescription(project), }], }; } const ProjectHandler = ({ params }) => { const myType = PROJECT_TYPE_LOOKUP[getPortfolioPath(`/${params.projectType}`)]; const myProject = getAllProjects().find((project) => ( project.slug === params.projectId && project.type === myType )); if (!myType || !myProject) { return <NotFoundHandler />; } return ( <div> <Helmet {...(getMetaData(myProject))} /> <BreadcrumbsList breadcrumbs={[ PARENT_BREADCRUMBS[myProject.type], myProject.shortName || myProject.name, ]} /> <ProjectsList projects={[myProject]} /> </div> ); }; ProjectHandler.propTypes = { params: PropTypes.object.isRequired, }; export default ProjectHandler;
JavaScript
CL
feeea908379f9af16418837b079f52eab8ac616dabb77ca64fd99bde7b6d4533
/*! * main.js * Uses jQuery and dataTables.js to create a responsive design for tabular data. * * @project Mobile Grid Evaluation * @date 2012-11-28 * @author Andrew Rota * */ $(document).ready(function () { var table; /** * Formatted Numbers Sorting Plug-in for DataTables * * @author Allan Jardine * @source http://www.datatables.net/plug-ins/sorting#formatted_numbers */ jQuery.extend( jQuery.fn.dataTableExt.oSort, { "formatted-num-pre": function ( a ) { a = (a==="-") ? 0 : a.replace( /[^\d\-\.]/g, "" ); return parseFloat( a ); }, "formatted-num-asc": function ( a, b ) { return a - b; }, "formatted-num-desc": function ( a, b ) { return b - a; } } ); /** * Returns a height for the table * * @return {number} The calculated height for the table */ function getHeight() { return $(this).height() - 190; } /** * Hides and styles columns based on table width * * @param {DataTable} table The table to be modified */ function configureForWidth(table, columns) { if ($(this).width() <= 899 && $(this).width() > 499) { $.each(columns, function(index, priority) { if (priority === 2) { table.fnSetColumnVis(index, true, true); } else if(priority === 3) { table.fnSetColumnVis(index, false, true); } }); $("#positions-table").addClass("medium"); $("#positions-table").removeClass("wide"); $("#positions-table").removeClass("narrow"); } else if ($(this).width() <= 499 && $(this).width() > 0) { $.each(columns, function(index, priority) { if (priority === 2 || priority === 3) { table.fnSetColumnVis(index, false, true); } }); $("#positions-table").addClass("narrow"); $("#positions-table").removeClass("wide"); $("#positions-table").removeClass("medium"); } else { $.each(columns, function(index, priority) { if (priority === 2 || priority === 3) { table.fnSetColumnVis(index, true, true); } }); $("#positions-table").addClass("wide"); $("#positions-table").removeClass("medium"); $("#positions-table").removeClass("narrow"); } } /** * Binds the click/touch events to each row * */ function bindSelectEvents() { $("#positions-table").on("click", "tr", function (e) { $('#selected-position').html($(e.target).parent().attr("data-security-name")); }); $("#positions-table").on("click", "tr span", function (e) { $('#selected-position').html($(e.target).parent().parent().attr("data-security-name")); }); } /** * Returns a string describing the number (whether it is positive, negative, or zero) * * @param {number} n The number to be described * @return {string} The descriptive string (either positive, negative, or zero) */ function getPositiveOrNegativeOrZero(n) { "use strict"; if (n > 0) { return "positive"; } else if (n < 0) { return "negative"; } else { return "zero"; } } /** * Adds parens and removes the negative symbol around numbers with class 'negative' * */ function formatNegativeNumbers() { $(".negative").each(function (index, element) { var value = $(this).html(); var absValue = value.replace("-", ""); $(this).html("(" + absValue + ")"); }); } /** * Displays the size of the window * */ function displayWindowSize() { var win = $(this); $('.window-size').html("(" + win.width() + ", " + win.height() + ")"); } var settings = { "aaData": positions, //source of data "aaSorting": [[1, "asc"]], //default sort "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) { $(nRow).attr('data-security-name', aData.security); }, //set security name as an attribute of each row (for click/touch event) "aoColumns": [ { "mData": "security", "sTitle": "Security", "sClass": "security priority2" }, { "mData": "symbol", "sTitle": "Symbol", "sClass": "symbol priority1" }, { "mData": function (source, type, val) { var quantity = source.quantity; return ($.format.number(quantity, '#,##0')); }, "sTitle": "Quantity", "sType": "formatted-num", "sClass": "quantity priority1" }, { "mData": "lastTrade", "mRender": function (data, type, full) { var lastTrade = data; return "$" + ($.format.number(lastTrade, '#,##0.00')); }, "sTitle": "Last Trade", "sType": "formatted-num", "sClass": "last-trade priority1" }, { "mData": function (source, type, val) { var marketValue = source.lastTrade * source.quantity; return marketValue; }, "mRender": function(data, type, full) { return "$" + ($.format.number(data, '#,##0.00')); }, "sType": "formatted-num", "sTitle": "Market Value", "sClass": "market-value priority1" }, { "mData": function (source, type, val) { var pricePaid = source.pricePaid; return pricePaid; }, "mRender": function(data, type, full) { return "$" + ($.format.number(data, '#,##0.00')); }, "sType": "formatted-num", "sTitle": "Price Paid", "sClass": "price-paid priority2" }, { "mData": function (source, type, val) { var totalCost = source.pricePaid * source.quantity; return totalCost; }, "mRender": function (data, type, full) { return "$" + ($.format.number(data, '#,##0.00')); }, "sType": "formatted-num", "sTitle": "Total Cost", "sClass": "total-cost priority3" }, { "mData": function (source, type, val) { var gain = (source.lastTrade * source.quantity) - (source.pricePaid * source.quantity); return gain; }, "mRender": function(data, type, full) { return "<span class='" + getPositiveOrNegativeOrZero(data) + "'>$" + $.format.number(data, '#,##0.00'); }, "sTitle": "Gain", "sType": "formatted-num", "sClass": "gain priority3" }, { "mData": function (source, type, val) { var gainPercentage = (((source.lastTrade * source.quantity) - (source.pricePaid * source.quantity)) / (source.pricePaid * source.quantity)) * 100; return gainPercentage; }, "mRender": function(data, type, full) { return ("<span class='" + getPositiveOrNegativeOrZero(data) + "'>" + $.format.number(data, '#,##0.00')) + "%"; }, "sTitle": "Gain %", "sType": "formatted-num", "sClass": "gain-percentage priority2" } ], "bFilter": false, //toggle search filter "sScrollY": getHeight(), //set vertical scroll, with height "bPaginate": false, //toggle pagination "bInfo": false, //toggle dataset info at bottom of table "bDestroy": true, //toggle allow replacing of table "bSort": true, //toggle sorting "bAutoWidth": true //toggle column width is automatically set }; function configureTable(settings) { displayWindowSize(); settings.sScrollY = getHeight(); //set scroll settings to new height table = $('#positions-table').dataTable(settings); //replace table with new settings configureForWidth(table, [3,1,1,1,1,2,3,3,2]); //prioritize columns to hide based on window width formatNegativeNumbers(); //reformat negative numbers } $(window).resize(function () { configureTable(settings); }); bindSelectEvents(); //bind rows to click/touch events on page load configureTable(settings); });
JavaScript
CL
e940ac5b9a87426d1468c16f708c1ecf9653c75e7cddbd0f203ba2c531d852f1
/** * Fido / Webauthn and all the functions to create / edit / delete it ... */ import psonoServer from './api-server'; import store from './store'; import helperService from './helper'; /** * Returns the current origin * * @returns {string} Returns the current origin */ function getOrigin() { const parsedUrl = helperService.parse_url(window.location.href); return parsedUrl.base_url; } /** * Initiate the second factor authentication with webauthn * * @returns {Promise} Returns a promise with the user information */ function verifyWebauthnInit() { const token = store.getState().user.token; const sessionSecretKey = store.getState().user.session_secret_key; const onSuccess = function (request) { return request.data; }; const onError = function (request) { return Promise.reject(request.data); }; return psonoServer .webauthnVerifyInit(token, sessionSecretKey, getOrigin()) .then(onSuccess, onError); } /** * Solve the second factor webauthn authentication * * @param {string} credential The credentials passed by the browser * * @returns {Promise} Returns a promise with the user information */ function verifyWebauthn(credential) { const token = store.getState().user.token; const sessionSecretKey = store.getState().user.session_secret_key; const onSuccess = function (request) { return request.data; }; const onError = function (request) { return Promise.reject(request.data); }; return psonoServer .webauthnVerify(token, sessionSecretKey, credential) .then(onSuccess, onError); } const webauthnService = { verifyWebauthnInit, verifyWebauthn, }; export default webauthnService;
JavaScript
CL
510d1e850393dabb24e0660e13de30bfd515886d85c0df86ceb4a74fce88e2b8
/** * Class for working with numbers and numerical data. * @property {Numbers} */ export { Numbers } from "./api/Numbers"; /** * Class for working with arrays of any types * @property {Arrays} */ export { Arrays } from "./api/Arrays"; /** * Class for working with arrays containing objects with key/value data. * @property {ArraysObjective} */ export { ArraysObjective } from "./api/ArraysObjective"; /** * Class for working with arrays containing numbers and numerical data. * @property {ArraysNumerical} */ export { ArraysNumerical } from "./api/ArraysNumerical"; /** * Class for working with string data. * @property {Strings} */ export { Strings } from "./api/Strings"; /** * Class for working with Cyrillic string data. * @property {StringsCyrillic} */ export { StringsCyrillic } from "./api/StringsCyrillic"; /** * Class for working with Latin string data. * @property {StringsLatin} */ export { StringsLatin } from "./api/StringsLatin"; /** * Class for creating mock data for algorithm/visualization testing. * @property {MockData} */ export { MockData } from "./api/MockData"; // ALGORITHMS /** * Class for sorting arrays containing numerical data. * @property {Sort} */ export { Sort } from "./api/Algorithms/Sort"; // DATA STRUCTURES /** * Stack data structure. * @property {Stack} */ export { Stack } from "./api/Data Structures/Stack"; /** * Queue data structure. * @property {Queue} */ export { Queue } from "./api/Data Structures/Queue";
JavaScript
CL
330e464f97634c705a8b8938bf1eccf6b9bece47007e9cd27be7192567a3dbc1
import React, { Component } from 'react'; import { Text } from 'react-native'; import { SafeAreaView, NavigationEvents } from 'react-navigation'; import PropTypes from 'prop-types'; import AuthForm from '../../components/AuthForm'; import NavLink from '../../components/NavLink'; export class Screen extends Component { constructor(props) { super(props); this.state = {}; } componentDidMount() { const { services } = this.props; const { firebase } = services; firebase.analytics().setCurrentScreen('PROFILE'); } render() { const { services } = this.props; const { state, signin, clearErrorMessage } = services; return ( <SafeAreaView forceInset={{ top: 'always' }}> <NavigationEvents onWillBlur={clearErrorMessage} /> <Text>Login Screen</Text> <AuthForm headerText="Login Form" errorMessage={state.errorMessage} onSubmit={signin} submitButtonText="Login" /> <NavLink text="Link to go Home" routeName="Home" /> </SafeAreaView> ); } } Screen.propTypes = { services: PropTypes.shape({ signin: PropTypes.func.isRequired, clearErrorMessage: PropTypes.func.isRequired, state: PropTypes.shape({ errorMessage: PropTypes.string, }), firebase: PropTypes.shape({ analytics: PropTypes.func.isRequired, }), }).isRequired, };
JavaScript
CL
0db597989549625bcc898619802d1fefee166d99d001ea9f1c1ac60dee7520de
const qs = require('qs') const fetch = require('node-fetch') const Bluebird = require('bluebird') const { forEach, replace } = require('lodash') // const consola = require('../utils/consola') // const { logError2CloudWatch } = require('../utils/logger') // const { // API_URL_BACKEND, // GOOGLE_MAP_API_URL, // API_REQUEST_TIMEOUT_LIMIT // } = require('../config/env') fetch.Promise = Bluebird module.exports = () => { const setBody = ({ data = null, type = 'json' } = {}) => { if (data) { switch (type) { case 'form-data': return { body: data } case 'x-www-form-urlencoded': return { form: data } default: return { body: JSON.stringify(data) } } } return {} } const setHeader = ({ headers = {}, method = 'GET', type = 'json', auth = null } = {}) => { let authorization = {} if (auth) { const { token, tokenType } = auth authorization = { Authorization: `${tokenType} ${token}` } } const TYPES = { 'text/plain': 'text/plain', 'form-data': headers['content-type'] } const contentType = ['GET', 'DELETE'].includes(method) ? {} : { 'Content-Type': `${TYPES[type] || `application/${type};charset=UTF-8`}` } return { 'cache-control': 'no-cache', ...authorization, ...contentType } } const setPath = ({ host = '', path = '', params = {}, query = {} } = {}) => { query = `${qs.stringify(query, { encode: true })}` forEach(params, (v, k) => (path = replace(path, `\/\:${k}`, `\/${v}`))) return query ? `${host}${path}?${query}` : `${host}${path}` } const defaultOpts = { method: 'GET', headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below) body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream timeout: 3000, compress: true } const getOptions = ( path = '', opts = defaultOpts, sevedHost = '', savedAuth = '' ) => { const { data, type = 'json', query = {}, params = {}, headers = {}, ...restOptions } = opts let { host = '', auth = false, ...options } = restOptions host = host || sevedHost auth = auth && savedAuth const header = setHeader({ headers, ...options, type, auth }) const body = setBody({ data, type }) const url = setPath({ host, path, params, query }) options = { ...defaultOpts, ...options, headers: header, ...body } console.log(url, JSON.stringify(options, null, 2), '\n\n') return { url, options } } const fetchAPI = (url, options) => { return fetch(url, options) .then(async (res) => { const { text = false } = options const json = await (text ? res.text() : res.json()).catch(() => ({})) return Promise.all([res, json]) }) .then( ([ { status = 500, statusText = 'Internal Server Error', ok = false } = {}, data ]) => { if (ok) { return [data] } else if (status >= 500) { throw new Error(statusText || 'Internal Server Error') } else { // logError2CloudWatch(url, options, { status, statusText, ...data }) return [null, { ...data, status }] } } ) .catch((err) => { // logError2CloudWatch(url, options, err) throw err }) } const API_URL_BACKEND = 'https://api.catalistplus.com/api' const auth = false return async (ctx, next) => { ctx.fetch = (path, opts) => { const { url, options } = getOptions(path, opts, API_URL_BACKEND, auth) return fetchAPI(url, options) } await next() } } /* { // These properties are part of the Fetch Standard method: 'GET', headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below) body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect signal: null, // pass an instance of AbortSignal to optionally abort requests // The following properties are node-fetch extensions follow: 20, // maximum redirect count. 0 to not follow redirect timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead. compress: true, // support gzip/deflate content encoding. false to disable size: 0, // maximum response body size in bytes. 0 to disable agent: null // http(s).Agent instance, allows custom proxy, certificate, dns lookup etc. } */
JavaScript
CL
9af2daf0656435c6120191246ccbccbfe708d8af9d9c7fdce10e422057ea4706
import { CALL_API, Schemas } from '../../middleware/api'; import ApiRoutes from '../../../../shared/routes/api'; import { defaultOpts, postOpts, putOpts, deleteOpts, makeGetUrl, } from '../../actions/reqHelpers'; import { Map } from 'immutable'; import moment from 'moment'; const ARCHIVED_MESSAGES_LIMIT = 10; const UPDATE_ONLINE_STATUSES_TIMEOUT = 10 * 60 * 1000; // 10 minutes export const MSG_CONVERSATION_POST_REQUEST = 'MSG_CONVERSATION_POST_REQUEST'; export const MSG_CONVERSATION_POST_SUCCESS = 'MSG_CONVERSATION_POST_SUCCESS'; export const MSG_CONVERSATION_POST_FAILURE = 'MSG_CONVERSATION_POST_FAILURE'; export const MSG_CONVERSATION_MSGS_REQUEST = 'MSG_CONVERSATION_MSGS_REQUEST'; export const MSG_CONVERSATION_MSGS_SUCCESS = 'MSG_CONVERSATION_MSGS_SUCCESS'; export const MSG_CONVERSATION_MSGS_FAILURE = 'MSG_CONVERSATION_MSGS_FAILURE'; export const MSG_CONVERSATION_LEAVE_REQUEST = 'MSG_CONVERSATION_LEAVE_REQUEST'; export const MSG_CONVERSATION_LEAVE_SUCCESS = 'MSG_CONVERSATION_LEAVE_SUCCESS'; export const MSG_CONVERSATION_LEAVE_FAILURE = 'MSG_CONVERSATION_LEAVE_FAILURE'; export const MSG_CONVERSATION_USERS_REQUEST = 'MSG_CONVERSATION_USERS_REQUEST'; export const MSG_CONVERSATION_USERS_SUCCESS = 'MSG_CONVERSATION_USERS_SUCCESS'; export const MSG_CONVERSATION_USERS_FAILURE = 'MSG_CONVERSATION_USERS_FAILURE'; export const MSG_CONVERSATION_ONLINE_REQUEST = 'MSG_CONVERSATION_ONLINE_REQUEST'; export const MSG_CONVERSATION_ONLINE_SUCCESS = 'MSG_CONVERSATION_ONLINE_SUCCESS'; export const MSG_CONVERSATION_ONLINE_FAILURE = 'MSG_CONVERSATION_ONLINE_FAILURE'; export const MSG_CONVERSATION_DELETE_REQUEST = 'MSG_CONVERSATION_DELETE_REQUEST'; export const MSG_CONVERSATION_DELETE_SUCCESS = 'MSG_CONVERSATION_DELETE_SUCCESS'; export const MSG_CONVERSATION_DELETE_FAILURE = 'MSG_CONVERSATION_DELETE_FAILURE'; export const MSG_CONVERSATION_DELETE_MSGS_REQUEST = 'MSG_CONVERSATION_DELETE_MSGS_REQUEST'; export const MSG_CONVERSATION_DELETE_MSGS_SUCCESS = 'MSG_CONVERSATION_DELETE_MSGS_SUCCESS'; export const MSG_CONVERSATION_DELETE_MSGS_FAILURE = 'MSG_CONVERSATION_DELETE_MSGS_FAILURE'; export const MSG_CONVERSATION_DISTURB_REQUEST = 'MSG_CONVERSATION_DISTURB_REQUEST'; export const MSG_CONVERSATION_DISTURB_SUCCESS = 'MSG_CONVERSATION_DISTURB_SUCCESS'; export const MSG_CONVERSATION_DISTURB_FAILURE = 'MSG_CONVERSATION_DISTURB_FAILURE'; export const MSG_CONVERSATION_MARK_ALL_READ_REQUEST = 'MSG_CONVERSATION_MARK_ALL_READ_REQUEST'; export const MSG_CONVERSATION_MARK_ALL_READ_SUCCESS = 'MSG_CONVERSATION_MARK_ALL_READ_SUCCESS'; export const MSG_CONVERSATION_MARK_ALL_READ_FAILURE = 'MSG_CONVERSATION_MARK_ALL_READ_FAILURE'; export function postNewConversation(userId) { return { [CALL_API]: { endpoint: ApiRoutes.messengerConversationsByUserId(userId), schema: Schemas.CONVERSATION, types: [ MSG_CONVERSATION_POST_REQUEST, MSG_CONVERSATION_POST_SUCCESS, MSG_CONVERSATION_POST_FAILURE, ], opts: postOpts(), }, }; } export function loadMessages(conversationId, data = {}) { return { [CALL_API]: { endpoint: makeGetUrl( ApiRoutes.messenger_load_messages_url(conversationId), data ), schema: Schemas.MESSAGE_COLL, types: [ MSG_CONVERSATION_MSGS_REQUEST, MSG_CONVERSATION_MSGS_SUCCESS, MSG_CONVERSATION_MSGS_FAILURE, ], opts: defaultOpts, }, conversationId, }; } export function loadArchivedMessages(conversationId) { return (dispatch, getState) => { const state = getState(); const conversation = state .entities .getIn(['conversation', String(conversationId)]); const messages = state .entities .get('message', Map()) .filter((m) => m.get('conversationId') === conversationId && m.get('createdAt')) // exclude replyMessages and submitted .sortBy((m) => moment(m.get('createdAt')) .valueOf()); const oldestMessage = messages.first(); const hasMore = ( messages.count() < conversation.get('messagesCount', +Infinity) ); return hasMore && oldestMessage && dispatch(loadMessages(conversationId, { toMessageId: oldestMessage.get('id'), limit: ARCHIVED_MESSAGES_LIMIT, })); }; } export function deleteMessages(conversationId, ids, everywhere = false) { return { [CALL_API]: { endpoint: ApiRoutes.messengerDeleteMessages(conversationId), schema: Schemas.NONE, types: [ MSG_CONVERSATION_DELETE_MSGS_REQUEST, MSG_CONVERSATION_DELETE_MSGS_SUCCESS, MSG_CONVERSATION_DELETE_MSGS_FAILURE, ], opts: deleteOpts({ ids: ids.join(','), all: !!everywhere, }), }, }; } export function leaveConversation(conversationId) { return { [CALL_API]: { endpoint: ApiRoutes.messengerConversationsByIdLeave(conversationId), schema: Schemas.NONE, types: [ MSG_CONVERSATION_LEAVE_REQUEST, MSG_CONVERSATION_LEAVE_SUCCESS, MSG_CONVERSATION_LEAVE_FAILURE, ], opts: putOpts(), }, conversationId, }; } export function deleteConversation(conversationId) { return { [CALL_API]: { endpoint: ApiRoutes.messengerConversationsById(conversationId), schema: Schemas.NONE, types: [ MSG_CONVERSATION_DELETE_REQUEST, MSG_CONVERSATION_DELETE_SUCCESS, MSG_CONVERSATION_DELETE_FAILURE, ], opts: deleteOpts(), }, conversationId, }; } export function dontDisturb(conversationId, flag) { return { [CALL_API]: { endpoint: ApiRoutes.messengerDontDisturb(conversationId), schema: Schemas.CONVERSATION, types: [ MSG_CONVERSATION_DISTURB_REQUEST, MSG_CONVERSATION_DISTURB_SUCCESS, MSG_CONVERSATION_DISTURB_FAILURE, ], opts: flag ? postOpts() : deleteOpts(), }, }; } let osId = void 0; export function updateOnlineStatuses() { return (dispatch, getState) => { const userIds = getState() .entities .get('conversation') .filter((c) => c.has('recipientId') && !!c.get('recipientId')) .map((c) => c.get('recipientId')) .join(','); if (osId && typeof clearTimeout === 'function') { clearTimeout(osId); } if (typeof setTimeout === 'function') { osId = setTimeout( () => dispatch(updateOnlineStatuses()), UPDATE_ONLINE_STATUSES_TIMEOUT ); } return userIds.length > 0 && dispatch({ [CALL_API]: { endpoint: makeGetUrl(ApiRoutes.onlineStatuses(), { userIds }), schema: Schemas.MESSAGE_COLL, types: [ MSG_CONVERSATION_ONLINE_REQUEST, MSG_CONVERSATION_ONLINE_SUCCESS, MSG_CONVERSATION_ONLINE_FAILURE, ], opts: defaultOpts, }, }); }; } export function fetchConversationUsers(conversationId, usersIds) { const endpoint = makeGetUrl( ApiRoutes.messengerConversationsByIdUsers(conversationId), { usersIds } ); return { [CALL_API]: { endpoint, schema: Schemas.TLOG_COLL, types: [ MSG_CONVERSATION_USERS_REQUEST, MSG_CONVERSATION_USERS_SUCCESS, MSG_CONVERSATION_USERS_FAILURE, ], opts: defaultOpts, }, }; } export function markAllMessagesRead(conversationId) { return { [CALL_API]: { endpoint: ApiRoutes.messengerMarkAllMessagesRead(conversationId), schema: Schemas.NONE, types: [ MSG_CONVERSATION_MARK_ALL_READ_REQUEST, MSG_CONVERSATION_MARK_ALL_READ_SUCCESS, MSG_CONVERSATION_MARK_ALL_READ_FAILURE, ], opts: putOpts(), }, conversationId, }; }
JavaScript
CL
d2ab7036efe3932191eaecd17ea3e73507d9df485a2c614f63e5bbd821741099
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. goog.provide('viz.mojom.FrameDeadline'); viz.mojom.FrameDeadline = class { constructor() { /** @type { !mojoBase.mojom.TimeTicks } */ this.frameStartTime; /** @type { !number } */ this.deadlineInFrames; /** @type { !boolean } */ this.useDefaultLowerBoundDeadline; /** @type { !mojoBase.mojom.TimeDelta } */ this.frameInterval; } };
JavaScript
CL
b626807c83592e5a4c075da2671f3733fb3cba582b44970819da1064ca4774c6
áfrica y la historia que le fue sustraída Nairobi - La noticia de que la Universidad de yale se ha comprometido a devolver miles de artefactos que uno de su-fem-sg investigadores llevó a esta universidad desde Perú el año 1911 , dummy-she hizo que dummy-she recordara una fiesta a la que dummy-I asistí hace poco - una fiesta de la que dummy-I tuve que salir antes de tiempo . Una persona de áfrica , amiga mía , me había invitado a dicha fiesta , que se llevaba a cabo en la casa de una persona conocida suya . El anfitrión , un americano bien acomodado , nos mostró con orgullo su-masc-sg colección de pinturas y esculturas . Cuando dummy-we mirábamos la colección , dummy-I vi un objeto que parecía ser africano , pero dummy-nonhum no estaba muy segura . En algunas ocasiones , dummy-I identifiqué erróneamente piezas de arte , catalogándolas como arte africano , mas posteriormente dummy-I me enteré que en verdad dummy-they eran piezas de arte nativo americano . La pieza era un cuero estirado y decorado con cuentas de colores , y se encontraba enmarcada detrás de un vidrio . Las cuentas eran del mismo tipo que las que usan las personas de mi pueblo , los Masáis ; pero el color predominante era el azul , no el rojo que es el favorito de nuestra gente . " ¿ De dónde dummy-nonhum es esto ? " , dummy-I pregunté , apuntando a la pieza en la pared . " Esto viene de Zimbabue " , dijo nuestro anfitrión . " dummy-it Es una falda de boda que fue usada en una ceremonia nupcial real de los Ndebele en el año 1931 " . Para una persona africana que-hum se encuentra lejos de su-hum-sg hogar , encontrar en exhibición algo de áfrica , inclusive así se trate del objeto más insignificante , dummy-it puede ser una ocasión feliz . Cuando dummy-I veo que se vende café de Kenia o Etiopía en Nueva york o París , por ejemplo , dummy-I me siento orgullosa de que existan estadounidenses y europeos que consideren valioso un producto proveniente de mi tierra natal . Enterarme de que un americano bien acomodado consideraba que una falda tradicional africana era digna de un sitial en su-nonhum-sg hogar dummy-nonhum suscitó el mismo sentimiento . No obstante , el siguiente comentario de nuestro anfitrión borró inmediatamente dicha emoción . Se jactó de que dummy-he había adquirido la falda ilegalmente a través de una persona amiga que-hum había " pagado " a un funcionario del gobierno de Zimbabue para sacarla ilegalmente del país como contrabando . La persona amiga con la que-hum me encontraba y yo cruzamos miradas , y tratamos de no mostrar nuestra desaprobación . " dummy-I Tengo tanto disgusto " , dummy-nonhum me dijo , un momento después . " Vámonos antes de que dummy-nonhum me emborrache y diga algo fuera de lugar a este sujeto " . dummy-we Salimos de la fiesta . De camino a casa , dummy-we despotricamos airadamente sobre lo que habíamos presenciado . Sin embargo , nuestra rabia fue impulsada más por el papel que desempeña el Occidente para sostener la corrupción en áfrica que por el destino que específicamente había tenido el artefacto de Zimbabue que acabábamos de ver . No fue hasta que dummy-I me enteré de que Yale había devuelto los objetos peruanos que empecé a pensar acerca de la importancia de los artefactos africanos desde una perspectiva cultural e histórica . Muchos artefactos africanos , por supuesto , han terminado en museos occidentales o en manos de coleccionistas privados occidentales . Las piezas son , en gran parte , el botín que los europeos saquearon de áfrica durante la trata de esclavos y la época colonial . Tal vez la pieza de arte más famosa es la escultura conocida como la reina Bangwa . Con un valor de varios millones de dólares , dummy-it es la pieza de arte africano más cara del mundo . Las exposiciones de arte africano por lo general incluyen relatos sobre el origen de cada pieza ; estos relatos a menudo están vinculados a un reino africano . Sin embargo , la información sobre cuál fue la travesía de un artefacto hasta llegar al occidente es con frecuencia vaga o inexistente . Por ejemplo , el periódico The new york times publicó un artículo el año pasado acerca de una exposición de arte africano en el Museo metropolitano . El Times informó que la reina Bangwa ha sido de propiedad de muchos coleccionistas famosos " desde que dummy-she salió de su-fem-sg santuario real en Camerún a finales del siglo xix " . De hecho , la reina Bangwa " salió " de Camerún con Gustav conrau , un explorador alemán de la época de la colonia que más tarde entregó la estatua a un museo en su-nonhum-sg país de origen . Teniendo en cuenta las tácticas de dudosa reputación que los agentes coloniales típicamente usaron para separar a los africanos de su-pl posesiones , es poco probable que la reina Bangwa hubiese salido por voluntad propia . Los artefactos africanos que están en exhibición en Nueva york , Londres , París y otros lugares tienen historias similares . El reclamo que hizo Perú pidiendo el retorno de su-nonhum-sg patrimonio cultural me hizo desear lo mismo para los artefactos africanos que fueron saqueados . Sin embargo , Perú es fundamentalmente distinto a cualquier país africano . su-nonhum-sg demanda refleja respeto por su-nonhum-sg pasado . Para los peruanos , los artefactos son un recordatorio de la gran civilización Inca que los conquistadores europeos destruyeron . Los africanos , por el contrario , tienden a disminuir la importancia de su-pl pasado . Hasta cierto punto , ellos parecen haber internalizado la idea colonial paternalista que conceptualizaba a áfrica como un lugar primitivo que necesitaba ser civilizado . dummy-we No atesoramos nuestros artefactos históricos , porque ellos nos recuerdan de la supuesta inferioridad de nuestras ricas civilizaciones . No es de extrañar que un artefacto de importancia cultural , como lo es una falda de una boda real , pueda ser sacado como contrabando de un país sin que nadie lo note . Hasta que los africanos reconozcan el valor de su-pl historia , la producción artística de su-pl culturas dummy-nonhum está a disposición de quien se la quiera llevar .
JavaScript
CL
a17556731ef5a67613dd4ecbf2296a10f1106e23f6a433b78187f62df6c2adb9
const { errors } = require('arsenal'); const collectCorsHeaders = require('../utilities/collectCorsHeaders'); const deleteBucket = require('./apiUtils/bucket/bucketDeletion'); const { metadataValidateBucket } = require('../metadata/metadataUtils'); const { pushMetric } = require('../utapi/utilities'); const monitoring = require('../utilities/monitoringHandler'); /** * bucketDelete - DELETE bucket (currently supports only non-versioned buckets) * @param {AuthInfo} authInfo - Instance of AuthInfo class with requester's info * @param {object} request - request object given by router * including normalized headers * @param {function} log - Werelogs log service * @param {function} cb - final callback to call * with the result and response headers * @return {undefined} */ function bucketDelete(authInfo, request, log, cb) { log.debug('processing request', { method: 'bucketDelete' }); if (authInfo.isRequesterPublicUser()) { log.debug('operation not available for public user'); monitoring.promMetrics( 'DELETE', request.bucketName, 403, 'deleteBucket'); return cb(errors.AccessDenied); } const bucketName = request.bucketName; const metadataValParams = { authInfo, bucketName, requestType: 'bucketDelete', request, }; return metadataValidateBucket(metadataValParams, log, (err, bucketMD) => { const corsHeaders = collectCorsHeaders(request.headers.origin, request.method, bucketMD); if (err) { log.debug('error processing request', { method: 'metadataValidateBucket', error: err }); monitoring.promMetrics( 'DELETE', bucketName, err.code, 'deleteBucket'); return cb(err, corsHeaders); } log.trace('passed checks', { method: 'metadataValidateBucket' }); return deleteBucket(authInfo, bucketMD, bucketName, authInfo.getCanonicalID(), log, err => { if (err) { monitoring.promMetrics( 'DELETE', bucketName, err.code, 'deleteBucket'); return cb(err, corsHeaders); } pushMetric('deleteBucket', log, { authInfo, bucket: bucketName, }); monitoring.promMetrics( 'DELETE', bucketName, '204', 'deleteBucket'); return cb(null, corsHeaders); }); }); } module.exports = bucketDelete;
JavaScript
CL
50efa5457ee43d80cc417e438f7adf8b890bf54d7f300a01d4a7e9a23cdab835
'use strict' const swapper = require('../utils/tokenSwapper') const { deployContract} = require('../utils/setupHelper') const {ethers} = require('hardhat') const {defaultAbiCoder} = ethers.utils const {deposit} = require('../utils/poolOps') const {expect} = require('chai') const time = require('../utils/time') const {BigNumber: BN} = require('ethers') const DECIMAL = BN.from('1000000000000000000') // Crv strategy behavior test suite function shouldBehaveLikeStrategy(poolName, collateralName) { let pool, strategy, controller, collateralToken, collateralDecimal, feeCollector, swapManager, accounts let owner, user4, user2, user3 function convertTo18(amount) { const multiplier = DECIMAL.div(BN.from('10').pow(collateralDecimal)) return BN.from(amount).mul(multiplier).toString() } function convertFrom18(amount) { const divisor = DECIMAL.div(BN.from('10').pow(collateralDecimal)) return BN.from(amount).div(divisor).toString() } describe(`${poolName}:: CrvStrategy basic tests`, function () { beforeEach(async function () { accounts = await ethers.getSigners() ;[owner, user4, user2, user3] = accounts pool = this.pool controller = this.controller strategy = this.strategy collateralToken = this.collateralToken feeCollector = this.feeCollector swapManager = this.swapManager // Decimal will be used for amount conversion collateralDecimal = await this.collateralToken.decimals() }) it('Should sweep erc20 from strategy', async function () { const metAddress = '0xa3d58c4e56fedcae3a7c43a725aee9a71f0ece4e' const token = await ethers.getContractAt('ERC20',metAddress) const tokenBalance = await swapper.swapEthForToken(1, metAddress, user4, strategy.address) await strategy.sweepErc20(metAddress) const totalSupply = await pool.totalSupply() const metBalanceInPool = await token.balanceOf(pool.address) expect(totalSupply).to.be.equal('0', `Total supply of ${poolName} is wrong`) expect(metBalanceInPool).to.be.equal(tokenBalance, 'ERC20 token balance is wrong') }) describe(`${poolName}:: DepositAll in CrvStrategy`, function () { it(`Should deposit ${collateralName} and call depositAll() in Strategy`, async function () { const depositAmount = await deposit(pool, collateralToken, 2, user3) const tokensHere = await pool.tokensHere() await strategy.depositAll() const vPoolBalance = await pool.balanceOf(user3.address) expect(convertFrom18(vPoolBalance)).to.be.equal( depositAmount, `${poolName} balance of user is wrong` ) const totalLocked = await pool.tokenLocked() const adjTotalLocked = await strategy.estimateFeeImpact(totalLocked) expect(tokensHere).to.be.gte(adjTotalLocked, 'Token locked is not correct') }) }) describe(`${poolName}:: DepositValue in CrvStrategy`, function () { it(`Should deposit ${collateralName} and call depositAll() in Strategy`, async function () { const depositAmount = await deposit(pool, collateralToken, 2, user3) const tokensHere = await pool.tokensHere() await strategy.depositAll() const vPoolBalance = await pool.balanceOf(user3.address) expect(convertFrom18(vPoolBalance)).to.be.equal( depositAmount, `${poolName} balance of user is wrong` ) const totalLocked = await pool.tokenLocked() const adjTotalLocked = await strategy.estimateFeeImpact(totalLocked) expect(tokensHere).to.be.gte(adjTotalLocked, 'Token locked is not correct') }) }) describe(`${poolName}:: Interest fee via CrvStrategy`, function () { it('Should handle interest fee correctly after withdraw', async function () { await deposit(pool, collateralToken, 40, user2) await pool.rebalance() const pricePerShare = await pool.getPricePerShare() const vPoolBalanceBefore = await pool.balanceOf(feeCollector.address) // Time travel 10 hours to earn some crv & dai await time.increase(100 * 60 * 60) await swapManager['updateOracles()']() await pool.rebalance() const pricePerShare2 = await pool.getPricePerShare() expect(pricePerShare2).to.be.gt(pricePerShare, 'PricePerShare should be higher after time travel') await pool.connect(user2).withdraw(await pool.balanceOf(user2.address)) const tokenLocked = await pool.tokenLocked() expect(tokenLocked).to.be.gt('0', 'Token locked should be greater than zero') const totalSupply = await pool.totalSupply() expect(totalSupply).to.be.gt('0', 'Total supply should be greater than zero') const vPoolBalanceAfter = await pool.balanceOf(feeCollector.address) expect(vPoolBalanceAfter).to.be.gt(vPoolBalanceBefore, 'Fee collected is not correct') const dust = DECIMAL.div(BN.from('100')) // Dust is less than 1e16 const tokensHere = await pool.tokensHere() expect(tokensHere).to.be.lt(dust, 'Tokens here is not correct') }) }) describe(`${poolName}:: Updates via Controller`, function () { it('Should call withdraw() in strategy', async function () { await deposit(pool, collateralToken, 20, user4) await pool.rebalance() const vPoolBalanceBefore = await pool.balanceOf(user4.address) const collateralBalanceBefore = await collateralToken.balanceOf(pool.address) const totalSupply = await pool.totalSupply() const price = await pool.getPricePerShare() const withdrawAmount = totalSupply.mul(price).div(DECIMAL).toString() const target = strategy.address const methodSignature = 'withdraw(uint256)' const data = defaultAbiCoder.encode(['uint256'], [withdrawAmount]) await controller.executeTransaction(target, 0, methodSignature, data) const vPoolBalance = await pool.balanceOf(user4.address) const collateralBalance = await collateralToken.balanceOf(pool.address) expect(collateralBalance).to.be.gt( collateralBalanceBefore, `${collateralName} balance of pool is wrong`) expect(vPoolBalance).to.be.eq(vPoolBalanceBefore, `${poolName} balance of user is wrong`) }) it('Should call withdrawAll() in strategy', async function () { await deposit(pool, collateralToken, 2, user3) await pool.rebalance() // const totalLockedBefore = await strategy.totalLocked() const target = strategy.address const methodSignature = 'withdrawAll()' const data = '0x' await controller.connect(owner).executeTransaction(target, 0, methodSignature, data) // const tokensInPool = await pool.tokensHere() const totalLocked = await strategy.totalLocked() expect(totalLocked).to.be.eq('0', 'Total Locked should be 0') // expect(tokensInPool).to.be.gte(totalLockedBefore, // 'Tokens in pool should be at least what was estimated') }) it('Should rebalance after withdrawAll() and adding new strategy', async function () { await deposit(pool, collateralToken, 10, user3) await pool.rebalance() // const totalLockedBefore = await strategy.totalLocked() const target = strategy.address let methodSignature = 'withdrawAll()' const data = '0x' await controller.connect(owner).executeTransaction(target, 0, methodSignature, data) strategy = await deployContract(this.newStrategy,[controller.address, pool.address]) methodSignature = 'approveToken()' await controller.executeTransaction(strategy.address, 0, methodSignature, data) await controller.updateStrategy(pool.address, strategy.address) await pool.rebalance() const totalLockedAfter = await strategy.totalLocked() expect(totalLockedAfter).to.be.gte('0', 'Total locked with new strategy is wrong') const withdrawAmount = await pool.balanceOf(user3.address) await pool.connect(user3).withdraw(withdrawAmount) const collateralBalance = convertTo18(await collateralToken.balanceOf(user3.address)) expect(collateralBalance).to.be.gt('0', `${collateralName} balance of user is wrong`) }) }) describe('Interest Earned', function () { it('Should get the interest earned', async function() { let interestEarned = await strategy.interestEarned() expect(interestEarned).to.be.eq('0', 'Phantom interest is occurring') await deposit(pool, collateralToken, 10, user3) await pool.rebalance() // Time travel 10 hours to earn some crv & dai await time.increase(100 * 60 * 60) await swapManager['updateOracles()']() // withdrawals trigger update to stored values await pool.connect(user3).withdraw(BN.from(1).mul(DECIMAL)) let interestEarnedAfter = await strategy.interestEarned() expect(interestEarnedAfter).to.be.gte(interestEarned, 'Interest did not grow (1)') await pool.connect(user3).withdraw(BN.from(1).mul(DECIMAL)) interestEarned = await strategy.interestEarned() await time.increase(100 * 60 * 60) await swapManager['updateOracles()']() await pool.connect(user3).withdraw(BN.from(1).mul(DECIMAL)) interestEarnedAfter = await strategy.interestEarned() expect(interestEarnedAfter).to.be.gte(interestEarned, 'Interest did not grow (2)') const percentIncrease = (interestEarnedAfter.sub(interestEarned)) .mul(BN.from(10000)) .div(interestEarned).toNumber() const readablePI = percentIncrease / 100 // actual interest diff here should be just over 100%, because we earn one extra block of interest expect(readablePI).to.be.lt(101, 'Interest calculation is wrong') }) }) }) } module.exports = {shouldBehaveLikeStrategy}
JavaScript
CL
c707be6890f925737e6d4de8ab152ea1c1ec0ac590912e988d37c850f4f20937
'use strict'; var dbm; var type; var seed; /** * We receive the dbmigrate dependency from dbmigrate initially. * This enables us to not have to rely on NODE_PATH. */ exports.setup = function(options, seedLink) { dbm = options.dbmigrate; type = dbm.dataType; seed = seedLink; }; exports.up = function(db, callback) { return db.addColumn('apology', 'tweetId', 'string', db.addColumn('apology', 'tweetUser', 'string', db.addColumn('apology', 'tweetImage', 'string', callback))); }; exports.down = function(db, callback) { return db.removeColumn('apology', 'tweetImage', db.removeColumn('apology', 'tweetUser', db.removeColumn('apology', 'tweetId', callback))); }; exports._meta = { "version": 1 };
JavaScript
CL
618c206e04a8fb0ff8d91a3d5aa5df8f3bd471492d00bc5bb4bf5dd950640e68
const object1 = {} Object.defineProperties(object1, { property1: { value: 42, writable: true }, property2: {} }) // define a single property const object2 = {}; Object.defineProperty(object2, 'property1', { value: 42, writable: false }); object2.property1 = 77; // throws an error in strict mode console.log(object2.property1); // expected output: 42 console.log(object2.property1) // expected output: 42 // configurable // true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. // Defaults to false. // enumerable // true if and only if this property shows up during enumeration of the properties on the corresponding object. // Defaults to false. // value // The value associated with the property.Can be any valid JavaScript value(number, object, function, etc). // Defaults to undefined. // writable // true if and only if the value associated with the property may be changed with an assignment operator. // Defaults to false. // get // A function which serves as a getter for the property, or undefined if there is no getter.The function's return value will be used as the value of the property. // Defaults to undefined. // set // A function which serves as a setter for the property, or undefined if there is no setter.The function will receive as its only argument the new value being assigned to the property. // Defaults to undefined.
JavaScript
CL
6a97ab600d0fd154bc49fba9f0241fe0df113efec33dbfa3c2cdc491bf33846f
import Vue from 'vue' import globalTable from '@/components/base/global-table/table.vue' // 全局表格组件 import globalSearch from '@/components/base/global-search.vue' // 全局筛选/查询组件 import globalMinPage from '@/components/base/global-table/min-page.vue' // 全局筛选/查询组件 import globalPage from '@/components/base/global-table/page.vue' // 分页 import globalRichText from '@/components/base/rich-text/global-rich-text.vue' import globalRichTextNew from '@/components/base/rich-text/global-rich-text-question.vue' import globalRichTextExamin from '@/components/base/rich-text/global-rich-text-examination.vue' import backTop from '@/components/base/backTop.vue' import globalEditor from '@/components/base/global-editor.vue' import globalNav from '@/components/base/global-nav.vue' // 全局菜单组件 import globalLoding from '@/components/base/global-loading.vue' import globalQuestionSearch from '@/components/base/search-questions.vue' const AutitMark = { install (vue) { Vue.component('global-search', globalSearch) Vue.component('global-rich-text', globalRichText) Vue.component('global-rich-text-question', globalRichTextNew) Vue.component('global-rich-text-examination', globalRichTextExamin) Vue.component('back-top', backTop) Vue.component('global-table', globalTable) Vue.component('global-min-page', globalMinPage) Vue.component('global-page', globalPage) Vue.component('global-editor', globalEditor) Vue.component('global-nav', globalNav) Vue.component('global-loading', globalLoding) Vue.component('global-question-search', globalQuestionSearch) } } export default AutitMark
JavaScript
CL
9c605220c7ed0af554869304c5634343c03cb647c0491745283fdfde238bfcfc
'use strict'; define(['services/utils/routeResolver' ], function() { angular.isUndefinedOrNull = function(val) { return angular.isUndefined(val) || val === null }; var app = angular.module('ocrApp', ['localization', 'ngSanitize', 'ngRoute', 'ngAnimate', 'ngResource', 'ngCookies', 'ui.bootstrap', 'ui', 'ui.select2', 'highcharts-ng', 'ngTable', 'smart-table', 'routeResolverServices', 'underscore', 'ngProgress', 'ui.bootstrap.transition', 'angularFileUpload', 'ngMaps', 'ngBootstrap', 'ngWebsocket', 'angular-growl', 'leaflet-directive', 'ngTagsInput', 'ngDragDrop', 'treeGrid', 'angular-button-spinner', 'angularTrix', 'htmlToPdfSave','angucomplete', 'ui.grid', 'ui.grid.grouping', 'ui.grid.selection', 'ui.grid.exporter', 'ui.grid.moveColumns']); app.run(['$rootScope', '$route', '$http', '$location', 'constantService', 'localize', 'authorizationService', '$websocket', 'configurationService', 'uiSelect2Config', function($rootScope, $route, $http, $location, constantService, localize, authorizationService, $websocket, configurationService, uiSelect2Config) { var userInfo; $rootScope.messagePageLocation = 'app/partials/message.html'; localize.setLanguage('en-US'); $rootScope.$on("$routeChangeStart", function (oldPath, newPath) { $rootScope.isWeb = true; $rootScope.pageTitle = newPath.$$route.title; if (newPath.$$route == undefined || newPath.$$route.isWeb) { $rootScope.layout = constantService.getWebLayout(); return; } userInfo = authorizationService.getUserInfo(); if(userInfo === undefined || userInfo === null){ $rootScope.layout = constantService.getWebLayout(); $location.path('/'); return; } $rootScope.isWeb = false; $rootScope.layout = constantService.getAppLayout(); $websocket.$new({ url: configurationService.wsDashboard, lazy: false, reconnect: false, reconnectInterval: 2000, enqueue: false, mock: false }); }); }]); app.config(['$routeProvider','routeResolverProvider','$controllerProvider', '$compileProvider', '$filterProvider', '$provide', '$locationProvider', '$httpProvider', 'growlProvider', function ($routeProvider,routeResolverProvider, $controllerProvider, $compileProvider, $filterProvider, $provide, $locationProvider, $httpProvider, growlProvider) { growlProvider.globalTimeToLive(6000); growlProvider.globalPosition('bottom-right'); growlProvider.globalReversedOrder(false); growlProvider.onlyUniqueMessages(true); growlProvider.globalDisableCountDown(true); growlProvider.globalDisableIcons(false); growlProvider.globalDisableCloseButton(false); app.register = { controller: $controllerProvider.register, //directive: $compileProvider.directive, filter: $filterProvider.register, //factory: $provide.factory, //service: $provide.service }; // Provider-based service. app.service = function( name, constructor ) { $provide.service( name, constructor ); return( this ); }; // Provider-based factory. app.factory = function( name, factory ) { $provide.factory( name, factory ); return( this ); }; // Provider-based directive. app.directive = function( name, factory ) { $compileProvider.directive( name, factory ); return( this ); }; var route = routeResolverProvider.route; $routeProvider //url, page and controller name prefix, dir path, title, isWeb .when('/', route.resolve('signin', 'app/security/', 'Signin', true)) .when('/home', route.resolve('home', 'app/dashboard/', 'Home', false)) .when('/dashboard', route.resolve('dashboard', 'app/dashboard/', 'Dashboard', false)) .otherwise({ redirectTo: '/dashboard' }); }]); return app; });
JavaScript
CL
bf140d284ae2534fdb8dc79f35d452d7e99af07c901ca31d08d9a1d9f3d1f309
/** @wordpress */ import { __ } from "@wordpress/i18n"; import { useEffect } from "@wordpress/element"; import { InnerBlocks, InspectorControls, RichText, } from "@wordpress/block-editor"; /** components */ import TextColumnsPanel from "./panels/text-columns"; const edit = ({ className, attributes, setAttributes, isSelected }) => { const { textColumns } = attributes; useEffect(() => { setAttributes({ align: "full" }); }); const onTextColumns = (textColumns) => setAttributes({ textColumns }); return ( <> <InspectorControls> <TextColumnsPanel textColumns={textColumns} onTextColumns={onTextColumns} /> </InspectorControls> <div className={className}> <section className="bg-fixed bg-no-repeat bg-cover background-flowing" style={{ backgroundImage: `url('/app/themes/sage/dist/images/background-flowing.jpg')`, backgroundPosition: `40% 20%`, }} > <div className="px-4 pb-16 bg-white-800"> <div className="container"> <div className="flex flex-col justify-between px-4 py-16 mx-auto md:flex-row"> <div className="w-full px-2 pr-8 mb-8 md:w-3/5"> <RichText tagName={`div`} placeholder={`Insert heading here.`} className={`inline-block leading-none text-4xl md:text-5xl font-display uppercase text-black-900`} value={attributes.heading && attributes.heading} onChange={(value) => setAttributes({ heading: value })} /> <div className={ textColumns && `col-count-1 sm:col-count-2 md:col-count-1 lg:col-count-2 xl:col-count-3 col-gap-md` } > <RichText tagName={`div`} className={`font-sans text-md`} placeholder={`Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.`} value={attributes.text && attributes.text} onChange={(value) => setAttributes({ text: value })} /> </div> </div> <div className="w-full md:w-2/5"> <div className="content-center w-full shadow:md transition-all transition transition-duration-2000 hover:shadow-epic bg-black-900"> <div className={`text-white w-full font-sans inline-block p-4 text-sm`} > <span className="inline-block pb-0 mb-0 font-sans text-sm text-white w-100"> Copy/paste embed code here. </span> <InnerBlocks templateLock={true} template={[["core/html"]]} /> </div> </div> </div> </div> </div> </div> </section> </div> </> ); }; export default edit;
JavaScript
CL
1c494cae33816453380534bb7f766f5a840f30edacf28c9e070ef6fe8cae9d72
import Vue from 'vue' import App from './App.vue' import Vuetify from 'vuetify' import VueRouter from 'vue-router' import 'vuetify/dist/vuetify.min.css' import * as VueGoogleMaps from "vue2-google-maps"; import store from './store' import compdefault from './components/default/Default2.vue' import googleMap from './components/map/GoogleMap3.vue' import googleMap2 from './components/map/GoogleMap4.vue' import admin from './components/admin/Admin2.vue' import cards from './components/admin/Cards.vue' import raport from './components/raport/Raport.vue' import YmapPlugin from 'vue-yandex-maps' Vue.use(YmapPlugin) Vue.use(VueRouter); Vue.use(Vuetify); Vue.use(VueGoogleMaps, { load: { key: "AIzaSyAkBWkvLQaraj01c3u-7GY6xmo4trsKLlQ", libraries: 'places,drawing,visualization'// necessary for places input } }); var router = new VueRouter({ mode: 'history', routes: [ { path: '/', component: compdefault }, { path: '/map', component: googleMap }, { path: '/admin', component: admin }, { path: '/mmb', component: googleMap2 }, { path: '/car', component: cards }, { path: '/raport', component: raport } ] }) new Vue({ el: '#app', router: router, render: h => h(App), store: store })
JavaScript
CL
2c1895e345d295215c5a2246d6561f17c1e5e6d40c49b04b7b448d66cb6cddb9
/** * 思路: * 1、先用require插件通过依赖关系压缩合并js * 2、cssMini方法合并index.html引用的css样式 * 3、图片压缩 * 4、读取requirejsMain。js的path配置文件并存储 * */ var rjs = require('requirejs') ,fs = require('fs') ,connect=require('gulp-connect') ,httpUrl = require('url') ,mock=require('mockjs') ,Tool = require('./tool')//md5 工具 ,path=require('path') ; /* ========================================================================== 项目压缩合并插件 ============================================================================ */ var Release = function (option,cd) { this.option = option; //this.Tool = Tool;//md5 工具 this.md5FileConf = {};//存放加密后文件列表信息 this.imgFile = {}; this.fileArr = [];//存放releae目录下有效文件地址 this.mainConfigFileArr = '';//requirejsMain.js 压缩后的文件文本内容 this.option["modules"] = eval(readFileSync(this.option.modules,true)); this.deleteFileConfig=eval(readFileSync(this.option.deleteFileConfig,true)); this._rjs(cd); }; Release.prototype._rjs=function (cd) { var _this = this; console.log("requirejs is:start"); rjs.optimize({ appDir: _this.option.appDir, baseUrl: _this.option.baseUrl, mainConfigFile: _this.option.appDir +_this.option.mainConfigFile, dir: _this.option.dir, optimize: _this.option.optimize, preserveLicenseComments: _this.option.preserveLicenseComments, optimizeCss: _this.option.optimizeCss, modules: _this.option.modules }, function () { console.log("requirejs is:end"); _this._release(); cd(); }, cd); }; Release.prototype._release=function (cd) { this.mainConfigFile=this.option.dir + this.option.mainConfigFile;//requirejsMain.js 压缩后的文件地址路径 this.mainConfigString=readFileSync(this.mainConfigFile,true); this.noReleaseConfig=(this.option.noReleaseConfig?this.option.noReleaseConfig:[]);//发布生产环境后不应该包括的文件已经文件夹 //this._rel(cd); console.log("==================================="); console.log("Add the version number to img is:start"); this._imgAddMd5(); console.log("Add the version number to img is:end"); console.log("Combination of CSS is :start"); cssMini(this.option.css,this.option.cssMini,this.option.dir); console.log("Combination of CSS is :end"); console.log("==================================="); console.log("To regenerate the html is:start"); writeHtml(this.option._index,this.option.index,true); console.log("To regenerate the html is:end"); console.log("==================================="); console.log("==================================="); console.log("To get the requireMain.js is:start"); this.requireMain=getRequireMain(this.mainConfigString); console.log("To get the requireMain.js is:end"); this.requireMain["paths"]=getMd5RequireMain(this.getRevision(true,true), this.requireMain); this.requireMain["baseUrl"]=this.option.dir; this.requireMain["urlArgs"]=function(id, url) { if (url.match("\.tpl$")) { return '?v='+Math.random(); } }; console.log("==================================="); console.log("To regenerate the requireMain.js is:start"); writeRequireMain(this.mainConfigFile,this.mainConfigString,this.requireMain); console.log("To regenerate the requireMain.js is:end"); console.log("==================================="); console.log("Project completed packaging"); }; /** * 循环目录返回 文件地址路径信息 * 回调函数返回值为: * filePath: 文件地址 * suffix:文件扩展名 * fileName: 文件名 * */ Release.prototype._loopFile=function(loopCallback){ var _this=this; if(!this.fileArr.length){ var loop = function (dir, callback) { var files = fs.readdirSync(dir); files.forEach(function(fileItem){ var fileItemObj={ filePath:dir + fileItem,//文件或者地址全路径 suffix:path.extname(dir + fileItem),//文件扩展名,为文件夹是为空 fileDir:dir //文件所在目录,或者文件夹上一个目录 }; if(is_delete(_this.deleteFileConfig,fileItemObj,_this.option.dir)){ //删除不需要的文件或者文件夹 deleteFile(fileItemObj.filePath) }else{ if (!fs.lstatSync(fileItemObj.filePath).isDirectory()) { callback && callback(fileItemObj.filePath, fileItem); } else { loop(fileItemObj.filePath + "/", callback) } } }); }; loop(this.option.dir, function (filePath, filesName) { var fileObj={ filePath: filePath, suffix:path.extname(filePath), fileName: filesName }; _this.fileArr.push(fileObj); loopCallback && loopCallback(fileObj); }); }else{ //避免多次循环文件 this.fileArr.forEach(function(item){ loopCallback && loopCallback(item) }); } }; //对外暴露方法 //获取文件名对应版本号信息 Release.prototype.getRevision = function (is_noSuffix, is_js) { var _this = this, revision = {}, revisionFun = function (file) { var string = readFileSync(file.filePath); var fileName = (is_noSuffix ? Tool.path_without_ext(file.filePath) : file.filePath ).replace(_this.option.dir, ""); revision[fileName] = file.filePath.replace(_this.option.dir, "") + "?v=" + Md5(string); }; this._loopFile(function (file) { if (is_js) { if (file.suffix == '.js') { revisionFun(file) } } else { revisionFun(file) } }); return revision; }; //图片MD5加密加版本号 Release.prototype._imgAddMd5 = function () { var _this=this,root=this.option.dirRoot, writeImgSync=function(filePath,string){ fs.writeFileSync(filePath,string.replace(new RegExp(_this.option.appDir,"g"),_this.option.dir),"utf-8") }; this._loopFile(function (file) { var string=readFileSync(file.filePath, true), arr = []; if(!string) return false; if (/.(js|tpl)$/g.test(file.suffix)) { arr = unique(string.match(/<img[^>]*>/g)); if (arr && arr.length) { arr.forEach(function (item) { var src = item.match(/src=(\'|\")[^\1]*?\1/g); if (!src||!(/.(png|gif|jpg)/g.test(src[0]))) return false; src = src[0].replace("src=", "module.exports="); src = eval(src); var imgPath = root+ Tool.join_path("./", src); if (fs.existsSync(imgPath) && (/.(png|gif|jpg)$/g.test(src))&&(src.indexOf("?v=")<=-1)) { string = string.replace(new RegExp(src, 'g'), src + "?v=" + Md5(readFileSync(imgPath))); } }); } writeImgSync(file.filePath,string); } if (/.(css|js)$/g.test(file.suffix)) { arr = unique(string.match(/url[^\(]*?\([^\)]*?\.(png|gif|jpg)(\'|\")*?\)/g)); if (arr && arr.length) { arr.forEach(function (item) { var src = item.replace(/url[^\(]*?\(/g, "").replace(")", "").replace(/(\'|\")/g, ""); var imgPath =Tool.join_path(file.filePath.replace(file.fileName, ""), src); if (fs.existsSync(imgPath) ) { if((/.(png|gif|jpg)$/g.test(src))&&(src.indexOf("?v=")<=-1)){ /* console.log("rootImgPath:"+root+imgPath); console.log("rootImgPath:"+imgPath); console.log("srcIMG:"+src); console.log("====================================================");*/ string = string.replace(new RegExp(src, 'g'),src + "?v=" + Md5(readFileSync(imgPath))); } }else{ imgPath = Tool.join_path(file.filePath.replace(file.fileName, ""),'../'+src); if (fs.existsSync(imgPath)&&(/.(png|gif|jpg)$/g.test(src))&&(src.indexOf("?v=")<=-1) ) { /* console.log("imgPath:"+imgPath);*/ //console.log("rootImgPath:"+root+imgPath); string = string.replace(new RegExp(src, 'g'),src + + "?v=" + Md5(readFileSync(imgPath))); }else{ //console.log("图片:"+src+" 不存在") } } }); } writeImgSync(file.filePath,string); } }); }; //css 合并 function cssMini(fileIn, fileOut,dir){ var finalCode=[]; fileIn.forEach(function(flieInItem){ finalCode.push(readFileSync(dir+flieInItem,true)); }); fs.writeFileSync(dir+fileOut, finalCode.join(""), 'utf8'); } //获取加密后的requireConfig.path配置 function getMd5RequireMain(revision,config){ var paths = config.paths; for (var key in paths) { if (revision[paths[key]]) { revision[key] = revision[paths[key]]; delete revision[paths[key]]; }else{ revision[key] = paths[key]; } } return revision } //获取requireConfig配置 function getRequireMain(mainConfigSting){ return eval("var require={},exports;require.config=function(option){exports =option;};"+mainConfigSting+";module.exports =(exports?exports:require);") } //重写 requireConfig function writeRequireMain(FileDir,mainConfigSting,config){ var configString=mainConfigSting.match(/require.config\(\{[\s\S]*?(\}\))/g); if(configString){ configString=configString[0]; mainConfigSting=mainConfigSting.replace(configString,"require.config("+JSON.stringify(config)+")"); }else{ mainConfigSting="var require="+JSON.stringify(config); } fs.writeFileSync(FileDir,mainConfigSting , 'utf8'); } //重新生成html function writeHtml(_html, html, is_release) { var string = readFileSync(_html, true), ifArr = string.match(/<(#if)[^>]*>[\s\S]*?<\/\1>/g) ; if (ifArr) { ifArr.forEach(function (item) { /*替换流程*/ // <#if -> if( // </#if> -> '} // <#else> -> '}else{str=' // > -> ){str=' var ite = item.replace("<#if", "if(").replace("<\/#if>", "'}").replace("<#else>", "'}else{str='").replace(/>[^>][1]?/, "){str='"); string = string.replace(item, eval("var isRelease=" + (is_release ? "true" : "false") + ",str='';" + (ite.replace(/\n/g, "$n").replace(/\r/g, "$r")) + ";module.exports=str").replace(/\$n/g, "\n").replace(/\$r/g, "\r")); }) } var scriptArr = string.match(/<(script)[^>]*(src)[1]?[^>]*>[\s\S]*?<\/\1>/g), linkArr = string.match(/<(link)[^>]*?>/g); scriptArr.forEach(function (item) { var src=item.match(/src=(\'|\")[^\1]*?\1/g)[0].replace("src=","module.exports="); src=eval(src); src=Tool.join_path("./",src); if(fs.existsSync(src)&&(path.extname(src)=='.js')){ string = string.replace(src, src+"?v="+Md5(readFileSync(src))); } }); linkArr.forEach(function (item) { var src=item.match(/href=(\'|\")[^\1]*?\1/g)[0].replace("href=","module.exports="); src=eval(src); src=Tool.join_path("./",src); if(fs.existsSync(src)&&(path.extname(src)=='.css')){ string = string.replace(src, src+"?v="+Md5(readFileSync(src))); } }); fs.writeFileSync(html,string ,'utf8') } //md5 统一加密方法 function Md5(string){ return Tool.md5(string).slice(0,7) } //判断文件或者文件夹是否是可删除 function is_delete(config,file,root){ var is_delet=false; if(root){ file={ filePath:file.filePath.replace(root,''), suffix:file.suffix, fileDir:file.fileDir.replace(root,'') }; } config.forEach(function(configItem){ if((configItem==file.filePath)||(configItem==file.fileDir)){ is_delet=true ; return false; }else{ var configItemArr= configItem.split("*"); if((configItemArr.length==1)&&(configItemArr[1]==file.suffix)){ is_delet=true ; return false; }else if((configItemArr.length==2)&&(configItemArr[0].indexOf(file.fileDir)==0)&&(configItemArr[1]==file.suffix)){ is_delet=true ; return false; } } }); return is_delet } /** * 根据地址创建目录以及文件 * 参数1:创建文件的路径地址 * 参数2:文件数据 * 参数3:是否采用utf-8 * */ function writeFile(paths,string,is_utf8){ if(fs.existsSync(paths)){ //该path地址文件已经存在 fs.writeFileSync(paths,string,is_utf8&&'utf8'); }else{ //该path地址文件不存在 var p=''; paths.split("/").forEach(function(ite){ p=(p?(p+"/"):"")+ite; if(!fs.existsSync(p)){ //目录不存在情况 if (p==paths) { fs.writeFileSync(p,string,is_utf8&&'utf8'); }else{ fs.mkdirSync(p) } }else{ //目录存在情况 if (!fs.lstatSync(p).isDirectory()) { fs.writeFileSync(p,string,is_utf8&&'utf8'); } } }); } } //数组去重复 function unique(arr) { if(arr){ var result = [], hash = {}; arr.forEach(function(item){ if (!hash[item]) { result.push(item); hash[item] = true; } }); return result; }else{ return arr } } /* ========================================================================== 服务启动插件 ============================================================================ */ var Connect =function(option){ connect.server({ port: option.port, root: option.root, livereload: option.livereload, middleware: function(connect, options) { return [ function(req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Content-Language', 'zh-CN'); //res.setHeader('Content-Type', 'text/html;charset=UTF-8'); var url=(req.url.split("?")[0].replace(option.proxyRoot+'/',"")); var filepath = path.join(options.root,url); var resEnd; var suffix=path.extname(filepath); if(suffix){ if(fs.existsSync(filepath)){ if(/.(css)$/g.test(suffix)){ resEnd=readFileSync(filepath,true) }else{ resEnd=readFileSync(filepath) } } }else if(fs.existsSync(filepath+"/index.html")){ resEnd=readFileSync(filepath+"/index.html",true) }else{ res.setHeader('Content-Type', 'text/html;charset=UTF-8');//解决返回数据中文格式乱码问题 var query=httpUrl.parse(req.url, true).query, data=eval(readFileSync(option.mockConfig,true)); url=url.replace(/^\//,""); if(data[url]){ if(typeof data[url] == 'string'){ filepath= Tool.join_path(options.root,option.dataDir+data[url]); }else if(typeof data[url] == 'object'){ var jsonFile=data[url][query[option.uid?option.uid:"uid"]]; filepath=(jsonFile?Tool.join_path(options.root,option.dataDir+jsonFile):""); } if(filepath&&fs.existsSync(filepath)){ resEnd= JSON.stringify(mock.mock(eval("module.exports ="+readFileSync(filepath,true)))); } }else{ console.log("The url "+url+" corresponding data does not exist"); } } return (typeof resEnd !='undefined')?res.end(resEnd): next(); } ]; } }); }; //删除文件或者问价夹 function deleteFile(path) { var files = []; if( fs.existsSync(path) ) { if(fs.lstatSync(path).isDirectory()){ //文件夹 files = fs.readdirSync(path); files.forEach(function(file,index){ var curPath = path + "/" + file; if(fs.statSync(curPath).isDirectory()) { deleteFile(curPath); } else { fs.unlinkSync(curPath); } }); fs.rmdirSync(path); }else{ //文件 fs.unlinkSync(path); } } } //读取文件方法 function readFileSync(path,is_utf8){ if(fs.existsSync(path)){ if(!is_utf8){ return fs.readFileSync(path) }else{ return fs.readFileSync(path,'utf8') } }else{ console.log("file "+path+" is not exists"); return "" } } //解析字符串并当做js执行 function evalFun(string){ return eval("module.exports ="+string) } /* ========================================================================== 拷贝组件到项目 ============================================================================ */ var copyCompts =function(option){ this.option=option; this.comptsDir=option.compts; loopCompts(this.comptsDir,option.deleteFileConfig,function(file){ var distDir=file.filePath.replace(option.compts,option.dist); switch (file.suffix){ case ".js": var jsString=readFileSync(file.filePath,true); jsString=comptsJsDirReplace(jsString,option.compts,option.dist.replace(option.appDir,"")); writeFile(distDir,jsString,true); break; case ".css": writeFile(distDir,readFileSync(file.filePath,true),true); break; case ".tpl": writeFile(distDir,readFileSync(file.filePath,true),true); break; default : writeFile(distDir,readFileSync(file.filePath)); break; } /* console.log("=========================="); console.log(file.filePath); console.log(distDir);*/ }) }; //js 地址替换 function comptsJsDirReplace(string,compts,dist){ return string.replace(new RegExp("../"+compts,"g"),dist); } //循环组件目录 function loopCompts(dirPath,deleteFileConfig,callback,root){ var files = fs.readdirSync(dirPath); files.forEach(function(fileItem){ var fileItemObj={ filePath:dirPath + fileItem,//文件或者地址全路径 suffix:path.extname(dirPath + fileItem),//文件扩展名,为文件夹是为空 fileDir:dirPath //文件所在目录,或者文件夹上一个目录 }; if(is_delete(deleteFileConfig,fileItemObj,root?root:dirPath)) return false; if (!fs.lstatSync(dirPath + fileItem).isDirectory()) { callback && callback(fileItemObj); } else { loopCompts(dirPath + fileItem + "/",deleteFileConfig,callback,dirPath) } }); } module.exports = { release:function(option){ return new Release(option) }, connect:Connect, copyCompts:function(option){ return new copyCompts(option) } };
JavaScript
CL
d131004a5b2141e3208463582f01a67c58970fd993b0daf83fe59d9ae8bea6b2
var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var CopyWebpackPlugin = require('copy-webpack-plugin'); var TsConfigPathsPlugin = require('awesome-typescript-loader').TsConfigPathsPlugin; const p = (f)=>path.resolve(__dirname + f) module.exports = { entry: { 'main': p('/app/index.ts') }, resolve: { extensions: ['', '.ts', '.tsx', '.js', '.jsx'], root: [ path.resolve('./node_modules'), path.resolve('./app/'), ], alias: { artw: path.resolve(__dirname + '/app/artw') }, }, devtool: 'source-map', module: { loaders: [{ test: /\.ts$/, loaders: 'awesome-typescript', query: { tsconfig: 'tsconfig.json', useWebpackText: true, module: "es2015", useForkChecker: true } }, {test: /\.css$/, loader: "style-loader!css-loader"}, { test: /.*\.(gif|png|jpe?g|svg)$/i, loader: 'file' }, //{test: /\.css$/, exclude: /\.useable\.css$/, loader: "style!css"}, //{test: /\.useable\.css$/, loader: "style/useable!css"}, {test: /\.txt/, loader: "raw"}, [ { test: /\.htm$/, name: "mandrillTemplates", loader: 'raw!html-minify' } ] ], }, 'html-minify-loader': { empty: true, // KEEP empty attributes cdata: true, // KEEP CDATA from scripts comments: true, // KEEP comments dom: { // options of !(htmlparser2)[https://github.com/fb55/htmlparser2] lowerCaseAttributeNames: false, // do not call .toLowerCase for each attribute name (Angular2 use camelCase attributes) } }, output: { filename: '[name].js', publicPath: '/', path: path.resolve(__dirname + '/dist'), }, plugins: [ new TsConfigPathsPlugin(), new CopyWebpackPlugin( [ {from: './src/index.html'}, { from: './assets', to: 'assets' }, { from: './libs', to: 'libs' }, ] ), new webpack.ProvidePlugin({}), new HtmlWebpackPlugin( { template: './app/index.html' } ) , new webpack.optimize.UglifyJsPlugin({minimize: true}) ], };
JavaScript
CL
3ee3be20554773001f3f7c73376e1253e3e18b9183765023dc6e56dbfbb66c69
/*! * Copyright 2010 - 2021 Hitachi Vantara. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * The Prompt Panel Class * * @name PromptPanel * @class * @property {String} guid The random generated id of the prompt panel * @property {ParameterDefinition} paramDefn The parameter definition fetched and parsed from the server * @property {Boolean} autoSubmit True if the prompt is in auto submit mode, false otherwise * @property {Dashboard} dashboard The dashboard object assigned to the prompt * @property {Boolean} parametersChanged True if the parameters have changed, False otherwise * @property {Object} onParameterChanged Collection of parameterNames and the callback called when that parameter is changed. * @property {Function} onBeforeRender Callback called if defined before any change is performed in the prompt components * @property {Function} onAfterRender Callback called if defined after any change is performed in the prompt components * @property {Function} onBeforeUpdate Callback called if defined before the prompt update cycle is called * @property {Function} onAfterUpdate Callback called if defined after the prompt update cycle is called * @property {Function} onStateChanged Callback called if defined after state variables have been changed on the prompt panel or parameter definition * @property {?Function} onSubmit Callback called when the submit function executes, null if no callback is registered. */ define(["cdf/lib/Base", "cdf/Logger", "dojo/number", "dojo/i18n", "common-ui/util/util", "common-ui/util/GUIDHelper", "./WidgetBuilder", "cdf/Dashboard.Clean", "./parameters/ParameterDefinitionDiffer", "common-ui/jquery-clean", "common-ui/underscore", "./components/CompositeComponent"], function(Base, Logger, DojoNumber, i18n, Utils, GUIDHelper, WidgetBuilder, Dashboard, ParamDiff, $, _, CompositeComponent) { // Add specific prompting message bundle if(pentaho.common.Messages) { pentaho.common.Messages.addUrlBundle("prompting", CONTEXT_PATH + "i18n?plugin=common-ui&name=resources/web/prompting/messages/messages"); } var _STATE_CONSTANTS = { readOnlyProperties: ["promptNeeded", "paginate", "totalPages", "showParameterUI", "allowAutoSubmit"], msgs: { notChangeReadonlyProp: function(readOnlyProperties) { return "Not possible to change the following read-only properties: " + readOnlyProperties + "."; }, incorrectBooleanType: function(name, value) { return "Unexpected value '" + value + "' for '" + name + "'. Must be boolean type."; }, notAllowedAutoSubmit: "Not possible to set 'autoSubmit'. It's limited by the 'allowAutoSubmit' flag.", incorrectNumberType: function(page) { return "Unexpected value '" + page + "' for 'page'. Must be a number type."; }, paginationNotActivated: function(page) { return "Not possible to set page '" + page + "'. The pagination should be activated."; }, incorrectPageValue: function(page, totalPages) { return "Not possible to set page '" + page + "'. The correct value should be between 0 and " + totalPages + "."; }, incorrectStateObjType: "The input parameter 'state' is incorrect. It should be an object." } }; /** * Creates a Widget calling the widget builder factory * * @name PromptPanel#_createWidget * @method * @param {Object} options with the properties to be added to the Widget * @param {String} type the type of the Widget to build * @returns {BaseComponent} A widget instance * @private */ function _createWidget(options, type) { var newObj = $.extend(options, { promptPanel: this }); return this.widgetBuilder.build(newObj, type); } /** * Creates a Widget for the Parameter * * @name PromptPanel#_createWidgetForParameter * @method * @param param {Parameter} The param to be created * @returns {Object} A widget for the given parameter * @private */ function _createWidgetForParameter(param) { return _createWidget.call(this, { param: param }); } /** * Creates a Widget for the Label * * @name PromptPanel#_createWidgetForLAbel * @method * @param {Parameter} param The param to be created * @returns {BaseComponent} A widget for the given parameter * @private */ function _createWidgetForLabel(param) { return _createWidget.call(this, { param: param }, "label"); } /** * Creates a Widget for the Error Label * * @name PromptPanel#_createWidgetForErrorLabel * @method * @param {Parameter} param The param to be created * @param {String} e The error message * @returns {BaseComponent} A widget for the given parameter * @private */ function _createWidgetForErrorLabel(param, e) { return _createWidget.call(this, { param: param, errorMessage: e }, "error-label"); } /** * Creates a Widget for the Parameter Panel * * @name PromptPanel#_createWidgetForParameterPanel * @method * @param {Parameter} param The param definition * @param {Array|BaseComponent} components The Array of components to add to the Group Panel * @returns {BaseComponent} The Widget for the Parameter Panel * @private */ function _createWidgetForParameterPanel(param, components) { return _createWidget.call(this, { param: param, components: components }, "parameter-panel"); } /** * Creates a Widget for the Group Panel * * @name PromptPanel#_createWidgetForGroupPanel * @method * @param {ParameterGroup} group The group definition * @param {Array|BaseComponent} components The Array of components to add to the Group Panel * @returns {BaseComponent} The Widget for the Group Panel * @private */ function _createWidgetForGroupPanel(group, components) { return _createWidget.call(this, { paramGroup: group, components: components }, "group-panel"); } /** * Creates a Widget for the Submit Panel * * @name PromptPanel#_createWidgetForSubmitPanel * @method * @returns {BaseComponent} * @private */ function _createWidgetForSubmitPanel() { return _createWidget.call(this, {}, "submit-panel"); } /** * Creates a Widget for the Prompt Panel * * @name PromptPanel#_createWidgetForPromptPanel * @method * @returns {BaseComponent} * @private */ function _createWidgetForPromptPanel() { return this.widgetBuilder.build(this, "prompt-panel"); } /** * @callback callback~cb * @param {BaseComponent} component The component */ /** * Pre-order traversal of a component and its descendants. * * @name PromptPanel#_mapComponents * @method * @param {BaeComponent} component The component to iterate * @param {callback~cb} callback The callback to call on each component * @private */ function _mapComponents(component, callback) { callback(component); if(component.components) { _mapComponentsList(component.components, callback); } } /** * Pre-order traversal of components given a list of root components. * * @name PromptPanel#_mapComponentsList * @method * @param {Array|BaseComponent} components The list of components to iterate * @param {callback~cb} callback The callback to call on each component */ function _mapComponentsList(components, callback) { $.each(components, function(i, component) { _mapComponents(component, callback); }); } /** * Gets a component by its parameter definition. * * @name _getComponentByParam * @method * @private * @param {ParameterDefinition} param * @param {bool} getPanel If true, retrieves the surrounding panel for the component * * @returns {BaseComponent|null} If no component is found, null will be returned */ var _getComponentByParam = function(param, getPanel) { var parameterName = this.getParameterName(param); return _getComponentByParamName.call(this, parameterName, getPanel); }; /** * Gets a component by its compile parameter name. Normally, it is a combination of the parameter name and the guid of the PromptPanel. * * @name _getComponentByParamName * @method * @private * @param {String} parameterName The compiled name of the prompt panel component * @param {bool} getPanel If true, retrieves the surrounding panel for the component * * @returns {BaseComponent|null} If no component is found, null will be returned */ var _getComponentByParamName = function(parameterName, getPanel) { for(var i in this.dashboard.components) { var component = this.dashboard.components[i]; if(component.parameter === parameterName) { var isPanel = component.type.search("Panel") > -1; if((getPanel && isPanel) || (!getPanel && !isPanel)) { return component; } } } return null; }; /** * Recursively adds the component and its children to the current dashboard * * @name _addComponent * @method * @private * @param {Array} component The parent component, which is added before its children */ var _addComponent = function(component) { this.dashboard.addComponent(component); this.dashboard.updateComponent(component); for(var i in component.components) { // Loop through panel components _addComponent.call(this, component.components[i]); } }; /** * Finds the specific submit component located on the parent panel component * @name _findSubmitComponent * @method * @private * @param {BaseComponent} panelComponent The parent panel component to search within for the submit component */ var _findSubmitComponent = function(panelComponent) { var result = null; for(var i = 0; i < panelComponent.components.length; i++) { if(panelComponent.components[i].promptType == "submit" && panelComponent.components[i].type == "FlowPromptLayoutComponent") { result = panelComponent.components[i]; break; } } return result; }; /** * Finds the specific submit button component located on the parent panel component. * @name _findSubmitBtnComponent * @method * @private * @param {cdf.dashboard.Dashboard} dashboard The dashboard instance to search within for the submit component. */ var _findSubmitBtnComponent = function(dashboard) { var result = null; if(dashboard && dashboard.components) { for(var i = 0; i < dashboard.components.length; i++) { if(dashboard.components[i].promptType === "submit" && dashboard.components[i].type === "SubmitPromptComponent") { result = dashboard.components[i]; break; } } } return result; }; /** * Finds error's components are located on the parent panel component * @name _findErrorComponents * @method * @private * @returns {Array} The array of error's components */ var _findErrorComponents = function(panelComponent) { var result = []; if(panelComponent.components) { result = panelComponent.components.filter(function(item) { return item.promptType == "label" && item.type == "TextComponent" && item.isErrorIndicator; }); } return result; }; /** * Removes a component from parent panel * @name _removeChildComponent * @method * @private * @param {BaseComponent} parent The parent component that has array of child components * @param {BaseComponent} toRemoveComponent The child component that should be deleted */ var _removeChildComponent = function(parent, toRemoveComponent) { var index = parent.components.indexOf(toRemoveComponent); if(index > -1) { parent.components.splice(index, 1); } }; /** * Compares the parameter value to its stored value * @name _areParamsDifferent * @method * @private * @param {String|Date|Number} paramValue The stored parameter value * @param {String|Date|Number} paramSelectedValue The value of the selected parameter * @param {String} paramType The parameter type * @returns {bool} The result of comparison */ var _areParamsDifferent = function(paramValue, paramSelectedValue, paramType) { if(paramValue && paramSelectedValue) { if(_.isArray(paramValue) && _.isArray(paramSelectedValue)) { if(paramValue.length != paramSelectedValue.length) { return true; } return !_.isEqual(paramValue.sort(), paramSelectedValue.sort()); } else { switch(paramType) { case "java.lang.String": // Used upper case to eliminate UPPER() post-process formula influence on the strings comparison if(!_.isArray(paramSelectedValue)) { return paramValue.toUpperCase() != paramSelectedValue.toUpperCase(); } else { return paramValue != paramSelectedValue; } case "java.sql.Date": // Set time to zero to eliminate its influence on the days comparison return (new Date(paramValue).setHours(0, 0, 0, 0)) != (new Date(paramSelectedValue).setHours(0, 0, 0, 0)); default: return paramValue != paramSelectedValue; } } } if(_.isArray(paramSelectedValue) && paramSelectedValue.length == 0) { return true; } return paramValue != paramSelectedValue; }; /** * Checks input state parameter to contain read only properties. If contains, it throws an exception. * * @name PromptPanel#_validateReadOnlyState * @method * @private * @param {Object} state The set of properties * @throws {Error} Exception if input state parameter contains read only properties */ var _validateReadOnlyState = function(state) { var cantModify = _STATE_CONSTANTS.readOnlyProperties.some(function(item) { return state.hasOwnProperty(item); }); if(cantModify) { throw new Error(_STATE_CONSTANTS.msgs.notChangeReadonlyProp(_STATE_CONSTANTS.readOnlyProperties)); } }; /** * Checks input value as boolean type. * * @name PromptPanel#_validateBooleanState * @method * @private * @param {String} name The name of the state property * @param {Object} value The value of the state property * @throws {Error} Exception if input value is not a boolean type */ var _validateBooleanState = function(name, value) { if(value != null && typeof value !== "boolean") { throw new Error(_STATE_CONSTANTS.msgs.incorrectBooleanType(name, value)); } }; /** * Validates property 'autoSubmit'. * * @name PromptPanel#_validateAutoSubmit * @method * @private * @param {Boolean} autoSubmit The value of the 'autoSubmit' property * @param {Boolean} allowAutoSubmit The whether auto-submit is allowed * @throws {Error} Exception if type of 'autoSubmit' is incorrect or setting autoSubmit is not allowed */ var _validateAutoSubmit = function(autoSubmit, allowAutoSubmit) { _validateBooleanState("autoSubmit", autoSubmit); if(autoSubmit != null && !allowAutoSubmit) { throw new Error(_STATE_CONSTANTS.msgs.notAllowedAutoSubmit); } }; /** * Validates property 'page'. * * @name PromptPanel#_validateStatePage * @method * @private * @param {Number} page The value of page * @param {Boolean} paginate The whether pagination is active * @param {Number} totalPages The value of total pages * @throws {Error} Exception if type of 'page' is incorrect or pagination is not activated or 'page' has incorrect value */ var _validateStatePage = function(page, paginate, totalPages) { if(page != null) { if(typeof page !== "number") { throw new Error(_STATE_CONSTANTS.msgs.incorrectNumberType(page)); } if(!paginate) { throw new Error(_STATE_CONSTANTS.msgs.paginationNotActivated(page)); } if(page < 0 || page >= totalPages) { throw new Error(_STATE_CONSTANTS.msgs.incorrectPageValue(page, totalPages - 1)); } } }; /** * Validates all state's properties. * * @name PromptPanel#_validateState * @method * @private * @param {Object} state The set of properties * @param {ParameterDefinition} paramDefn The parameter definition instance * @throws {Error} Exception if input 'state' parameter is invalid */ var _validateState = function(state, paramDefn) { if(!state || typeof state !== "object") { throw new Error(_STATE_CONSTANTS.msgs.incorrectStateObjType); } _validateReadOnlyState(state); _validateBooleanState("parametersChanged", state.parametersChanged); _validateAutoSubmit(state.autoSubmit, paramDefn.allowAutoSubmit()); _validateStatePage(state.page, paramDefn.paginate, paramDefn.totalPages); }; var PromptPanel = Base.extend({ guid: undefined, paramDefn: undefined, autoSubmit: undefined, dashboard: undefined, parametersChanged: false, onParameterChanged: null, onBeforeRender: null, onAfterRender: null, onBeforeUpdate: null, onAfterUpdate: null, onStateChanged: null, onSubmit: null, /** * Constructor for the PromptPanel * Override to the Base constructor * * @name PromptPanel#constructor * @method * @param {String} destinationId The html id to place the prompt * @param {ParameterDefinition} paramDefn The parameter definition assigned to the prompt * @param {Object} [options] Extra configuration options to be passed to the prompt renderer constructor. */ constructor: function(destinationId, paramDefn, options) { if(!destinationId) { throw new Error("destinationId is required"); } /** * The html id destination where the prompt will be rendered * * @name PromptPanel#destinationId * @type String * @default undefined */ this.destinationId = destinationId; this.setParamDefn(paramDefn); this.promptGUIDHelper = new GUIDHelper(); this.guid = this.promptGUIDHelper.generateGUID(); this.dashboard = new Dashboard(options); this.dashboard.flatParameters = true; // PRD-5909 this.paramDiffer = new ParamDiff(); this.widgetBuilder = WidgetBuilder; this.isEnableSubmitButton = true; }, /** * Returns the dashboard store on the prompt panel * * @return {Object} */ getDashboard: function() { return this.dashboard; }, /** * Returns the parameter definition if it has been set. Otherwise an exception is thrown. * * @returns {Object} */ getParamDefn: function() { if(!this.paramDefn) { throw new Error("paramDefn is required. Call PromptPanel#setParamDefn"); } return this.paramDefn; }, /** * Registers a post init event on the dashboard * @param {Function} callback The function to be executed when the event is triggered */ onPostInit: function(callback) { this.getDashboard().on("cdf:postInit", callback); }, /** * Sets the parameter definition for the prompt panel. Also sets whether the prompt panel has auto submit * @param paramDefn {Object} The parameter definition object */ setParamDefn: function(paramDefn) { var prevParamDefn = this.paramDefn; this.paramDefn = paramDefn; var fireStateChanged = function(paramName, oldParamDefn, newParamDefn, getValueCallback) { if(this.onStateChanged == null) { return; } var oldVal = oldParamDefn ? getValueCallback(oldParamDefn) : undefined; var newVal = newParamDefn ? getValueCallback(newParamDefn) : undefined; if(oldVal != newVal) { this.onStateChanged(paramName, oldVal, newVal); } }.bind(this); if(paramDefn) { if(this.autoSubmit == undefined) { this.setAutoSubmit(paramDefn.allowAutoSubmit()); } fireStateChanged("promptNeeded", prevParamDefn, this.paramDefn, function(paramDefn) { return paramDefn.promptNeeded; }); fireStateChanged("paginate", prevParamDefn, this.paramDefn, function(paramDefn) { return paramDefn.paginate; }); fireStateChanged("totalPages", prevParamDefn, this.paramDefn, function(paramDefn) { return paramDefn.totalPages; }); fireStateChanged("showParameterUI", prevParamDefn, this.paramDefn, function(paramDefn) { return paramDefn.showParameterUI(); }); fireStateChanged("allowAutoSubmit", prevParamDefn, this.paramDefn, function(paramDefn) { return paramDefn.allowAutoSubmit(); }); fireStateChanged("page", prevParamDefn, this.paramDefn, function(paramDefn) { return paramDefn.page; }); } }, /** * Sets the autoSubmit property on the PromptPanel * * @param autoSubmit {Boolean} The autoSubmit boolean */ setAutoSubmit: function(autoSubmit) { var prevVal = this.autoSubmit; this.autoSubmit = autoSubmit; if(this.onStateChanged != null && prevVal != this.autoSubmit) { this.onStateChanged("autoSubmit", prevVal, this.autoSubmit); } }, /** * Get the current auto submit setting for this panel. * * @name PromptPanel#getAutoSubmitSetting * @method * @returns {Boolean} */ getAutoSubmitSetting: function() { return this.autoSubmit; }, /** * Returns a parameter name unique to this parameter panel. * * @name PromptPanel#getParameterName * @method * @param {Parameter} parameter The parameter * @returns {String} The parameter name */ getParameterName: function(parameter) { if(typeof parameter === "string") { return this.guid + parameter; } return this.guid + parameter.name; }, /** * Returns a map of parameter name value. This will extract the current parameter value from the dashboard * instance as necessary * * @name PromptPanel#getParameterValues * @method * @returns {Object} parameters The parameters name|value pair assigned to the dashboard instance */ getParameterValues: function() { function parseNumber(val) { try { return DojoNumber.parse(val, {locale: Util.normalizeDojoLocale(SESSION_LOCALE)}); } catch(e) { return DojoNumber.parse(val, {locale: "en"}); } } var params = {}; this.getParamDefn().mapParameters(function(param) { var value = this.getParameterValue(this.getParameterName(param)); if(value === "" || typeof value == "undefined") { return; } if(param.multiSelect && !$.isArray(value)) { value = [value]; } if(Utils.isNumberType(param.type)) { var localization = i18n.getLocalization("dojo.cldr", "number", SESSION_LOCALE.toLowerCase()); var defaultLocalization = i18n.getLocalization("dojo.cldr", "number", null); var valueParsed; try { if(value.indexOf(localization ? localization.decimal : defaultLocalization.decimal) > 0) { valueParsed = parseNumber(value); if(valueParsed.toString().indexOf(defaultLocalization.decimal) < 0) { valueParsed = DojoNumber.format(valueParsed, { places: value.length - value.indexOf(localization ? localization.decimal : defaultLocalization.decimal) - 1 }); defaultLocalization = i18n.getLocalization("dojo.cldr", "number", null); valueParsed = valueParsed.split(defaultLocalization.group).join(""); } } else { valueParsed = parseNumber(value); } } catch(e) { valueParsed = value; } } params[param.name] = isNaN(valueParsed) ? value : valueParsed; }, this); return params; }, /** * Generate a unique GUID for a widget of this panel. * * @name PromptPanel#generateWidgetGUID * @method * @returns {String} The join of the guid of the prompt with a new one generated by the GUIDHelper */ generateWidgetGUID: function() { return this.guid + "-" + this.promptGUIDHelper.generateGUID(); }, /** * Sets the parameter value in Dashboards' parameter map to a properly initialized value. * * @name PromptPanel#_initializeParameterValue * @method * @param {ParameterDefinition} paramDefn The parameter definition map * @param {Parameter} param The parameter name * @private */ _initializeParameterValue: function(paramDefn, param) { var value = param.getSelectedValuesValue(); if(value.length === 0) { value = ""; // Dashboards' null value is an empty string } else if(value.length === 1) { value = value[0]; } this.setParameterValue(param, value); }, /** * Sets the parameter value in the dashboard instance parameter map * * @name PromptPanel#setParameterValue * @method * @param {Parameter} param The name of the parameter * @param {Object} value The value of the parameter */ setParameterValue: function(param, value) { this.dashboard.setParameter(this.getParameterName(param), value); }, /** * Gets the parameter value from the dashboard instance parameter map * * @name PromptPanel#getParameterValue * @method * @param {Parameter} param The parameter name * @returns {Object} The parameter value stored in the dashboard instance */ getParameterValue: function(param) { if(typeof param !== "string") { param = this.getParameterName(param); } return this.dashboard.getParameterValue(param); }, /** * Called by the prompt-panel component when the CDE components have been updated. * * @name PromptPanel#_ready * @method * @private */ _ready: function() { this.ready(this); }, /** * Called when the prompt-panel component's submit button is clicked or auto-submit is enabled and a parameter * value changes. * * @name PromptPanel#_submit * @method * @param {Object} [options] Additional configuration options. * @param {Boolean} [options.isInit] Flag indicating if submit is being executed during initialization. * @private */ _submit: function(options) { this.submit(this, options); }, /** * Called when the prompt-panel component's submit button is pressed (mouse-down only). * * @name PromptPanel#_submitStart * @method * @private */ _submitStart: function() { this.submitStart(this); }, /** * Called by the prompt-panel component when the CDE components have been updated. * * @name PromptPanel#ready * @method * @param {PromptPanel} promptPanel */ ready: function(promptPanel) { }, /** * Called when the prompt-panel component's submit button is clicked or auto-submit is enabled and a parameter * value changes. * * @name PromptPanel#submit * @method * @param {PromptPanel} promptPanel A prompt panel whose settings should be used for configuration purposes. * @param {Object} [options] Additional configuration options. * @param {Boolean} [options.isInit] Flag indicating if submit is being executed during initialization. */ submit: function(promptPanel, options) { if(this.onSubmit) { if(typeof this.onSubmit === "function") { this.onSubmit(options); } else { Logger.warn("The onSubmit event callback is not a function"); } } }, /** * Called when the prompt-panel component's submit button is pressed (mouse-down only). * * @name PromptPanel#submitStart * @method * @param {PromptPanel} promptPanel */ submitStart: function(promptPanel) { }, /** * Called when a parameter value changes. * * The current implementation of WidgetBuilder#build hooks * a method to the "postChange" CDF method of just built widgets * that have a "parameter". * This method calls its PromptPanel's "parameterChanged" method. * * @name PromptPanel#parameterChanged * @method * @param {Parameter} param * @param {String} name * @param {Object} value * @param {Object} [options] - The options object. * @param {boolean} [options.isForceRefresh=false] - Indicates that will force refresh on this call * @param {boolean} [options.isSuppressSubmit=false] - Indicates that will suppress submit on this call */ parameterChanged: function(param, name, value, options) { if(this.onParameterChanged) { var paramCallback = this.onParameterChanged[name] ? this.onParameterChanged[name] : this.onParameterChanged[""]; if(paramCallback) { if(typeof paramCallback === "function") { paramCallback(name, value, param); } else { Logger.warn("The parameterChanged callback for '" + name + "' is not a function"); } } } if(param.list && (!value || value == "" || value == "null")) { if(!this.nullValueParams) { this.nullValueParams = []; } this.nullValueParams.push(param); } this._setTimeoutRefreshPrompt(options); this.parametersChanged = true; if(this.onStateChanged != null) { this.onStateChanged("parametersChanged", false, this.parametersChanged); } }, /** * Method called to sync the refresh of the prompt with the renderer calling a setTimeout 0 * * @name PromptPanel#_setTimeoutRefreshPrompt * @method * @param {Object} options * @private * */ _setTimeoutRefreshPrompt: function(options) { var myself = this; setTimeout(function() { if(!options) { options = {}; } myself.refreshPrompt(options.isForceRefresh, options.isSuppressSubmit); }, 0); }, /** * This is called to refresh the prompt panel. * It should return a new parameter definition. * If it returns undefined no update will happen * * This method should be overridden. * The default implementation simply calls the provided callback with no parameter definition. * * @name PromptPanel#getParameterDefinition * @method * @param {PromptPanel} promptPanel the panel that needs a new parameter definition * @param {Function} callback function to call when the parameter definition has been fetched. * * The callback signature is: <pre>void function([newParamDef=undefined])</pre> and is called in the global context. */ getParameterDefinition: function(promptPanel, callback) { callback(); }, /** * Called to refresh the prompt panel. This will invoke getParameterDefinition() to get a new parameter definition. * If the new parameter definition is undefined (default impl) no re-initialization will be done. * * @name PromptPanel#refreshPrompt * @param {Boolean} isForceRefresh The flag indicates ability to update all components regardless of the difference * previous and new xml from server * @param {boolean} isSuppressSubmit The flag indicates to suppress submit * @method */ refreshPrompt: function(isForceRefresh, isSuppressSubmit) { try { this.isForceRefresh = isForceRefresh; this.isSuppressSubmit = isSuppressSubmit; this.getParameterDefinition(this, this.refresh.bind(this)); } catch(e) { this.isForceRefresh = undefined; this.isSuppressSubmit = undefined; console.log(e); alert("Exception caught attempting to execute refreshCallback"); } }, /** * Refreshes the prompt panel with a given parameter definition. * * @name PromptPanel#refresh * @method * @param {ParameterDefinition} paramDefn the parameter definition used to refresh the prompt panel. * When unspecified, nothing is done. * @param {Boolean} noAutoAutoSubmit Prevents auto-submiting, even when auto-submit is false, * in the case the the parameter UI is not shown. */ refresh: function(paramDefn, noAutoAutoSubmit) { var myself = this; // Should really throw an error? Or return? if(this.dashboard.waitingForInit && this.dashboard.waitingForInit.length) { Logger.warn("Overlapping refresh!"); setTimeout(function() { myself.refresh(paramDefn, noAutoAutoSubmit); }, 0); return; } if(paramDefn) { this.diff = this.paramDiffer.diff(this.getParamDefn(), paramDefn, this.nullValueParams); this.isRefresh = true; this.setParamDefn(paramDefn); this.nullValueParams = null; if(this.dashboard.components) { // Create dictionary by parameter name, of topValue of multi-select listboxes, for restoring later, when possible. // But not for mobile, cause the UIs vary. Would need more time to check each. var topValuesByParam; if(!(/android|ipad|iphone/i).test(navigator.userAgent)) { topValuesByParam = this._multiListBoxTopValuesByParam = {}; } var focusedParam; _mapComponentsList(this.dashboard.components, function(c) { if(!c.components && c.param && c.promptType === "prompt") { if(!focusedParam) { var ph = c.placeholder(); if($(":focus", ph).length) { focusedParam = c.param.name; } } if(topValuesByParam && c.type === "SelectMultiComponent") { var topValue = c.topValue(); if(topValue != null) { topValuesByParam["_" + c.param.name] = topValue; } } } else if(topValuesByParam && c.type === "ScrollingPromptPanelLayoutComponent") { // save last scroll position for prompt panel var scrollTopElem = c.placeholder().children(".prompt-panel"); var scrollTopValue = scrollTopElem.scrollTop(); var scrollLeftElem = scrollTopElem.children(".parameter-wrapper"); var scrollLeftValue = scrollLeftElem.scrollLeft(); if(scrollTopValue != null && scrollLeftValue != null) { topValuesByParam["_" + c.name] = { scrollTopValue: scrollTopValue, scrollLeftValue: scrollLeftValue }; } } if(c.param) { c.param = paramDefn.getParameter(c.param.name); } }); this._focusedParam = focusedParam; } this.init(noAutoAutoSubmit); } }, /** * Removes a set of components determined by the ParameterDefinitionDiffer#diff * * @name PromptPanel#_removeComponentsByDiff * @method * @param {JSON} toRemoveDiff The group of paramters which need to be removed */ _removeComponentsByDiff: function(toRemoveDiff) { var toRemove = []; for(var groupName in toRemoveDiff) { var removeWrap = toRemoveDiff[groupName]; var params = removeWrap.params; for(var i = 0; i < params.length; i++) { var param = params[i]; var component = _getComponentByParam.call(this, param, true); // get component panel by param if(component != null) { toRemove.push(component); // removes the component from the group panel and also removes the group panel if it's empty var groupPanel = this.dashboard.getComponentByName(groupName); if(groupPanel) { _removeChildComponent.call(this, groupPanel, component); if(groupPanel.components.length == 0) { toRemove.push(groupPanel); } } } } } // removes the submit panel if it's needed var panelComponent = this.dashboard.getComponentByName("prompt" + this.guid); if(panelComponent) { // we need to remove components from prompt panel component also for(var i in toRemove) { _removeChildComponent.call(this, panelComponent, toRemove[i]); } if(panelComponent.components.length == 1) { var submitPanel = _findSubmitComponent.call(this, panelComponent); if(submitPanel) { toRemove.push(submitPanel); _removeChildComponent.call(this, panelComponent, submitPanel); } } this.removeDashboardComponents(toRemove); // we need clear global panel if it's empty after removing child components if(panelComponent.components.length == 0) { panelComponent.clear(); } } }, /** * Adds a set of components determined by the ParameterDefinitionDiffer#diff * * @name PromptPanel#_addComponentsByDiff * @method * @param {JSON} toAddDiff The group of parameters which need to be added */ _addComponentsByDiff: function(toAddDiff) { var panelComponent = this.dashboard.getComponentByName("prompt" + this.guid); for(var groupName in toAddDiff) { var addWrap = toAddDiff[groupName]; var params = addWrap.params; var fieldComponents = []; for(var i = 0; i < params.length; i++) { var param = params[i]; var component = this._buildPanelForParameter(param); // creates a panel component if(param.after) { // Find component panel to insert after component.after = _getComponentByParam.call(this, param.after, true); } fieldComponents.push(component); } // creates a new group panel if it's not present and adds the panel components to the group panel var groupPanel = this.dashboard.getComponentByName(groupName); if(!groupPanel) { groupPanel = _createWidgetForGroupPanel.call(this, addWrap.group, fieldComponents); panelComponent.components.push(groupPanel); } else { for(var j in fieldComponents) { var fieldComponent = fieldComponents[j]; var insertAt = 0; if(fieldComponent.after) { var insertAfter = groupPanel.components.indexOf(fieldComponent.after); insertAt = insertAfter + 1; } groupPanel.components.splice(insertAt, 0, fieldComponent); } } } // creates a new submit panel if it's not present and adds the submit panel to the prompt panel if(panelComponent.components.length > 0 && !_findSubmitComponent.call(this, panelComponent)) { var submitPanel = _createWidgetForSubmitPanel.call(this); panelComponent.components.push(submitPanel); } _addComponent.call(this, panelComponent); }, /** * Change error's components determined by the ParameterDefinitionDiffer#diff * * @name PromptPanel#_changeErrors * @method * @param {Parameter} param The parameter * @private */ _changeErrors: function(param) { if(param.isErrorChanged) { var errors = this.getParamDefn().errors[param.name]; var panel = _getComponentByParam.call(this, param, true); var existingErrors = _findErrorComponents.call(this, panel); // remove unused old errors components var toRemove = []; for(var errIndex in existingErrors) { var errComp = existingErrors[errIndex]; var _isExistingErrComp = errors && errors.some(function(item) { return item == errComp.label; }); if(!_isExistingErrComp) { for(var i in existingErrors) { _removeChildComponent.call(this, panel, errComp); } errComp.clearAndRemove = true; toRemove.push(errComp); } } if(toRemove.length > 0) { this.removeDashboardComponents(toRemove); } // add new errors components if(errors) { for(var errIndex in errors) { var error = errors[errIndex]; var isExist = existingErrors.some(function(item) { return item.label == error; }); if(!isExist) { var errIndex = panel.components.length - 1; var errorComponent = _createWidgetForErrorLabel.call(this, param, error); this.dashboard.addComponent(errorComponent); panel.components.splice(errIndex, 0, errorComponent); panel.addErrorLabel(errorComponent); this.dashboard.updateComponent(errorComponent); } } } // checks existing errors components to set correct css style var existingErrorComponents = _findErrorComponents.call(this, panel); if(existingErrorComponents.length > 0) { if(!panel.cssClass || (panel.cssClass && panel.cssClass.indexOf("error") == -1)) { panel.cssClass = (panel.cssClass || "") + " error"; panel.addErrorClass(); } } else { panel.cssClass = (panel.cssClass || "").replace(" error", ""); panel.removeErrorClass(); } } }, /** * Changes the data and selects the current value(s) of a set of components determined by the ParameterDefinitionDiffer#diff. * * @name PromptPanel#_changeComponentsByDiff * @method * @param {JSON} toChangeDiff The group of parameters which need to have their data changed */ _changeComponentsByDiff: function(toChangeDiff) { for(var groupName in toChangeDiff) { var changeWrap = toChangeDiff[groupName]; var params = changeWrap.params; for(var i in params) { var param = params[i]; var component = _getComponentByParam.call(this, param); if(component != null) { var updateNeeded = false; // also we should check and update errors components this._changeErrors(param); // Create new widget to get properly formatted values array var newValuesArray = this.widgetBuilder.build({ param: param, promptPanel: this, changed: true }, param.attributes["parameter-render-type"]).valuesArray; if(JSON.stringify(component.valuesArray) !== JSON.stringify(newValuesArray) || param.forceUpdate) { // Find selected value in param values list and set it. This works, even if the data in valuesArray is different this._initializeParameterValue(null, param); // Set new values array component.valuesArray = newValuesArray; updateNeeded = true; } if(this.autoSubmit) { this.forceSubmit = true; } if(!updateNeeded) { var paramSelectedValues = param.getSelectedValuesValue(); var dashboardParameter = this.dashboard.getParameterValue(component.parameter); // if the dashboardParameter is not an array, paramSelectedValues shouldn't be either if(!_.isArray(dashboardParameter) && paramSelectedValues.length == 1) { paramSelectedValues = paramSelectedValues[0]; } updateNeeded = _areParamsDifferent(dashboardParameter, paramSelectedValues, param.type); if(param.isErrorChanged) { updateNeeded = true; } } if(updateNeeded) { var groupPanel = this.dashboard.getComponentByName(groupName); _mapComponents(groupPanel, function(component) { // avoid redrawing the composite container DOM if(!(component instanceof CompositeComponent)) { this.dashboard.updateComponent(component); } }.bind(this)); } } } } }, /** * Updates the dashboard and prompt panel based off of differences in the parameter definition * * @method update * @param {JSON} diff - contains the differences between the old and new parameter definitions produced by ParameterDefinitionDiffer.diff */ update: function(diff) { var toRemove = Object.keys(diff.toRemove).length > 0, toAdd = Object.keys(diff.toAdd).length > 0, toChangeData = Object.keys(diff.toChangeData).length > 0; if((toRemove || toAdd || toChangeData) && this.onBeforeRender) { this.onBeforeRender(); } // Determine if there are params which need to be removed if(toRemove) { this._removeComponentsByDiff(diff.toRemove); } // Determine if there are params which need to be added if(toAdd) { this._addComponentsByDiff(diff.toAdd); } // Determine if there are params which need to be changed if(toChangeData) { this._changeComponentsByDiff(diff.toChangeData); } if((toRemove || toAdd || toChangeData) && this.onAfterRender) { this.onAfterRender(); } }, /** * Initialize this prompt panel. * This will create the components and pass them to CDF to be loaded. * * @name PromptPanel#init * @method * @param {Boolean} noAutoAutoSubmit Prevents auto-submiting, even when auto-submit is false, * in the case the the parameter UI is not shown. */ init: function(noAutoAutoSubmit) { if(this.onBeforeUpdate) { this.onBeforeUpdate(); } var myself = this; var fireSubmit = true; var topValuesByParam = this._multiListBoxTopValuesByParam; if(topValuesByParam) { delete this._multiListBoxTopValuesByParam; } var focusedParam = this._focusedParam; if(focusedParam) { delete this._focusedParam; } var components = []; var updateComponent = (function(component) { components.push(component); // Don't fire the submit on load if we have a submit button. // It will take care of firing this itself (based on auto-submit) if(fireSubmit && component.promptType == "submit") { fireSubmit = false; } if(!component.components && component.param && component.promptType === "prompt") { var name = component.param.name; if(focusedParam && focusedParam === name) { focusedParam = null; component.autoFocus = true; } if(topValuesByParam && component.type === "SelectMultiComponent") { var topValue = topValuesByParam["_" + name]; if(topValue != null) { component.autoTopValue = topValue; } } } else if(topValuesByParam && component.type === "ScrollingPromptPanelLayoutComponent") { // save prompt pane reference and scroll value to dummy component var scrollValue = topValuesByParam["_" + component.name]; if(scrollValue != null) { var setScroll = function() { var scrollElem = $("#" + component.htmlObject).children(".prompt-panel"); scrollElem.scrollTop(scrollValue.scrollTopValue); scrollElem.children(".parameter-wrapper").scrollLeft(scrollValue.scrollLeftValue); }; // restore last scroll position for prompt panel if(!this.isRefresh) { this.dashboard.postInit(function() { if(scrollTopValue) { setScroll(); scrollValue = undefined; } }); } else { setTimeout(function() { setScroll(); }, 50); } } } }).bind(this); var paramDefn = this.getParamDefn(); if(!this.isRefresh && paramDefn.showParameterUI()) { // First time init if(this.onBeforeRender) { this.onBeforeRender(); } this.promptGUIDHelper.reset(); // Clear the widget helper for this prompt var layout = _createWidgetForPromptPanel.call(this); _mapComponents(layout, updateComponent); this.dashboard.addComponents(components); this.dashboard.init(); if(this.onAfterRender) { this.onAfterRender(); } } else if(this.diff) { this.update(this.diff); var layout = this.dashboard.getComponentByName("prompt" + this.guid); if(!layout) { return; } var updateCallback = (function(component) { if(!component) { return; } if(this.isForceRefresh) { this.dashboard.updateComponent(component); } updateComponent(component); }).bind(this); _mapComponents(layout, updateCallback); } else { // Simple parameter value initialization paramDefn.mapParameters(function(param) { // initialize parameter values regardless of whether we're showing the parameter or not this._initializeParameterValue(paramDefn, param); }, this); // Must submit, independently of auto-submit value. // All parameters are initialized, fire the submit fireSubmit = !noAutoAutoSubmit; } if(this.isRefresh) { this.dashboard.components.forEach(function(component) { if(component.needsUpdateOnNextRefresh && !this.dashboard.isComponentUpdating(component)){ this.dashboard.updateComponent(component); } }, this); } if(!this.isSuppressSubmit && (this.forceSubmit || fireSubmit)) { this.submit(this, {isInit: !this.isRefresh}); } try{ if(this.onAfterUpdate) { this.onAfterUpdate(); } } finally { this.diff = null; this.isRefresh = null; this.forceSubmit = false; this.isForceRefresh = undefined; this.isSuppressSubmit = undefined; } }, /** * Hides this instance of PromptPanel * * @name PromptPanel#hide * @method */ hide: function() { $("#" + this.destinationId).css("display", "none"); }, /** * Creates a panel for a parameter * If no widget for the parameter is created this method returns null * * @name PromptPanel#_buildPanelForParameter * @method * @param {Parameter} param * @returns {BaseComponent} The panel parameter. It returns undefined if the panel is not created * @private */ _buildPanelForParameter: function(param) { var panelComponents = []; var paramDefn = this.getParamDefn(); // initialize parameter values regardless of whether we're showing the parameter or not this._initializeParameterValue(paramDefn, param); // add the label widget if(!paramDefn.removeParameterLabel) { panelComponents.push(_createWidgetForLabel.call(this, param)); } // add the error widgets var errors = paramDefn.errors[param.name]; if(errors) { $.each(errors, function(i, e) { panelComponents.push(_createWidgetForErrorLabel.call(this, param, e)); }.bind(this)); } // add the parameter widget var widget = _createWidgetForParameter.call(this, param); if(widget) { panelComponents.push(widget); } else { // No widget created. Do not create a label or parameter panel Logger.log("No widget created, return"); return undefined; } var panel = _createWidgetForParameterPanel.call(this, param, panelComponents); if(errors && errors.length > 0) { panel.cssClass = (panel.cssClass || "") + " error"; } return panel; }, /** * Creates a Widget for the Submit Component * * @name PromptPanel#createWidgetForSubmitComponent * @method * @returns {BaseComponent} */ createWidgetForSubmitComponent: function() { return _createWidget.call(this, {}, "submit"); }, /** * Builds the Panel and its components for the parameters * * @name PromptPanel#buildPanelComponents * @method * @returns {Array|BaseComponents} */ buildPanelComponents: function() { var panelGroupComponents = []; var paramDefn = this.getParamDefn(); // Create a composite panel of the correct layout type for each group $.each(paramDefn.parameterGroups, function(i, group) { var components = []; // Create a label and a CDF widget for each parameter $.each(group.parameters, function(i, param) { if(param.attributes["hidden"] == "true") { // initialize parameter values regardless of whether we're showing the parameter or not this._initializeParameterValue(paramDefn, param); return; } components.push(this._buildPanelForParameter(param)); }.bind(this)); if(components.length > 0) { panelGroupComponents.push(_createWidgetForGroupPanel.call(this, group, components)); } }.bind(this)); if(panelGroupComponents.length > 0) { panelGroupComponents.push(_createWidgetForSubmitPanel.call(this)); } return panelGroupComponents; }, /** * Removes all components from the current instance of dashboard * * @name PromptPanel#removeDashboardComponents * @method * @param {Array|BaseComponent} components The list of components to be removed * @param {Boolean} postponeClear */ removeDashboardComponents: function(components, postponeClear) { var myself = this; // Traverse all embedded components to remove them var removed = []; _mapComponentsList(components, function(component) { var rc = myself.dashboard.removeComponent(component.name); if(rc) { removed.push(rc); } }); // Remove references to each removed components parameter but leave the parameter so it may be reselected if it's reused by // another component $.each(removed, function(i, component) { // It would be wise to always call component.clear() here except that since Dashboards.init() schedules the components // to update() in a setTimeout(). To prevent that, we'll clear the removed components with the GarbageCollectorComponent // when we initialize the next set of components. if(!postponeClear) { if(component.remove) { component.remove(); } else { component.clear(); if(component.clearAndRemove) { $("#" + component.htmlObject).remove(); } } } if(component.parameter) { // Remove our parameter from any other listening components $.each(myself.dashboard.components, function(i, comp) { if($.isArray(comp.listeners)) { comp.listeners = $.grep(comp.listeners, function(l) { return l !== component.parameter; }); } }); } }); }, /** * Makes visible the progress indicator by calling the function Dashboard#showProgressIndicator. * * @name PromptPanel#showProgressIndicator * @method */ showProgressIndicator: function() { this.getDashboard().showProgressIndicator(); }, /** * Hides the progress indicator by calling the function Dashboard#hideProgressIndicator. * * @name PromptPanel#hideProgressIndicator * @method */ hideProgressIndicator: function() { this.getDashboard().hideProgressIndicator(); }, /** * Sets the default options for blockUI * * @name PromptPanel#setBlockUiOptions * @method * @param {Object} options - The options to configure the block ui * @param {string} options.message - The message or html to display on block ui * @param {Object} options.css - A json that accepts valid css key/value pairs * @param {Object} options.overlayCSS - A json that accepts valid css key/value pairs for the block ui overlay * @param {boolean} options.showOverlay - Allows you to show or hide the overlay on block ui * @example * var defaults = { * message : '', * css : { * left : '0%', * top : '0%', * marginLeft : '85px', * width : '100%', * height : '100%', * opacity : '1', * backgroundColor : '#ffffcc' * }, * overlayCSS : { * backgroundColor : '#000000', * opacity : '0.6', * cursor : 'wait' * }, * showOverlay : false * }; * promptPanel.setBlockUiOptions(defaults); */ setBlockUiOptions: function(options) { this.getDashboard()._setBlockUiOptions(options); }, /** * Gets a current state of the prompting system. * * @name PromptPanel#getState * @method * @returns {Object} The current state which consists of the next properties: * <ul> * <li>'promptNeeded' &lt;Boolean&gt; - True if prompts are needed, False otherwise (read only property)</li> * <li>'paginate' &lt;Boolean&gt; - True if pagination is active, False otherwise (read only property)</li> * <li>'totalPages' &lt;Number&gt; - The number of total pages of the report (read only property)</li> * <li>'showParameterUI' &lt;Boolean&gt; - The boolean value of the parameter ShowParameters (read only property)</li> * <li>'allowAutoSubmit' &lt;Boolean&gt; - The value of autoSubmit, or if it is undefined the value of autoSubmitUI (read only property)</li> * <li>'parametersChanged' &lt;Boolean&gt; - True if the parameters have changed, False otherwise</li> * <li>'autoSubmit' &lt;Boolean&gt; - True is the prompt is in auto submit mode, False otherwise</li> * <li>'page' &lt;Number&gt; - The number of the page</li> * <li>'isSuppressSubmit' &lt;Boolean&gt; True if is to suppress submit, False otherwise</li> * <li>'isForceRefresh' &lt;Boolean&gt; True if is to force refresh, False otherwise</li> * </ul> * @example * var currentState = api.operation.state(); * // Return value: * // { * // "promptNeeded":false, * // "paginate":true, * // "totalPages":10, * // "showParameterUI":true, * // "allowAutoSubmit":false, * // "parametersChanged":false, * // "autoSubmit":false, * // "page":1, * // "isSuppressSubmit":false, * // "isForceRefresh":false * // } */ getState: function() { var paramDefn = this.getParamDefn(); var result = { promptNeeded: paramDefn.promptNeeded, paginate: paramDefn.paginate, totalPages: paramDefn.totalPages, showParameterUI: paramDefn.showParameterUI(), allowAutoSubmit: paramDefn.allowAutoSubmit(), parametersChanged: this.parametersChanged, autoSubmit: this.autoSubmit, page: paramDefn.page, isSuppressSubmit: this.isSuppressSubmit, isForceRefresh: this.isForceRefresh }; return result; }, /** * Modifies a state of the prompting system. * * @name PromptPanel#setState * @method * @param {Object} state The set of flags which will be applied to current state. * @param {Boolean} [state.parametersChanged] True if the parameters have changed, False otherwise * @param {Boolean} [state.autoSubmit] True is the prompt is in auto submit mode, False otherwise. It's limited by the 'allowAutoSubmit' flag * @param {Number} [state.page] The number of the current page. It's limited in range by the 'totalPages' and 'paginate' flags * @throws {Error} Exception if input 'state' parameter is invalid * @example * var state = { * "parametersChanged":true, * "autoSubmit":true, * "page":5 * }; * * var updatedState = api.operation.state(state); * // Return value: * // { * // "promptNeeded":false, * // "paginate":true, * // "totalPages":10, * // "showParameterUI":true, * // "allowAutoSubmit":true, * // "parametersChanged":true, * // "autoSubmit":true, * // "page":5 * // } */ setState: function(state) { var paramDefn = this.getParamDefn(); _validateState(state, paramDefn); if(state.parametersChanged != null) { if(this.onStateChanged != null && this.parametersChanged != state.parametersChanged) { this.onStateChanged("parametersChanged", this.parametersChanged, state.parametersChanged); } this.parametersChanged = state.parametersChanged; } (state.autoSubmit != null) && this.setAutoSubmit(state.autoSubmit); (state.page != null) && (paramDefn.page = state.page); this.setParamDefn(paramDefn); }, /** * Enables or disables a submit button in a submit panel. Checks if it's necessary change "disabled" attribute * of the button and applies it to a submit button component in the dashboard. * * @name PromptPanel#setDisabledSubmitButton * @method * @param {Boolean} disabled When `true` enables the submit button, when `false` disables it. * @example * promptPanel.setDisabledSubmitButton(true); */ setDisabledSubmitButton: function(disabled) { var disabledFlag = Boolean(disabled); if(this.isEnableSubmitButton === disabledFlag) { var submitBtnComponent = _findSubmitBtnComponent.call(this, this.getDashboard()); if(submitBtnComponent) { submitBtnComponent.setDisabledButton(disabledFlag); } this.isEnableSubmitButton = !disabledFlag; } } }); return PromptPanel; });
JavaScript
CL
56f15a23348a5da706a595493d6877d3a46423b31104887e4bb692e95e4e8bc8
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { __awaiter } from "tslib"; import { semverInc } from '../../../utils/semver'; import { ReleaseAction } from '../actions'; /** * Release action that cuts a new patch release for the current latest release-train version * branch (i.e. the patch branch). The patch segment is incremented. The changelog is generated * for the new patch version, but also needs to be cherry-picked into the next development branch. */ export class CutNewPatchAction extends ReleaseAction { constructor() { super(...arguments); this._newVersion = semverInc(this.active.latest.version, 'patch'); } getDescription() { return __awaiter(this, void 0, void 0, function* () { const { branchName } = this.active.latest; const newVersion = this._newVersion; return `Cut a new patch release for the "${branchName}" branch (v${newVersion}).`; }); } perform() { return __awaiter(this, void 0, void 0, function* () { const { branchName } = this.active.latest; const newVersion = this._newVersion; const { pullRequest, releaseNotes } = yield this.checkoutBranchAndStageVersion(newVersion, branchName); yield this.waitForPullRequestToBeMerged(pullRequest); yield this.buildAndPublish(releaseNotes, branchName, 'latest'); yield this.cherryPickChangelogIntoNextBranch(releaseNotes, branchName); }); } static isActive(active) { return __awaiter(this, void 0, void 0, function* () { // Patch versions can be cut at any time. See: // https://hackmd.io/2Le8leq0S6G_R5VEVTNK9A#Release-prompt-options. return true; }); } } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY3V0LW5ldy1wYXRjaC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uLy4uL2Rldi1pbmZyYS9yZWxlYXNlL3B1Ymxpc2gvYWN0aW9ucy9jdXQtbmV3LXBhdGNoLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7R0FNRzs7QUFFSCxPQUFPLEVBQUMsU0FBUyxFQUFDLE1BQU0sdUJBQXVCLENBQUM7QUFFaEQsT0FBTyxFQUFDLGFBQWEsRUFBQyxNQUFNLFlBQVksQ0FBQztBQUV6Qzs7OztHQUlHO0FBQ0gsTUFBTSxPQUFPLGlCQUFrQixTQUFRLGFBQWE7SUFBcEQ7O1FBQ1UsZ0JBQVcsR0FBRyxTQUFTLENBQUMsSUFBSSxDQUFDLE1BQU0sQ0FBQyxNQUFNLENBQUMsT0FBTyxFQUFFLE9BQU8sQ0FBQyxDQUFDO0lBeUJ2RSxDQUFDO0lBdkJnQixjQUFjOztZQUMzQixNQUFNLEVBQUMsVUFBVSxFQUFDLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxNQUFNLENBQUM7WUFDeEMsTUFBTSxVQUFVLEdBQUcsSUFBSSxDQUFDLFdBQVcsQ0FBQztZQUNwQyxPQUFPLG9DQUFvQyxVQUFVLGNBQWMsVUFBVSxJQUFJLENBQUM7UUFDcEYsQ0FBQztLQUFBO0lBRWMsT0FBTzs7WUFDcEIsTUFBTSxFQUFDLFVBQVUsRUFBQyxHQUFHLElBQUksQ0FBQyxNQUFNLENBQUMsTUFBTSxDQUFDO1lBQ3hDLE1BQU0sVUFBVSxHQUFHLElBQUksQ0FBQyxXQUFXLENBQUM7WUFFcEMsTUFBTSxFQUFDLFdBQVcsRUFBRSxZQUFZLEVBQUMsR0FDN0IsTUFBTSxJQUFJLENBQUMsNkJBQTZCLENBQUMsVUFBVSxFQUFFLFVBQVUsQ0FBQyxDQUFDO1lBRXJFLE1BQU0sSUFBSSxDQUFDLDRCQUE0QixDQUFDLFdBQVcsQ0FBQyxDQUFDO1lBQ3JELE1BQU0sSUFBSSxDQUFDLGVBQWUsQ0FBQyxZQUFZLEVBQUUsVUFBVSxFQUFFLFFBQVEsQ0FBQyxDQUFDO1lBQy9ELE1BQU0sSUFBSSxDQUFDLGlDQUFpQyxDQUFDLFlBQVksRUFBRSxVQUFVLENBQUMsQ0FBQztRQUN6RSxDQUFDO0tBQUE7SUFFRCxNQUFNLENBQWdCLFFBQVEsQ0FBQyxNQUEyQjs7WUFDeEQsOENBQThDO1lBQzlDLG1FQUFtRTtZQUNuRSxPQUFPLElBQUksQ0FBQztRQUNkLENBQUM7S0FBQTtDQUNGIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBAbGljZW5zZVxuICogQ29weXJpZ2h0IEdvb2dsZSBMTEMgQWxsIFJpZ2h0cyBSZXNlcnZlZC5cbiAqXG4gKiBVc2Ugb2YgdGhpcyBzb3VyY2UgY29kZSBpcyBnb3Zlcm5lZCBieSBhbiBNSVQtc3R5bGUgbGljZW5zZSB0aGF0IGNhbiBiZVxuICogZm91bmQgaW4gdGhlIExJQ0VOU0UgZmlsZSBhdCBodHRwczovL2FuZ3VsYXIuaW8vbGljZW5zZVxuICovXG5cbmltcG9ydCB7c2VtdmVySW5jfSBmcm9tICcuLi8uLi8uLi91dGlscy9zZW12ZXInO1xuaW1wb3J0IHtBY3RpdmVSZWxlYXNlVHJhaW5zfSBmcm9tICcuLi8uLi92ZXJzaW9uaW5nL2FjdGl2ZS1yZWxlYXNlLXRyYWlucyc7XG5pbXBvcnQge1JlbGVhc2VBY3Rpb259IGZyb20gJy4uL2FjdGlvbnMnO1xuXG4vKipcbiAqIFJlbGVhc2UgYWN0aW9uIHRoYXQgY3V0cyBhIG5ldyBwYXRjaCByZWxlYXNlIGZvciB0aGUgY3VycmVudCBsYXRlc3QgcmVsZWFzZS10cmFpbiB2ZXJzaW9uXG4gKiBicmFuY2ggKGkuZS4gdGhlIHBhdGNoIGJyYW5jaCkuIFRoZSBwYXRjaCBzZWdtZW50IGlzIGluY3JlbWVudGVkLiBUaGUgY2hhbmdlbG9nIGlzIGdlbmVyYXRlZFxuICogZm9yIHRoZSBuZXcgcGF0Y2ggdmVyc2lvbiwgYnV0IGFsc28gbmVlZHMgdG8gYmUgY2hlcnJ5LXBpY2tlZCBpbnRvIHRoZSBuZXh0IGRldmVsb3BtZW50IGJyYW5jaC5cbiAqL1xuZXhwb3J0IGNsYXNzIEN1dE5ld1BhdGNoQWN0aW9uIGV4dGVuZHMgUmVsZWFzZUFjdGlvbiB7XG4gIHByaXZhdGUgX25ld1ZlcnNpb24gPSBzZW12ZXJJbmModGhpcy5hY3RpdmUubGF0ZXN0LnZlcnNpb24sICdwYXRjaCcpO1xuXG4gIG92ZXJyaWRlIGFzeW5jIGdldERlc2NyaXB0aW9uKCkge1xuICAgIGNvbnN0IHticmFuY2hOYW1lfSA9IHRoaXMuYWN0aXZlLmxhdGVzdDtcbiAgICBjb25zdCBuZXdWZXJzaW9uID0gdGhpcy5fbmV3VmVyc2lvbjtcbiAgICByZXR1cm4gYEN1dCBhIG5ldyBwYXRjaCByZWxlYXNlIGZvciB0aGUgXCIke2JyYW5jaE5hbWV9XCIgYnJhbmNoICh2JHtuZXdWZXJzaW9ufSkuYDtcbiAgfVxuXG4gIG92ZXJyaWRlIGFzeW5jIHBlcmZvcm0oKSB7XG4gICAgY29uc3Qge2JyYW5jaE5hbWV9ID0gdGhpcy5hY3RpdmUubGF0ZXN0O1xuICAgIGNvbnN0IG5ld1ZlcnNpb24gPSB0aGlzLl9uZXdWZXJzaW9uO1xuXG4gICAgY29uc3Qge3B1bGxSZXF1ZXN0LCByZWxlYXNlTm90ZXN9ID1cbiAgICAgICAgYXdhaXQgdGhpcy5jaGVja291dEJyYW5jaEFuZFN0YWdlVmVyc2lvbihuZXdWZXJzaW9uLCBicmFuY2hOYW1lKTtcblxuICAgIGF3YWl0IHRoaXMud2FpdEZvclB1bGxSZXF1ZXN0VG9CZU1lcmdlZChwdWxsUmVxdWVzdCk7XG4gICAgYXdhaXQgdGhpcy5idWlsZEFuZFB1Ymxpc2gocmVsZWFzZU5vdGVzLCBicmFuY2hOYW1lLCAnbGF0ZXN0Jyk7XG4gICAgYXdhaXQgdGhpcy5jaGVycnlQaWNrQ2hhbmdlbG9nSW50b05leHRCcmFuY2gocmVsZWFzZU5vdGVzLCBicmFuY2hOYW1lKTtcbiAgfVxuXG4gIHN0YXRpYyBvdmVycmlkZSBhc3luYyBpc0FjdGl2ZShhY3RpdmU6IEFjdGl2ZVJlbGVhc2VUcmFpbnMpIHtcbiAgICAvLyBQYXRjaCB2ZXJzaW9ucyBjYW4gYmUgY3V0IGF0IGFueSB0aW1lLiBTZWU6XG4gICAgLy8gaHR0cHM6Ly9oYWNrbWQuaW8vMkxlOGxlcTBTNkdfUjVWRVZUTks5QSNSZWxlYXNlLXByb21wdC1vcHRpb25zLlxuICAgIHJldHVybiB0cnVlO1xuICB9XG59XG4iXX0=
JavaScript
CL
53b3320f94eb92ca27caa75662dae03e5baf3719d1de2214bbb63c461045ed59
import React from 'react' import Link from 'next/link' import { gql, useMutation, useApolloClient } from '@apollo/client' import { createStyles, makeStyles } from '@material-ui/core/styles' import Button from '@material-ui/core/Button' import TextField from '@material-ui/core/TextField' import Paper from '@material-ui/core/Paper' import Container from '@material-ui/core/Container' import Typography from '@material-ui/core/Typography' import GlobalLoading from '../components/GlobalLoading' import { useRouter } from 'next/router' import { useForm } from 'react-hook-form' import { validateEmail, validatePassword } from '../utils/registerValidation' const REGISTER_USER = gql` mutation register($email: String!, $password: String!, $nick: String!) { register(email: $email, password: $password, nick: $nick) { token } } ` const useStyles = makeStyles((theme) => createStyles({ paper: { marginTop: theme.spacing(8), display: 'flex', flexDirection: 'column', alignItems: 'center', padding: 4 }, button: { marginTop: 4 } }) ) /** * Страница с регистрацией * * @returns { React.ReactElement } */ function Register() { const { register, handleSubmit, errors } = useForm({ mode: 'onChange' }) const Router = useRouter() const [registerUser, { loading, error }] = useMutation(REGISTER_USER, { errorPolicy: 'all' }) const client = useApolloClient() const styles = useStyles() return ( <div> {loading && <GlobalLoading />} <Container maxWidth="xs"> <Paper elevation={3} className={styles.paper}> <Typography component="h1" variant="h5"> Регистрация </Typography> <form> <TextField required fullWidth label="Имя" name="nick" variant="outlined" margin="normal" autoComplete="name" error={errors.nick} helperText={errors.nick && 'Имя должно быть длинее 5 символов'} inputRef={register({ required: true, minLength: 5 })} /> <TextField required fullWidth label="Почта" name="email" variant="outlined" margin="normal" autoComplete="email" error={errors.email} helperText={errors.email && 'Неверная почта'} inputRef={register({ required: true, validate: validateEmail })} /> <TextField required fullWidth label="Пароль" name="password" variant="outlined" margin="normal" type="password" autoComplete="current-password" error={errors.password} helperText={ errors.password && 'Пароль должен быть длиннее 8 символов, и может содержать латинские быквы, цифры, спецсимволы' } inputRef={register({ required: true, validate: validatePassword })} /> {error && error && ( <Typography color="error">{error.message}</Typography> )} <Button fullWidth color="primary" variant="contained" className={styles.button} onClick={handleSubmit((data) => registerUser({ variables: data }).then((response) => { if (!response.errors) { document.cookie = 'user=' + response.data.register.token client.resetStore() Router.push('/me') } }) )} > Зарегестрироваться </Button> </form> <Link href="/login"> <Button fullWidth className={styles.button}> Есть аккаунт? Войдите </Button> </Link> </Paper> </Container> </div> ) } Register.title = 'Регистрация' Register.login = 'restricts' export default Register
JavaScript
CL
b970aa664b1644daad0d1cf5dcdb95223397fcab73116f3f7361569485417f16
#!/usr/bin/env node var fs = require('fs'), path = require('path'), exec = require('child_process').exec, xcode = require('xcode'), plist = require('plist'), _ = require('underscore'), util = require('util'), xcconfig, codeSignJSON, xcBuildConfiguration, nativeTarget, projects, projectName, projectTargetId, extensionName, extensionTargetId, targetId, projectId, pbxPath, xcodeproj f = util.format; const swiftVersion = "3.0", swiftPattern = /([\s\S]*)(SWIFT_VERSION)[\s|\t]*=[\s|\t]*([0-9|\.]*)([\s\S]*)/, swiftOldPattern = /([\s\S]*)(SWIFT_OLD_VERSION)[\s|\t]*=[\s|\t]*([0-9|\.]*)([\s\S]*)/, teamPattern = /([\s\S]*)(DEVELOPMENT_TEAM)[\s|\t]*=[\s|\t]*([A-Z|0-9]*)([\s\S]*)/, encoding = 'utf-8', filepath = 'platforms/ios/cordova/build.xcconfig', nonCli = '__NON-CLI__', patchProjectFile = './custom_plugins/com.kcchen.sharingfrom/hooks/patches/projectFile.js.patch', patchPbxProject = './custom_plugins/com.kcchen.sharingfrom/hooks/patches/pbxProject.js.patch', COMMENT_KEY = /_comment$/, FILETYPE_BY_EXTENSION = { a: 'archive.ar', app: 'wrapper.application', appex: 'wrapper.app-extension', bundle: 'wrapper.plug-in', dylib: 'compiled.mach-o.dylib', framework: 'wrapper.framework', h: 'sourcecode.c.h', m: 'sourcecode.c.objc', markdown: 'text', mdimporter: 'wrapper.cfbundle', octest: 'wrapper.cfbundle', pch: 'sourcecode.c.h', plist: 'text.plist.xml', sh: 'text.script.sh', swift: 'sourcecode.swift', tbd: 'sourcecode.text-based-dylib-definition', xcassets: 'folder.assetcatalog', xcconfig: 'text.xcconfig', xcdatamodel: 'wrapper.xcdatamodel', xcodeproj: 'wrapper.pb-project', xctest: 'wrapper.cfbundle', xib: 'file.xib' }; module.exports = function (context) { // console.log('> check ios... ' + (context.opts.cordova.platforms.indexOf('ios') != -1)) if (context.opts.cordova.platforms.indexOf('ios') === -1) return; console.log('#################### BEFORE PLUGIN SHARINGFROM REMOVE ####################') if (openXcConfig()) { // removeSwiftVersion() // removeDevelopmentTeam() fs.writeFileSync(filepath, xcconfig, encoding) } if (prepare()) { removeManualSigining() removeTargetDependency(extensionTargetId, 'CordovaLib') removeExtensionBuildFlag() removeAllBuildPhase() removeExtensionTarget(extensionName, 'app_extension') // removeNoncli() fs.writeFileSync(pbxPath, xcodeproj.writeSync()); } applyPatchBack([patchProjectFile]) // applyPatchBack([patchPbxProject, patchProjectFile]) console.log('-------------------- BEFORE PLUGIN SHARINGFROM REMOVE FINISHED --------------------') return function prepare() { if (!openXcodeProj()) return false; if (!openCodeSignJSON()) return false; try { xcBuildConfiguration = xcodeproj.pbxXCBuildConfigurationSection() nativeTarget = xcodeproj.pbxNativeTargetSection() projects = xcodeproj.pbxProjectSection() } catch (e) { console.log('> check filepath... ' + pbxPath + " not existed.") console.error(e) return false } var nativeTargets = xcodeproj.pbxNativeTargetSection() if (_.size(projects) / 2 === 1) { projectName = xcodeproj.getFirstTarget().firstTarget.name.replace(/\"/g, '') targetId = xcodeproj.getFirstTarget().firstTarget.buildConfigurationList projectId = _.keys(projects)[0] console.log("> get Project Name... " + projectName) console.log("> get Project ID... " + projectId) console.log("> get Target ID... " + targetId) } else { throw new Error('The project and target not only ONE, currently no support for multiple projects.'); } for (var key in nativeTargets) { if (!nativeTargets[key].name) continue if (nativeTargets[key].name.indexOf(extensionName) !== -1) { extensionTargetId = key console.log("> get " + extensionName + " uuid... " + key) } if (nativeTargets[key].name.indexOf(projectName) !== -1) { projectTargetId = key console.log("> get " + projectName + " uuid... " + key) } } return true } function openXcodeProj() { pbxPath = getXcodeProjectPath(context) if (!pbxPath) return false console.log('> get Project Path... ' + pbxPath); xcodeproj = xcode.project(pbxPath); xcodeproj.parseSync(); return true } function openXcConfig() { try { xcconfig = fs.readFileSync(filepath, encoding); console.log("> check filepath [" + filepath + "]... " + !(!xcconfig)) } catch (e) { console.error("> check filepath [" + filepath + "]... NOT EXISTED.") console.error(e) return } return !(!xcconfig); } function removeSwiftVersion() { xcconfig = xcconfig.replace(/^\s*[\r\n]/gm, '\n') var matchesOld = xcconfig.match(swiftOldPattern) if (matchesOld) { printRegEx(matchesOld) var matches = xcconfig.match(swiftPattern) if (matches) { if (matchesOld[3] == matches[3]) { xcconfig = matches[1] + matches[4] } else { xcconfig = matches[1] + matches[2] + " = " + matchesOld[3] + matches[4] } matchesOld = xcconfig.match(swiftOldPattern) console.log('> replace SWIFT_VERSION... ' + matches[2] + " = " + matchesOld[3]) printRegEx(matchesOld) xcconfig = matchesOld[1] + matchesOld[4] console.log('@ REMOVE SWIFT_OLD_VERSION... ' + matchesOld[2] + " = " + matches[3]) } else { // should not happen } } else { // not set SWIFT_OLD_VERSION, remove SWIFT_VERSION // var matches = xcconfig.match(swiftPattern) // xcconfig += '\n' + versionString + ' = ' + version; // console.log('> save SWIFT_VERSION... ' + swiftVersion) } } function removeDevelopmentTeam() { matches = xcconfig.match(teamPattern) if (matches) { xcconfig = matches[1] + matches[4] } } function openCodeSignJSON() { try { codeSignJSON = require('./codeSign.json'); console.log("> check codeSign.json ... " + !(!codeSignJSON)) extensionName = codeSignJSON.extension.name } catch (e) { console.error("> check codeSign.json ... NOT EXISTED.") console.error(e) return false } return !(!codeSignJSON); } function removeManualSigining() { _.filter( xcodeproj.hash.project.objects['XCBuildConfiguration'], function (entry, id, context) { if (!entry.buildSettings || !entry.buildSettings.PRODUCT_NAME) return for (target in codeSignJSON) { if (!codeSignJSON[target].name && codeSignJSON[target].name != 'extension') continue for (build in codeSignJSON[target]) { if (entry.buildSettings.PRODUCT_NAME.indexOf(codeSignJSON[target].name) != -1 && entry.name.indexOf(build) != -1) { for (item in codeSignJSON[target][build]) { delete xcodeproj.hash.project.objects['XCBuildConfiguration'][id].buildSettings[item] console.log("> remove " + item + " : " + codeSignJSON[target][build][item] + " from " + target + " / " + build) } delete xcodeproj.hash.project.objects['XCBuildConfiguration'][id].buildSettings['DEVELOPMENT_TEAM'] } } } } ) for (project in projects) { if (!projects[project].targets) continue for (target of projects[project].targets) { if (!projects[project].attributes) projects[project]['attributes'] = {} if (!projects[project].attributes['TargetAttributes']) projects[project].attributes['TargetAttributes'] = {} if (!projects[project].attributes['TargetAttributes'][target.value]) projects[project].attributes['TargetAttributes'][target.value] = {} if (target.comment.indexOf(codeSignJSON['extension'].name) != -1) { delete projects[project].attributes['TargetAttributes'][target.value] console.log("> remove Manual Signing to " + target.value) } } } console.log("> END removeManualSigining...") } function removeTargetDependency(targetId, dependencyName) { var pbxTargetDependency = 'PBXTargetDependency', pbxContainerItemProxy = 'PBXContainerItemProxy', projectXcodeproj = dependencyName + '.xcodeproj', pbxTargetDependencySection = xcodeproj.hash.project.objects[pbxTargetDependency], pbxContainerItemProxySection = xcodeproj.hash.project.objects[pbxContainerItemProxy], pbxFileReferenceSection = xcodeproj.pbxFileReferenceSection(), nativeTargets = xcodeproj.pbxNativeTargetSection(), removeProxyKey, removeDependencyKey, isMultipleDependency = false, count = 0; for (key in pbxTargetDependencySection) { // console.log(pbxTargetDependencySection[key]) if (pbxTargetDependencySection[key].name) { if (pbxTargetDependencySection[key].name.indexOf(dependencyName) != -1) { count++ } } else if (pbxTargetDependencySection[key].target_comment) { if (pbxTargetDependencySection[key].target_comment.indexOf(dependencyName) != -1) { count++ } } } if (count == 1) { isMultipleDependency = false } else if (count > 1) { isMultipleDependency = true } else { console.error("> " + dependencyName + " can not be found in TargetDependency Section.") return } console.log("> " + dependencyName + " is multiple entry? " + isMultipleDependency) for (key in pbxTargetDependencySection) { if (pbxTargetDependencySection[key].name) { if (pbxTargetDependencySection[key].name.indexOf(dependencyName) != -1) { if (isMultipleDependency) { var hasComment = false; for (k in pbxTargetDependencySection) { if (k.indexOf(key + '_comment') != -1) { hasComment = true } } if (hasComment) { continue } else { removeDependencyKey = key removeProxyKey = pbxTargetDependencySection[key].targetProxy console.log("> remove " + pbxTargetDependency + " key:" + key + " from... " + hasComment) // console.log(pbxTargetDependencySection) delete pbxTargetDependencySection[key] } } else { removeDependencyKey = key removeProxyKey = pbxTargetDependencySection[key].targetProxy console.log("> remove " + pbxTargetDependency + " key:" + key + " from... ") console.log(pbxTargetDependencySection) delete pbxTargetDependencySection[key] break } } } else if (pbxTargetDependencySection[key].target_comment) { if (pbxTargetDependencySection[key].target_comment.indexOf(dependencyName) != -1) { if (isMultipleDependency) { var hasComment = false; for (k in pbxTargetDependencySection) { if (k.indexOf(key + '_comment') != -1) { hasComment = true } } if (hasComment) { continue } else { removeDependencyKey = key removeProxyKey = pbxTargetDependencySection[key].targetProxy console.log("> remove " + pbxTargetDependency + " key:" + key + " from... " + hasComment) // console.log(pbxTargetDependencySection) delete pbxTargetDependencySection[key] } } else { removeDependencyKey = key removeProxyKey = pbxTargetDependencySection[key].targetProxy console.log("> remove " + pbxTargetDependency + " key:" + key + " from... ") console.log(pbxTargetDependencySection) delete pbxTargetDependencySection[key] break } } } } for (key in pbxContainerItemProxySection) { if (!pbxContainerItemProxySection[key].containerPortal) continue if (key === removeProxyKey) { console.log("> remove " + pbxContainerItemProxy + " key:" + key + " from... ") // console.log(pbxContainerItemProxySection) delete pbxContainerItemProxySection[key] } } if (nativeTargets[targetId] && nativeTargets[targetId].dependencies) { for (index in nativeTargets[targetId].dependencies) { console.log("> index:" + index + ' targetId:' + targetId) // console.log(nativeTargets[targetId].dependencies[index]) if (!nativeTargets[targetId].dependencies || !nativeTargets[targetId].dependencies[index]) { continue } else { if (nativeTargets[targetId].dependencies[index] && nativeTargets[targetId].dependencies[index]['value'] === removeDependencyKey) { console.log("> remove nativeTargets dependencies key:" + removeDependencyKey + " from... " + index) console.log(nativeTargets[targetId].dependencies) nativeTargets[targetId].dependencies.splice(index, 1) // console.log(nativeTargets[targetId].dependencies) } } } } console.log("> END removeTargetDependency...") } function removeExtensionBuildFlag() { _.filter( xcodeproj.hash.project.objects['XCBuildConfiguration'], function (entry, id, context) { if (!entry.buildSettings || !entry.buildSettings.PRODUCT_NAME) return if (entry.buildSettings.PRODUCT_NAME.indexOf(extensionName) != -1) { console.log("> remove ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES from " + id + " | " + entry.buildSettings.PRODUCT_NAME + " " + projectName + " / " + extensionName ) console.log("> remove ALWAYS_SEARCH_USER_PATHS from " + id + " | " + entry.buildSettings.PRODUCT_NAME + " " + projectName + " / " + extensionName ) delete entry.buildSettings.ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES delete entry.buildSettings.ALWAYS_SEARCH_USER_PATHS } } ) console.log("> END removeExtensionBuildFlag...") } function removeAllBuildPhase() { removeBuildPhase( ['com.kcchen.sharingfrom/ShareViewController.swift'], 'PBXSourcesBuildPhase', extensionTargetId ) removeBuildPhase( ['MainInterface.storyboard'], 'PBXResourcesBuildPhase', extensionTargetId ) } function producttypeForTargettype(targetType) { PRODUCTTYPE_BY_TARGETTYPE = { application: 'com.apple.product-type.application', app_extension: 'com.apple.product-type.app-extension', bundle: 'com.apple.product-type.bundle', command_line_tool: 'com.apple.product-type.tool', dynamic_library: 'com.apple.product-type.library.dynamic', framework: 'com.apple.product-type.framework', static_library: 'com.apple.product-type.library.static', unit_test_bundle: 'com.apple.product-type.bundle.unit-test', watch_app: 'com.apple.product-type.application.watchapp', watch_extension: 'com.apple.product-type.watchkit-extension' }; return PRODUCTTYPE_BY_TARGETTYPE[targetType] } function filetypeForProducttype(productType) { FILETYPE_BY_PRODUCTTYPE = { 'com.apple.product-type.application': '"wrapper.application"', 'com.apple.product-type.app-extension': '"wrapper.app-extension"', 'com.apple.product-type.bundle': '"wrapper.plug-in"', 'com.apple.product-type.tool': '"compiled.mach-o.dylib"', 'com.apple.product-type.library.dynamic': '"compiled.mach-o.dylib"', 'com.apple.product-type.framework': '"wrapper.framework"', 'com.apple.product-type.library.static': '"archive.ar"', 'com.apple.product-type.bundle.unit-test': '"wrapper.cfbundle"', 'com.apple.product-type.application.watchapp': '"wrapper.application"', 'com.apple.product-type.watchkit-extension': '"wrapper.app-extension"' }; return FILETYPE_BY_PRODUCTTYPE[productType] } function unquoted(text) { return text.replace(/(^")|("$)/g, '') } function defaultExtension(filetype) { for (var extension in FILETYPE_BY_EXTENSION) { if (FILETYPE_BY_EXTENSION.hasOwnProperty(unquoted(extension))) { if (FILETYPE_BY_EXTENSION[unquoted(extension)] === filetype) return extension; } } } function removeExtensionTarget(name, targetType) { var pbxProjectSection = xcodeproj.pbxProjectSection(), productsGroup = xcodeproj.pbxGroupByName('Products'); if (!producttypeForTargettype(targetType)) { throw new Error("Target type invalid: " + targetType); } removeTargetDependency(projectTargetId, name) removeFromPbxProjectSection(extensionTargetId) console.log("> get productFile...") console.log(productsGroup) console.log("> get productName..." + name) var productType = producttypeForTargettype(targetType) console.log("> get productType..." + productType) var productFileType = filetypeForProducttype(productType).replace(/[\"|\']/g, '') console.log("> get productFileType..." + productFileType) var productFileName = name + '.' + defaultExtension(productFileType); console.log("> get productFileName..." + productFileName) removeFromProduct(productsGroup, productFileName) removeFromBuildConfiguration(extensionName) removeNativeTarget(extensionName) removeNoncli() } function removeNativeTarget(name) { var pbxNativeTargetSection = xcodeproj.pbxNativeTargetSection() for (key in pbxNativeTargetSection) { if (!pbxNativeTargetSection[key].name) { continue } else { if (pbxNativeTargetSection[key].name.indexOf(name) != -1) { console.log("> remove native target ..." + key) delete pbxNativeTargetSection[key] var commentKey = f("%s_comment", key); if (pbxNativeTargetSection[commentKey] != undefined) { console.log("> remove native target comment ..." + commentKey) delete pbxNativeTargetSection[commentKey]; } } } } } function removeFromBuildConfiguration(name) { var pbxXCBuildConfigurationSection = xcodeproj.pbxXCBuildConfigurationSection(), pbxXCConfigurationList = xcodeproj.pbxXCConfigurationList() for (key in pbxXCBuildConfigurationSection) { if (!pbxXCBuildConfigurationSection[key].buildSettings || !pbxXCBuildConfigurationSection[key].buildSettings.PRODUCT_NAME) { continue } else { if (pbxXCBuildConfigurationSection[key].buildSettings.PRODUCT_NAME.indexOf(name) != -1) { console.log("> remove build configuration ..." + key) delete pbxXCBuildConfigurationSection[key] var commentKey = f("%s_comment", key); if (pbxXCBuildConfigurationSection[commentKey] != undefined) { console.log("> remove build configuration comment ..." + commentKey) delete pbxXCBuildConfigurationSection[commentKey]; } } } } for (commentKey in pbxXCConfigurationList) { if (!COMMENT_KEY.test(commentKey)) continue if (pbxXCConfigurationList[commentKey].indexOf(name) != -1) { console.log("> remove build configuration list comment..." + commentKey) delete pbxXCConfigurationList[commentKey] var key = commentKey.split(COMMENT_KEY)[0] if (pbxXCConfigurationList[key] != undefined) { console.log("> remove build configuration comment ..." + key) delete pbxXCConfigurationList[key]; } } } } function removeFromProduct(productsGroup, productFileName) { var productKey, removeIndex if (productsGroup.children) { for (key in productsGroup.children) { if (productsGroup.children[key].comment.indexOf(productFileName) != -1) { productKey = productsGroup.children[key]['value'] removeIndex = key } } console.log("> remove " + productFileName + " reference from PRODUCT Group ..." + productKey) if (productKey) productsGroup.children.splice(removeIndex, 1) } removeFromFileReference(productKey) removeFromBuildFile(productKey) removeBuildPhase([], 'PBXCopyFilesBuildPhase', projectTargetId) } function removeFromBuildFile(fileKey) { console.log("> remove build file ..." + fileKey) for (key in xcodeproj.pbxBuildFileSection()) { if (!xcodeproj.pbxBuildFileSection()[key].fileRef) { continue } else { if (xcodeproj.pbxBuildFileSection()[key].fileRef === fileKey) { delete xcodeproj.pbxBuildFileSection()[key]; var commentKey = f("%s_comment", key); if (xcodeproj.pbxBuildFileSection()[commentKey] != undefined) { console.log("> remove build file comment ..." + commentKey) delete xcodeproj.pbxBuildFileSection()[commentKey]; } } } } } function removeFromFileReference(fileKey) { console.log("> remove file reference ..." + fileKey) delete xcodeproj.pbxFileReferenceSection()[fileKey]; var commentKey = f("%s_comment", fileKey); if (xcodeproj.pbxFileReferenceSection()[commentKey] != undefined) { console.log("> remove file reference comment ..." + commentKey) delete xcodeproj.pbxFileReferenceSection()[commentKey]; } } function addToPbxFileReferenceSection(file) { var commentKey = f("%s_comment", file.fileRef); this.pbxFileReferenceSection()[file.fileRef] = pbxFileReferenceObj(file); this.pbxFileReferenceSection()[commentKey] = pbxFileReferenceComment(file); } function removeFromPbxCopyfilesBuildPhase(file) { var sources = xcodeproj.buildPhaseObject('PBXCopyFilesBuildPhase', 'Copy Files', file.target); sources.files.push(pbxBuildPhaseObj(file)); } function removeFromPbxProjectSection(targetId) { // console.log("> removeFromPbxProjectSection: " + targetId) // console.log(xcodeproj.pbxProjectSection()[xcodeproj.getFirstProject()['uuid']]['targets']) var buildPhaseObject for (key in xcodeproj.pbxProjectSection()[xcodeproj.getFirstProject()['uuid']]['targets']) { console.log("> remove from PbxProjectSection: " + targetId + " | " + xcodeproj.pbxProjectSection()[xcodeproj.getFirstProject()['uuid']]['targets'][key]['value']) if (xcodeproj.pbxProjectSection()[xcodeproj.getFirstProject()['uuid']]['targets'][key]['value'] == targetId) { xcodeproj.pbxProjectSection()[xcodeproj.getFirstProject()['uuid']]['targets'].splice(key, 1) } } } function removeNoncli() { var pbxXCConfigurationList = xcodeproj.pbxXCConfigurationList() try { projects[projectId].buildConfigurationList_comment = projects[projectId].buildConfigurationList_comment.replace(projectName, "__NON-CLI__") console.log("> update __NON-CLI__..." + projects[projectId].buildConfigurationList_comment); var commentKey = f("%s_comment", projects[projectId].buildConfigurationList); pbxXCConfigurationList[commentKey] = pbxXCConfigurationList[commentKey].replace(projectName, "__NON-CLI__") console.log("> update __NON-CLI__..." + pbxXCConfigurationList[commentKey]); } catch (e) { throw new Error('Replace __NON-CLI__ failed'); } } function compareFiles(fileArray, jsonArray) { console.log() var isEqual = true for (file of fileArray) { var isContain = false var i = file.indexOf('/') var filename if (i != -1) { filename = file.substring(i + 1) } else { filename = file } // console.log("> filename = " + filename) for (entry of jsonArray) { if (!entry.comment) { continue } else { if (entry.comment.indexOf(filename) != -1) { isContain = true } } } if (!isContain) { isEqual = false } } for (entry of jsonArray) { var isContain = false if (!entry.comment) { continue } else { for (file of fileArray) { var i = file.indexOf('/') var filename if (i != -1) { filename = file.substring(i + 1) } else { filename = file } console.log("> filename = " + filename) if (entry.comment.indexOf(filename) != -1) { isContain = true } } if (!isContain) { isEqual = false } } } console.log("> compareFiles..." + isEqual) console.log(fileArray) console.log(jsonArray) return isEqual } function checkPair(entry) { var isPair = true var pairKey, pairCommentKey if (_.size(entry) == 2) { for (var key in entry) { if (COMMENT_KEY.test(key)) { pairCommentKey = key.split(COMMENT_KEY)[0] } else { pairKey = key } } } else { return null } if (pairKey === pairCommentKey) { return pairKey } else { return null } } function removeBuildPhase(filePathsArray, buildPhaseType, nativeTargetId) { var buildPhaseSection = xcodeproj.hash.project.objects[buildPhaseType], nativeTargets = xcodeproj.pbxNativeTargetSection(), buildFileSection = xcodeproj.pbxBuildFileSection(), removeBuildPhaseKey, removeBuildPhaseCommentKey if (!buildPhaseSection) return console.log("> buildPhaseType = " + buildPhaseType) if (buildPhaseType === 'PBXCopyFilesBuildPhase') { console.log(buildPhaseSection) console.log("> buildPhaseType = " + _.size(buildPhaseSection)) var pairKey = checkPair(buildPhaseSection) if (pairKey != null) { removeBuildPhaseKey = pairKey removeBuildPhaseCommentKey = f("%s_comment", removeBuildPhaseKey) // console.log("> remove BuildPhase " + removeBuildPhaseKey + " from... ") // console.log(buildPhaseSection) delete buildPhaseSection[removeBuildPhaseKey] delete buildPhaseSection[removeBuildPhaseCommentKey] // console.log(buildPhaseSection) } } else { for (key in buildPhaseSection) { // console.log(key) // console.log(buildPhaseSection[key]) if (!buildPhaseSection[key].files) { continue } else { if (_.size(filePathsArray) === _.size(buildPhaseSection[key].files) && compareFiles(filePathsArray, buildPhaseSection[key].files)) { removeBuildPhaseKey = key removeBuildPhaseCommentKey = f("%s_comment", removeBuildPhaseKey) console.log("> find same files from " + key + " | " + _.size(filePathsArray)) console.log("> remove BuildPhase " + removeBuildPhaseKey + " from... ") // console.log(buildPhaseSection) delete buildPhaseSection[removeBuildPhaseKey] delete buildPhaseSection[removeBuildPhaseCommentKey] console.log(buildPhaseSection) } } } } // if (removeBuildPhaseKey) delete buildPhaseSection[removeBuildPhaseKey] // if (removeBuildPhaseCommentKey) delete buildPhaseSection[removeBuildPhaseCommentKey] // console.log("> nativeTargets") // console.log(nativeTargets) for (targetKey in nativeTargets) { if (!nativeTargets[targetKey].buildPhases) { continue } else { if (targetKey === nativeTargetId) { for (entryKey in nativeTargets[targetKey].buildPhases) { console.log("> nativeTargets... " + nativeTargets[targetKey].buildPhases[entryKey].value + " | " + removeBuildPhaseKey) if (nativeTargets[targetKey].buildPhases[entryKey].value === removeBuildPhaseKey) { console.log("> remove BuildPhase Reference " + removeBuildPhaseKey + " from nativeTargets... ") // console.log(nativeTargets[targetKey].buildPhases) nativeTargets[targetKey].buildPhases.splice(entryKey, 1) // console.log(nativeTargets[targetKey].buildPhases) } } } } } return removeBuildPhaseKey } function addTarget(xcodeproj, name, type, subfolder) { // Setup uuid and name of new target var targetUuid = xcodeproj.generateUuid(), targetType = type, targetSubfolder = subfolder || name, targetName = name.trim(); // Check type against list of allowed target types if (!targetName) { throw new Error("Target name missing."); } // Check type against list of allowed target types if (!targetType) { throw new Error("Target type missing."); } // Check type against list of allowed target types if (!producttypeForTargettype(targetType)) { throw new Error("Target type invalid: " + targetType); } // Build Configuration: Create var buildConfigurationsList = [{ name: 'Debug', isa: 'XCBuildConfiguration', buildSettings: { GCC_PREPROCESSOR_DEFINITIONS: ['"DEBUG=1"', '"$(inherited)"'], INFOPLIST_FILE: '"' + path.join(targetSubfolder, targetSubfolder + '-Info.plist' + '"'), LD_RUNPATH_SEARCH_PATHS: '"$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"', PRODUCT_NAME: '"' + targetName + '"', SKIP_INSTALL: 'YES' } }, { name: 'Release', isa: 'XCBuildConfiguration', buildSettings: { INFOPLIST_FILE: '"' + path.join(targetSubfolder, targetSubfolder + '-Info.plist' + '"'), LD_RUNPATH_SEARCH_PATHS: '"$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"', PRODUCT_NAME: '"' + targetName + '"', SKIP_INSTALL: 'YES' } } ]; // Build Configuration: Add var buildConfigurations = xcodeproj.addXCConfigurationList(buildConfigurationsList, 'Release', 'Build configuration list for PBXNativeTarget "' + targetName + '"'); // Product: Create console.log("> get productFile...") var productName = targetName console.log("> get productName..." + productName) var productType = producttypeForTargettype(targetType) console.log("> get productType..." + productType) var productFileType = filetypeForProducttype(productType).replace(/[\"|\']/g, '') console.log("> get productFileType..." + productFileType) var productFile = addProductFile( productName, { group: 'Copy Files', 'target': targetUuid, 'explicitFileType': productFileType } ), productFileName = productFile.basename; console.log("> get productFileName..." + productFileName) // console.log(productFile) console.log(sep) // Product: Add to build file list xcodeproj.addToPbxBuildFileSection(productFile); // Target: Create var target = { uuid: targetUuid, pbxNativeTarget: { isa: 'PBXNativeTarget', name: '"' + targetName + '"', productName: '"' + targetName + '"', productReference: productFile.fileRef, productType: '"' + producttypeForTargettype(targetType) + '"', buildConfigurationList: buildConfigurations.uuid, buildPhases: [], buildRules: [], dependencies: [] } }; // Target: Add to PBXNativeTarget section xcodeproj.addToPbxNativeTargetSection(target) // Product: Embed (only for "extension"-type targets) if (targetType === 'app_extension') { // Create CopyFiles phase in first target addBuildPhase([], 'PBXCopyFilesBuildPhase', 'Copy Files', xcodeproj.getFirstTarget().uuid, targetType) // Add product to CopyFiles phase xcodeproj.addToPbxCopyfilesBuildPhase(productFile) // this.addBuildPhaseToTarget(newPhase.buildPhase, this.getFirstTarget().uuid) }; // Target: Add uuid to root project xcodeproj.addToPbxProjectSection(target); // Target: Add dependency for this target to first (main) target xcodeproj.addTargetDependency(xcodeproj.getFirstTarget().uuid, [target.uuid]); // Return target on success return target; }; function applyPatchBack(patches) { try { var command = ""; for (patch of patches) { command += validatePatch(patch) } console.log("> exec command... " + command) if (command != '') { exec( command, function (error, stdout) { console.log("> patch back... "); console.log(stdout); }.bind(this) ); } } catch (e) { console.error('> check patches... ' + patches + " not existed.") } } function validatePatch(patch) { var tester = fs.readFileSync(patch, encoding); console.log('> check patch file ' + patch + '... ' + !(!tester)) if (!(!tester)) { return 'patch -R -p2 -d platforms/ < ' + patch + ";" } return "" } function getXcodeProjectPath(context) { var root = path.join(context.opts.projectRoot, "platforms", 'ios') var xcodeProjDir; var xcodeCordovaProj; try { xcodeProjDir = fs.readdirSync(root).filter(function (e) { return e.match(/\.xcodeproj$/i); })[0]; if (!xcodeProjDir) { throw new Error('The provided path "' + root + '" is not a Cordova iOS project.'); } var cordovaProjName = xcodeProjDir.substring(xcodeProjDir.lastIndexOf(path.sep) + 1, xcodeProjDir.indexOf('.xcodeproj')); xcodeCordovaProj = path.join(root, cordovaProjName); } catch (e) { throw new Error('The provided path "' + root + '" is not a Cordova iOS project.'); } return path.join(root, xcodeProjDir, 'project.pbxproj') } function printRegEx(matches) { console.log(' -> matches: ' + matches.length) matches.forEach(function (element) { if (element) { if (element.length < 30) { console.log(' -> matches element... ' + element) } else { var short = element.substring(0, 30) console.log(' -> matches element... ' + short.replace('/[\n\r]+/g', ' \n')) } } else { console.log(' -> matches element... null') } }, this); } };
JavaScript
CL
54fb7387ee196f450d9751c19d95543801b81e86a2427644e2e1e34ba735b70a
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getCursorBandPositionSelector = void 0; var create_selector_1 = require("../../../../state/create_selector"); var get_settings_specs_1 = require("../../../../state/selectors/get_settings_specs"); var events_1 = require("../../../../utils/events"); var crosshair_utils_1 = require("../../crosshair/crosshair_utils"); var common_1 = require("../utils/common"); var compute_chart_dimensions_1 = require("./compute_chart_dimensions"); var compute_series_geometries_1 = require("./compute_series_geometries"); var compute_small_multiple_scales_1 = require("./compute_small_multiple_scales"); var count_bars_in_cluster_1 = require("./count_bars_in_cluster"); var get_geometries_index_keys_1 = require("./get_geometries_index_keys"); var get_oriented_projected_pointer_position_1 = require("./get_oriented_projected_pointer_position"); var get_specs_1 = require("./get_specs"); var is_tooltip_snap_enabled_1 = require("./is_tooltip_snap_enabled"); var getExternalPointerEventStateSelector = function (state) { return state.externalEvents.pointer; }; exports.getCursorBandPositionSelector = create_selector_1.createCustomCachedSelector([ get_oriented_projected_pointer_position_1.getOrientedProjectedPointerPositionSelector, getExternalPointerEventStateSelector, compute_chart_dimensions_1.computeChartDimensionsSelector, get_settings_specs_1.getSettingsSpecSelector, compute_series_geometries_1.computeSeriesGeometriesSelector, get_specs_1.getSeriesSpecsSelector, count_bars_in_cluster_1.countBarsInClusterSelector, is_tooltip_snap_enabled_1.isTooltipSnapEnableSelector, get_geometries_index_keys_1.getGeometriesIndexKeysSelector, compute_small_multiple_scales_1.computeSmallMultipleScalesSelector, ], function (orientedProjectedPointerPosition, externalPointerEvent, chartDimensions, settingsSpec, seriesGeometries, seriesSpec, totalBarsInCluster, isTooltipSnapEnabled, geometriesIndexKeys, smallMultipleScales) { return getCursorBand(orientedProjectedPointerPosition, externalPointerEvent, chartDimensions.chartDimensions, settingsSpec, seriesGeometries.scales.xScale, seriesSpec, totalBarsInCluster, isTooltipSnapEnabled, geometriesIndexKeys, smallMultipleScales); }); function getCursorBand(orientedProjectedPointerPosition, externalPointerEvent, chartDimensions, settingsSpec, xScale, seriesSpecs, totalBarsInCluster, isTooltipSnapEnabled, geometriesIndexKeys, smallMultipleScales) { if (!xScale) { return; } var isLineAreaOnly = common_1.isLineAreaOnlyChart(seriesSpecs); var pointerPosition = __assign({}, orientedProjectedPointerPosition); var xValue; var fromExternalEvent = false; if (events_1.isValidPointerOverEvent(xScale, externalPointerEvent)) { fromExternalEvent = true; var x = xScale.pureScale(externalPointerEvent.x); if (x == null || x > chartDimensions.width || x < 0) { return; } pointerPosition = { x: x, y: 0, verticalPanelValue: null, horizontalPanelValue: null, }; xValue = { value: externalPointerEvent.x, withinBandwidth: true, }; } else { xValue = xScale.invertWithStep(orientedProjectedPointerPosition.x, geometriesIndexKeys); if (!xValue) { return; } } var horizontal = smallMultipleScales.horizontal, vertical = smallMultipleScales.vertical; var topPos = vertical.scale(pointerPosition.verticalPanelValue) || 0; var leftPos = horizontal.scale(pointerPosition.horizontalPanelValue) || 0; var panel = { width: horizontal.bandwidth, height: vertical.bandwidth, top: chartDimensions.top + topPos, left: chartDimensions.left + leftPos, }; var cursorBand = crosshair_utils_1.getCursorBandPosition(settingsSpec.rotation, panel, pointerPosition, { value: xValue.value, withinBandwidth: true, }, isTooltipSnapEnabled, xScale, isLineAreaOnly ? 0 : totalBarsInCluster); return (cursorBand && __assign(__assign({}, cursorBand), { fromExternalEvent: fromExternalEvent })); } //# sourceMappingURL=get_cursor_band.js.map
JavaScript
CL
6a48b3149d55316a7f954179183aebe68c220fefcb86e66c978f3809fb066e8b
/** * Return a integer between 0 and max * @param max * @returns {number} */ function getRandomInt(max) { return Math.floor(Math.random() * max); } /** * Resolve a promise after x ms * @param ms * @returns {Promise<unknown>} */ function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } /** * Generate aleatory cardModel based on getRandomInt() * @param cardNumber * @returns {{duration: number, image: string, type: string, title: string, cardinality: string}[]} */ function generateXCardModel(cardNumber) { const cardType = ['video', 'elearning', 'learning_plan', 'playlist']; const randomTitle = ['Smooth Son', 'The Servants\'s School', 'Thoughts in the Hunter', 'The Tears of the Dragon', 'The Dreamer\'s Princess', 'The Luck of the Abyss', 'The Whispering Serpent', 'Witches in the Emperor', 'The Door of the Female', 'Sword in the Thorns', 'The Stones of the Cloud', 'The Husband of the Bridges', 'The Winter of the Moons', 'The Twins of the Swords'] // getRandomInt is useful for giving some aleatory to the model structure return Array.from({length: cardNumber}, (value, index) => ({ // Random query param avoid the backend cache! Different image for concurrent http call! image: `https://picsum.photos/300/150?_=${getRandomInt(100)}`, type: cardType[getRandomInt(cardType.length)], duration: getRandomInt(5000), // seconds title: randomTitle[getRandomInt(randomTitle.length)], cardinality: getRandomInt(100) % 2 ? 'single' : 'collection' })) } /** * Utility for convert seconds to hours. * If the time is less then 1h different format is applied * @param sec * @returns {string|null} */ function fromSecToH(sec) { if (!!sec && typeof sec === 'number') { const hours = Math.trunc(sec / 3600); const min = (sec / 3600 - hours) * 60; const minTruncated = Math.abs(Math.trunc((sec / 3600 - hours) * 60)); const formSec = Math.abs(Math.trunc((minTruncated - min) * 60)); if (hours > 0) { return `${hours}h ${minTruncated}min` } else { return `${timeFormatter(minTruncated)}:${timeFormatter(formSec)}` } } return null; } // not exported function, used only from fromSecToH() function timeFormatter(number) { let absNumber = Math.abs(number); return absNumber < 10 ? `0${absNumber}` : absNumber; } /** * This function use the template (html item) for get the html Element from html string! more powerful then using innerHTML * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template * @param html * @returns {ChildNode} */ function htmlToElement(html) { const template = document.createElement('template'); html = html.trim(); // Never return a text node of whitespace as the result template.innerHTML = html; return template.content.firstChild; } export {getRandomInt, delay, generateXCardModel, fromSecToH, htmlToElement};
JavaScript
CL
ce47d80501b7d2f33f884c19f046bab78098b428c1bd217f31b58a56ddaec86d
/** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file friendly errors plugin * @author wangyongqing <wangyongqing01@baidu.com> */ const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin'); const {textColor} = require('san-cli-utils/randomColor'); // 这里处理 loader 缺失的问题 const rules = [ { type: 'cant-resolve-loader', re: /Can't resolve '(.*loader)'/, msg: (e, match) => ` Failed to resolve loader: ${textColor(match[1])}\n` + ' You may need to install it.\n' }, { type: 'cant-resolve-html', re: /Can't resolve '(.*(html|htm|tpl))'/, msg: (e, match) => ` Failed to resolve page: ${textColor(match[1])}\n` + ' You may need to check you configuration.\n' } ]; const defaultTransformers = [ error => { if (error.webpackError) { /* eslint-disable operator-linebreak */ const message = typeof error.webpackError === 'string' ? error.webpackError : error.webpackError.message || ''; for (const {re, msg, type} of rules) { const match = message.match(re); if (match) { return Object.assign(error || {}, { type, shortMessage: msg(error, match) }); } } if (!error.message) { return Object.assign(error || {}, { type: 'unknown-webpack-error', shortMessage: message }); } } return error; } ]; const defaultFormatters = [ errors => { errors = errors.filter(e => e.shortMessage); if (errors.length) { return errors.map(e => e.shortMessage); } } ]; module.exports = class SanFriendlyErrorsPlugin extends FriendlyErrorsPlugin { constructor(options = {}) { const additionalFormatters = options.additionalFormatters || []; const additionalTransformers = options.additionalTransformers || []; options.additionalFormatters = [...defaultFormatters, ...additionalFormatters]; options.additionalTransformers = [...defaultTransformers, ...additionalTransformers]; super(options); } // 置空,太多 log 了 displaySuccess() {} };
JavaScript
CL
b3093dde304a37c961b7bfcbcd90e3ef5478e95b92be3ace07bd46ba1176c307
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating // requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel // MIT license (function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; }()); /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas, David Knight. Dual MIT/BSD license */ window.matchMedia || (window.matchMedia = function() { "use strict"; // For browsers that support matchMedium api such as IE 9 and webkit var styleMedia = (window.styleMedia || window.media); // For those that don't support matchMedium if (!styleMedia) { var style = document.createElement('style'), script = document.getElementsByTagName('script')[0], info = null; style.type = 'text/css'; style.id = 'matchmediajs-test'; script.parentNode.insertBefore(style, script); // 'style.currentStyle' is used by IE <= 8 and 'window.getComputedStyle' for all other browsers info = ('getComputedStyle' in window) && window.getComputedStyle(style, null) || style.currentStyle; styleMedia = { matchMedium: function(media) { var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }'; // 'style.styleSheet' is used by IE <= 8 and 'style.textContent' for all other browsers if (style.styleSheet) { style.styleSheet.cssText = text; } else { style.textContent = text; } // Test if media query is true or false return info.width === '1px'; } }; } return function(media) { return { matches: styleMedia.matchMedium(media || 'all'), media: media || 'all' }; }; }()); /*! jQuery v2.1.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m=a.document,n="2.1.0",o=function(a,b){return new o.fn.init(a,b)},p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};o.fn=o.prototype={jquery:n,constructor:o,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=o.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return o.each(this,a,b)},map:function(a){return this.pushStack(o.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},o.extend=o.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||o.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(o.isPlainObject(d)||(e=o.isArray(d)))?(e?(e=!1,f=c&&o.isArray(c)?c:[]):f=c&&o.isPlainObject(c)?c:{},g[b]=o.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},o.extend({expando:"jQuery"+(n+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===o.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isPlainObject:function(a){if("object"!==o.type(a)||a.nodeType||o.isWindow(a))return!1;try{if(a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(b){return!1}return!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=o.trim(a),a&&(1===a.indexOf("use strict")?(b=m.createElement("script"),b.text=a,m.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":k.call(a)},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?o.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),o.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||o.guid++,f):void 0},now:Date.now,support:l}),o.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=o.type(a);return"function"===c||o.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);o.find=t,o.expr=t.selectors,o.expr[":"]=o.expr.pseudos,o.unique=t.uniqueSort,o.text=t.getText,o.isXMLDoc=t.isXML,o.contains=t.contains;var u=o.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(o.isFunction(b))return o.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return o.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return o.filter(b,a,c);b=o.filter(b,a)}return o.grep(a,function(a){return g.call(b,a)>=0!==c})}o.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?o.find.matchesSelector(d,a)?[d]:[]:o.find.matches(a,o.grep(b,function(a){return 1===a.nodeType}))},o.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(o(a).filter(function(){for(b=0;c>b;b++)if(o.contains(e[b],this))return!0}));for(b=0;c>b;b++)o.find(a,e[b],d);return d=this.pushStack(c>1?o.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?o(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=o.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof o?b[0]:b,o.merge(this,o.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:m,!0)),v.test(c[1])&&o.isPlainObject(b))for(c in b)o.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=m.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=m,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):o.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(o):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),o.makeArray(a,this))};A.prototype=o.fn,y=o(m);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};o.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&o(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),o.fn.extend({has:function(a){var b=o(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(o.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?o(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&o.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?o.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(o(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(o.unique(o.merge(this.get(),o(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}o.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return o.dir(a,"parentNode")},parentsUntil:function(a,b,c){return o.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return o.dir(a,"nextSibling")},prevAll:function(a){return o.dir(a,"previousSibling")},nextUntil:function(a,b,c){return o.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return o.dir(a,"previousSibling",c)},siblings:function(a){return o.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return o.sibling(a.firstChild)},contents:function(a){return a.contentDocument||o.merge([],a.childNodes)}},function(a,b){o.fn[a]=function(c,d){var e=o.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=o.filter(d,e)),this.length>1&&(C[a]||o.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return o.each(a.match(E)||[],function(a,c){b[c]=!0}),b}o.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):o.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){o.each(b,function(b,c){var d=o.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&o.each(arguments,function(a,b){var c;while((c=o.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?o.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},o.extend({Deferred:function(a){var b=[["resolve","done",o.Callbacks("once memory"),"resolved"],["reject","fail",o.Callbacks("once memory"),"rejected"],["notify","progress",o.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return o.Deferred(function(c){o.each(b,function(b,f){var g=o.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&o.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?o.extend(a,d):d}},e={};return d.pipe=d.then,o.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&o.isFunction(a.promise)?e:0,g=1===f?a:o.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&o.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;o.fn.ready=function(a){return o.ready.promise().done(a),this},o.extend({isReady:!1,readyWait:1,holdReady:function(a){a?o.readyWait++:o.ready(!0)},ready:function(a){(a===!0?--o.readyWait:o.isReady)||(o.isReady=!0,a!==!0&&--o.readyWait>0||(H.resolveWith(m,[o]),o.fn.trigger&&o(m).trigger("ready").off("ready")))}});function I(){m.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),o.ready()}o.ready.promise=function(b){return H||(H=o.Deferred(),"complete"===m.readyState?setTimeout(o.ready):(m.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},o.ready.promise();var J=o.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===o.type(c)){e=!0;for(h in c)o.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,o.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(o(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};o.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=o.expando+Math.random()}K.uid=1,K.accepts=o.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,o.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(o.isEmptyObject(f))o.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,o.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{o.isArray(b)?d=b.concat(b.map(o.camelCase)):(e=o.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!o.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?o.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}o.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),o.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length; while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=o.camelCase(d.slice(5)),P(f,d,e[d]));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=o.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),o.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||o.isArray(c)?d=L.access(a,b,o.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=o.queue(a,b),d=c.length,e=c.shift(),f=o._queueHooks(a,b),g=function(){o.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:o.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),o.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?o.queue(this[0],a):void 0===b?this:this.each(function(){var c=o.queue(this,a,b);o._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&o.dequeue(this,a)})},dequeue:function(a){return this.each(function(){o.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=o.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=L.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var Q=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,R=["Top","Right","Bottom","Left"],S=function(a,b){return a=b||a,"none"===o.css(a,"display")||!o.contains(a.ownerDocument,a)},T=/^(?:checkbox|radio)$/i;!function(){var a=m.createDocumentFragment(),b=a.appendChild(m.createElement("div"));b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";l.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return m.activeElement}catch(a){}}o.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=o.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof o!==U&&o.event.triggered!==b.type?o.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],n=q=h[1],p=(h[2]||"").split(".").sort(),n&&(l=o.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=o.event.special[n]||{},k=o.extend({type:n,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&o.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(n,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),o.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],n=q=h[1],p=(h[2]||"").split(".").sort(),n){l=o.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||o.removeEvent(a,n,r.handle),delete i[n])}else for(n in i)o.event.remove(a,n+b[j],c,d,!0);o.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,p=[d||m],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||m,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+o.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[o.expando]?b:new o.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:o.makeArray(c,[b]),n=o.event.special[q]||{},e||!n.trigger||n.trigger.apply(d,c)!==!1)){if(!e&&!n.noBubble&&!o.isWindow(d)){for(i=n.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||m)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:n.bindType||q,l=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),l&&l.apply(g,c),l=k&&g[k],l&&l.apply&&o.acceptData(g)&&(b.result=l.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||n._default&&n._default.apply(p.pop(),c)!==!1||!o.acceptData(d)||k&&o.isFunction(d[q])&&!o.isWindow(d)&&(h=d[k],h&&(d[k]=null),o.event.triggered=q,d[q](),o.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=o.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=o.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=o.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((o.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?o(e,this).index(i)>=0:o.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||m,d=c.documentElement,e=c.body,a.pageX=b.clientX+(d&&d.scrollLeft||e&&e.scrollLeft||0)-(d&&d.clientLeft||e&&e.clientLeft||0),a.pageY=b.clientY+(d&&d.scrollTop||e&&e.scrollTop||0)-(d&&d.clientTop||e&&e.clientTop||0)),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},fix:function(a){if(a[o.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=W.test(e)?this.mouseHooks:V.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new o.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=m),3===a.target.nodeType&&(a.target=a.target.parentNode),g.filter?g.filter(a,f):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==_()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===_()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&o.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return o.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=o.extend(new o.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?o.event.trigger(e,null,b):o.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},o.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)},o.Event=function(a,b){return this instanceof o.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.getPreventDefault&&a.getPreventDefault()?Z:$):this.type=a,b&&o.extend(this,b),this.timeStamp=a&&a.timeStamp||o.now(),void(this[o.expando]=!0)):new o.Event(a,b)},o.Event.prototype={isDefaultPrevented:$,isPropagationStopped:$,isImmediatePropagationStopped:$,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=Z,a&&a.preventDefault&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=Z,a&&a.stopPropagation&&a.stopPropagation()},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z,this.stopPropagation()}},o.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){o.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!o.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.focusinBubbles||o.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){o.event.simulate(b,a.target,o.event.fix(a),!0)};o.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=L.access(d,b);e||d.addEventListener(a,c,!0),L.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=L.access(d,b)-1;e?L.access(d,b,e):(d.removeEventListener(a,c,!0),L.remove(d,b))}}}),o.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(g in a)this.on(g,b,c,a[g],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=$;else if(!d)return this;return 1===e&&(f=d,d=function(a){return o().off(a),f.apply(this,arguments)},d.guid=f.guid||(f.guid=o.guid++)),this.each(function(){o.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,o(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=$),this.each(function(){o.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){o.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?o.event.trigger(a,b,c,!0):void 0}});var ab=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bb=/<([\w:]+)/,cb=/<|&#?\w+;/,db=/<(?:script|style|link)/i,eb=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/^$|\/(?:java|ecma)script/i,gb=/^true\/(.*)/,hb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ib={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,"",""]};ib.optgroup=ib.option,ib.tbody=ib.tfoot=ib.colgroup=ib.caption=ib.thead,ib.th=ib.td;function jb(a,b){return o.nodeName(a,"table")&&o.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function kb(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function lb(a){var b=gb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function mb(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function nb(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)o.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=o.extend({},h),M.set(b,i))}}function ob(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&o.nodeName(a,b)?o.merge([a],c):c}function pb(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}o.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=o.contains(a.ownerDocument,a);if(!(l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||o.isXMLDoc(a)))for(g=ob(h),f=ob(a),d=0,e=f.length;e>d;d++)pb(f[d],g[d]);if(b)if(c)for(f=f||ob(a),g=g||ob(h),d=0,e=f.length;e>d;d++)nb(f[d],g[d]);else nb(a,h);return g=ob(h,"script"),g.length>0&&mb(g,!i&&ob(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,n=a.length;n>m;m++)if(e=a[m],e||0===e)if("object"===o.type(e))o.merge(l,e.nodeType?[e]:e);else if(cb.test(e)){f=f||k.appendChild(b.createElement("div")),g=(bb.exec(e)||["",""])[1].toLowerCase(),h=ib[g]||ib._default,f.innerHTML=h[1]+e.replace(ab,"<$1></$2>")+h[2],j=h[0];while(j--)f=f.lastChild;o.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===o.inArray(e,d))&&(i=o.contains(e.ownerDocument,e),f=ob(k.appendChild(e),"script"),i&&mb(f),c)){j=0;while(e=f[j++])fb.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f,g,h=o.event.special,i=0;void 0!==(c=a[i]);i++){if(o.acceptData(c)&&(f=c[L.expando],f&&(b=L.cache[f]))){if(d=Object.keys(b.events||{}),d.length)for(g=0;void 0!==(e=d[g]);g++)h[e]?o.event.remove(c,e):o.removeEvent(c,e,b.handle);L.cache[f]&&delete L.cache[f]}delete M.cache[c[M.expando]]}}}),o.fn.extend({text:function(a){return J(this,function(a){return void 0===a?o.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?o.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||o.cleanData(ob(c)),c.parentNode&&(b&&o.contains(c.ownerDocument,c)&&mb(ob(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(o.cleanData(ob(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return o.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!db.test(a)&&!ib[(bb.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(ab,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(o.cleanData(ob(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,o.cleanData(ob(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,n=k-1,p=a[0],q=o.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&eb.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(c=o.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=o.map(ob(c,"script"),kb),g=f.length;k>j;j++)h=c,j!==n&&(h=o.clone(h,!0,!0),g&&o.merge(f,ob(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,o.map(f,lb),j=0;g>j;j++)h=f[j],fb.test(h.type||"")&&!L.access(h,"globalEval")&&o.contains(i,h)&&(h.src?o._evalUrl&&o._evalUrl(h.src):o.globalEval(h.textContent.replace(hb,"")))}return this}}),o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){o.fn[a]=function(a){for(var c,d=[],e=o(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),o(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qb,rb={};function sb(b,c){var d=o(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:o.css(d[0],"display");return d.detach(),e}function tb(a){var b=m,c=rb[a];return c||(c=sb(a,b),"none"!==c&&c||(qb=(qb||o("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=qb[0].contentDocument,b.write(),b.close(),c=sb(a,b),qb.detach()),rb[a]=c),c}var ub=/^margin/,vb=new RegExp("^("+Q+")(?!px)[a-z%]+$","i"),wb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)};function xb(a,b,c){var d,e,f,g,h=a.style;return c=c||wb(a),c&&(g=c.getPropertyValue(b)||c[b]),c&&(""!==g||o.contains(a.ownerDocument,a)||(g=o.style(a,b)),vb.test(g)&&ub.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function yb(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d="padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",e=m.documentElement,f=m.createElement("div"),g=m.createElement("div");g.style.backgroundClip="content-box",g.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===g.style.backgroundClip,f.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",f.appendChild(g);function h(){g.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%",e.appendChild(f);var d=a.getComputedStyle(g,null);b="1%"!==d.top,c="4px"===d.width,e.removeChild(f)}a.getComputedStyle&&o.extend(l,{pixelPosition:function(){return h(),b},boxSizingReliable:function(){return null==c&&h(),c},reliableMarginRight:function(){var b,c=g.appendChild(m.createElement("div"));return c.style.cssText=g.style.cssText=d,c.style.marginRight=c.style.width="0",g.style.width="1px",e.appendChild(f),b=!parseFloat(a.getComputedStyle(c,null).marginRight),e.removeChild(f),g.innerHTML="",b}})}(),o.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var zb=/^(none|table(?!-c[ea]).+)/,Ab=new RegExp("^("+Q+")(.*)$","i"),Bb=new RegExp("^([+-])=("+Q+")","i"),Cb={position:"absolute",visibility:"hidden",display:"block"},Db={letterSpacing:0,fontWeight:400},Eb=["Webkit","O","Moz","ms"];function Fb(a,b){if(b in a)return b;var c=b[0].toUpperCase()+b.slice(1),d=b,e=Eb.length;while(e--)if(b=Eb[e]+c,b in a)return b;return d}function Gb(a,b,c){var d=Ab.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Hb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=o.css(a,c+R[f],!0,e)),d?("content"===c&&(g-=o.css(a,"padding"+R[f],!0,e)),"margin"!==c&&(g-=o.css(a,"border"+R[f]+"Width",!0,e))):(g+=o.css(a,"padding"+R[f],!0,e),"padding"!==c&&(g+=o.css(a,"border"+R[f]+"Width",!0,e)));return g}function Ib(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=wb(a),g="border-box"===o.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=xb(a,b,f),(0>e||null==e)&&(e=a.style[b]),vb.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Hb(a,b,c||(g?"border":"content"),d,f)+"px"}function Jb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=L.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&S(d)&&(f[g]=L.access(d,"olddisplay",tb(d.nodeName)))):f[g]||(e=S(d),(c&&"none"!==c||!e)&&L.set(d,"olddisplay",e?c:o.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}o.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=xb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=o.camelCase(b),i=a.style;return b=o.cssProps[h]||(o.cssProps[h]=Fb(i,h)),g=o.cssHooks[b]||o.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=Bb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(o.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||o.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]="",i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=o.camelCase(b);return b=o.cssProps[h]||(o.cssProps[h]=Fb(a.style,h)),g=o.cssHooks[b]||o.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=xb(a,b,d)),"normal"===e&&b in Db&&(e=Db[b]),""===c||c?(f=parseFloat(e),c===!0||o.isNumeric(f)?f||0:e):e}}),o.each(["height","width"],function(a,b){o.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&zb.test(o.css(a,"display"))?o.swap(a,Cb,function(){return Ib(a,b,d)}):Ib(a,b,d):void 0},set:function(a,c,d){var e=d&&wb(a);return Gb(a,c,d?Hb(a,b,d,"border-box"===o.css(a,"boxSizing",!1,e),e):0)}}}),o.cssHooks.marginRight=yb(l.reliableMarginRight,function(a,b){return b?o.swap(a,{display:"inline-block"},xb,[a,"marginRight"]):void 0}),o.each({margin:"",padding:"",border:"Width"},function(a,b){o.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+R[d]+b]=f[d]||f[d-2]||f[0];return e}},ub.test(a)||(o.cssHooks[a+b].set=Gb)}),o.fn.extend({css:function(a,b){return J(this,function(a,b,c){var d,e,f={},g=0;if(o.isArray(b)){for(d=wb(a),e=b.length;e>g;g++)f[b[g]]=o.css(a,b[g],!1,d);return f}return void 0!==c?o.style(a,b,c):o.css(a,b)},a,b,arguments.length>1)},show:function(){return Jb(this,!0)},hide:function(){return Jb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){S(this)?o(this).show():o(this).hide()})}});function Kb(a,b,c,d,e){return new Kb.prototype.init(a,b,c,d,e)}o.Tween=Kb,Kb.prototype={constructor:Kb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(o.cssNumber[c]?"":"px")},cur:function(){var a=Kb.propHooks[this.prop];return a&&a.get?a.get(this):Kb.propHooks._default.get(this)},run:function(a){var b,c=Kb.propHooks[this.prop];return this.pos=b=this.options.duration?o.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Kb.propHooks._default.set(this),this}},Kb.prototype.init.prototype=Kb.prototype,Kb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=o.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){o.fx.step[a.prop]?o.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[o.cssProps[a.prop]]||o.cssHooks[a.prop])?o.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Kb.propHooks.scrollTop=Kb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},o.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},o.fx=Kb.prototype.init,o.fx.step={};var Lb,Mb,Nb=/^(?:toggle|show|hide)$/,Ob=new RegExp("^(?:([+-])=|)("+Q+")([a-z%]*)$","i"),Pb=/queueHooks$/,Qb=[Vb],Rb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=Ob.exec(b),f=e&&e[3]||(o.cssNumber[a]?"":"px"),g=(o.cssNumber[a]||"px"!==f&&+d)&&Ob.exec(o.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,o.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function Sb(){return setTimeout(function(){Lb=void 0}),Lb=o.now()}function Tb(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=R[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ub(a,b,c){for(var d,e=(Rb[b]||[]).concat(Rb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Vb(a,b,c){var d,e,f,g,h,i,j,k=this,l={},m=a.style,n=a.nodeType&&S(a),p=L.get(a,"fxshow");c.queue||(h=o._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,k.always(function(){k.always(function(){h.unqueued--,o.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],j=o.css(a,"display"),"none"===j&&(j=tb(a.nodeName)),"inline"===j&&"none"===o.css(a,"float")&&(m.display="inline-block")),c.overflow&&(m.overflow="hidden",k.always(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Nb.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(n?"hide":"show")){if("show"!==e||!p||void 0===p[d])continue;n=!0}l[d]=p&&p[d]||o.style(a,d)}if(!o.isEmptyObject(l)){p?"hidden"in p&&(n=p.hidden):p=L.access(a,"fxshow",{}),f&&(p.hidden=!n),n?o(a).show():k.done(function(){o(a).hide()}),k.done(function(){var b;L.remove(a,"fxshow");for(b in l)o.style(a,b,l[b])});for(d in l)g=Ub(n?p[d]:0,d,k),d in p||(p[d]=g.start,n&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function Wb(a,b){var c,d,e,f,g;for(c in a)if(d=o.camelCase(c),e=b[d],f=a[c],o.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=o.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function Xb(a,b,c){var d,e,f=0,g=Qb.length,h=o.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Lb||Sb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:o.extend({},b),opts:o.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:Lb||Sb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=o.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(Wb(k,j.opts.specialEasing);g>f;f++)if(d=Qb[f].call(j,a,k,j.opts))return d;return o.map(k,Ub,j),o.isFunction(j.opts.start)&&j.opts.start.call(a,j),o.fx.timer(o.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}o.Animation=o.extend(Xb,{tweener:function(a,b){o.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],Rb[c]=Rb[c]||[],Rb[c].unshift(b)},prefilter:function(a,b){b?Qb.unshift(a):Qb.push(a)}}),o.speed=function(a,b,c){var d=a&&"object"==typeof a?o.extend({},a):{complete:c||!c&&b||o.isFunction(a)&&a,duration:a,easing:c&&b||b&&!o.isFunction(b)&&b};return d.duration=o.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in o.fx.speeds?o.fx.speeds[d.duration]:o.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){o.isFunction(d.old)&&d.old.call(this),d.queue&&o.dequeue(this,d.queue)},d},o.fn.extend({fadeTo:function(a,b,c,d){return this.filter(S).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=o.isEmptyObject(a),f=o.speed(b,c,d),g=function(){var b=Xb(this,o.extend({},a),f);(e||L.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=o.timers,g=L.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Pb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&o.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=L.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=o.timers,g=d?d.length:0;for(c.finish=!0,o.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),o.each(["toggle","show","hide"],function(a,b){var c=o.fn[b];o.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Tb(b,!0),a,d,e)}}),o.each({slideDown:Tb("show"),slideUp:Tb("hide"),slideToggle:Tb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){o.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),o.timers=[],o.fx.tick=function(){var a,b=0,c=o.timers;for(Lb=o.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||o.fx.stop(),Lb=void 0},o.fx.timer=function(a){o.timers.push(a),a()?o.fx.start():o.timers.pop()},o.fx.interval=13,o.fx.start=function(){Mb||(Mb=setInterval(o.fx.tick,o.fx.interval))},o.fx.stop=function(){clearInterval(Mb),Mb=null},o.fx.speeds={slow:600,fast:200,_default:400},o.fn.delay=function(a,b){return a=o.fx?o.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a=m.createElement("input"),b=m.createElement("select"),c=b.appendChild(m.createElement("option"));a.type="checkbox",l.checkOn=""!==a.value,l.optSelected=c.selected,b.disabled=!0,l.optDisabled=!c.disabled,a=m.createElement("input"),a.value="t",a.type="radio",l.radioValue="t"===a.value}();var Yb,Zb,$b=o.expr.attrHandle;o.fn.extend({attr:function(a,b){return J(this,o.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){o.removeAttr(this,a)})}}),o.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===U?o.prop(a,b,c):(1===f&&o.isXMLDoc(a)||(b=b.toLowerCase(),d=o.attrHooks[b]||(o.expr.match.bool.test(b)?Zb:Yb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=o.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void o.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=o.propFix[c]||c,o.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&o.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),Zb={set:function(a,b,c){return b===!1?o.removeAttr(a,c):a.setAttribute(c,c),c}},o.each(o.expr.match.bool.source.match(/\w+/g),function(a,b){var c=$b[b]||o.find.attr;$b[b]=function(a,b,d){var e,f; return d||(f=$b[b],$b[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,$b[b]=f),e}});var _b=/^(?:input|select|textarea|button)$/i;o.fn.extend({prop:function(a,b){return J(this,o.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[o.propFix[a]||a]})}}),o.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!o.isXMLDoc(a),f&&(b=o.propFix[b]||b,e=o.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){return a.hasAttribute("tabindex")||_b.test(a.nodeName)||a.href?a.tabIndex:-1}}}}),l.optSelected||(o.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null}}),o.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){o.propFix[this.toLowerCase()]=this});var ac=/[\t\r\n\f]/g;o.fn.extend({addClass:function(a){var b,c,d,e,f,g,h="string"==typeof a&&a,i=0,j=this.length;if(o.isFunction(a))return this.each(function(b){o(this).addClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ac," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=o.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0===arguments.length||"string"==typeof a&&a,i=0,j=this.length;if(o.isFunction(a))return this.each(function(b){o(this).removeClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ac," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?o.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(o.isFunction(a)?function(c){o(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=o(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===U||"boolean"===c)&&(this.className&&L.set(this,"__className__",this.className),this.className=this.className||a===!1?"":L.get(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ac," ").indexOf(b)>=0)return!0;return!1}});var bc=/\r/g;o.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=o.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,o(this).val()):a,null==e?e="":"number"==typeof e?e+="":o.isArray(e)&&(e=o.map(e,function(a){return null==a?"":a+""})),b=o.valHooks[this.type]||o.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=o.valHooks[e.type]||o.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(bc,""):null==c?"":c)}}}),o.extend({valHooks:{select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&o.nodeName(c.parentNode,"optgroup"))){if(b=o(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=o.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=o.inArray(o(d).val(),f)>=0)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),o.each(["radio","checkbox"],function(){o.valHooks[this]={set:function(a,b){return o.isArray(b)?a.checked=o.inArray(o(a).val(),b)>=0:void 0}},l.checkOn||(o.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})}),o.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){o.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),o.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var cc=o.now(),dc=/\?/;o.parseJSON=function(a){return JSON.parse(a+"")},o.parseXML=function(a){var b,c;if(!a||"string"!=typeof a)return null;try{c=new DOMParser,b=c.parseFromString(a,"text/xml")}catch(d){b=void 0}return(!b||b.getElementsByTagName("parsererror").length)&&o.error("Invalid XML: "+a),b};var ec,fc,gc=/#.*$/,hc=/([?&])_=[^&]*/,ic=/^(.*?):[ \t]*([^\r\n]*)$/gm,jc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,kc=/^(?:GET|HEAD)$/,lc=/^\/\//,mc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,nc={},oc={},pc="*/".concat("*");try{fc=location.href}catch(qc){fc=m.createElement("a"),fc.href="",fc=fc.href}ec=mc.exec(fc.toLowerCase())||[];function rc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(o.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function sc(a,b,c,d){var e={},f=a===oc;function g(h){var i;return e[h]=!0,o.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function tc(a,b){var c,d,e=o.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&o.extend(!0,a,d),a}function uc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function vc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}o.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:fc,type:"GET",isLocal:jc.test(ec[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":pc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":o.parseJSON,"text xml":o.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?tc(tc(a,o.ajaxSettings),b):tc(o.ajaxSettings,a)},ajaxPrefilter:rc(nc),ajaxTransport:rc(oc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=o.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?o(l):o.event,n=o.Deferred(),p=o.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!f){f={};while(b=ic.exec(e))f[b[1].toLowerCase()]=b[2]}b=f[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?e:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return c&&c.abort(b),x(0,b),this}};if(n.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||fc)+"").replace(gc,"").replace(lc,ec[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=o.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(h=mc.exec(k.url.toLowerCase()),k.crossDomain=!(!h||h[1]===ec[1]&&h[2]===ec[2]&&(h[3]||("http:"===h[1]?"80":"443"))===(ec[3]||("http:"===ec[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=o.param(k.data,k.traditional)),sc(nc,k,b,v),2===t)return v;i=k.global,i&&0===o.active++&&o.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!kc.test(k.type),d=k.url,k.hasContent||(k.data&&(d=k.url+=(dc.test(d)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=hc.test(d)?d.replace(hc,"$1_="+cc++):d+(dc.test(d)?"&":"?")+"_="+cc++)),k.ifModified&&(o.lastModified[d]&&v.setRequestHeader("If-Modified-Since",o.lastModified[d]),o.etag[d]&&v.setRequestHeader("If-None-Match",o.etag[d])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+pc+"; q=0.01":""):k.accepts["*"]);for(j in k.headers)v.setRequestHeader(j,k.headers[j]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(j in{success:1,error:1,complete:1})v[j](k[j]);if(c=sc(oc,k,b,v)){v.readyState=1,i&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,c.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,f,h){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),c=void 0,e=h||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,f&&(u=uc(k,v,f)),u=vc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(o.lastModified[d]=w),w=v.getResponseHeader("etag"),w&&(o.etag[d]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?n.resolveWith(l,[r,x,v]):n.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,i&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),i&&(m.trigger("ajaxComplete",[v,k]),--o.active||o.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return o.get(a,b,c,"json")},getScript:function(a,b){return o.get(a,void 0,b,"script")}}),o.each(["get","post"],function(a,b){o[b]=function(a,c,d,e){return o.isFunction(c)&&(e=e||d,d=c,c=void 0),o.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),o.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){o.fn[b]=function(a){return this.on(b,a)}}),o._evalUrl=function(a){return o.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},o.fn.extend({wrapAll:function(a){var b;return o.isFunction(a)?this.each(function(b){o(this).wrapAll(a.call(this,b))}):(this[0]&&(b=o(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return this.each(o.isFunction(a)?function(b){o(this).wrapInner(a.call(this,b))}:function(){var b=o(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=o.isFunction(a);return this.each(function(c){o(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){o.nodeName(this,"body")||o(this).replaceWith(this.childNodes)}).end()}}),o.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0},o.expr.filters.visible=function(a){return!o.expr.filters.hidden(a)};var wc=/%20/g,xc=/\[\]$/,yc=/\r?\n/g,zc=/^(?:submit|button|image|reset|file)$/i,Ac=/^(?:input|select|textarea|keygen)/i;function Bc(a,b,c,d){var e;if(o.isArray(b))o.each(b,function(b,e){c||xc.test(a)?d(a,e):Bc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==o.type(b))d(a,b);else for(e in b)Bc(a+"["+e+"]",b[e],c,d)}o.param=function(a,b){var c,d=[],e=function(a,b){b=o.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=o.ajaxSettings&&o.ajaxSettings.traditional),o.isArray(a)||a.jquery&&!o.isPlainObject(a))o.each(a,function(){e(this.name,this.value)});else for(c in a)Bc(c,a[c],b,e);return d.join("&").replace(wc,"+")},o.fn.extend({serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=o.prop(this,"elements");return a?o.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!o(this).is(":disabled")&&Ac.test(this.nodeName)&&!zc.test(a)&&(this.checked||!T.test(a))}).map(function(a,b){var c=o(this).val();return null==c?null:o.isArray(c)?o.map(c,function(a){return{name:b.name,value:a.replace(yc,"\r\n")}}):{name:b.name,value:c.replace(yc,"\r\n")}}).get()}}),o.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(a){}};var Cc=0,Dc={},Ec={0:200,1223:204},Fc=o.ajaxSettings.xhr();a.ActiveXObject&&o(a).on("unload",function(){for(var a in Dc)Dc[a]()}),l.cors=!!Fc&&"withCredentials"in Fc,l.ajax=Fc=!!Fc,o.ajaxTransport(function(a){var b;return l.cors||Fc&&!a.crossDomain?{send:function(c,d){var e,f=a.xhr(),g=++Cc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)f.setRequestHeader(e,c[e]);b=function(a){return function(){b&&(delete Dc[g],b=f.onload=f.onerror=null,"abort"===a?f.abort():"error"===a?d(f.status,f.statusText):d(Ec[f.status]||f.status,f.statusText,"string"==typeof f.responseText?{text:f.responseText}:void 0,f.getAllResponseHeaders()))}},f.onload=b(),f.onerror=b("error"),b=Dc[g]=b("abort"),f.send(a.hasContent&&a.data||null)},abort:function(){b&&b()}}:void 0}),o.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return o.globalEval(a),a}}}),o.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),o.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(d,e){b=o("<script>").prop({async:!0,charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&e("error"===a.type?404:200,a.type)}),m.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Gc=[],Hc=/(=)\?(?=&|$)|\?\?/;o.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Gc.pop()||o.expando+"_"+cc++;return this[a]=!0,a}}),o.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Hc.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Hc.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=o.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Hc,"$1"+e):b.jsonp!==!1&&(b.url+=(dc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||o.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Gc.push(e)),g&&o.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),o.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||m;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=o.buildFragment([a],b,e),e&&e.length&&o(e).remove(),o.merge([],d.childNodes))};var Ic=o.fn.load;o.fn.load=function(a,b,c){if("string"!=typeof a&&Ic)return Ic.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h),a=a.slice(0,h)),o.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&o.ajax({url:a,type:e,dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?o("<div>").append(o.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,f||[a.responseText,b,a])}),this},o.expr.filters.animated=function(a){return o.grep(o.timers,function(b){return a===b.elem}).length};var Jc=a.document.documentElement;function Kc(a){return o.isWindow(a)?a:9===a.nodeType&&a.defaultView}o.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=o.css(a,"position"),l=o(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=o.css(a,"top"),i=o.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),o.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},o.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){o.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,o.contains(b,d)?(typeof d.getBoundingClientRect!==U&&(e=d.getBoundingClientRect()),c=Kc(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===o.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),o.nodeName(a[0],"html")||(d=a.offset()),d.top+=o.css(a[0],"borderTopWidth",!0),d.left+=o.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-o.css(c,"marginTop",!0),left:b.left-d.left-o.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||Jc;while(a&&!o.nodeName(a,"html")&&"static"===o.css(a,"position"))a=a.offsetParent;return a||Jc})}}),o.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(b,c){var d="pageYOffset"===c;o.fn[b]=function(e){return J(this,function(b,e,f){var g=Kc(b);return void 0===f?g?g[c]:b[e]:void(g?g.scrollTo(d?a.pageXOffset:f,d?f:a.pageYOffset):b[e]=f)},b,e,arguments.length,null)}}),o.each(["top","left"],function(a,b){o.cssHooks[b]=yb(l.pixelPosition,function(a,c){return c?(c=xb(a,b),vb.test(c)?o(a).position()[b]+"px":c):void 0})}),o.each({Height:"height",Width:"width"},function(a,b){o.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){o.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return J(this,function(b,c,d){var e;return o.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?o.css(b,c,g):o.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),o.fn.size=function(){return this.length},o.fn.andSelf=o.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return o});var Lc=a.jQuery,Mc=a.$;return o.noConflict=function(b){return a.$===o&&(a.$=Mc),b&&a.jQuery===o&&(a.jQuery=Lc),o},typeof b===U&&(a.jQuery=a.$=o),o}); $.ajaxPrefilter(function(e,r,c){function a(){var r=Array.prototype.slice.call(arguments);l&&null!=s?("function"==typeof e.success&&f.done(e.success),f.resolveWith(c,[s,"success",c])):(u&&f.fail(u),f.rejectWith(c,r))}function t(e){var r=Array.prototype.slice.call(arguments);o.set(n,e,i),f.resolveWith(c,r)}var o=window.lscache;if(o&&e.localCache){var i=e.cacheTTL||10,n=e.cacheKey||e.url.replace(/jQuery.*/,"")+e.type+(e.data||""),l="function"==typeof e.isCacheValid?e.isCacheValid():!o.isExpired(n),s=o.get(n,!0,!0),u="function"==typeof e.error?e.error:null;e.error=function(){};var f=new $.Deferred;return c.fail(a).done(t),l&&s?c.abort():l=!0,f.promise(c)}}); /** * @license * Lo-Dash 2.4.1 (Custom Build) lodash.com/license | Underscore.js 1.5.2 underscorejs.org/LICENSE * Build: `lodash modern -o ./dist/lodash.js` */ ;(function(){function n(n,t,e){e=(e||0)-1;for(var r=n?n.length:0;++e<r;)if(n[e]===t)return e;return-1}function t(t,e){var r=typeof e;if(t=t.l,"boolean"==r||null==e)return t[e]?0:-1;"number"!=r&&"string"!=r&&(r="object");var u="number"==r?e:m+e;return t=(t=t[r])&&t[u],"object"==r?t&&-1<n(t,e)?0:-1:t?0:-1}function e(n){var t=this.l,e=typeof n;if("boolean"==e||null==n)t[n]=true;else{"number"!=e&&"string"!=e&&(e="object");var r="number"==e?n:m+n,t=t[e]||(t[e]={});"object"==e?(t[r]||(t[r]=[])).push(n):t[r]=true }}function r(n){return n.charCodeAt(0)}function u(n,t){for(var e=n.m,r=t.m,u=-1,o=e.length;++u<o;){var i=e[u],a=r[u];if(i!==a){if(i>a||typeof i=="undefined")return 1;if(i<a||typeof a=="undefined")return-1}}return n.n-t.n}function o(n){var t=-1,r=n.length,u=n[0],o=n[r/2|0],i=n[r-1];if(u&&typeof u=="object"&&o&&typeof o=="object"&&i&&typeof i=="object")return false;for(u=f(),u["false"]=u["null"]=u["true"]=u.undefined=false,o=f(),o.k=n,o.l=u,o.push=e;++t<r;)o.push(n[t]);return o}function i(n){return"\\"+U[n] }function a(){return h.pop()||[]}function f(){return g.pop()||{k:null,l:null,m:null,"false":false,n:0,"null":false,number:null,object:null,push:null,string:null,"true":false,undefined:false,o:null}}function l(n){n.length=0,h.length<_&&h.push(n)}function c(n){var t=n.l;t&&c(t),n.k=n.l=n.m=n.object=n.number=n.string=n.o=null,g.length<_&&g.push(n)}function p(n,t,e){t||(t=0),typeof e=="undefined"&&(e=n?n.length:0);var r=-1;e=e-t||0;for(var u=Array(0>e?0:e);++r<e;)u[r]=n[t+r];return u}function s(e){function h(n,t,e){if(!n||!V[typeof n])return n; t=t&&typeof e=="undefined"?t:tt(t,e,3);for(var r=-1,u=V[typeof n]&&Fe(n),o=u?u.length:0;++r<o&&(e=u[r],false!==t(n[e],e,n)););return n}function g(n,t,e){var r;if(!n||!V[typeof n])return n;t=t&&typeof e=="undefined"?t:tt(t,e,3);for(r in n)if(false===t(n[r],r,n))break;return n}function _(n,t,e){var r,u=n,o=u;if(!u)return o;for(var i=arguments,a=0,f=typeof e=="number"?2:i.length;++a<f;)if((u=i[a])&&V[typeof u])for(var l=-1,c=V[typeof u]&&Fe(u),p=c?c.length:0;++l<p;)r=c[l],"undefined"==typeof o[r]&&(o[r]=u[r]); return o}function U(n,t,e){var r,u=n,o=u;if(!u)return o;var i=arguments,a=0,f=typeof e=="number"?2:i.length;if(3<f&&"function"==typeof i[f-2])var l=tt(i[--f-1],i[f--],2);else 2<f&&"function"==typeof i[f-1]&&(l=i[--f]);for(;++a<f;)if((u=i[a])&&V[typeof u])for(var c=-1,p=V[typeof u]&&Fe(u),s=p?p.length:0;++c<s;)r=p[c],o[r]=l?l(o[r],u[r]):u[r];return o}function H(n){var t,e=[];if(!n||!V[typeof n])return e;for(t in n)me.call(n,t)&&e.push(t);return e}function J(n){return n&&typeof n=="object"&&!Te(n)&&me.call(n,"__wrapped__")?n:new Q(n) }function Q(n,t){this.__chain__=!!t,this.__wrapped__=n}function X(n){function t(){if(r){var n=p(r);be.apply(n,arguments)}if(this instanceof t){var o=nt(e.prototype),n=e.apply(o,n||arguments);return wt(n)?n:o}return e.apply(u,n||arguments)}var e=n[0],r=n[2],u=n[4];return $e(t,n),t}function Z(n,t,e,r,u){if(e){var o=e(n);if(typeof o!="undefined")return o}if(!wt(n))return n;var i=ce.call(n);if(!K[i])return n;var f=Ae[i];switch(i){case T:case F:return new f(+n);case W:case P:return new f(n);case z:return o=f(n.source,C.exec(n)),o.lastIndex=n.lastIndex,o }if(i=Te(n),t){var c=!r;r||(r=a()),u||(u=a());for(var s=r.length;s--;)if(r[s]==n)return u[s];o=i?f(n.length):{}}else o=i?p(n):U({},n);return i&&(me.call(n,"index")&&(o.index=n.index),me.call(n,"input")&&(o.input=n.input)),t?(r.push(n),u.push(o),(i?St:h)(n,function(n,i){o[i]=Z(n,t,e,r,u)}),c&&(l(r),l(u)),o):o}function nt(n){return wt(n)?ke(n):{}}function tt(n,t,e){if(typeof n!="function")return Ut;if(typeof t=="undefined"||!("prototype"in n))return n;var r=n.__bindData__;if(typeof r=="undefined"&&(De.funcNames&&(r=!n.name),r=r||!De.funcDecomp,!r)){var u=ge.call(n); De.funcNames||(r=!O.test(u)),r||(r=E.test(u),$e(n,r))}if(false===r||true!==r&&1&r[1])return n;switch(e){case 1:return function(e){return n.call(t,e)};case 2:return function(e,r){return n.call(t,e,r)};case 3:return function(e,r,u){return n.call(t,e,r,u)};case 4:return function(e,r,u,o){return n.call(t,e,r,u,o)}}return Mt(n,t)}function et(n){function t(){var n=f?i:this;if(u){var h=p(u);be.apply(h,arguments)}return(o||c)&&(h||(h=p(arguments)),o&&be.apply(h,o),c&&h.length<a)?(r|=16,et([e,s?r:-4&r,h,null,i,a])):(h||(h=arguments),l&&(e=n[v]),this instanceof t?(n=nt(e.prototype),h=e.apply(n,h),wt(h)?h:n):e.apply(n,h)) }var e=n[0],r=n[1],u=n[2],o=n[3],i=n[4],a=n[5],f=1&r,l=2&r,c=4&r,s=8&r,v=e;return $e(t,n),t}function rt(e,r){var u=-1,i=st(),a=e?e.length:0,f=a>=b&&i===n,l=[];if(f){var p=o(r);p?(i=t,r=p):f=false}for(;++u<a;)p=e[u],0>i(r,p)&&l.push(p);return f&&c(r),l}function ut(n,t,e,r){r=(r||0)-1;for(var u=n?n.length:0,o=[];++r<u;){var i=n[r];if(i&&typeof i=="object"&&typeof i.length=="number"&&(Te(i)||yt(i))){t||(i=ut(i,t,e));var a=-1,f=i.length,l=o.length;for(o.length+=f;++a<f;)o[l++]=i[a]}else e||o.push(i)}return o }function ot(n,t,e,r,u,o){if(e){var i=e(n,t);if(typeof i!="undefined")return!!i}if(n===t)return 0!==n||1/n==1/t;if(n===n&&!(n&&V[typeof n]||t&&V[typeof t]))return false;if(null==n||null==t)return n===t;var f=ce.call(n),c=ce.call(t);if(f==D&&(f=q),c==D&&(c=q),f!=c)return false;switch(f){case T:case F:return+n==+t;case W:return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case z:case P:return n==oe(t)}if(c=f==$,!c){var p=me.call(n,"__wrapped__"),s=me.call(t,"__wrapped__");if(p||s)return ot(p?n.__wrapped__:n,s?t.__wrapped__:t,e,r,u,o); if(f!=q)return false;if(f=n.constructor,p=t.constructor,f!=p&&!(dt(f)&&f instanceof f&&dt(p)&&p instanceof p)&&"constructor"in n&&"constructor"in t)return false}for(f=!u,u||(u=a()),o||(o=a()),p=u.length;p--;)if(u[p]==n)return o[p]==t;var v=0,i=true;if(u.push(n),o.push(t),c){if(p=n.length,v=t.length,(i=v==p)||r)for(;v--;)if(c=p,s=t[v],r)for(;c--&&!(i=ot(n[c],s,e,r,u,o)););else if(!(i=ot(n[v],s,e,r,u,o)))break}else g(t,function(t,a,f){return me.call(f,a)?(v++,i=me.call(n,a)&&ot(n[a],t,e,r,u,o)):void 0}),i&&!r&&g(n,function(n,t,e){return me.call(e,t)?i=-1<--v:void 0 });return u.pop(),o.pop(),f&&(l(u),l(o)),i}function it(n,t,e,r,u){(Te(t)?St:h)(t,function(t,o){var i,a,f=t,l=n[o];if(t&&((a=Te(t))||Pe(t))){for(f=r.length;f--;)if(i=r[f]==t){l=u[f];break}if(!i){var c;e&&(f=e(l,t),c=typeof f!="undefined")&&(l=f),c||(l=a?Te(l)?l:[]:Pe(l)?l:{}),r.push(t),u.push(l),c||it(l,t,e,r,u)}}else e&&(f=e(l,t),typeof f=="undefined"&&(f=t)),typeof f!="undefined"&&(l=f);n[o]=l})}function at(n,t){return n+he(Re()*(t-n+1))}function ft(e,r,u){var i=-1,f=st(),p=e?e.length:0,s=[],v=!r&&p>=b&&f===n,h=u||v?a():s; for(v&&(h=o(h),f=t);++i<p;){var g=e[i],y=u?u(g,i,e):g;(r?!i||h[h.length-1]!==y:0>f(h,y))&&((u||v)&&h.push(y),s.push(g))}return v?(l(h.k),c(h)):u&&l(h),s}function lt(n){return function(t,e,r){var u={};e=J.createCallback(e,r,3),r=-1;var o=t?t.length:0;if(typeof o=="number")for(;++r<o;){var i=t[r];n(u,i,e(i,r,t),t)}else h(t,function(t,r,o){n(u,t,e(t,r,o),o)});return u}}function ct(n,t,e,r,u,o){var i=1&t,a=4&t,f=16&t,l=32&t;if(!(2&t||dt(n)))throw new ie;f&&!e.length&&(t&=-17,f=e=false),l&&!r.length&&(t&=-33,l=r=false); var c=n&&n.__bindData__;return c&&true!==c?(c=p(c),c[2]&&(c[2]=p(c[2])),c[3]&&(c[3]=p(c[3])),!i||1&c[1]||(c[4]=u),!i&&1&c[1]&&(t|=8),!a||4&c[1]||(c[5]=o),f&&be.apply(c[2]||(c[2]=[]),e),l&&we.apply(c[3]||(c[3]=[]),r),c[1]|=t,ct.apply(null,c)):(1==t||17===t?X:et)([n,t,e,r,u,o])}function pt(n){return Be[n]}function st(){var t=(t=J.indexOf)===Wt?n:t;return t}function vt(n){return typeof n=="function"&&pe.test(n)}function ht(n){var t,e;return n&&ce.call(n)==q&&(t=n.constructor,!dt(t)||t instanceof t)?(g(n,function(n,t){e=t }),typeof e=="undefined"||me.call(n,e)):false}function gt(n){return We[n]}function yt(n){return n&&typeof n=="object"&&typeof n.length=="number"&&ce.call(n)==D||false}function mt(n,t,e){var r=Fe(n),u=r.length;for(t=tt(t,e,3);u--&&(e=r[u],false!==t(n[e],e,n)););return n}function bt(n){var t=[];return g(n,function(n,e){dt(n)&&t.push(e)}),t.sort()}function _t(n){for(var t=-1,e=Fe(n),r=e.length,u={};++t<r;){var o=e[t];u[n[o]]=o}return u}function dt(n){return typeof n=="function"}function wt(n){return!(!n||!V[typeof n]) }function jt(n){return typeof n=="number"||n&&typeof n=="object"&&ce.call(n)==W||false}function kt(n){return typeof n=="string"||n&&typeof n=="object"&&ce.call(n)==P||false}function xt(n){for(var t=-1,e=Fe(n),r=e.length,u=Xt(r);++t<r;)u[t]=n[e[t]];return u}function Ct(n,t,e){var r=-1,u=st(),o=n?n.length:0,i=false;return e=(0>e?Ie(0,o+e):e)||0,Te(n)?i=-1<u(n,t,e):typeof o=="number"?i=-1<(kt(n)?n.indexOf(t,e):u(n,t,e)):h(n,function(n){return++r<e?void 0:!(i=n===t)}),i}function Ot(n,t,e){var r=true;t=J.createCallback(t,e,3),e=-1; var u=n?n.length:0;if(typeof u=="number")for(;++e<u&&(r=!!t(n[e],e,n)););else h(n,function(n,e,u){return r=!!t(n,e,u)});return r}function Nt(n,t,e){var r=[];t=J.createCallback(t,e,3),e=-1;var u=n?n.length:0;if(typeof u=="number")for(;++e<u;){var o=n[e];t(o,e,n)&&r.push(o)}else h(n,function(n,e,u){t(n,e,u)&&r.push(n)});return r}function It(n,t,e){t=J.createCallback(t,e,3),e=-1;var r=n?n.length:0;if(typeof r!="number"){var u;return h(n,function(n,e,r){return t(n,e,r)?(u=n,false):void 0}),u}for(;++e<r;){var o=n[e]; if(t(o,e,n))return o}}function St(n,t,e){var r=-1,u=n?n.length:0;if(t=t&&typeof e=="undefined"?t:tt(t,e,3),typeof u=="number")for(;++r<u&&false!==t(n[r],r,n););else h(n,t);return n}function Et(n,t,e){var r=n?n.length:0;if(t=t&&typeof e=="undefined"?t:tt(t,e,3),typeof r=="number")for(;r--&&false!==t(n[r],r,n););else{var u=Fe(n),r=u.length;h(n,function(n,e,o){return e=u?u[--r]:--r,t(o[e],e,o)})}return n}function Rt(n,t,e){var r=-1,u=n?n.length:0;if(t=J.createCallback(t,e,3),typeof u=="number")for(var o=Xt(u);++r<u;)o[r]=t(n[r],r,n); else o=[],h(n,function(n,e,u){o[++r]=t(n,e,u)});return o}function At(n,t,e){var u=-1/0,o=u;if(typeof t!="function"&&e&&e[t]===n&&(t=null),null==t&&Te(n)){e=-1;for(var i=n.length;++e<i;){var a=n[e];a>o&&(o=a)}}else t=null==t&&kt(n)?r:J.createCallback(t,e,3),St(n,function(n,e,r){e=t(n,e,r),e>u&&(u=e,o=n)});return o}function Dt(n,t,e,r){if(!n)return e;var u=3>arguments.length;t=J.createCallback(t,r,4);var o=-1,i=n.length;if(typeof i=="number")for(u&&(e=n[++o]);++o<i;)e=t(e,n[o],o,n);else h(n,function(n,r,o){e=u?(u=false,n):t(e,n,r,o) });return e}function $t(n,t,e,r){var u=3>arguments.length;return t=J.createCallback(t,r,4),Et(n,function(n,r,o){e=u?(u=false,n):t(e,n,r,o)}),e}function Tt(n){var t=-1,e=n?n.length:0,r=Xt(typeof e=="number"?e:0);return St(n,function(n){var e=at(0,++t);r[t]=r[e],r[e]=n}),r}function Ft(n,t,e){var r;t=J.createCallback(t,e,3),e=-1;var u=n?n.length:0;if(typeof u=="number")for(;++e<u&&!(r=t(n[e],e,n)););else h(n,function(n,e,u){return!(r=t(n,e,u))});return!!r}function Bt(n,t,e){var r=0,u=n?n.length:0;if(typeof t!="number"&&null!=t){var o=-1; for(t=J.createCallback(t,e,3);++o<u&&t(n[o],o,n);)r++}else if(r=t,null==r||e)return n?n[0]:v;return p(n,0,Se(Ie(0,r),u))}function Wt(t,e,r){if(typeof r=="number"){var u=t?t.length:0;r=0>r?Ie(0,u+r):r||0}else if(r)return r=zt(t,e),t[r]===e?r:-1;return n(t,e,r)}function qt(n,t,e){if(typeof t!="number"&&null!=t){var r=0,u=-1,o=n?n.length:0;for(t=J.createCallback(t,e,3);++u<o&&t(n[u],u,n);)r++}else r=null==t||e?1:Ie(0,t);return p(n,r)}function zt(n,t,e,r){var u=0,o=n?n.length:u;for(e=e?J.createCallback(e,r,1):Ut,t=e(t);u<o;)r=u+o>>>1,e(n[r])<t?u=r+1:o=r; return u}function Pt(n,t,e,r){return typeof t!="boolean"&&null!=t&&(r=e,e=typeof t!="function"&&r&&r[t]===n?null:t,t=false),null!=e&&(e=J.createCallback(e,r,3)),ft(n,t,e)}function Kt(){for(var n=1<arguments.length?arguments:arguments[0],t=-1,e=n?At(Ve(n,"length")):0,r=Xt(0>e?0:e);++t<e;)r[t]=Ve(n,t);return r}function Lt(n,t){var e=-1,r=n?n.length:0,u={};for(t||!r||Te(n[0])||(t=[]);++e<r;){var o=n[e];t?u[o]=t[e]:o&&(u[o[0]]=o[1])}return u}function Mt(n,t){return 2<arguments.length?ct(n,17,p(arguments,2),null,t):ct(n,1,null,null,t) }function Vt(n,t,e){function r(){c&&ve(c),i=c=p=v,(g||h!==t)&&(s=Ue(),a=n.apply(l,o),c||i||(o=l=null))}function u(){var e=t-(Ue()-f);0<e?c=_e(u,e):(i&&ve(i),e=p,i=c=p=v,e&&(s=Ue(),a=n.apply(l,o),c||i||(o=l=null)))}var o,i,a,f,l,c,p,s=0,h=false,g=true;if(!dt(n))throw new ie;if(t=Ie(0,t)||0,true===e)var y=true,g=false;else wt(e)&&(y=e.leading,h="maxWait"in e&&(Ie(t,e.maxWait)||0),g="trailing"in e?e.trailing:g);return function(){if(o=arguments,f=Ue(),l=this,p=g&&(c||!y),false===h)var e=y&&!c;else{i||y||(s=f);var v=h-(f-s),m=0>=v; m?(i&&(i=ve(i)),s=f,a=n.apply(l,o)):i||(i=_e(r,v))}return m&&c?c=ve(c):c||t===h||(c=_e(u,t)),e&&(m=true,a=n.apply(l,o)),!m||c||i||(o=l=null),a}}function Ut(n){return n}function Gt(n,t,e){var r=true,u=t&&bt(t);t&&(e||u.length)||(null==e&&(e=t),o=Q,t=n,n=J,u=bt(t)),false===e?r=false:wt(e)&&"chain"in e&&(r=e.chain);var o=n,i=dt(o);St(u,function(e){var u=n[e]=t[e];i&&(o.prototype[e]=function(){var t=this.__chain__,e=this.__wrapped__,i=[e];if(be.apply(i,arguments),i=u.apply(n,i),r||t){if(e===i&&wt(i))return this; i=new o(i),i.__chain__=t}return i})})}function Ht(){}function Jt(n){return function(t){return t[n]}}function Qt(){return this.__wrapped__}e=e?Y.defaults(G.Object(),e,Y.pick(G,A)):G;var Xt=e.Array,Yt=e.Boolean,Zt=e.Date,ne=e.Function,te=e.Math,ee=e.Number,re=e.Object,ue=e.RegExp,oe=e.String,ie=e.TypeError,ae=[],fe=re.prototype,le=e._,ce=fe.toString,pe=ue("^"+oe(ce).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),se=te.ceil,ve=e.clearTimeout,he=te.floor,ge=ne.prototype.toString,ye=vt(ye=re.getPrototypeOf)&&ye,me=fe.hasOwnProperty,be=ae.push,_e=e.setTimeout,de=ae.splice,we=ae.unshift,je=function(){try{var n={},t=vt(t=re.defineProperty)&&t,e=t(n,n,n)&&t }catch(r){}return e}(),ke=vt(ke=re.create)&&ke,xe=vt(xe=Xt.isArray)&&xe,Ce=e.isFinite,Oe=e.isNaN,Ne=vt(Ne=re.keys)&&Ne,Ie=te.max,Se=te.min,Ee=e.parseInt,Re=te.random,Ae={};Ae[$]=Xt,Ae[T]=Yt,Ae[F]=Zt,Ae[B]=ne,Ae[q]=re,Ae[W]=ee,Ae[z]=ue,Ae[P]=oe,Q.prototype=J.prototype;var De=J.support={};De.funcDecomp=!vt(e.a)&&E.test(s),De.funcNames=typeof ne.name=="string",J.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:N,variable:"",imports:{_:J}},ke||(nt=function(){function n(){}return function(t){if(wt(t)){n.prototype=t; var r=new n;n.prototype=null}return r||e.Object()}}());var $e=je?function(n,t){M.value=t,je(n,"__bindData__",M)}:Ht,Te=xe||function(n){return n&&typeof n=="object"&&typeof n.length=="number"&&ce.call(n)==$||false},Fe=Ne?function(n){return wt(n)?Ne(n):[]}:H,Be={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},We=_t(Be),qe=ue("("+Fe(We).join("|")+")","g"),ze=ue("["+Fe(Be).join("")+"]","g"),Pe=ye?function(n){if(!n||ce.call(n)!=q)return false;var t=n.valueOf,e=vt(t)&&(e=ye(t))&&ye(e);return e?n==e||ye(n)==e:ht(n) }:ht,Ke=lt(function(n,t,e){me.call(n,e)?n[e]++:n[e]=1}),Le=lt(function(n,t,e){(me.call(n,e)?n[e]:n[e]=[]).push(t)}),Me=lt(function(n,t,e){n[e]=t}),Ve=Rt,Ue=vt(Ue=Zt.now)&&Ue||function(){return(new Zt).getTime()},Ge=8==Ee(d+"08")?Ee:function(n,t){return Ee(kt(n)?n.replace(I,""):n,t||0)};return J.after=function(n,t){if(!dt(t))throw new ie;return function(){return 1>--n?t.apply(this,arguments):void 0}},J.assign=U,J.at=function(n){for(var t=arguments,e=-1,r=ut(t,true,false,1),t=t[2]&&t[2][t[1]]===n?1:r.length,u=Xt(t);++e<t;)u[e]=n[r[e]]; return u},J.bind=Mt,J.bindAll=function(n){for(var t=1<arguments.length?ut(arguments,true,false,1):bt(n),e=-1,r=t.length;++e<r;){var u=t[e];n[u]=ct(n[u],1,null,null,n)}return n},J.bindKey=function(n,t){return 2<arguments.length?ct(t,19,p(arguments,2),null,n):ct(t,3,null,null,n)},J.chain=function(n){return n=new Q(n),n.__chain__=true,n},J.compact=function(n){for(var t=-1,e=n?n.length:0,r=[];++t<e;){var u=n[t];u&&r.push(u)}return r},J.compose=function(){for(var n=arguments,t=n.length;t--;)if(!dt(n[t]))throw new ie; return function(){for(var t=arguments,e=n.length;e--;)t=[n[e].apply(this,t)];return t[0]}},J.constant=function(n){return function(){return n}},J.countBy=Ke,J.create=function(n,t){var e=nt(n);return t?U(e,t):e},J.createCallback=function(n,t,e){var r=typeof n;if(null==n||"function"==r)return tt(n,t,e);if("object"!=r)return Jt(n);var u=Fe(n),o=u[0],i=n[o];return 1!=u.length||i!==i||wt(i)?function(t){for(var e=u.length,r=false;e--&&(r=ot(t[u[e]],n[u[e]],null,true)););return r}:function(n){return n=n[o],i===n&&(0!==i||1/i==1/n) }},J.curry=function(n,t){return t=typeof t=="number"?t:+t||n.length,ct(n,4,null,null,null,t)},J.debounce=Vt,J.defaults=_,J.defer=function(n){if(!dt(n))throw new ie;var t=p(arguments,1);return _e(function(){n.apply(v,t)},1)},J.delay=function(n,t){if(!dt(n))throw new ie;var e=p(arguments,2);return _e(function(){n.apply(v,e)},t)},J.difference=function(n){return rt(n,ut(arguments,true,true,1))},J.filter=Nt,J.flatten=function(n,t,e,r){return typeof t!="boolean"&&null!=t&&(r=e,e=typeof t!="function"&&r&&r[t]===n?null:t,t=false),null!=e&&(n=Rt(n,e,r)),ut(n,t) },J.forEach=St,J.forEachRight=Et,J.forIn=g,J.forInRight=function(n,t,e){var r=[];g(n,function(n,t){r.push(t,n)});var u=r.length;for(t=tt(t,e,3);u--&&false!==t(r[u--],r[u],n););return n},J.forOwn=h,J.forOwnRight=mt,J.functions=bt,J.groupBy=Le,J.indexBy=Me,J.initial=function(n,t,e){var r=0,u=n?n.length:0;if(typeof t!="number"&&null!=t){var o=u;for(t=J.createCallback(t,e,3);o--&&t(n[o],o,n);)r++}else r=null==t||e?1:t||r;return p(n,0,Se(Ie(0,u-r),u))},J.intersection=function(){for(var e=[],r=-1,u=arguments.length,i=a(),f=st(),p=f===n,s=a();++r<u;){var v=arguments[r]; (Te(v)||yt(v))&&(e.push(v),i.push(p&&v.length>=b&&o(r?e[r]:s)))}var p=e[0],h=-1,g=p?p.length:0,y=[];n:for(;++h<g;){var m=i[0],v=p[h];if(0>(m?t(m,v):f(s,v))){for(r=u,(m||s).push(v);--r;)if(m=i[r],0>(m?t(m,v):f(e[r],v)))continue n;y.push(v)}}for(;u--;)(m=i[u])&&c(m);return l(i),l(s),y},J.invert=_t,J.invoke=function(n,t){var e=p(arguments,2),r=-1,u=typeof t=="function",o=n?n.length:0,i=Xt(typeof o=="number"?o:0);return St(n,function(n){i[++r]=(u?t:n[t]).apply(n,e)}),i},J.keys=Fe,J.map=Rt,J.mapValues=function(n,t,e){var r={}; return t=J.createCallback(t,e,3),h(n,function(n,e,u){r[e]=t(n,e,u)}),r},J.max=At,J.memoize=function(n,t){function e(){var r=e.cache,u=t?t.apply(this,arguments):m+arguments[0];return me.call(r,u)?r[u]:r[u]=n.apply(this,arguments)}if(!dt(n))throw new ie;return e.cache={},e},J.merge=function(n){var t=arguments,e=2;if(!wt(n))return n;if("number"!=typeof t[2]&&(e=t.length),3<e&&"function"==typeof t[e-2])var r=tt(t[--e-1],t[e--],2);else 2<e&&"function"==typeof t[e-1]&&(r=t[--e]);for(var t=p(arguments,1,e),u=-1,o=a(),i=a();++u<e;)it(n,t[u],r,o,i); return l(o),l(i),n},J.min=function(n,t,e){var u=1/0,o=u;if(typeof t!="function"&&e&&e[t]===n&&(t=null),null==t&&Te(n)){e=-1;for(var i=n.length;++e<i;){var a=n[e];a<o&&(o=a)}}else t=null==t&&kt(n)?r:J.createCallback(t,e,3),St(n,function(n,e,r){e=t(n,e,r),e<u&&(u=e,o=n)});return o},J.omit=function(n,t,e){var r={};if(typeof t!="function"){var u=[];g(n,function(n,t){u.push(t)});for(var u=rt(u,ut(arguments,true,false,1)),o=-1,i=u.length;++o<i;){var a=u[o];r[a]=n[a]}}else t=J.createCallback(t,e,3),g(n,function(n,e,u){t(n,e,u)||(r[e]=n) });return r},J.once=function(n){var t,e;if(!dt(n))throw new ie;return function(){return t?e:(t=true,e=n.apply(this,arguments),n=null,e)}},J.pairs=function(n){for(var t=-1,e=Fe(n),r=e.length,u=Xt(r);++t<r;){var o=e[t];u[t]=[o,n[o]]}return u},J.partial=function(n){return ct(n,16,p(arguments,1))},J.partialRight=function(n){return ct(n,32,null,p(arguments,1))},J.pick=function(n,t,e){var r={};if(typeof t!="function")for(var u=-1,o=ut(arguments,true,false,1),i=wt(n)?o.length:0;++u<i;){var a=o[u];a in n&&(r[a]=n[a]) }else t=J.createCallback(t,e,3),g(n,function(n,e,u){t(n,e,u)&&(r[e]=n)});return r},J.pluck=Ve,J.property=Jt,J.pull=function(n){for(var t=arguments,e=0,r=t.length,u=n?n.length:0;++e<r;)for(var o=-1,i=t[e];++o<u;)n[o]===i&&(de.call(n,o--,1),u--);return n},J.range=function(n,t,e){n=+n||0,e=typeof e=="number"?e:+e||1,null==t&&(t=n,n=0);var r=-1;t=Ie(0,se((t-n)/(e||1)));for(var u=Xt(t);++r<t;)u[r]=n,n+=e;return u},J.reject=function(n,t,e){return t=J.createCallback(t,e,3),Nt(n,function(n,e,r){return!t(n,e,r) })},J.remove=function(n,t,e){var r=-1,u=n?n.length:0,o=[];for(t=J.createCallback(t,e,3);++r<u;)e=n[r],t(e,r,n)&&(o.push(e),de.call(n,r--,1),u--);return o},J.rest=qt,J.shuffle=Tt,J.sortBy=function(n,t,e){var r=-1,o=Te(t),i=n?n.length:0,p=Xt(typeof i=="number"?i:0);for(o||(t=J.createCallback(t,e,3)),St(n,function(n,e,u){var i=p[++r]=f();o?i.m=Rt(t,function(t){return n[t]}):(i.m=a())[0]=t(n,e,u),i.n=r,i.o=n}),i=p.length,p.sort(u);i--;)n=p[i],p[i]=n.o,o||l(n.m),c(n);return p},J.tap=function(n,t){return t(n),n },J.throttle=function(n,t,e){var r=true,u=true;if(!dt(n))throw new ie;return false===e?r=false:wt(e)&&(r="leading"in e?e.leading:r,u="trailing"in e?e.trailing:u),L.leading=r,L.maxWait=t,L.trailing=u,Vt(n,t,L)},J.times=function(n,t,e){n=-1<(n=+n)?n:0;var r=-1,u=Xt(n);for(t=tt(t,e,1);++r<n;)u[r]=t(r);return u},J.toArray=function(n){return n&&typeof n.length=="number"?p(n):xt(n)},J.transform=function(n,t,e,r){var u=Te(n);if(null==e)if(u)e=[];else{var o=n&&n.constructor;e=nt(o&&o.prototype)}return t&&(t=J.createCallback(t,r,4),(u?St:h)(n,function(n,r,u){return t(e,n,r,u) })),e},J.union=function(){return ft(ut(arguments,true,true))},J.uniq=Pt,J.values=xt,J.where=Nt,J.without=function(n){return rt(n,p(arguments,1))},J.wrap=function(n,t){return ct(t,16,[n])},J.xor=function(){for(var n=-1,t=arguments.length;++n<t;){var e=arguments[n];if(Te(e)||yt(e))var r=r?ft(rt(r,e).concat(rt(e,r))):e}return r||[]},J.zip=Kt,J.zipObject=Lt,J.collect=Rt,J.drop=qt,J.each=St,J.eachRight=Et,J.extend=U,J.methods=bt,J.object=Lt,J.select=Nt,J.tail=qt,J.unique=Pt,J.unzip=Kt,Gt(J),J.clone=function(n,t,e,r){return typeof t!="boolean"&&null!=t&&(r=e,e=t,t=false),Z(n,t,typeof e=="function"&&tt(e,r,1)) },J.cloneDeep=function(n,t,e){return Z(n,true,typeof t=="function"&&tt(t,e,1))},J.contains=Ct,J.escape=function(n){return null==n?"":oe(n).replace(ze,pt)},J.every=Ot,J.find=It,J.findIndex=function(n,t,e){var r=-1,u=n?n.length:0;for(t=J.createCallback(t,e,3);++r<u;)if(t(n[r],r,n))return r;return-1},J.findKey=function(n,t,e){var r;return t=J.createCallback(t,e,3),h(n,function(n,e,u){return t(n,e,u)?(r=e,false):void 0}),r},J.findLast=function(n,t,e){var r;return t=J.createCallback(t,e,3),Et(n,function(n,e,u){return t(n,e,u)?(r=n,false):void 0 }),r},J.findLastIndex=function(n,t,e){var r=n?n.length:0;for(t=J.createCallback(t,e,3);r--;)if(t(n[r],r,n))return r;return-1},J.findLastKey=function(n,t,e){var r;return t=J.createCallback(t,e,3),mt(n,function(n,e,u){return t(n,e,u)?(r=e,false):void 0}),r},J.has=function(n,t){return n?me.call(n,t):false},J.identity=Ut,J.indexOf=Wt,J.isArguments=yt,J.isArray=Te,J.isBoolean=function(n){return true===n||false===n||n&&typeof n=="object"&&ce.call(n)==T||false},J.isDate=function(n){return n&&typeof n=="object"&&ce.call(n)==F||false },J.isElement=function(n){return n&&1===n.nodeType||false},J.isEmpty=function(n){var t=true;if(!n)return t;var e=ce.call(n),r=n.length;return e==$||e==P||e==D||e==q&&typeof r=="number"&&dt(n.splice)?!r:(h(n,function(){return t=false}),t)},J.isEqual=function(n,t,e,r){return ot(n,t,typeof e=="function"&&tt(e,r,2))},J.isFinite=function(n){return Ce(n)&&!Oe(parseFloat(n))},J.isFunction=dt,J.isNaN=function(n){return jt(n)&&n!=+n},J.isNull=function(n){return null===n},J.isNumber=jt,J.isObject=wt,J.isPlainObject=Pe,J.isRegExp=function(n){return n&&typeof n=="object"&&ce.call(n)==z||false },J.isString=kt,J.isUndefined=function(n){return typeof n=="undefined"},J.lastIndexOf=function(n,t,e){var r=n?n.length:0;for(typeof e=="number"&&(r=(0>e?Ie(0,r+e):Se(e,r-1))+1);r--;)if(n[r]===t)return r;return-1},J.mixin=Gt,J.noConflict=function(){return e._=le,this},J.noop=Ht,J.now=Ue,J.parseInt=Ge,J.random=function(n,t,e){var r=null==n,u=null==t;return null==e&&(typeof n=="boolean"&&u?(e=n,n=1):u||typeof t!="boolean"||(e=t,u=true)),r&&u&&(t=1),n=+n||0,u?(t=n,n=0):t=+t||0,e||n%1||t%1?(e=Re(),Se(n+e*(t-n+parseFloat("1e-"+((e+"").length-1))),t)):at(n,t) },J.reduce=Dt,J.reduceRight=$t,J.result=function(n,t){if(n){var e=n[t];return dt(e)?n[t]():e}},J.runInContext=s,J.size=function(n){var t=n?n.length:0;return typeof t=="number"?t:Fe(n).length},J.some=Ft,J.sortedIndex=zt,J.template=function(n,t,e){var r=J.templateSettings;n=oe(n||""),e=_({},e,r);var u,o=_({},e.imports,r.imports),r=Fe(o),o=xt(o),a=0,f=e.interpolate||S,l="__p+='",f=ue((e.escape||S).source+"|"+f.source+"|"+(f===N?x:S).source+"|"+(e.evaluate||S).source+"|$","g");n.replace(f,function(t,e,r,o,f,c){return r||(r=o),l+=n.slice(a,c).replace(R,i),e&&(l+="'+__e("+e+")+'"),f&&(u=true,l+="';"+f+";\n__p+='"),r&&(l+="'+((__t=("+r+"))==null?'':__t)+'"),a=c+t.length,t }),l+="';",f=e=e.variable,f||(e="obj",l="with("+e+"){"+l+"}"),l=(u?l.replace(w,""):l).replace(j,"$1").replace(k,"$1;"),l="function("+e+"){"+(f?"":e+"||("+e+"={});")+"var __t,__p='',__e=_.escape"+(u?",__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}":";")+l+"return __p}";try{var c=ne(r,"return "+l).apply(v,o)}catch(p){throw p.source=l,p}return t?c(t):(c.source=l,c)},J.unescape=function(n){return null==n?"":oe(n).replace(qe,gt)},J.uniqueId=function(n){var t=++y;return oe(null==n?"":n)+t },J.all=Ot,J.any=Ft,J.detect=It,J.findWhere=It,J.foldl=Dt,J.foldr=$t,J.include=Ct,J.inject=Dt,Gt(function(){var n={};return h(J,function(t,e){J.prototype[e]||(n[e]=t)}),n}(),false),J.first=Bt,J.last=function(n,t,e){var r=0,u=n?n.length:0;if(typeof t!="number"&&null!=t){var o=u;for(t=J.createCallback(t,e,3);o--&&t(n[o],o,n);)r++}else if(r=t,null==r||e)return n?n[u-1]:v;return p(n,Ie(0,u-r))},J.sample=function(n,t,e){return n&&typeof n.length!="number"&&(n=xt(n)),null==t||e?n?n[at(0,n.length-1)]:v:(n=Tt(n),n.length=Se(Ie(0,t),n.length),n) },J.take=Bt,J.head=Bt,h(J,function(n,t){var e="sample"!==t;J.prototype[t]||(J.prototype[t]=function(t,r){var u=this.__chain__,o=n(this.__wrapped__,t,r);return u||null!=t&&(!r||e&&typeof t=="function")?new Q(o,u):o})}),J.VERSION="2.4.1",J.prototype.chain=function(){return this.__chain__=true,this},J.prototype.toString=function(){return oe(this.__wrapped__)},J.prototype.value=Qt,J.prototype.valueOf=Qt,St(["join","pop","shift"],function(n){var t=ae[n];J.prototype[n]=function(){var n=this.__chain__,e=t.apply(this.__wrapped__,arguments); return n?new Q(e,n):e}}),St(["push","reverse","sort","unshift"],function(n){var t=ae[n];J.prototype[n]=function(){return t.apply(this.__wrapped__,arguments),this}}),St(["concat","slice","splice"],function(n){var t=ae[n];J.prototype[n]=function(){return new Q(t.apply(this.__wrapped__,arguments),this.__chain__)}}),J}var v,h=[],g=[],y=0,m=+new Date+"",b=75,_=40,d=" \t\x0B\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000",w=/\b__p\+='';/g,j=/\b(__p\+=)''\+/g,k=/(__e\(.*?\)|\b__t\))\+'';/g,x=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,C=/\w*$/,O=/^\s*function[ \n\r\t]+\w/,N=/<%=([\s\S]+?)%>/g,I=RegExp("^["+d+"]*0+(?=.$)"),S=/($^)/,E=/\bthis\b/,R=/['\n\r\t\u2028\u2029\\]/g,A="Array Boolean Date Function Math Number Object RegExp String _ attachEvent clearTimeout isFinite isNaN parseInt setTimeout".split(" "),D="[object Arguments]",$="[object Array]",T="[object Boolean]",F="[object Date]",B="[object Function]",W="[object Number]",q="[object Object]",z="[object RegExp]",P="[object String]",K={}; K[B]=false,K[D]=K[$]=K[T]=K[F]=K[W]=K[q]=K[z]=K[P]=true;var L={leading:false,maxWait:0,trailing:false},M={configurable:false,enumerable:false,value:null,writable:false},V={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false},U={"\\":"\\","'":"'","\n":"n","\r":"r","\t":"t","\u2028":"u2028","\u2029":"u2029"},G=V[typeof window]&&window||this,H=V[typeof exports]&&exports&&!exports.nodeType&&exports,J=V[typeof module]&&module&&!module.nodeType&&module,Q=J&&J.exports===H&&H,X=V[typeof global]&&global;!X||X.global!==X&&X.window!==X||(G=X); var Y=s();typeof define=="function"&&typeof define.amd=="object"&&define.amd?(G._=Y, define(function(){return Y})):H&&J?Q?(J.exports=Y)._=Y:H._=Y:G._=Y}).call(this); !function(a,b){"function"==typeof define&&define.amd?define([],b):"undefined"!=typeof module&&module.exports?module.exports=b():a.lscache=b()}(this,function(){function a(){var a="__lscachetest__",b=a;if(void 0!==i)return i;try{f(a,b),g(a),i=!0}catch(c){i=!1}return i}function b(){return void 0===j&&(j=null!=window.JSON),j}function c(a){return a+l}function d(){return Math.floor((new Date).getTime()/n)}function e(a){return localStorage.getItem(k+p+a)}function f(a,b){localStorage.removeItem(k+p+a),localStorage.setItem(k+p+a,b)}function g(a){localStorage.removeItem(k+p+a)}function h(a,b){q&&"console"in window&&"function"==typeof window.console.warn&&(window.console.warn("lscache - "+a),b&&window.console.warn("lscache - The error was: "+b.message))}var i,j,k="lscache-",l="-cacheexpiration",m=10,n=6e4,o=Math.floor(864e13/n),p="",q=!1,r={set:function(i,j,n){if(a()){if("string"!=typeof j){if(!b())return;try{j=JSON.stringify(j)}catch(q){return}}try{f(i,j)}catch(q){if("QUOTA_EXCEEDED_ERR"!==q.name&&"NS_ERROR_DOM_QUOTA_REACHED"!==q.name&&"QuotaExceededError"!==q.name)return void h("Could not add item with key '"+i+"'",q);for(var r,s=[],t=0;t<localStorage.length;t++)if(r=localStorage.key(t),0===r.indexOf(k+p)&&r.indexOf(l)<0){var u=r.substr((k+p).length),v=c(u),w=e(v);w=w?parseInt(w,m):o,s.push({key:u,size:(e(u)||"").length,expiration:w})}s.sort(function(a,b){return b.expiration-a.expiration});for(var x=(j||"").length;s.length&&x>0;)r=s.pop(),h("Cache is full, removing item with key '"+i+"'"),g(r.key),g(c(r.key)),x-=r.size;try{f(i,j)}catch(q){return void h("Could not add item with key '"+i+"', perhaps it's too big?",q)}}n?f(c(i),(d()+n).toString(m)):g(c(i))}},isExpired:function(b){if(!a())return null;var f=c(b),g=e(f);if(g){var h=parseInt(g,m);if(d()>=h)return!0}return!1},get:function(d,f,h){if(!a())return null;var i;if(f=f===!0,h=h===!0,r.isExpired(d)){if(!f){var j=c(d);i=e(d),g(d),g(j)}if(!h)return null}if(i||(i=e(d)),!i||!b())return i;try{return JSON.parse(i)}catch(k){return i}},remove:function(b){return a()?(g(b),void g(c(b))):null},supported:function(){return a()},flush:function(){if(a())for(var b=localStorage.length-1;b>=0;--b){var c=localStorage.key(b);0===c.indexOf(k+p)&&localStorage.removeItem(c)}},setBucket:function(a){p=a},resetBucket:function(){p=""},enableWarnings:function(a){q=a}};return r}); /*! handlebars v1.3.0 Copyright (C) 2011 by Yehuda Katz 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. @license */ /* exported Handlebars */ var Handlebars = (function() { // handlebars/safe-string.js var __module4__ = (function() { "use strict"; var __exports__; // Build out our basic SafeString type function SafeString(string) { this.string = string; } SafeString.prototype.toString = function() { return "" + this.string; }; __exports__ = SafeString; return __exports__; })(); // handlebars/utils.js var __module3__ = (function(__dependency1__) { "use strict"; var __exports__ = {}; /*jshint -W004 */ var SafeString = __dependency1__; var escape = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" }; var badChars = /[&<>"'`]/g; var possible = /[&<>"'`]/; function escapeChar(chr) { return escape[chr] || "&amp;"; } function extend(obj, value) { for(var key in value) { if(Object.prototype.hasOwnProperty.call(value, key)) { obj[key] = value[key]; } } } __exports__.extend = extend;var toString = Object.prototype.toString; __exports__.toString = toString; // Sourced from lodash // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt var isFunction = function(value) { return typeof value === 'function'; }; // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value === 'function' && toString.call(value) === '[object Function]'; }; } var isFunction; __exports__.isFunction = isFunction; var isArray = Array.isArray || function(value) { return (value && typeof value === 'object') ? toString.call(value) === '[object Array]' : false; }; __exports__.isArray = isArray; function escapeExpression(string) { // don't escape SafeStrings, since they're already safe if (string instanceof SafeString) { return string.toString(); } else if (!string && string !== 0) { return ""; } // Force a string conversion as this will be done by the append regardless and // the regex test will do this transparently behind the scenes, causing issues if // an object's to string has escaped characters in it. string = "" + string; if(!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); } __exports__.escapeExpression = escapeExpression;function isEmpty(value) { if (!value && value !== 0) { return true; } else if (isArray(value) && value.length === 0) { return true; } else { return false; } } __exports__.isEmpty = isEmpty; return __exports__; })(__module4__); // handlebars/exception.js var __module5__ = (function() { "use strict"; var __exports__; var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; function Exception(message, node) { var line; if (node && node.firstLine) { line = node.firstLine; message += ' - ' + line + ':' + node.firstColumn; } var tmp = Error.prototype.constructor.call(this, message); // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. for (var idx = 0; idx < errorProps.length; idx++) { this[errorProps[idx]] = tmp[errorProps[idx]]; } if (line) { this.lineNumber = line; this.column = node.firstColumn; } } Exception.prototype = new Error(); __exports__ = Exception; return __exports__; })(); // handlebars/base.js var __module2__ = (function(__dependency1__, __dependency2__) { "use strict"; var __exports__ = {}; var Utils = __dependency1__; var Exception = __dependency2__; var VERSION = "1.3.0"; __exports__.VERSION = VERSION;var COMPILER_REVISION = 4; __exports__.COMPILER_REVISION = COMPILER_REVISION; var REVISION_CHANGES = { 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it 2: '== 1.0.0-rc.3', 3: '== 1.0.0-rc.4', 4: '>= 1.0.0' }; __exports__.REVISION_CHANGES = REVISION_CHANGES; var isArray = Utils.isArray, isFunction = Utils.isFunction, toString = Utils.toString, objectType = '[object Object]'; function HandlebarsEnvironment(helpers, partials) { this.helpers = helpers || {}; this.partials = partials || {}; registerDefaultHelpers(this); } __exports__.HandlebarsEnvironment = HandlebarsEnvironment;HandlebarsEnvironment.prototype = { constructor: HandlebarsEnvironment, logger: logger, log: log, registerHelper: function(name, fn, inverse) { if (toString.call(name) === objectType) { if (inverse || fn) { throw new Exception('Arg not supported with multiple helpers'); } Utils.extend(this.helpers, name); } else { if (inverse) { fn.not = inverse; } this.helpers[name] = fn; } }, registerPartial: function(name, str) { if (toString.call(name) === objectType) { Utils.extend(this.partials, name); } else { this.partials[name] = str; } } }; function registerDefaultHelpers(instance) { instance.registerHelper('helperMissing', function(arg) { if(arguments.length === 2) { return undefined; } else { throw new Exception("Missing helper: '" + arg + "'"); } }); instance.registerHelper('blockHelperMissing', function(context, options) { var inverse = options.inverse || function() {}, fn = options.fn; if (isFunction(context)) { context = context.call(this); } if(context === true) { return fn(this); } else if(context === false || context == null) { return inverse(this); } else if (isArray(context)) { if(context.length > 0) { return instance.helpers.each(context, options); } else { return inverse(this); } } else { return fn(context); } }); instance.registerHelper('each', function(context, options) { var fn = options.fn, inverse = options.inverse; var i = 0, ret = "", data; if (isFunction(context)) { context = context.call(this); } if (options.data) { data = createFrame(options.data); } if(context && typeof context === 'object') { if (isArray(context)) { for(var j = context.length; i<j; i++) { if (data) { data.index = i; data.first = (i === 0); data.last = (i === (context.length-1)); } ret = ret + fn(context[i], { data: data }); } } else { for(var key in context) { if(context.hasOwnProperty(key)) { if(data) { data.key = key; data.index = i; data.first = (i === 0); } ret = ret + fn(context[key], {data: data}); i++; } } } } if(i === 0){ ret = inverse(this); } return ret; }); instance.registerHelper('if', function(conditional, options) { if (isFunction(conditional)) { conditional = conditional.call(this); } // Default behavior is to render the positive path if the value is truthy and not empty. // The `includeZero` option may be set to treat the condtional as purely not empty based on the // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative. if ((!options.hash.includeZero && !conditional) || Utils.isEmpty(conditional)) { return options.inverse(this); } else { return options.fn(this); } }); instance.registerHelper('unless', function(conditional, options) { return instance.helpers['if'].call(this, conditional, {fn: options.inverse, inverse: options.fn, hash: options.hash}); }); instance.registerHelper('with', function(context, options) { if (isFunction(context)) { context = context.call(this); } if (!Utils.isEmpty(context)) return options.fn(context); }); instance.registerHelper('log', function(context, options) { var level = options.data && options.data.level != null ? parseInt(options.data.level, 10) : 1; instance.log(level, context); }); } var logger = { methodMap: { 0: 'debug', 1: 'info', 2: 'warn', 3: 'error' }, // State enum DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, level: 3, // can be overridden in the host environment log: function(level, obj) { if (logger.level <= level) { var method = logger.methodMap[level]; if (typeof console !== 'undefined' && console[method]) { console[method].call(console, obj); } } } }; __exports__.logger = logger; function log(level, obj) { logger.log(level, obj); } __exports__.log = log;var createFrame = function(object) { var obj = {}; Utils.extend(obj, object); return obj; }; __exports__.createFrame = createFrame; return __exports__; })(__module3__, __module5__); // handlebars/runtime.js var __module6__ = (function(__dependency1__, __dependency2__, __dependency3__) { "use strict"; var __exports__ = {}; var Utils = __dependency1__; var Exception = __dependency2__; var COMPILER_REVISION = __dependency3__.COMPILER_REVISION; var REVISION_CHANGES = __dependency3__.REVISION_CHANGES; function checkRevision(compilerInfo) { var compilerRevision = compilerInfo && compilerInfo[0] || 1, currentRevision = COMPILER_REVISION; if (compilerRevision !== currentRevision) { if (compilerRevision < currentRevision) { var runtimeVersions = REVISION_CHANGES[currentRevision], compilerVersions = REVISION_CHANGES[compilerRevision]; throw new Exception("Template was precompiled with an older version of Handlebars than the current runtime. "+ "Please update your precompiler to a newer version ("+runtimeVersions+") or downgrade your runtime to an older version ("+compilerVersions+")."); } else { // Use the embedded version info since the runtime doesn't know about this revision yet throw new Exception("Template was precompiled with a newer version of Handlebars than the current runtime. "+ "Please update your runtime to a newer version ("+compilerInfo[1]+")."); } } } __exports__.checkRevision = checkRevision;// TODO: Remove this line and break up compilePartial function template(templateSpec, env) { if (!env) { throw new Exception("No environment passed to template"); } // Note: Using env.VM references rather than local var references throughout this section to allow // for external users to override these as psuedo-supported APIs. var invokePartialWrapper = function(partial, name, context, helpers, partials, data) { var result = env.VM.invokePartial.apply(this, arguments); if (result != null) { return result; } if (env.compile) { var options = { helpers: helpers, partials: partials, data: data }; partials[name] = env.compile(partial, { data: data !== undefined }, env); return partials[name](context, options); } else { throw new Exception("The partial " + name + " could not be compiled when running in runtime-only mode"); } }; // Just add water var container = { escapeExpression: Utils.escapeExpression, invokePartial: invokePartialWrapper, programs: [], program: function(i, fn, data) { var programWrapper = this.programs[i]; if(data) { programWrapper = program(i, fn, data); } else if (!programWrapper) { programWrapper = this.programs[i] = program(i, fn); } return programWrapper; }, merge: function(param, common) { var ret = param || common; if (param && common && (param !== common)) { ret = {}; Utils.extend(ret, common); Utils.extend(ret, param); } return ret; }, programWithDepth: env.VM.programWithDepth, noop: env.VM.noop, compilerInfo: null }; return function(context, options) { options = options || {}; var namespace = options.partial ? options : env, helpers, partials; if (!options.partial) { helpers = options.helpers; partials = options.partials; } var result = templateSpec.call( container, namespace, context, helpers, partials, options.data); if (!options.partial) { env.VM.checkRevision(container.compilerInfo); } return result; }; } __exports__.template = template;function programWithDepth(i, fn, data /*, $depth */) { var args = Array.prototype.slice.call(arguments, 3); var prog = function(context, options) { options = options || {}; return fn.apply(this, [context, options.data || data].concat(args)); }; prog.program = i; prog.depth = args.length; return prog; } __exports__.programWithDepth = programWithDepth;function program(i, fn, data) { var prog = function(context, options) { options = options || {}; return fn(context, options.data || data); }; prog.program = i; prog.depth = 0; return prog; } __exports__.program = program;function invokePartial(partial, name, context, helpers, partials, data) { var options = { partial: true, helpers: helpers, partials: partials, data: data }; if(partial === undefined) { throw new Exception("The partial " + name + " could not be found"); } else if(partial instanceof Function) { return partial(context, options); } } __exports__.invokePartial = invokePartial;function noop() { return ""; } __exports__.noop = noop; return __exports__; })(__module3__, __module5__, __module2__); // handlebars.runtime.js var __module1__ = (function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__) { "use strict"; var __exports__; /*globals Handlebars: true */ var base = __dependency1__; // Each of these augment the Handlebars object. No need to setup here. // (This is done to easily share code between commonjs and browse envs) var SafeString = __dependency2__; var Exception = __dependency3__; var Utils = __dependency4__; var runtime = __dependency5__; // For compatibility and usage outside of module systems, make the Handlebars object a namespace var create = function() { var hb = new base.HandlebarsEnvironment(); Utils.extend(hb, base); hb.SafeString = SafeString; hb.Exception = Exception; hb.Utils = Utils; hb.VM = runtime; hb.template = function(spec) { return runtime.template(spec, hb); }; return hb; }; var Handlebars = create(); Handlebars.create = create; __exports__ = Handlebars; return __exports__; })(__module2__, __module4__, __module5__, __module3__, __module6__); // handlebars/compiler/ast.js var __module7__ = (function(__dependency1__) { "use strict"; var __exports__; var Exception = __dependency1__; function LocationInfo(locInfo){ locInfo = locInfo || {}; this.firstLine = locInfo.first_line; this.firstColumn = locInfo.first_column; this.lastColumn = locInfo.last_column; this.lastLine = locInfo.last_line; } var AST = { ProgramNode: function(statements, inverseStrip, inverse, locInfo) { var inverseLocationInfo, firstInverseNode; if (arguments.length === 3) { locInfo = inverse; inverse = null; } else if (arguments.length === 2) { locInfo = inverseStrip; inverseStrip = null; } LocationInfo.call(this, locInfo); this.type = "program"; this.statements = statements; this.strip = {}; if(inverse) { firstInverseNode = inverse[0]; if (firstInverseNode) { inverseLocationInfo = { first_line: firstInverseNode.firstLine, last_line: firstInverseNode.lastLine, last_column: firstInverseNode.lastColumn, first_column: firstInverseNode.firstColumn }; this.inverse = new AST.ProgramNode(inverse, inverseStrip, inverseLocationInfo); } else { this.inverse = new AST.ProgramNode(inverse, inverseStrip); } this.strip.right = inverseStrip.left; } else if (inverseStrip) { this.strip.left = inverseStrip.right; } }, MustacheNode: function(rawParams, hash, open, strip, locInfo) { LocationInfo.call(this, locInfo); this.type = "mustache"; this.strip = strip; // Open may be a string parsed from the parser or a passed boolean flag if (open != null && open.charAt) { // Must use charAt to support IE pre-10 var escapeFlag = open.charAt(3) || open.charAt(2); this.escaped = escapeFlag !== '{' && escapeFlag !== '&'; } else { this.escaped = !!open; } if (rawParams instanceof AST.SexprNode) { this.sexpr = rawParams; } else { // Support old AST API this.sexpr = new AST.SexprNode(rawParams, hash); } this.sexpr.isRoot = true; // Support old AST API that stored this info in MustacheNode this.id = this.sexpr.id; this.params = this.sexpr.params; this.hash = this.sexpr.hash; this.eligibleHelper = this.sexpr.eligibleHelper; this.isHelper = this.sexpr.isHelper; }, SexprNode: function(rawParams, hash, locInfo) { LocationInfo.call(this, locInfo); this.type = "sexpr"; this.hash = hash; var id = this.id = rawParams[0]; var params = this.params = rawParams.slice(1); // a mustache is an eligible helper if: // * its id is simple (a single part, not `this` or `..`) var eligibleHelper = this.eligibleHelper = id.isSimple; // a mustache is definitely a helper if: // * it is an eligible helper, and // * it has at least one parameter or hash segment this.isHelper = eligibleHelper && (params.length || hash); // if a mustache is an eligible helper but not a definite // helper, it is ambiguous, and will be resolved in a later // pass or at runtime. }, PartialNode: function(partialName, context, strip, locInfo) { LocationInfo.call(this, locInfo); this.type = "partial"; this.partialName = partialName; this.context = context; this.strip = strip; }, BlockNode: function(mustache, program, inverse, close, locInfo) { LocationInfo.call(this, locInfo); if(mustache.sexpr.id.original !== close.path.original) { throw new Exception(mustache.sexpr.id.original + " doesn't match " + close.path.original, this); } this.type = 'block'; this.mustache = mustache; this.program = program; this.inverse = inverse; this.strip = { left: mustache.strip.left, right: close.strip.right }; (program || inverse).strip.left = mustache.strip.right; (inverse || program).strip.right = close.strip.left; if (inverse && !program) { this.isInverse = true; } }, ContentNode: function(string, locInfo) { LocationInfo.call(this, locInfo); this.type = "content"; this.string = string; }, HashNode: function(pairs, locInfo) { LocationInfo.call(this, locInfo); this.type = "hash"; this.pairs = pairs; }, IdNode: function(parts, locInfo) { LocationInfo.call(this, locInfo); this.type = "ID"; var original = "", dig = [], depth = 0; for(var i=0,l=parts.length; i<l; i++) { var part = parts[i].part; original += (parts[i].separator || '') + part; if (part === ".." || part === "." || part === "this") { if (dig.length > 0) { throw new Exception("Invalid path: " + original, this); } else if (part === "..") { depth++; } else { this.isScoped = true; } } else { dig.push(part); } } this.original = original; this.parts = dig; this.string = dig.join('.'); this.depth = depth; // an ID is simple if it only has one part, and that part is not // `..` or `this`. this.isSimple = parts.length === 1 && !this.isScoped && depth === 0; this.stringModeValue = this.string; }, PartialNameNode: function(name, locInfo) { LocationInfo.call(this, locInfo); this.type = "PARTIAL_NAME"; this.name = name.original; }, DataNode: function(id, locInfo) { LocationInfo.call(this, locInfo); this.type = "DATA"; this.id = id; }, StringNode: function(string, locInfo) { LocationInfo.call(this, locInfo); this.type = "STRING"; this.original = this.string = this.stringModeValue = string; }, IntegerNode: function(integer, locInfo) { LocationInfo.call(this, locInfo); this.type = "INTEGER"; this.original = this.integer = integer; this.stringModeValue = Number(integer); }, BooleanNode: function(bool, locInfo) { LocationInfo.call(this, locInfo); this.type = "BOOLEAN"; this.bool = bool; this.stringModeValue = bool === "true"; }, CommentNode: function(comment, locInfo) { LocationInfo.call(this, locInfo); this.type = "comment"; this.comment = comment; } }; // Must be exported as an object rather than the root of the module as the jison lexer // most modify the object to operate properly. __exports__ = AST; return __exports__; })(__module5__); // handlebars/compiler/parser.js var __module9__ = (function() { "use strict"; var __exports__; /* jshint ignore:start */ /* Jison generated parser */ var handlebars = (function(){ var parser = {trace: function trace() { }, yy: {}, symbols_: {"error":2,"root":3,"statements":4,"EOF":5,"program":6,"simpleInverse":7,"statement":8,"openInverse":9,"closeBlock":10,"openBlock":11,"mustache":12,"partial":13,"CONTENT":14,"COMMENT":15,"OPEN_BLOCK":16,"sexpr":17,"CLOSE":18,"OPEN_INVERSE":19,"OPEN_ENDBLOCK":20,"path":21,"OPEN":22,"OPEN_UNESCAPED":23,"CLOSE_UNESCAPED":24,"OPEN_PARTIAL":25,"partialName":26,"partial_option0":27,"sexpr_repetition0":28,"sexpr_option0":29,"dataName":30,"param":31,"STRING":32,"INTEGER":33,"BOOLEAN":34,"OPEN_SEXPR":35,"CLOSE_SEXPR":36,"hash":37,"hash_repetition_plus0":38,"hashSegment":39,"ID":40,"EQUALS":41,"DATA":42,"pathSegments":43,"SEP":44,"$accept":0,"$end":1}, terminals_: {2:"error",5:"EOF",14:"CONTENT",15:"COMMENT",16:"OPEN_BLOCK",18:"CLOSE",19:"OPEN_INVERSE",20:"OPEN_ENDBLOCK",22:"OPEN",23:"OPEN_UNESCAPED",24:"CLOSE_UNESCAPED",25:"OPEN_PARTIAL",32:"STRING",33:"INTEGER",34:"BOOLEAN",35:"OPEN_SEXPR",36:"CLOSE_SEXPR",40:"ID",41:"EQUALS",42:"DATA",44:"SEP"}, productions_: [0,[3,2],[3,1],[6,2],[6,3],[6,2],[6,1],[6,1],[6,0],[4,1],[4,2],[8,3],[8,3],[8,1],[8,1],[8,1],[8,1],[11,3],[9,3],[10,3],[12,3],[12,3],[13,4],[7,2],[17,3],[17,1],[31,1],[31,1],[31,1],[31,1],[31,1],[31,3],[37,1],[39,3],[26,1],[26,1],[26,1],[30,2],[21,1],[43,3],[43,1],[27,0],[27,1],[28,0],[28,2],[29,0],[29,1],[38,1],[38,2]], performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) { var $0 = $$.length - 1; switch (yystate) { case 1: return new yy.ProgramNode($$[$0-1], this._$); break; case 2: return new yy.ProgramNode([], this._$); break; case 3:this.$ = new yy.ProgramNode([], $$[$0-1], $$[$0], this._$); break; case 4:this.$ = new yy.ProgramNode($$[$0-2], $$[$0-1], $$[$0], this._$); break; case 5:this.$ = new yy.ProgramNode($$[$0-1], $$[$0], [], this._$); break; case 6:this.$ = new yy.ProgramNode($$[$0], this._$); break; case 7:this.$ = new yy.ProgramNode([], this._$); break; case 8:this.$ = new yy.ProgramNode([], this._$); break; case 9:this.$ = [$$[$0]]; break; case 10: $$[$0-1].push($$[$0]); this.$ = $$[$0-1]; break; case 11:this.$ = new yy.BlockNode($$[$0-2], $$[$0-1].inverse, $$[$0-1], $$[$0], this._$); break; case 12:this.$ = new yy.BlockNode($$[$0-2], $$[$0-1], $$[$0-1].inverse, $$[$0], this._$); break; case 13:this.$ = $$[$0]; break; case 14:this.$ = $$[$0]; break; case 15:this.$ = new yy.ContentNode($$[$0], this._$); break; case 16:this.$ = new yy.CommentNode($$[$0], this._$); break; case 17:this.$ = new yy.MustacheNode($$[$0-1], null, $$[$0-2], stripFlags($$[$0-2], $$[$0]), this._$); break; case 18:this.$ = new yy.MustacheNode($$[$0-1], null, $$[$0-2], stripFlags($$[$0-2], $$[$0]), this._$); break; case 19:this.$ = {path: $$[$0-1], strip: stripFlags($$[$0-2], $$[$0])}; break; case 20:this.$ = new yy.MustacheNode($$[$0-1], null, $$[$0-2], stripFlags($$[$0-2], $$[$0]), this._$); break; case 21:this.$ = new yy.MustacheNode($$[$0-1], null, $$[$0-2], stripFlags($$[$0-2], $$[$0]), this._$); break; case 22:this.$ = new yy.PartialNode($$[$0-2], $$[$0-1], stripFlags($$[$0-3], $$[$0]), this._$); break; case 23:this.$ = stripFlags($$[$0-1], $$[$0]); break; case 24:this.$ = new yy.SexprNode([$$[$0-2]].concat($$[$0-1]), $$[$0], this._$); break; case 25:this.$ = new yy.SexprNode([$$[$0]], null, this._$); break; case 26:this.$ = $$[$0]; break; case 27:this.$ = new yy.StringNode($$[$0], this._$); break; case 28:this.$ = new yy.IntegerNode($$[$0], this._$); break; case 29:this.$ = new yy.BooleanNode($$[$0], this._$); break; case 30:this.$ = $$[$0]; break; case 31:$$[$0-1].isHelper = true; this.$ = $$[$0-1]; break; case 32:this.$ = new yy.HashNode($$[$0], this._$); break; case 33:this.$ = [$$[$0-2], $$[$0]]; break; case 34:this.$ = new yy.PartialNameNode($$[$0], this._$); break; case 35:this.$ = new yy.PartialNameNode(new yy.StringNode($$[$0], this._$), this._$); break; case 36:this.$ = new yy.PartialNameNode(new yy.IntegerNode($$[$0], this._$)); break; case 37:this.$ = new yy.DataNode($$[$0], this._$); break; case 38:this.$ = new yy.IdNode($$[$0], this._$); break; case 39: $$[$0-2].push({part: $$[$0], separator: $$[$0-1]}); this.$ = $$[$0-2]; break; case 40:this.$ = [{part: $$[$0]}]; break; case 43:this.$ = []; break; case 44:$$[$0-1].push($$[$0]); break; case 47:this.$ = [$$[$0]]; break; case 48:$$[$0-1].push($$[$0]); break; } }, table: [{3:1,4:2,5:[1,3],8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],25:[1,15]},{1:[3]},{5:[1,16],8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],25:[1,15]},{1:[2,2]},{5:[2,9],14:[2,9],15:[2,9],16:[2,9],19:[2,9],20:[2,9],22:[2,9],23:[2,9],25:[2,9]},{4:20,6:18,7:19,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,21],20:[2,8],22:[1,13],23:[1,14],25:[1,15]},{4:20,6:22,7:19,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,21],20:[2,8],22:[1,13],23:[1,14],25:[1,15]},{5:[2,13],14:[2,13],15:[2,13],16:[2,13],19:[2,13],20:[2,13],22:[2,13],23:[2,13],25:[2,13]},{5:[2,14],14:[2,14],15:[2,14],16:[2,14],19:[2,14],20:[2,14],22:[2,14],23:[2,14],25:[2,14]},{5:[2,15],14:[2,15],15:[2,15],16:[2,15],19:[2,15],20:[2,15],22:[2,15],23:[2,15],25:[2,15]},{5:[2,16],14:[2,16],15:[2,16],16:[2,16],19:[2,16],20:[2,16],22:[2,16],23:[2,16],25:[2,16]},{17:23,21:24,30:25,40:[1,28],42:[1,27],43:26},{17:29,21:24,30:25,40:[1,28],42:[1,27],43:26},{17:30,21:24,30:25,40:[1,28],42:[1,27],43:26},{17:31,21:24,30:25,40:[1,28],42:[1,27],43:26},{21:33,26:32,32:[1,34],33:[1,35],40:[1,28],43:26},{1:[2,1]},{5:[2,10],14:[2,10],15:[2,10],16:[2,10],19:[2,10],20:[2,10],22:[2,10],23:[2,10],25:[2,10]},{10:36,20:[1,37]},{4:38,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,7],22:[1,13],23:[1,14],25:[1,15]},{7:39,8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,21],20:[2,6],22:[1,13],23:[1,14],25:[1,15]},{17:23,18:[1,40],21:24,30:25,40:[1,28],42:[1,27],43:26},{10:41,20:[1,37]},{18:[1,42]},{18:[2,43],24:[2,43],28:43,32:[2,43],33:[2,43],34:[2,43],35:[2,43],36:[2,43],40:[2,43],42:[2,43]},{18:[2,25],24:[2,25],36:[2,25]},{18:[2,38],24:[2,38],32:[2,38],33:[2,38],34:[2,38],35:[2,38],36:[2,38],40:[2,38],42:[2,38],44:[1,44]},{21:45,40:[1,28],43:26},{18:[2,40],24:[2,40],32:[2,40],33:[2,40],34:[2,40],35:[2,40],36:[2,40],40:[2,40],42:[2,40],44:[2,40]},{18:[1,46]},{18:[1,47]},{24:[1,48]},{18:[2,41],21:50,27:49,40:[1,28],43:26},{18:[2,34],40:[2,34]},{18:[2,35],40:[2,35]},{18:[2,36],40:[2,36]},{5:[2,11],14:[2,11],15:[2,11],16:[2,11],19:[2,11],20:[2,11],22:[2,11],23:[2,11],25:[2,11]},{21:51,40:[1,28],43:26},{8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,3],22:[1,13],23:[1,14],25:[1,15]},{4:52,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,5],22:[1,13],23:[1,14],25:[1,15]},{14:[2,23],15:[2,23],16:[2,23],19:[2,23],20:[2,23],22:[2,23],23:[2,23],25:[2,23]},{5:[2,12],14:[2,12],15:[2,12],16:[2,12],19:[2,12],20:[2,12],22:[2,12],23:[2,12],25:[2,12]},{14:[2,18],15:[2,18],16:[2,18],19:[2,18],20:[2,18],22:[2,18],23:[2,18],25:[2,18]},{18:[2,45],21:56,24:[2,45],29:53,30:60,31:54,32:[1,57],33:[1,58],34:[1,59],35:[1,61],36:[2,45],37:55,38:62,39:63,40:[1,64],42:[1,27],43:26},{40:[1,65]},{18:[2,37],24:[2,37],32:[2,37],33:[2,37],34:[2,37],35:[2,37],36:[2,37],40:[2,37],42:[2,37]},{14:[2,17],15:[2,17],16:[2,17],19:[2,17],20:[2,17],22:[2,17],23:[2,17],25:[2,17]},{5:[2,20],14:[2,20],15:[2,20],16:[2,20],19:[2,20],20:[2,20],22:[2,20],23:[2,20],25:[2,20]},{5:[2,21],14:[2,21],15:[2,21],16:[2,21],19:[2,21],20:[2,21],22:[2,21],23:[2,21],25:[2,21]},{18:[1,66]},{18:[2,42]},{18:[1,67]},{8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,4],22:[1,13],23:[1,14],25:[1,15]},{18:[2,24],24:[2,24],36:[2,24]},{18:[2,44],24:[2,44],32:[2,44],33:[2,44],34:[2,44],35:[2,44],36:[2,44],40:[2,44],42:[2,44]},{18:[2,46],24:[2,46],36:[2,46]},{18:[2,26],24:[2,26],32:[2,26],33:[2,26],34:[2,26],35:[2,26],36:[2,26],40:[2,26],42:[2,26]},{18:[2,27],24:[2,27],32:[2,27],33:[2,27],34:[2,27],35:[2,27],36:[2,27],40:[2,27],42:[2,27]},{18:[2,28],24:[2,28],32:[2,28],33:[2,28],34:[2,28],35:[2,28],36:[2,28],40:[2,28],42:[2,28]},{18:[2,29],24:[2,29],32:[2,29],33:[2,29],34:[2,29],35:[2,29],36:[2,29],40:[2,29],42:[2,29]},{18:[2,30],24:[2,30],32:[2,30],33:[2,30],34:[2,30],35:[2,30],36:[2,30],40:[2,30],42:[2,30]},{17:68,21:24,30:25,40:[1,28],42:[1,27],43:26},{18:[2,32],24:[2,32],36:[2,32],39:69,40:[1,70]},{18:[2,47],24:[2,47],36:[2,47],40:[2,47]},{18:[2,40],24:[2,40],32:[2,40],33:[2,40],34:[2,40],35:[2,40],36:[2,40],40:[2,40],41:[1,71],42:[2,40],44:[2,40]},{18:[2,39],24:[2,39],32:[2,39],33:[2,39],34:[2,39],35:[2,39],36:[2,39],40:[2,39],42:[2,39],44:[2,39]},{5:[2,22],14:[2,22],15:[2,22],16:[2,22],19:[2,22],20:[2,22],22:[2,22],23:[2,22],25:[2,22]},{5:[2,19],14:[2,19],15:[2,19],16:[2,19],19:[2,19],20:[2,19],22:[2,19],23:[2,19],25:[2,19]},{36:[1,72]},{18:[2,48],24:[2,48],36:[2,48],40:[2,48]},{41:[1,71]},{21:56,30:60,31:73,32:[1,57],33:[1,58],34:[1,59],35:[1,61],40:[1,28],42:[1,27],43:26},{18:[2,31],24:[2,31],32:[2,31],33:[2,31],34:[2,31],35:[2,31],36:[2,31],40:[2,31],42:[2,31]},{18:[2,33],24:[2,33],36:[2,33],40:[2,33]}], defaultActions: {3:[2,2],16:[2,1],50:[2,42]}, parseError: function parseError(str, hash) { throw new Error(str); }, parse: function parse(input) { var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; this.lexer.setInput(input); this.lexer.yy = this.yy; this.yy.lexer = this.lexer; this.yy.parser = this; if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {}; var yyloc = this.lexer.yylloc; lstack.push(yyloc); var ranges = this.lexer.options && this.lexer.options.ranges; if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError; function popStack(n) { stack.length = stack.length - 2 * n; vstack.length = vstack.length - n; lstack.length = lstack.length - n; } function lex() { var token; token = self.lexer.lex() || 1; if (typeof token !== "number") { token = self.symbols_[token] || token; } return token; } var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected; while (true) { state = stack[stack.length - 1]; if (this.defaultActions[state]) { action = this.defaultActions[state]; } else { if (symbol === null || typeof symbol == "undefined") { symbol = lex(); } action = table[state] && table[state][symbol]; } if (typeof action === "undefined" || !action.length || !action[0]) { var errStr = ""; if (!recovering) { expected = []; for (p in table[state]) if (this.terminals_[p] && p > 2) { expected.push("'" + this.terminals_[p] + "'"); } if (this.lexer.showPosition) { errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'"; } else { errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'"); } this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected}); } } if (action[0] instanceof Array && action.length > 1) { throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); } switch (action[0]) { case 1: stack.push(symbol); vstack.push(this.lexer.yytext); lstack.push(this.lexer.yylloc); stack.push(action[1]); symbol = null; if (!preErrorSymbol) { yyleng = this.lexer.yyleng; yytext = this.lexer.yytext; yylineno = this.lexer.yylineno; yyloc = this.lexer.yylloc; if (recovering > 0) recovering--; } else { symbol = preErrorSymbol; preErrorSymbol = null; } break; case 2: len = this.productions_[action[1]][1]; yyval.$ = vstack[vstack.length - len]; yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column}; if (ranges) { yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]]; } r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); if (typeof r !== "undefined") { return r; } if (len) { stack = stack.slice(0, -1 * len * 2); vstack = vstack.slice(0, -1 * len); lstack = lstack.slice(0, -1 * len); } stack.push(this.productions_[action[1]][0]); vstack.push(yyval.$); lstack.push(yyval._$); newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; stack.push(newState); break; case 3: return true; } } return true; } }; function stripFlags(open, close) { return { left: open.charAt(2) === '~', right: close.charAt(0) === '~' || close.charAt(1) === '~' }; } /* Jison generated lexer */ var lexer = (function(){ var lexer = ({EOF:1, parseError:function parseError(str, hash) { if (this.yy.parser) { this.yy.parser.parseError(str, hash); } else { throw new Error(str); } }, setInput:function (input) { this._input = input; this._more = this._less = this.done = false; this.yylineno = this.yyleng = 0; this.yytext = this.matched = this.match = ''; this.conditionStack = ['INITIAL']; this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0}; if (this.options.ranges) this.yylloc.range = [0,0]; this.offset = 0; return this; }, input:function () { var ch = this._input[0]; this.yytext += ch; this.yyleng++; this.offset++; this.match += ch; this.matched += ch; var lines = ch.match(/(?:\r\n?|\n).*/g); if (lines) { this.yylineno++; this.yylloc.last_line++; } else { this.yylloc.last_column++; } if (this.options.ranges) this.yylloc.range[1]++; this._input = this._input.slice(1); return ch; }, unput:function (ch) { var len = ch.length; var lines = ch.split(/(?:\r\n?|\n)/g); this._input = ch + this._input; this.yytext = this.yytext.substr(0, this.yytext.length-len-1); //this.yyleng -= len; this.offset -= len; var oldLines = this.match.split(/(?:\r\n?|\n)/g); this.match = this.match.substr(0, this.match.length-1); this.matched = this.matched.substr(0, this.matched.length-1); if (lines.length-1) this.yylineno -= lines.length-1; var r = this.yylloc.range; this.yylloc = {first_line: this.yylloc.first_line, last_line: this.yylineno+1, first_column: this.yylloc.first_column, last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length: this.yylloc.first_column - len }; if (this.options.ranges) { this.yylloc.range = [r[0], r[0] + this.yyleng - len]; } return this; }, more:function () { this._more = true; return this; }, less:function (n) { this.unput(this.match.slice(n)); }, pastInput:function () { var past = this.matched.substr(0, this.matched.length - this.match.length); return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); }, upcomingInput:function () { var next = this.match; if (next.length < 20) { next += this._input.substr(0, 20-next.length); } return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, ""); }, showPosition:function () { var pre = this.pastInput(); var c = new Array(pre.length + 1).join("-"); return pre + this.upcomingInput() + "\n" + c+"^"; }, next:function () { if (this.done) { return this.EOF; } if (!this._input) this.done = true; var token, match, tempMatch, index, col, lines; if (!this._more) { this.yytext = ''; this.match = ''; } var rules = this._currentRules(); for (var i=0;i < rules.length; i++) { tempMatch = this._input.match(this.rules[rules[i]]); if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { match = tempMatch; index = i; if (!this.options.flex) break; } } if (match) { lines = match[0].match(/(?:\r\n?|\n).*/g); if (lines) this.yylineno += lines.length; this.yylloc = {first_line: this.yylloc.last_line, last_line: this.yylineno+1, first_column: this.yylloc.last_column, last_column: lines ? lines[lines.length-1].length-lines[lines.length-1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length}; this.yytext += match[0]; this.match += match[0]; this.matches = match; this.yyleng = this.yytext.length; if (this.options.ranges) { this.yylloc.range = [this.offset, this.offset += this.yyleng]; } this._more = false; this._input = this._input.slice(match[0].length); this.matched += match[0]; token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]); if (this.done && this._input) this.done = false; if (token) return token; else return; } if (this._input === "") { return this.EOF; } else { return this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(), {text: "", token: null, line: this.yylineno}); } }, lex:function lex() { var r = this.next(); if (typeof r !== 'undefined') { return r; } else { return this.lex(); } }, begin:function begin(condition) { this.conditionStack.push(condition); }, popState:function popState() { return this.conditionStack.pop(); }, _currentRules:function _currentRules() { return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules; }, topState:function () { return this.conditionStack[this.conditionStack.length-2]; }, pushState:function begin(condition) { this.begin(condition); }}); lexer.options = {}; lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { function strip(start, end) { return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng-end); } var YYSTATE=YY_START switch($avoiding_name_collisions) { case 0: if(yy_.yytext.slice(-2) === "\\\\") { strip(0,1); this.begin("mu"); } else if(yy_.yytext.slice(-1) === "\\") { strip(0,1); this.begin("emu"); } else { this.begin("mu"); } if(yy_.yytext) return 14; break; case 1:return 14; break; case 2: this.popState(); return 14; break; case 3:strip(0,4); this.popState(); return 15; break; case 4:return 35; break; case 5:return 36; break; case 6:return 25; break; case 7:return 16; break; case 8:return 20; break; case 9:return 19; break; case 10:return 19; break; case 11:return 23; break; case 12:return 22; break; case 13:this.popState(); this.begin('com'); break; case 14:strip(3,5); this.popState(); return 15; break; case 15:return 22; break; case 16:return 41; break; case 17:return 40; break; case 18:return 40; break; case 19:return 44; break; case 20:// ignore whitespace break; case 21:this.popState(); return 24; break; case 22:this.popState(); return 18; break; case 23:yy_.yytext = strip(1,2).replace(/\\"/g,'"'); return 32; break; case 24:yy_.yytext = strip(1,2).replace(/\\'/g,"'"); return 32; break; case 25:return 42; break; case 26:return 34; break; case 27:return 34; break; case 28:return 33; break; case 29:return 40; break; case 30:yy_.yytext = strip(1,2); return 40; break; case 31:return 'INVALID'; break; case 32:return 5; break; } }; lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:[\s\S]*?--\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{!--)/,/^(?:\{\{![\s\S]*?\}\})/,/^(?:\{\{(~)?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:-?[0-9]+(?=([~}\s)])))/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)]))))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:$)/]; lexer.conditions = {"mu":{"rules":[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32],"inclusive":false},"emu":{"rules":[2],"inclusive":false},"com":{"rules":[3],"inclusive":false},"INITIAL":{"rules":[0,1,32],"inclusive":true}}; return lexer;})() parser.lexer = lexer; function Parser () { this.yy = {}; }Parser.prototype = parser;parser.Parser = Parser; return new Parser; })();__exports__ = handlebars; /* jshint ignore:end */ return __exports__; })(); // handlebars/compiler/base.js var __module8__ = (function(__dependency1__, __dependency2__) { "use strict"; var __exports__ = {}; var parser = __dependency1__; var AST = __dependency2__; __exports__.parser = parser; function parse(input) { // Just return if an already-compile AST was passed in. if(input.constructor === AST.ProgramNode) { return input; } parser.yy = AST; return parser.parse(input); } __exports__.parse = parse; return __exports__; })(__module9__, __module7__); // handlebars/compiler/compiler.js var __module10__ = (function(__dependency1__) { "use strict"; var __exports__ = {}; var Exception = __dependency1__; function Compiler() {} __exports__.Compiler = Compiler;// the foundHelper register will disambiguate helper lookup from finding a // function in a context. This is necessary for mustache compatibility, which // requires that context functions in blocks are evaluated by blockHelperMissing, // and then proceed as if the resulting value was provided to blockHelperMissing. Compiler.prototype = { compiler: Compiler, disassemble: function() { var opcodes = this.opcodes, opcode, out = [], params, param; for (var i=0, l=opcodes.length; i<l; i++) { opcode = opcodes[i]; if (opcode.opcode === 'DECLARE') { out.push("DECLARE " + opcode.name + "=" + opcode.value); } else { params = []; for (var j=0; j<opcode.args.length; j++) { param = opcode.args[j]; if (typeof param === "string") { param = "\"" + param.replace("\n", "\\n") + "\""; } params.push(param); } out.push(opcode.opcode + " " + params.join(" ")); } } return out.join("\n"); }, equals: function(other) { var len = this.opcodes.length; if (other.opcodes.length !== len) { return false; } for (var i = 0; i < len; i++) { var opcode = this.opcodes[i], otherOpcode = other.opcodes[i]; if (opcode.opcode !== otherOpcode.opcode || opcode.args.length !== otherOpcode.args.length) { return false; } for (var j = 0; j < opcode.args.length; j++) { if (opcode.args[j] !== otherOpcode.args[j]) { return false; } } } len = this.children.length; if (other.children.length !== len) { return false; } for (i = 0; i < len; i++) { if (!this.children[i].equals(other.children[i])) { return false; } } return true; }, guid: 0, compile: function(program, options) { this.opcodes = []; this.children = []; this.depths = {list: []}; this.options = options; // These changes will propagate to the other compiler components var knownHelpers = this.options.knownHelpers; this.options.knownHelpers = { 'helperMissing': true, 'blockHelperMissing': true, 'each': true, 'if': true, 'unless': true, 'with': true, 'log': true }; if (knownHelpers) { for (var name in knownHelpers) { this.options.knownHelpers[name] = knownHelpers[name]; } } return this.accept(program); }, accept: function(node) { var strip = node.strip || {}, ret; if (strip.left) { this.opcode('strip'); } ret = this[node.type](node); if (strip.right) { this.opcode('strip'); } return ret; }, program: function(program) { var statements = program.statements; for(var i=0, l=statements.length; i<l; i++) { this.accept(statements[i]); } this.isSimple = l === 1; this.depths.list = this.depths.list.sort(function(a, b) { return a - b; }); return this; }, compileProgram: function(program) { var result = new this.compiler().compile(program, this.options); var guid = this.guid++, depth; this.usePartial = this.usePartial || result.usePartial; this.children[guid] = result; for(var i=0, l=result.depths.list.length; i<l; i++) { depth = result.depths.list[i]; if(depth < 2) { continue; } else { this.addDepth(depth - 1); } } return guid; }, block: function(block) { var mustache = block.mustache, program = block.program, inverse = block.inverse; if (program) { program = this.compileProgram(program); } if (inverse) { inverse = this.compileProgram(inverse); } var sexpr = mustache.sexpr; var type = this.classifySexpr(sexpr); if (type === "helper") { this.helperSexpr(sexpr, program, inverse); } else if (type === "simple") { this.simpleSexpr(sexpr); // now that the simple mustache is resolved, we need to // evaluate it by executing `blockHelperMissing` this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); this.opcode('emptyHash'); this.opcode('blockValue'); } else { this.ambiguousSexpr(sexpr, program, inverse); // now that the simple mustache is resolved, we need to // evaluate it by executing `blockHelperMissing` this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); this.opcode('emptyHash'); this.opcode('ambiguousBlockValue'); } this.opcode('append'); }, hash: function(hash) { var pairs = hash.pairs, pair, val; this.opcode('pushHash'); for(var i=0, l=pairs.length; i<l; i++) { pair = pairs[i]; val = pair[1]; if (this.options.stringParams) { if(val.depth) { this.addDepth(val.depth); } this.opcode('getContext', val.depth || 0); this.opcode('pushStringParam', val.stringModeValue, val.type); if (val.type === 'sexpr') { // Subexpressions get evaluated and passed in // in string params mode. this.sexpr(val); } } else { this.accept(val); } this.opcode('assignToHash', pair[0]); } this.opcode('popHash'); }, partial: function(partial) { var partialName = partial.partialName; this.usePartial = true; if(partial.context) { this.ID(partial.context); } else { this.opcode('push', 'depth0'); } this.opcode('invokePartial', partialName.name); this.opcode('append'); }, content: function(content) { this.opcode('appendContent', content.string); }, mustache: function(mustache) { this.sexpr(mustache.sexpr); if(mustache.escaped && !this.options.noEscape) { this.opcode('appendEscaped'); } else { this.opcode('append'); } }, ambiguousSexpr: function(sexpr, program, inverse) { var id = sexpr.id, name = id.parts[0], isBlock = program != null || inverse != null; this.opcode('getContext', id.depth); this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); this.opcode('invokeAmbiguous', name, isBlock); }, simpleSexpr: function(sexpr) { var id = sexpr.id; if (id.type === 'DATA') { this.DATA(id); } else if (id.parts.length) { this.ID(id); } else { // Simplified ID for `this` this.addDepth(id.depth); this.opcode('getContext', id.depth); this.opcode('pushContext'); } this.opcode('resolvePossibleLambda'); }, helperSexpr: function(sexpr, program, inverse) { var params = this.setupFullMustacheParams(sexpr, program, inverse), name = sexpr.id.parts[0]; if (this.options.knownHelpers[name]) { this.opcode('invokeKnownHelper', params.length, name); } else if (this.options.knownHelpersOnly) { throw new Exception("You specified knownHelpersOnly, but used the unknown helper " + name, sexpr); } else { this.opcode('invokeHelper', params.length, name, sexpr.isRoot); } }, sexpr: function(sexpr) { var type = this.classifySexpr(sexpr); if (type === "simple") { this.simpleSexpr(sexpr); } else if (type === "helper") { this.helperSexpr(sexpr); } else { this.ambiguousSexpr(sexpr); } }, ID: function(id) { this.addDepth(id.depth); this.opcode('getContext', id.depth); var name = id.parts[0]; if (!name) { this.opcode('pushContext'); } else { this.opcode('lookupOnContext', id.parts[0]); } for(var i=1, l=id.parts.length; i<l; i++) { this.opcode('lookup', id.parts[i]); } }, DATA: function(data) { this.options.data = true; if (data.id.isScoped || data.id.depth) { throw new Exception('Scoped data references are not supported: ' + data.original, data); } this.opcode('lookupData'); var parts = data.id.parts; for(var i=0, l=parts.length; i<l; i++) { this.opcode('lookup', parts[i]); } }, STRING: function(string) { this.opcode('pushString', string.string); }, INTEGER: function(integer) { this.opcode('pushLiteral', integer.integer); }, BOOLEAN: function(bool) { this.opcode('pushLiteral', bool.bool); }, comment: function() {}, // HELPERS opcode: function(name) { this.opcodes.push({ opcode: name, args: [].slice.call(arguments, 1) }); }, declare: function(name, value) { this.opcodes.push({ opcode: 'DECLARE', name: name, value: value }); }, addDepth: function(depth) { if(depth === 0) { return; } if(!this.depths[depth]) { this.depths[depth] = true; this.depths.list.push(depth); } }, classifySexpr: function(sexpr) { var isHelper = sexpr.isHelper; var isEligible = sexpr.eligibleHelper; var options = this.options; // if ambiguous, we can possibly resolve the ambiguity now if (isEligible && !isHelper) { var name = sexpr.id.parts[0]; if (options.knownHelpers[name]) { isHelper = true; } else if (options.knownHelpersOnly) { isEligible = false; } } if (isHelper) { return "helper"; } else if (isEligible) { return "ambiguous"; } else { return "simple"; } }, pushParams: function(params) { var i = params.length, param; while(i--) { param = params[i]; if(this.options.stringParams) { if(param.depth) { this.addDepth(param.depth); } this.opcode('getContext', param.depth || 0); this.opcode('pushStringParam', param.stringModeValue, param.type); if (param.type === 'sexpr') { // Subexpressions get evaluated and passed in // in string params mode. this.sexpr(param); } } else { this[param.type](param); } } }, setupFullMustacheParams: function(sexpr, program, inverse) { var params = sexpr.params; this.pushParams(params); this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); if (sexpr.hash) { this.hash(sexpr.hash); } else { this.opcode('emptyHash'); } return params; } }; function precompile(input, options, env) { if (input == null || (typeof input !== 'string' && input.constructor !== env.AST.ProgramNode)) { throw new Exception("You must pass a string or Handlebars AST to Handlebars.precompile. You passed " + input); } options = options || {}; if (!('data' in options)) { options.data = true; } var ast = env.parse(input); var environment = new env.Compiler().compile(ast, options); return new env.JavaScriptCompiler().compile(environment, options); } __exports__.precompile = precompile;function compile(input, options, env) { if (input == null || (typeof input !== 'string' && input.constructor !== env.AST.ProgramNode)) { throw new Exception("You must pass a string or Handlebars AST to Handlebars.compile. You passed " + input); } options = options || {}; if (!('data' in options)) { options.data = true; } var compiled; function compileInput() { var ast = env.parse(input); var environment = new env.Compiler().compile(ast, options); var templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true); return env.template(templateSpec); } // Template is only compiled on first use and cached after that point. return function(context, options) { if (!compiled) { compiled = compileInput(); } return compiled.call(this, context, options); }; } __exports__.compile = compile; return __exports__; })(__module5__); // handlebars/compiler/javascript-compiler.js var __module11__ = (function(__dependency1__, __dependency2__) { "use strict"; var __exports__; var COMPILER_REVISION = __dependency1__.COMPILER_REVISION; var REVISION_CHANGES = __dependency1__.REVISION_CHANGES; var log = __dependency1__.log; var Exception = __dependency2__; function Literal(value) { this.value = value; } function JavaScriptCompiler() {} JavaScriptCompiler.prototype = { // PUBLIC API: You can override these methods in a subclass to provide // alternative compiled forms for name lookup and buffering semantics nameLookup: function(parent, name /* , type*/) { var wrap, ret; if (parent.indexOf('depth') === 0) { wrap = true; } if (/^[0-9]+$/.test(name)) { ret = parent + "[" + name + "]"; } else if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) { ret = parent + "." + name; } else { ret = parent + "['" + name + "']"; } if (wrap) { return '(' + parent + ' && ' + ret + ')'; } else { return ret; } }, compilerInfo: function() { var revision = COMPILER_REVISION, versions = REVISION_CHANGES[revision]; return "this.compilerInfo = ["+revision+",'"+versions+"'];\n"; }, appendToBuffer: function(string) { if (this.environment.isSimple) { return "return " + string + ";"; } else { return { appendToBuffer: true, content: string, toString: function() { return "buffer += " + string + ";"; } }; } }, initializeBuffer: function() { return this.quotedString(""); }, namespace: "Handlebars", // END PUBLIC API compile: function(environment, options, context, asObject) { this.environment = environment; this.options = options || {}; log('debug', this.environment.disassemble() + "\n\n"); this.name = this.environment.name; this.isChild = !!context; this.context = context || { programs: [], environments: [], aliases: { } }; this.preamble(); this.stackSlot = 0; this.stackVars = []; this.registers = { list: [] }; this.hashes = []; this.compileStack = []; this.inlineStack = []; this.compileChildren(environment, options); var opcodes = environment.opcodes, opcode; this.i = 0; for(var l=opcodes.length; this.i<l; this.i++) { opcode = opcodes[this.i]; if(opcode.opcode === 'DECLARE') { this[opcode.name] = opcode.value; } else { this[opcode.opcode].apply(this, opcode.args); } // Reset the stripNext flag if it was not set by this operation. if (opcode.opcode !== this.stripNext) { this.stripNext = false; } } // Flush any trailing content that might be pending. this.pushSource(''); if (this.stackSlot || this.inlineStack.length || this.compileStack.length) { throw new Exception('Compile completed with content left on stack'); } return this.createFunctionContext(asObject); }, preamble: function() { var out = []; if (!this.isChild) { var namespace = this.namespace; var copies = "helpers = this.merge(helpers, " + namespace + ".helpers);"; if (this.environment.usePartial) { copies = copies + " partials = this.merge(partials, " + namespace + ".partials);"; } if (this.options.data) { copies = copies + " data = data || {};"; } out.push(copies); } else { out.push(''); } if (!this.environment.isSimple) { out.push(", buffer = " + this.initializeBuffer()); } else { out.push(""); } // track the last context pushed into place to allow skipping the // getContext opcode when it would be a noop this.lastContext = 0; this.source = out; }, createFunctionContext: function(asObject) { var locals = this.stackVars.concat(this.registers.list); if(locals.length > 0) { this.source[1] = this.source[1] + ", " + locals.join(", "); } // Generate minimizer alias mappings if (!this.isChild) { for (var alias in this.context.aliases) { if (this.context.aliases.hasOwnProperty(alias)) { this.source[1] = this.source[1] + ', ' + alias + '=' + this.context.aliases[alias]; } } } if (this.source[1]) { this.source[1] = "var " + this.source[1].substring(2) + ";"; } // Merge children if (!this.isChild) { this.source[1] += '\n' + this.context.programs.join('\n') + '\n'; } if (!this.environment.isSimple) { this.pushSource("return buffer;"); } var params = this.isChild ? ["depth0", "data"] : ["Handlebars", "depth0", "helpers", "partials", "data"]; for(var i=0, l=this.environment.depths.list.length; i<l; i++) { params.push("depth" + this.environment.depths.list[i]); } // Perform a second pass over the output to merge content when possible var source = this.mergeSource(); if (!this.isChild) { source = this.compilerInfo()+source; } if (asObject) { params.push(source); return Function.apply(this, params); } else { var functionSource = 'function ' + (this.name || '') + '(' + params.join(',') + ') {\n ' + source + '}'; log('debug', functionSource + "\n\n"); return functionSource; } }, mergeSource: function() { // WARN: We are not handling the case where buffer is still populated as the source should // not have buffer append operations as their final action. var source = '', buffer; for (var i = 0, len = this.source.length; i < len; i++) { var line = this.source[i]; if (line.appendToBuffer) { if (buffer) { buffer = buffer + '\n + ' + line.content; } else { buffer = line.content; } } else { if (buffer) { source += 'buffer += ' + buffer + ';\n '; buffer = undefined; } source += line + '\n '; } } return source; }, // [blockValue] // // On stack, before: hash, inverse, program, value // On stack, after: return value of blockHelperMissing // // The purpose of this opcode is to take a block of the form // `{{#foo}}...{{/foo}}`, resolve the value of `foo`, and // replace it on the stack with the result of properly // invoking blockHelperMissing. blockValue: function() { this.context.aliases.blockHelperMissing = 'helpers.blockHelperMissing'; var params = ["depth0"]; this.setupParams(0, params); this.replaceStack(function(current) { params.splice(1, 0, current); return "blockHelperMissing.call(" + params.join(", ") + ")"; }); }, // [ambiguousBlockValue] // // On stack, before: hash, inverse, program, value // Compiler value, before: lastHelper=value of last found helper, if any // On stack, after, if no lastHelper: same as [blockValue] // On stack, after, if lastHelper: value ambiguousBlockValue: function() { this.context.aliases.blockHelperMissing = 'helpers.blockHelperMissing'; var params = ["depth0"]; this.setupParams(0, params); var current = this.topStack(); params.splice(1, 0, current); this.pushSource("if (!" + this.lastHelper + ") { " + current + " = blockHelperMissing.call(" + params.join(", ") + "); }"); }, // [appendContent] // // On stack, before: ... // On stack, after: ... // // Appends the string value of `content` to the current buffer appendContent: function(content) { if (this.pendingContent) { content = this.pendingContent + content; } if (this.stripNext) { content = content.replace(/^\s+/, ''); } this.pendingContent = content; }, // [strip] // // On stack, before: ... // On stack, after: ... // // Removes any trailing whitespace from the prior content node and flags // the next operation for stripping if it is a content node. strip: function() { if (this.pendingContent) { this.pendingContent = this.pendingContent.replace(/\s+$/, ''); } this.stripNext = 'strip'; }, // [append] // // On stack, before: value, ... // On stack, after: ... // // Coerces `value` to a String and appends it to the current buffer. // // If `value` is truthy, or 0, it is coerced into a string and appended // Otherwise, the empty string is appended append: function() { // Force anything that is inlined onto the stack so we don't have duplication // when we examine local this.flushInline(); var local = this.popStack(); this.pushSource("if(" + local + " || " + local + " === 0) { " + this.appendToBuffer(local) + " }"); if (this.environment.isSimple) { this.pushSource("else { " + this.appendToBuffer("''") + " }"); } }, // [appendEscaped] // // On stack, before: value, ... // On stack, after: ... // // Escape `value` and append it to the buffer appendEscaped: function() { this.context.aliases.escapeExpression = 'this.escapeExpression'; this.pushSource(this.appendToBuffer("escapeExpression(" + this.popStack() + ")")); }, // [getContext] // // On stack, before: ... // On stack, after: ... // Compiler value, after: lastContext=depth // // Set the value of the `lastContext` compiler value to the depth getContext: function(depth) { if(this.lastContext !== depth) { this.lastContext = depth; } }, // [lookupOnContext] // // On stack, before: ... // On stack, after: currentContext[name], ... // // Looks up the value of `name` on the current context and pushes // it onto the stack. lookupOnContext: function(name) { this.push(this.nameLookup('depth' + this.lastContext, name, 'context')); }, // [pushContext] // // On stack, before: ... // On stack, after: currentContext, ... // // Pushes the value of the current context onto the stack. pushContext: function() { this.pushStackLiteral('depth' + this.lastContext); }, // [resolvePossibleLambda] // // On stack, before: value, ... // On stack, after: resolved value, ... // // If the `value` is a lambda, replace it on the stack by // the return value of the lambda resolvePossibleLambda: function() { this.context.aliases.functionType = '"function"'; this.replaceStack(function(current) { return "typeof " + current + " === functionType ? " + current + ".apply(depth0) : " + current; }); }, // [lookup] // // On stack, before: value, ... // On stack, after: value[name], ... // // Replace the value on the stack with the result of looking // up `name` on `value` lookup: function(name) { this.replaceStack(function(current) { return current + " == null || " + current + " === false ? " + current + " : " + this.nameLookup(current, name, 'context'); }); }, // [lookupData] // // On stack, before: ... // On stack, after: data, ... // // Push the data lookup operator lookupData: function() { this.pushStackLiteral('data'); }, // [pushStringParam] // // On stack, before: ... // On stack, after: string, currentContext, ... // // This opcode is designed for use in string mode, which // provides the string value of a parameter along with its // depth rather than resolving it immediately. pushStringParam: function(string, type) { this.pushStackLiteral('depth' + this.lastContext); this.pushString(type); // If it's a subexpression, the string result // will be pushed after this opcode. if (type !== 'sexpr') { if (typeof string === 'string') { this.pushString(string); } else { this.pushStackLiteral(string); } } }, emptyHash: function() { this.pushStackLiteral('{}'); if (this.options.stringParams) { this.push('{}'); // hashContexts this.push('{}'); // hashTypes } }, pushHash: function() { if (this.hash) { this.hashes.push(this.hash); } this.hash = {values: [], types: [], contexts: []}; }, popHash: function() { var hash = this.hash; this.hash = this.hashes.pop(); if (this.options.stringParams) { this.push('{' + hash.contexts.join(',') + '}'); this.push('{' + hash.types.join(',') + '}'); } this.push('{\n ' + hash.values.join(',\n ') + '\n }'); }, // [pushString] // // On stack, before: ... // On stack, after: quotedString(string), ... // // Push a quoted version of `string` onto the stack pushString: function(string) { this.pushStackLiteral(this.quotedString(string)); }, // [push] // // On stack, before: ... // On stack, after: expr, ... // // Push an expression onto the stack push: function(expr) { this.inlineStack.push(expr); return expr; }, // [pushLiteral] // // On stack, before: ... // On stack, after: value, ... // // Pushes a value onto the stack. This operation prevents // the compiler from creating a temporary variable to hold // it. pushLiteral: function(value) { this.pushStackLiteral(value); }, // [pushProgram] // // On stack, before: ... // On stack, after: program(guid), ... // // Push a program expression onto the stack. This takes // a compile-time guid and converts it into a runtime-accessible // expression. pushProgram: function(guid) { if (guid != null) { this.pushStackLiteral(this.programExpression(guid)); } else { this.pushStackLiteral(null); } }, // [invokeHelper] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of helper invocation // // Pops off the helper's parameters, invokes the helper, // and pushes the helper's return value onto the stack. // // If the helper is not found, `helperMissing` is called. invokeHelper: function(paramSize, name, isRoot) { this.context.aliases.helperMissing = 'helpers.helperMissing'; this.useRegister('helper'); var helper = this.lastHelper = this.setupHelper(paramSize, name, true); var nonHelper = this.nameLookup('depth' + this.lastContext, name, 'context'); var lookup = 'helper = ' + helper.name + ' || ' + nonHelper; if (helper.paramsInit) { lookup += ',' + helper.paramsInit; } this.push( '(' + lookup + ',helper ' + '? helper.call(' + helper.callParams + ') ' + ': helperMissing.call(' + helper.helperMissingParams + '))'); // Always flush subexpressions. This is both to prevent the compounding size issue that // occurs when the code has to be duplicated for inlining and also to prevent errors // due to the incorrect options object being passed due to the shared register. if (!isRoot) { this.flushInline(); } }, // [invokeKnownHelper] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of helper invocation // // This operation is used when the helper is known to exist, // so a `helperMissing` fallback is not required. invokeKnownHelper: function(paramSize, name) { var helper = this.setupHelper(paramSize, name); this.push(helper.name + ".call(" + helper.callParams + ")"); }, // [invokeAmbiguous] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of disambiguation // // This operation is used when an expression like `{{foo}}` // is provided, but we don't know at compile-time whether it // is a helper or a path. // // This operation emits more code than the other options, // and can be avoided by passing the `knownHelpers` and // `knownHelpersOnly` flags at compile-time. invokeAmbiguous: function(name, helperCall) { this.context.aliases.functionType = '"function"'; this.useRegister('helper'); this.emptyHash(); var helper = this.setupHelper(0, name, helperCall); var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper'); var nonHelper = this.nameLookup('depth' + this.lastContext, name, 'context'); var nextStack = this.nextStack(); if (helper.paramsInit) { this.pushSource(helper.paramsInit); } this.pushSource('if (helper = ' + helperName + ') { ' + nextStack + ' = helper.call(' + helper.callParams + '); }'); this.pushSource('else { helper = ' + nonHelper + '; ' + nextStack + ' = typeof helper === functionType ? helper.call(' + helper.callParams + ') : helper; }'); }, // [invokePartial] // // On stack, before: context, ... // On stack after: result of partial invocation // // This operation pops off a context, invokes a partial with that context, // and pushes the result of the invocation back. invokePartial: function(name) { var params = [this.nameLookup('partials', name, 'partial'), "'" + name + "'", this.popStack(), "helpers", "partials"]; if (this.options.data) { params.push("data"); } this.context.aliases.self = "this"; this.push("self.invokePartial(" + params.join(", ") + ")"); }, // [assignToHash] // // On stack, before: value, hash, ... // On stack, after: hash, ... // // Pops a value and hash off the stack, assigns `hash[key] = value` // and pushes the hash back onto the stack. assignToHash: function(key) { var value = this.popStack(), context, type; if (this.options.stringParams) { type = this.popStack(); context = this.popStack(); } var hash = this.hash; if (context) { hash.contexts.push("'" + key + "': " + context); } if (type) { hash.types.push("'" + key + "': " + type); } hash.values.push("'" + key + "': (" + value + ")"); }, // HELPERS compiler: JavaScriptCompiler, compileChildren: function(environment, options) { var children = environment.children, child, compiler; for(var i=0, l=children.length; i<l; i++) { child = children[i]; compiler = new this.compiler(); var index = this.matchExistingProgram(child); if (index == null) { this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children index = this.context.programs.length; child.index = index; child.name = 'program' + index; this.context.programs[index] = compiler.compile(child, options, this.context); this.context.environments[index] = child; } else { child.index = index; child.name = 'program' + index; } } }, matchExistingProgram: function(child) { for (var i = 0, len = this.context.environments.length; i < len; i++) { var environment = this.context.environments[i]; if (environment && environment.equals(child)) { return i; } } }, programExpression: function(guid) { this.context.aliases.self = "this"; if(guid == null) { return "self.noop"; } var child = this.environment.children[guid], depths = child.depths.list, depth; var programParams = [child.index, child.name, "data"]; for(var i=0, l = depths.length; i<l; i++) { depth = depths[i]; if(depth === 1) { programParams.push("depth0"); } else { programParams.push("depth" + (depth - 1)); } } return (depths.length === 0 ? "self.program(" : "self.programWithDepth(") + programParams.join(", ") + ")"; }, register: function(name, val) { this.useRegister(name); this.pushSource(name + " = " + val + ";"); }, useRegister: function(name) { if(!this.registers[name]) { this.registers[name] = true; this.registers.list.push(name); } }, pushStackLiteral: function(item) { return this.push(new Literal(item)); }, pushSource: function(source) { if (this.pendingContent) { this.source.push(this.appendToBuffer(this.quotedString(this.pendingContent))); this.pendingContent = undefined; } if (source) { this.source.push(source); } }, pushStack: function(item) { this.flushInline(); var stack = this.incrStack(); if (item) { this.pushSource(stack + " = " + item + ";"); } this.compileStack.push(stack); return stack; }, replaceStack: function(callback) { var prefix = '', inline = this.isInline(), stack, createdStack, usedLiteral; // If we are currently inline then we want to merge the inline statement into the // replacement statement via ',' if (inline) { var top = this.popStack(true); if (top instanceof Literal) { // Literals do not need to be inlined stack = top.value; usedLiteral = true; } else { // Get or create the current stack name for use by the inline createdStack = !this.stackSlot; var name = !createdStack ? this.topStackName() : this.incrStack(); prefix = '(' + this.push(name) + ' = ' + top + '),'; stack = this.topStack(); } } else { stack = this.topStack(); } var item = callback.call(this, stack); if (inline) { if (!usedLiteral) { this.popStack(); } if (createdStack) { this.stackSlot--; } this.push('(' + prefix + item + ')'); } else { // Prevent modification of the context depth variable. Through replaceStack if (!/^stack/.test(stack)) { stack = this.nextStack(); } this.pushSource(stack + " = (" + prefix + item + ");"); } return stack; }, nextStack: function() { return this.pushStack(); }, incrStack: function() { this.stackSlot++; if(this.stackSlot > this.stackVars.length) { this.stackVars.push("stack" + this.stackSlot); } return this.topStackName(); }, topStackName: function() { return "stack" + this.stackSlot; }, flushInline: function() { var inlineStack = this.inlineStack; if (inlineStack.length) { this.inlineStack = []; for (var i = 0, len = inlineStack.length; i < len; i++) { var entry = inlineStack[i]; if (entry instanceof Literal) { this.compileStack.push(entry); } else { this.pushStack(entry); } } } }, isInline: function() { return this.inlineStack.length; }, popStack: function(wrapped) { var inline = this.isInline(), item = (inline ? this.inlineStack : this.compileStack).pop(); if (!wrapped && (item instanceof Literal)) { return item.value; } else { if (!inline) { if (!this.stackSlot) { throw new Exception('Invalid stack pop'); } this.stackSlot--; } return item; } }, topStack: function(wrapped) { var stack = (this.isInline() ? this.inlineStack : this.compileStack), item = stack[stack.length - 1]; if (!wrapped && (item instanceof Literal)) { return item.value; } else { return item; } }, quotedString: function(str) { return '"' + str .replace(/\\/g, '\\\\') .replace(/"/g, '\\"') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4 .replace(/\u2029/g, '\\u2029') + '"'; }, setupHelper: function(paramSize, name, missingParams) { var params = [], paramsInit = this.setupParams(paramSize, params, missingParams); var foundHelper = this.nameLookup('helpers', name, 'helper'); return { params: params, paramsInit: paramsInit, name: foundHelper, callParams: ["depth0"].concat(params).join(", "), helperMissingParams: missingParams && ["depth0", this.quotedString(name)].concat(params).join(", ") }; }, setupOptions: function(paramSize, params) { var options = [], contexts = [], types = [], param, inverse, program; options.push("hash:" + this.popStack()); if (this.options.stringParams) { options.push("hashTypes:" + this.popStack()); options.push("hashContexts:" + this.popStack()); } inverse = this.popStack(); program = this.popStack(); // Avoid setting fn and inverse if neither are set. This allows // helpers to do a check for `if (options.fn)` if (program || inverse) { if (!program) { this.context.aliases.self = "this"; program = "self.noop"; } if (!inverse) { this.context.aliases.self = "this"; inverse = "self.noop"; } options.push("inverse:" + inverse); options.push("fn:" + program); } for(var i=0; i<paramSize; i++) { param = this.popStack(); params.push(param); if(this.options.stringParams) { types.push(this.popStack()); contexts.push(this.popStack()); } } if (this.options.stringParams) { options.push("contexts:[" + contexts.join(",") + "]"); options.push("types:[" + types.join(",") + "]"); } if(this.options.data) { options.push("data:data"); } return options; }, // the params and contexts arguments are passed in arrays // to fill in setupParams: function(paramSize, params, useRegister) { var options = '{' + this.setupOptions(paramSize, params).join(',') + '}'; if (useRegister) { this.useRegister('options'); params.push('options'); return 'options=' + options; } else { params.push(options); return ''; } } }; var reservedWords = ( "break else new var" + " case finally return void" + " catch for switch while" + " continue function this with" + " default if throw" + " delete in try" + " do instanceof typeof" + " abstract enum int short" + " boolean export interface static" + " byte extends long super" + " char final native synchronized" + " class float package throws" + " const goto private transient" + " debugger implements protected volatile" + " double import public let yield" ).split(" "); var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {}; for(var i=0, l=reservedWords.length; i<l; i++) { compilerWords[reservedWords[i]] = true; } JavaScriptCompiler.isValidJavaScriptVariableName = function(name) { if(!JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name)) { return true; } return false; }; __exports__ = JavaScriptCompiler; return __exports__; })(__module2__, __module5__); // handlebars.js var __module0__ = (function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__) { "use strict"; var __exports__; /*globals Handlebars: true */ var Handlebars = __dependency1__; // Compiler imports var AST = __dependency2__; var Parser = __dependency3__.parser; var parse = __dependency3__.parse; var Compiler = __dependency4__.Compiler; var compile = __dependency4__.compile; var precompile = __dependency4__.precompile; var JavaScriptCompiler = __dependency5__; var _create = Handlebars.create; var create = function() { var hb = _create(); hb.compile = function(input, options) { return compile(input, options, hb); }; hb.precompile = function (input, options) { return precompile(input, options, hb); }; hb.AST = AST; hb.Compiler = Compiler; hb.JavaScriptCompiler = JavaScriptCompiler; hb.Parser = Parser; hb.parse = parse; return hb; }; Handlebars = create(); Handlebars.create = create; __exports__ = Handlebars; return __exports__; })(__module1__, __module7__, __module8__, __module10__, __module11__); return __module0__; })(); /*! Hammer.JS - v2.0.2 - 2014-07-28 * http://hammerjs.github.io/ * * Copyright (c) 2014 Jorik Tangelder <j.tangelder@gmail.com>; * Licensed under the MIT license */ !function(a,b,c,d){"use strict";function e(a,b,c){return setTimeout(k(a,c),b)}function f(a,b,c){return Array.isArray(a)?(g(a,c[b],c),!0):!1}function g(a,b,c){var e,f;if(a)if(a.forEach)a.forEach(b,c);else if(a.length!==d)for(e=0,f=a.length;f>e;e++)b.call(c,a[e],e,a);else for(e in a)a.hasOwnProperty(e)&&b.call(c,a[e],e,a)}function h(a,b,c){for(var e=Object.keys(b),f=0,g=e.length;g>f;f++)(!c||c&&a[e[f]]===d)&&(a[e[f]]=b[e[f]]);return a}function i(a,b){return h(a,b,!0)}function j(a,b,c){var d,e=b.prototype;d=a.prototype=Object.create(e),d.constructor=a,d._super=e,c&&h(d,c)}function k(a,b){return function(){return a.apply(b,arguments)}}function l(a,b){return typeof a==hb?a.apply(b?b[0]||d:d,b):a}function m(a,b){return a===d?b:a}function n(a,b,c){g(r(b),function(b){a.addEventListener(b,c,!1)})}function o(a,b,c){g(r(b),function(b){a.removeEventListener(b,c,!1)})}function p(a,b){for(;a;){if(a==b)return!0;a=a.parentNode}return!1}function q(a,b){return a.indexOf(b)>-1}function r(a){return a.trim().split(/\s+/g)}function s(a,b,c){if(a.indexOf&&!c)return a.indexOf(b);for(var d=0,e=a.length;e>d;d++)if(c&&a[d][c]==b||!c&&a[d]===b)return d;return-1}function t(a){return Array.prototype.slice.call(a,0)}function u(a,b,c){for(var d=[],e=[],f=0,g=a.length;g>f;f++){var h=b?a[f][b]:a[f];s(e,h)<0&&d.push(a[f]),e[f]=h}return c&&(d=b?d.sort(function(a,c){return a[b]>c[b]}):d.sort()),d}function v(a,b){for(var c,e,f=b[0].toUpperCase()+b.slice(1),g=0,h=fb.length;h>g;g++)if(c=fb[g],e=c?c+f:b,e in a)return e;return d}function w(){return lb++}function x(b,c){var d=this;this.manager=b,this.callback=c,this.element=b.element,this.target=b.options.inputTarget,this.domHandler=function(a){l(b.options.enable,[b])&&d.handler(a)},this.evEl&&n(this.element,this.evEl,this.domHandler),this.evTarget&&n(this.target,this.evTarget,this.domHandler),this.evWin&&n(a,this.evWin,this.domHandler)}function y(a){var b;return new(b=ob?M:pb?N:nb?P:L)(a,z)}function z(a,b,c){var d=c.pointers.length,e=c.changedPointers.length,f=b&vb&&d-e===0,g=b&(xb|yb)&&d-e===0;c.isFirst=!!f,c.isFinal=!!g,f&&(a.session={}),c.eventType=b,A(a,c),a.emit("hammer.input",c),a.recognize(c),a.session.prevInput=c}function A(a,b){var c=a.session,d=b.pointers,e=d.length;c.firstInput||(c.firstInput=D(b)),e>1&&!c.firstMultiple?c.firstMultiple=D(b):1===e&&(c.firstMultiple=!1);var f=c.firstInput,g=c.firstMultiple,h=g?g.center:f.center,i=b.center=E(d);b.timeStamp=kb(),b.deltaTime=b.timeStamp-f.timeStamp,b.angle=I(h,i),b.distance=H(h,i),B(c,b),b.offsetDirection=G(b.deltaX,b.deltaY),b.scale=g?K(g.pointers,d):1,b.rotation=g?J(g.pointers,d):0,C(c,b);var j=a.element;p(b.srcEvent.target,j)&&(j=b.srcEvent.target),b.target=j}function B(a,b){var c=b.center,d=a.offsetDelta||{},e=a.prevDelta||{},f=a.prevInput||{};(b.eventType===vb||f.eventType===xb)&&(e=a.prevDelta={x:f.deltaX||0,y:f.deltaY||0},d=a.offsetDelta={x:c.x,y:c.y}),b.deltaX=e.x+(c.x-d.x),b.deltaY=e.y+(c.y-d.y)}function C(a,b){var c,e,f,g,h=a.lastInterval||b,i=b.timeStamp-h.timeStamp;if(b.eventType!=yb&&(i>ub||h.velocity===d)){var j=h.deltaX-b.deltaX,k=h.deltaY-b.deltaY,l=F(i,j,k);e=l.x,f=l.y,c=jb(l.x)>jb(l.y)?l.x:l.y,g=G(j,k),a.lastInterval=b}else c=h.velocity,e=h.velocityX,f=h.velocityY,g=h.direction;b.velocity=c,b.velocityX=e,b.velocityY=f,b.direction=g}function D(a){for(var b=[],c=0;c<a.pointers.length;c++)b[c]={clientX:ib(a.pointers[c].clientX),clientY:ib(a.pointers[c].clientY)};return{timeStamp:kb(),pointers:b,center:E(b),deltaX:a.deltaX,deltaY:a.deltaY}}function E(a){var b=a.length;if(1===b)return{x:ib(a[0].clientX),y:ib(a[0].clientY)};for(var c=0,d=0,e=0;b>e;e++)c+=a[e].clientX,d+=a[e].clientY;return{x:ib(c/b),y:ib(d/b)}}function F(a,b,c){return{x:b/a||0,y:c/a||0}}function G(a,b){return a===b?zb:jb(a)>=jb(b)?a>0?Ab:Bb:b>0?Cb:Db}function H(a,b,c){c||(c=Hb);var d=b[c[0]]-a[c[0]],e=b[c[1]]-a[c[1]];return Math.sqrt(d*d+e*e)}function I(a,b,c){c||(c=Hb);var d=b[c[0]]-a[c[0]],e=b[c[1]]-a[c[1]];return 180*Math.atan2(e,d)/Math.PI}function J(a,b){return I(b[1],b[0],Ib)-I(a[1],a[0],Ib)}function K(a,b){return H(b[0],b[1],Ib)/H(a[0],a[1],Ib)}function L(){this.evEl=Kb,this.evWin=Lb,this.allow=!0,this.pressed=!1,x.apply(this,arguments)}function M(){this.evEl=Ob,this.evWin=Pb,x.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}function N(){this.evTarget=Rb,this.targetIds={},x.apply(this,arguments)}function O(a,b){var c=t(a.touches),d=this.targetIds;if(b&(vb|wb)&&1===c.length)return d[c[0].identifier]=!0,[c,c];var e,f,g=t(a.targetTouches),h=t(a.changedTouches),i=[];if(b===vb)for(e=0,f=g.length;f>e;e++)d[g[e].identifier]=!0;for(e=0,f=h.length;f>e;e++)d[h[e].identifier]&&i.push(h[e]),b&(xb|yb)&&delete d[h[e].identifier];return i.length?[u(g.concat(i),"identifier",!0),i]:void 0}function P(){x.apply(this,arguments);var a=k(this.handler,this);this.touch=new N(this.manager,a),this.mouse=new L(this.manager,a)}function Q(a,b){this.manager=a,this.set(b)}function R(a){if(q(a,Xb))return Xb;var b=q(a,Yb),c=q(a,Zb);return b&&c?Yb+" "+Zb:b||c?b?Yb:Zb:q(a,Wb)?Wb:Vb}function S(a){this.id=w(),this.manager=null,this.options=i(a||{},this.defaults),this.options.enable=m(this.options.enable,!0),this.state=$b,this.simultaneous={},this.requireFail=[]}function T(a){return a&dc?"cancel":a&bc?"end":a&ac?"move":a&_b?"start":""}function U(a){return a==Db?"down":a==Cb?"up":a==Ab?"left":a==Bb?"right":""}function V(a,b){var c=b.manager;return c?c.get(a):a}function W(){S.apply(this,arguments)}function X(){W.apply(this,arguments),this.pX=null,this.pY=null}function Y(){W.apply(this,arguments)}function Z(){S.apply(this,arguments),this._timer=null,this._input=null}function $(){W.apply(this,arguments)}function _(){W.apply(this,arguments)}function ab(){S.apply(this,arguments),this.pTime=!1,this.pCenter=!1,this._timer=null,this._input=null,this.count=0}function bb(a,b){return b=b||{},b.recognizers=m(b.recognizers,bb.defaults.preset),new cb(a,b)}function cb(a,b){b=b||{},this.options=i(b,bb.defaults),this.options.inputTarget=this.options.inputTarget||a,this.handlers={},this.session={},this.recognizers=[],this.element=a,this.input=y(this),this.touchAction=new Q(this,this.options.touchAction),db(this,!0),g(b.recognizers,function(a){var b=this.add(new a[0](a[1]));a[2]&&b.recognizeWith(a[2]),a[3]&&b.requireFailure(a[2])},this)}function db(a,b){var c=a.element;g(a.options.cssProps,function(a,d){c.style[v(c.style,d)]=b?a:""})}function eb(a,c){var d=b.createEvent("Event");d.initEvent(a,!0,!0),d.gesture=c,c.target.dispatchEvent(d)}var fb=["","webkit","moz","MS","ms","o"],gb=b.createElement("div"),hb="function",ib=Math.round,jb=Math.abs,kb=Date.now,lb=1,mb=/mobile|tablet|ip(ad|hone|od)|android/i,nb="ontouchstart"in a,ob=v(a,"PointerEvent")!==d,pb=nb&&mb.test(navigator.userAgent),qb="touch",rb="pen",sb="mouse",tb="kinect",ub=25,vb=1,wb=2,xb=4,yb=8,zb=1,Ab=2,Bb=4,Cb=8,Db=16,Eb=Ab|Bb,Fb=Cb|Db,Gb=Eb|Fb,Hb=["x","y"],Ib=["clientX","clientY"];x.prototype={handler:function(){},destroy:function(){this.evEl&&o(this.element,this.evEl,this.domHandler),this.evTarget&&o(this.target,this.evTarget,this.domHandler),this.evWin&&o(a,this.evWin,this.domHandler)}};var Jb={mousedown:vb,mousemove:wb,mouseup:xb},Kb="mousedown",Lb="mousemove mouseup";j(L,x,{handler:function(a){var b=Jb[a.type];b&vb&&0===a.button&&(this.pressed=!0),b&wb&&1!==a.which&&(b=xb),this.pressed&&this.allow&&(b&xb&&(this.pressed=!1),this.callback(this.manager,b,{pointers:[a],changedPointers:[a],pointerType:sb,srcEvent:a}))}});var Mb={pointerdown:vb,pointermove:wb,pointerup:xb,pointercancel:yb,pointerout:yb},Nb={2:qb,3:rb,4:sb,5:tb},Ob="pointerdown",Pb="pointermove pointerup pointercancel";a.MSPointerEvent&&(Ob="MSPointerDown",Pb="MSPointerMove MSPointerUp MSPointerCancel"),j(M,x,{handler:function(a){var b=this.store,c=!1,d=a.type.toLowerCase().replace("ms",""),e=Mb[d],f=Nb[a.pointerType]||a.pointerType,g=f==qb;e&vb&&(0===a.button||g)?b.push(a):e&(xb|yb)&&(c=!0);var h=s(b,a.pointerId,"pointerId");0>h||(b[h]=a,this.callback(this.manager,e,{pointers:b,changedPointers:[a],pointerType:f,srcEvent:a}),c&&b.splice(h,1))}});var Qb={touchstart:vb,touchmove:wb,touchend:xb,touchcancel:yb},Rb="touchstart touchmove touchend touchcancel";j(N,x,{handler:function(a){var b=Qb[a.type],c=O.call(this,a,b);c&&this.callback(this.manager,b,{pointers:c[0],changedPointers:c[1],pointerType:qb,srcEvent:a})}}),j(P,x,{handler:function(a,b,c){var d=c.pointerType==qb,e=c.pointerType==sb;if(d)this.mouse.allow=!1;else if(e&&!this.mouse.allow)return;b&(xb|yb)&&(this.mouse.allow=!0),this.callback(a,b,c)},destroy:function(){this.touch.destroy(),this.mouse.destroy()}});var Sb=v(gb.style,"touchAction"),Tb=Sb!==d,Ub="compute",Vb="auto",Wb="manipulation",Xb="none",Yb="pan-x",Zb="pan-y";Q.prototype={set:function(a){a==Ub&&(a=this.compute()),Tb&&(this.manager.element.style[Sb]=a),this.actions=a.toLowerCase().trim()},update:function(){this.set(this.manager.options.touchAction)},compute:function(){var a=[];return g(this.manager.recognizers,function(b){l(b.options.enable,[b])&&(a=a.concat(b.getTouchAction()))}),R(a.join(" "))},preventDefaults:function(a){if(!Tb){var b=a.srcEvent,c=a.offsetDirection;if(this.manager.session.prevented)return void b.preventDefault();var d=this.actions,e=q(d,Xb),f=q(d,Zb),g=q(d,Yb);return e||f&&g||f&&c&Eb||g&&c&Fb?this.preventSrc(b):void 0}},preventSrc:function(a){this.manager.session.prevented=!0,a.preventDefault()}};var $b=1,_b=2,ac=4,bc=8,cc=bc,dc=16,ec=32;S.prototype={defaults:{},set:function(a){return h(this.options,a),this.manager&&this.manager.touchAction.update(),this},recognizeWith:function(a){if(f(a,"recognizeWith",this))return this;var b=this.simultaneous;return a=V(a,this),b[a.id]||(b[a.id]=a,a.recognizeWith(this)),this},dropRecognizeWith:function(a){return f(a,"dropRecognizeWith",this)?this:(a=V(a,this),delete this.simultaneous[a.id],this)},requireFailure:function(a){if(f(a,"requireFailure",this))return this;var b=this.requireFail;return a=V(a,this),-1===s(b,a)&&(b.push(a),a.requireFailure(this)),this},dropRequireFailure:function(a){if(f(a,"dropRequireFailure",this))return this;a=V(a,this);var b=s(this.requireFail,a);return b>-1&&this.requireFail.splice(b,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(a){return!!this.simultaneous[a.id]},emit:function(a){function b(b){c.manager.emit(c.options.event+(b?T(d):""),a)}var c=this,d=this.state;bc>d&&b(!0),b(),d>=bc&&b(!0)},tryEmit:function(a){return this.canEmit()?this.emit(a):void(this.state=ec)},canEmit:function(){for(var a=0;a<this.requireFail.length;a++)if(!(this.requireFail[a].state&(ec|$b)))return!1;return!0},recognize:function(a){var b=h({},a);return l(this.options.enable,[this,b])?(this.state&(cc|dc|ec)&&(this.state=$b),this.state=this.process(b),void(this.state&(_b|ac|bc|dc)&&this.tryEmit(b))):(this.reset(),void(this.state=ec))},process:function(){},getTouchAction:function(){},reset:function(){}},j(W,S,{defaults:{pointers:1},attrTest:function(a){var b=this.options.pointers;return 0===b||a.pointers.length===b},process:function(a){var b=this.state,c=a.eventType,d=b&(_b|ac),e=this.attrTest(a);return d&&(c&yb||!e)?b|dc:d||e?c&xb?b|bc:b&_b?b|ac:_b:ec}}),j(X,W,{defaults:{event:"pan",threshold:10,pointers:1,direction:Gb},getTouchAction:function(){var a=this.options.direction;if(a===Gb)return[Xb];var b=[];return a&Eb&&b.push(Zb),a&Fb&&b.push(Yb),b},directionTest:function(a){var b=this.options,c=!0,d=a.distance,e=a.direction,f=a.deltaX,g=a.deltaY;return e&b.direction||(b.direction&Eb?(e=0===f?zb:0>f?Ab:Bb,c=f!=this.pX,d=Math.abs(a.deltaX)):(e=0===g?zb:0>g?Cb:Db,c=g!=this.pY,d=Math.abs(a.deltaY))),a.direction=e,c&&d>b.threshold&&e&b.direction},attrTest:function(a){return W.prototype.attrTest.call(this,a)&&(this.state&_b||!(this.state&_b)&&this.directionTest(a))},emit:function(a){this.pX=a.deltaX,this.pY=a.deltaY;var b=U(a.direction);b&&this.manager.emit(this.options.event+b,a),this._super.emit.call(this,a)}}),j(Y,W,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[Xb]},attrTest:function(a){return this._super.attrTest.call(this,a)&&(Math.abs(a.scale-1)>this.options.threshold||this.state&_b)},emit:function(a){if(this._super.emit.call(this,a),1!==a.scale){var b=a.scale<1?"in":"out";this.manager.emit(this.options.event+b,a)}}}),j(Z,S,{defaults:{event:"press",pointers:1,time:500,threshold:5},getTouchAction:function(){return[Vb]},process:function(a){var b=this.options,c=a.pointers.length===b.pointers,d=a.distance<b.threshold,f=a.deltaTime>b.time;if(this._input=a,!d||!c||a.eventType&(xb|yb)&&!f)this.reset();else if(a.eventType&vb)this.reset(),this._timer=e(function(){this.state=cc,this.tryEmit()},b.time,this);else if(a.eventType&xb)return cc;return ec},reset:function(){clearTimeout(this._timer)},emit:function(a){this.state===cc&&(a&&a.eventType&xb?this.manager.emit(this.options.event+"up",a):(this._input.timeStamp=kb(),this.manager.emit(this.options.event,this._input)))}}),j($,W,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[Xb]},attrTest:function(a){return this._super.attrTest.call(this,a)&&(Math.abs(a.rotation)>this.options.threshold||this.state&_b)}}),j(_,W,{defaults:{event:"swipe",threshold:10,velocity:.65,direction:Eb|Fb,pointers:1},getTouchAction:function(){return X.prototype.getTouchAction.call(this)},attrTest:function(a){var b,c=this.options.direction;return c&(Eb|Fb)?b=a.velocity:c&Eb?b=a.velocityX:c&Fb&&(b=a.velocityY),this._super.attrTest.call(this,a)&&c&a.direction&&jb(b)>this.options.velocity&&a.eventType&xb},emit:function(a){var b=U(a.direction);b&&this.manager.emit(this.options.event+b,a),this.manager.emit(this.options.event,a)}}),j(ab,S,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:2,posThreshold:10},getTouchAction:function(){return[Wb]},process:function(a){var b=this.options,c=a.pointers.length===b.pointers,d=a.distance<b.threshold,f=a.deltaTime<b.time;if(this.reset(),a.eventType&vb&&0===this.count)return this.failTimeout();if(d&&f&&c){if(a.eventType!=xb)return this.failTimeout();var g=this.pTime?a.timeStamp-this.pTime<b.interval:!0,h=!this.pCenter||H(this.pCenter,a.center)<b.posThreshold;this.pTime=a.timeStamp,this.pCenter=a.center,h&&g?this.count+=1:this.count=1,this._input=a;var i=this.count%b.taps;if(0===i)return this.hasRequireFailures()?(this._timer=e(function(){this.state=cc,this.tryEmit()},b.interval,this),_b):cc}return ec},failTimeout:function(){return this._timer=e(function(){this.state=ec},this.options.interval,this),ec},reset:function(){clearTimeout(this._timer)},emit:function(){this.state==cc&&(this._input.tapCount=this.count,this.manager.emit(this.options.event,this._input))}}),bb.VERSION="2.0.2",bb.defaults={domEvents:!1,touchAction:Ub,inputTarget:null,enable:!0,preset:[[$,{enable:!1}],[Y,{enable:!1},["rotate"]],[_,{direction:Eb}],[X,{direction:Eb},["swipe"]],[ab],[ab,{event:"doubletap",taps:2},["tap"]],[Z]],cssProps:{userSelect:"none",touchSelect:"none",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}};var fc=1,gc=2;cb.prototype={set:function(a){return h(this.options,a),this},stop:function(a){this.session.stopped=a?gc:fc},recognize:function(a){var b=this.session;if(!b.stopped){this.touchAction.preventDefaults(a);var c,d=this.recognizers,e=b.curRecognizer;(!e||e&&e.state&cc)&&(e=b.curRecognizer=null);for(var f=0,g=d.length;g>f;f++)c=d[f],b.stopped===gc||e&&c!=e&&!c.canRecognizeWith(e)?c.reset():c.recognize(a),!e&&c.state&(_b|ac|bc)&&(e=b.curRecognizer=c)}},get:function(a){if(a instanceof S)return a;for(var b=this.recognizers,c=0;c<b.length;c++)if(b[c].options.event==a)return b[c];return null},add:function(a){if(f(a,"add",this))return this;var b=this.get(a.options.event);return b&&this.remove(b),this.recognizers.push(a),a.manager=this,this.touchAction.update(),a},remove:function(a){if(f(a,"remove",this))return this;var b=this.recognizers;return a=this.get(a),b.splice(s(b,a),1),this.touchAction.update(),this},on:function(a,b){var c=this.handlers;return g(r(a),function(a){c[a]=c[a]||[],c[a].push(b)}),this},off:function(a,b){var c=this.handlers;return g(r(a),function(a){b?c[a].splice(s(c[a],b),1):delete c[a]}),this},emit:function(a,b){this.options.domEvents&&eb(a,b);var c=this.handlers[a]&&this.handlers[a].slice();if(c&&c.length){b.type=a,b.preventDefault=function(){b.srcEvent.preventDefault()};for(var d=0,e=c.length;e>d;d++)c[d](b)}},destroy:function(){this.element&&db(this,!1),this.handlers={},this.session={},this.input.destroy(),this.element=null}},h(bb,{INPUT_START:vb,INPUT_MOVE:wb,INPUT_END:xb,INPUT_CANCEL:yb,STATE_POSSIBLE:$b,STATE_BEGAN:_b,STATE_CHANGED:ac,STATE_ENDED:bc,STATE_RECOGNIZED:cc,STATE_CANCELLED:dc,STATE_FAILED:ec,DIRECTION_NONE:zb,DIRECTION_LEFT:Ab,DIRECTION_RIGHT:Bb,DIRECTION_UP:Cb,DIRECTION_DOWN:Db,DIRECTION_HORIZONTAL:Eb,DIRECTION_VERTICAL:Fb,DIRECTION_ALL:Gb,Manager:cb,Input:x,TouchAction:Q,Recognizer:S,AttrRecognizer:W,Tap:ab,Pan:X,Swipe:_,Pinch:Y,Rotate:$,Press:Z,on:n,off:o,each:g,merge:i,extend:h,inherit:j,bindFn:k,prefixed:v}),typeof define==hb&&define.amd?define(function(){return bb}):"undefined"!=typeof module&&module.exports?module.exports=bb:a[c]=bb}(window,document,"Hammer"); //# sourceMappingURL=hammer.min.map (function($, Hammer, dataAttr) { function hammerify(el, options) { var $el = $(el); if(!$el.data(dataAttr)) { $el.data(dataAttr, new Hammer($el[0], options)); } } $.fn.hammer = function(options) { return this.each(function() { hammerify(this, options); }); }; // extend the emit method to also trigger jQuery events Hammer.Manager.prototype.emit = (function(originalEmit) { return function(type, data) { originalEmit.call(this, type, data); jQuery(this.element).triggerHandler({ type: type, gesture: data }); }; })(Hammer.Manager.prototype.emit); })(jQuery, Hammer, "hammer");
JavaScript
CL
2027a7df0fbbe0d6830f73a85437a49bc86f2617089c3e8f013f643979854330
import React from "react"; import Head from "next/head"; import Nav from "../components/Nav/nav"; import Header from "../components/Header/header"; import Production from "../components/Production/production"; import Goods from "../components/Goods/goods"; import style from '../styles/Home.module.sass' import FeedBackSubLink from "../components/FeedBackSubLink/feedBackSubLink"; import Contact from "../components/Contact/contact"; import Footer from "../components/Footer/footer"; const Index = () => { const goodImages = [ { src:'/images/battaryWhite.jpg', title:'Інфрачервоні обігрівачі', text:'Електричне низькотемпературне опалення' }, { src:'/images/battaryBrown.jpg', title:'Інфрачервоні обігрівачі', text:'Електричне низькотемпературне опалення' }, // { // src:'/images/image 5.jpg', // title:'Пенекрит', // text:'Пенекрит - водонепроникний матеріал для гідроізоляції швів та тріщин в бетонних конструкціях при виконанні гідроізоляційних робіт.' // }, // { // src:'/images/image 6.jpg', // title:'Пенетрон', // text:'Пенетрон - проникаюча гідроізоляція для бетону. Повищує показники водонепроникності , міцності та морозостійкості бетону.' // }, // { // src:'/images/image 7.jpg', // title:'Поліфлюід', // text:'Поліфлюід - являє собою безбарвний розчин глибокого проникнення для гідроізоляції пористих матеріалів. Він призначений для осушення поверхонь і захисту поверхонь від вологи , не утворює плівки на поверхні, не змінює колір матеріалів, він містить антізамерзающіе і самоочищаються елементи, володіє фунгіцидними властивостями.' // }, // { // src:'/images/larix.jpg', // title:'E - Larix', // text:'Засіб "E - Larix" прекрасно діє проти різних форм цвілі, дріжджових грибків з діючим дезинфікуючим ефектом. Представлений в механічному розпилювачі, який забезпечує легку маніпуляцію і полегшує ліквідацію цвілі навіть в важкодоступних місцях.' // } ] return ( <> <Head> <meta charSet="utf-8"/> <title>індіго експерт - професійне знищення грибка з стін, грибок на стіні</title> <meta name="msapplication-TileColor" content="#000000" /> <meta name="msapplication-TileImage" content="/ms-icon-144x144.png" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="знищення та виведення грибка, методи виведення грибком з стін, м. Івано-Франківськ індіго експерт" /> <meta name="keywords" content="знищення грибка Івано-Франківськ, вивести грибок на стіні, як здолати грибок, індіго експерт" /> <meta name="google-site-verification" content="hLL3b-cRafAUAClrSSzfIPZ3ALPEBbDYHI6Xk7t9sVY" /> <meta property="og:title" content="Індіго Експерт - професійне знищення грибка" /> <meta property="og:site_name" content="Індіго Експерт - професійне знищення грибка" /> <meta property="og:url" content="https://indigo-expert.com.ua/" /> <meta property="og:description" content="Знищення та виведення грибка, методи виведення грибком з стін, м. Івано-Франківськ індіго експерт" /> <meta property="og:image" content="https://scontent.fiev25-1.fna.fbcdn.net/v/t1.0-1/c210.0.540.540a/44539065_1132148556940440_3142985560302288896_n.jpg?_nc_cat=105&ccb=2&_nc_sid=dbb9e7&_nc_ohc=QNGaPiyKMRIAX9EP4_c&_nc_ht=scontent.fiev25-1.fna&oh=b18bc64c7d580efdfaaa920e863c02f0&oe=5FE38489" /> </Head> <header> <Nav /> <Header /> </header> <section id='second'> <Production /> </section> <section className={style.goodContainer} id='prod'> { goodImages.map((image, index) => { return <Goods key={index} item={image} /> }) } </section> <section> <FeedBackSubLink title={'клієнти які скористались нашими послугами'} pageLink={'/feedback'} linkText={'Перейти до відгуків'} /> </section> <section id='contact'> <div className={style.mapContactContainer}> <iframe width="100%" height="600" frameBorder="0" scrolling="no" marginHeight="0" marginWidth="0" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d8814.37353705389!2d24.723437097840808!3d48.94341355973691!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4730c1a30368a433%3A0x61a56ca6b122429c!2z0LLRg9C70LjRhtGPINCc0LDQutGB0LjQvNC-0LLQuNGH0LAsIDE1LCDQhtCy0LDQvdC-LdCk0YDQsNC90LrRltCy0YHRjNC6LCDQhtCy0LDQvdC-LdCk0YDQsNC90LrRltCy0YHRjNC60LAg0L7QsdC70LDRgdGC0YwsIDc2MDAw!5e0!3m2!1suk!2sua!4v1600546169529!5m2!1suk!2sua"/> <Contact /> </div> </section> <section> <FeedBackSubLink title={'Наші партнери'} pageLink={'/partner'} linkText={'Перейти до партнерів'} /> </section> <footer> <Footer /> </footer> </> ) } export default Index
JavaScript
CL
ff2e442e18c552cf1d3f535e78c04cc0da1f53da01151c913cbb8d46da22b920
/** * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var async = require("async"); var Changeset = require("ep_etherpad-lite/static/js/Changeset"); var padManager = require("../db/PadManager"); var ERR = require("async-stacktrace"); var _ = require('underscore'); var Security = require('ep_etherpad-lite/static/js/security'); var hooks = require('ep_etherpad-lite/static/js/pluginfw/hooks'); var eejs = require('ep_etherpad-lite/node/eejs'); var _analyzeLine = require('./ExportHelper')._analyzeLine; var _encodeWhitespace = require('./ExportHelper')._encodeWhitespace; function getPadHTML(pad, revNum, callback) { var atext = pad.atext; var html; async.waterfall([ // fetch revision atext function (callback) { if (revNum != undefined) { pad.getInternalRevisionAText(revNum, function (err, revisionAtext) { if(ERR(err, callback)) return; atext = revisionAtext; callback(); }); } else { callback(null); } }, // convert atext to html function (callback) { html = getHTMLFromAtext(pad, atext); callback(null); }], // run final callback function (err) { if(ERR(err, callback)) return; callback(null, html); }); } exports.getPadHTML = getPadHTML; exports.getHTMLFromAtext = getHTMLFromAtext; function getHTMLFromAtext(pad, atext, authorColors) { var apool = pad.apool(); var textLines = atext.text.slice(0, -1).split('\n'); var attribLines = Changeset.splitAttributionLines(atext.attribs, atext.text); var tags = ['h1', 'h2', 'strong', 'em', 'u', 's']; var props = ['heading1', 'heading2', 'bold', 'italic', 'underline', 'strikethrough']; // prepare tags stored as ['tag', true] to be exported hooks.aCallAll("exportHtmlAdditionalTags", pad, function(err, newProps){ newProps.forEach(function (propName, i){ tags.push(propName); props.push(propName); }); }); // prepare tags stored as ['tag', 'value'] to be exported. This will generate HTML // with tags like <span data-tag="value"> hooks.aCallAll("exportHtmlAdditionalTagsWithData", pad, function(err, newProps){ newProps.forEach(function (propName, i){ tags.push('span data-' + propName[0] + '="' + propName[1] + '"'); props.push(propName); }); }); // holds a map of used styling attributes (*1, *2, etc) in the apool // and maps them to an index in props // *3:2 -> the attribute *3 means strong // *2:5 -> the attribute *2 means s(trikethrough) var anumMap = {}; var css = ""; var stripDotFromAuthorID = function(id){ return id.replace(/\./g,'_'); }; if(authorColors){ css+="<style>\n"; for (var a in apool.numToAttrib) { var attr = apool.numToAttrib[a]; //skip non author attributes if(attr[0] === "author" && attr[1] !== ""){ //add to props array var propName = "author" + stripDotFromAuthorID(attr[1]); var newLength = props.push(propName); anumMap[a] = newLength -1; css+="." + propName + " {background-color: " + authorColors[attr[1]]+ "}\n"; } else if(attr[0] === "removed") { var propName = "removed"; var newLength = props.push(propName); anumMap[a] = newLength -1; css+=".removed {text-decoration: line-through; " + "-ms-filter:'progid:DXImageTransform.Microsoft.Alpha(Opacity=80)'; "+ "filter: alpha(opacity=80); "+ "opacity: 0.8; "+ "}\n"; } } css+="</style>"; } // iterates over all props(h1,h2,strong,...), checks if it is used in // this pad, and if yes puts its attrib id->props value into anumMap props.forEach(function (propName, i) { var attrib = [propName, true]; if (_.isArray(propName)) { // propName can be in the form of ['color', 'red'], // see hook exportHtmlAdditionalTagsWithData attrib = propName; } var propTrueNum = apool.putAttrib(attrib, true); if (propTrueNum >= 0) { anumMap[propTrueNum] = i; } }); function getLineHTML(text, attribs) { // Use order of tags (b/i/u) as order of nesting, for simplicity // and decent nesting. For example, // <b>Just bold<b> <b><i>Bold and italics</i></b> <i>Just italics</i> // becomes // <b>Just bold <i>Bold and italics</i></b> <i>Just italics</i> var taker = Changeset.stringIterator(text); var assem = Changeset.stringAssembler(); var openTags = []; function getSpanClassFor(i){ //return if author colors are disabled if (!authorColors) return false; var property = props[i]; // we are not insterested on properties in the form of ['color', 'red'], // see hook exportHtmlAdditionalTagsWithData if (_.isArray(property)) { return false; } if(property.substr(0,6) === "author"){ return stripDotFromAuthorID(property); } if(property === "removed"){ return "removed"; } return false; } // tags added by exportHtmlAdditionalTagsWithData will be exported as <span> with // data attributes function isSpanWithData(i){ var property = props[i]; return _.isArray(property); } function emitOpenTag(i) { openTags.unshift(i); var spanClass = getSpanClassFor(i); if(spanClass){ assem.append('<span class="'); assem.append(spanClass); assem.append('">'); } else { assem.append('<'); assem.append(tags[i]); assem.append('>'); } } // this closes an open tag and removes its reference from openTags function emitCloseTag(i) { openTags.shift(); var spanClass = getSpanClassFor(i); var spanWithData = isSpanWithData(i); if(spanClass || spanWithData){ assem.append('</span>'); } else { assem.append('</'); assem.append(tags[i]); assem.append('>'); } } var urls = _findURLs(text); var idx = 0; function processNextChars(numChars) { if (numChars <= 0) { return; } var iter = Changeset.opIterator(Changeset.subattribution(attribs, idx, idx + numChars)); idx += numChars; // this iterates over every op string and decides which tags to open or to close // based on the attribs used while (iter.hasNext()) { var o = iter.next(); var usedAttribs = []; // mark all attribs as used Changeset.eachAttribNumber(o.attribs, function (a) { if (a in anumMap) { usedAttribs.push(anumMap[a]); // i = 0 => bold, etc. } }); var outermostTag = -1; // find the outer most open tag that is no longer used for (var i = openTags.length - 1; i >= 0; i--) { if (usedAttribs.indexOf(openTags[i]) === -1) { outermostTag = i; break; } } // close all tags upto the outer most if (outermostTag != -1) { while ( outermostTag >= 0 ) { emitCloseTag(openTags[0]); outermostTag--; } } // open all tags that are used but not open for (i=0; i < usedAttribs.length; i++) { if (openTags.indexOf(usedAttribs[i]) === -1) { emitOpenTag(usedAttribs[i]) } } var chars = o.chars; if (o.lines) { chars--; // exclude newline at end of line, if present } var s = taker.take(chars); //removes the characters with the code 12. Don't know where they come //from but they break the abiword parser and are completly useless s = s.replace(String.fromCharCode(12), ""); assem.append(_encodeWhitespace(Security.escapeHTML(s))); } // end iteration over spans in line // close all the tags that are open after the last op while (openTags.length > 0) { emitCloseTag(openTags[0]) } } // end processNextChars if (urls) { urls.forEach(function (urlData) { var startIndex = urlData[0]; var url = urlData[1]; var urlLength = url.length; processNextChars(startIndex - idx); assem.append('<a href="' + Security.escapeHTMLAttribute(url) + '">'); processNextChars(urlLength); assem.append('</a>'); }); } processNextChars(text.length - idx); return _processSpaces(assem.toString()); } // end getLineHTML var pieces = [css]; // Need to deal with constraints imposed on HTML lists; can // only gain one level of nesting at once, can't change type // mid-list, etc. // People might use weird indenting, e.g. skip a level, // so we want to do something reasonable there. We also // want to deal gracefully with blank lines. // => keeps track of the parents level of indentation var lists = []; // e.g. [[1,'bullet'], [3,'bullet'], ...] var listLevels = [] for (var i = 0; i < textLines.length; i++) { var line = _analyzeLine(textLines[i], attribLines[i], apool); var lineContent = getLineHTML(line.text, line.aline); listLevels.push(line.listLevel) if (line.listLevel)//If we are inside a list { // do list stuff var whichList = -1; // index into lists or -1 if (line.listLevel) { whichList = lists.length; for (var j = lists.length - 1; j >= 0; j--) { if (line.listLevel <= lists[j][0]) { whichList = j; } } } if (whichList >= lists.length)//means we are on a deeper level of indentation than the previous line { if(lists.length > 0){ pieces.push('</li>') } lists.push([line.listLevel, line.listTypeName]); // if there is a previous list we need to open x tags, where x is the difference of the levels // if there is no previous list we need to open x tags, where x is the wanted level var toOpen = lists.length > 1 ? line.listLevel - lists[lists.length - 2][0] - 1 : line.listLevel - 1 if(line.listTypeName == "number") { if(toOpen > 0){ pieces.push(new Array(toOpen + 1).join('<ol>')) } pieces.push('<ol class="'+line.listTypeName+'"><li>', lineContent || '<br>'); } else { if(toOpen > 0){ pieces.push(new Array(toOpen + 1).join('<ul>')) } pieces.push('<ul class="'+line.listTypeName+'"><li>', lineContent || '<br>'); } } //the following code *seems* dead after my patch. //I keep it just in case I'm wrong... /*else if (whichList == -1)//means we are not inside a list { if (line.text) { console.log('trace 1'); // non-blank line, end all lists if(line.listTypeName == "number") { pieces.push(new Array(lists.length + 1).join('</li></ol>')); } else { pieces.push(new Array(lists.length + 1).join('</li></ul>')); } lists.length = 0; pieces.push(lineContent, '<br>'); } else { console.log('trace 2'); pieces.push('<br><br>'); } }*/ else//means we are getting closer to the lowest level of indentation or are at the same level { var toClose = lists.length > 0 ? listLevels[listLevels.length - 2] - line.listLevel : 0 if( toClose > 0){ pieces.push('</li>') if(lists[lists.length - 1][1] == "number") { pieces.push(new Array(toClose+1).join('</ol>')) pieces.push('<li>', lineContent || '<br>'); } else { pieces.push(new Array(toClose+1).join('</ul>')) pieces.push('<li>', lineContent || '<br>'); } lists = lists.slice(0,whichList+1) } else { pieces.push('</li><li>', lineContent || '<br>'); } } } else//outside any list, need to close line.listLevel of lists { if(lists.length > 0){ if(lists[lists.length - 1][1] == "number"){ pieces.push('</li></ol>'); pieces.push(new Array(listLevels[listLevels.length - 2]).join('</ol>')) } else { pieces.push('</li></ul>'); pieces.push(new Array(listLevels[listLevels.length - 2]).join('</ul>')) } } lists = [] var context = { line: line, lineContent: lineContent, apool: apool, attribLine: attribLines[i], text: textLines[i], padId: pad.id } var lineContentFromHook = hooks.callAllStr("getLineHTMLForExport", context, " ", " ", ""); if (lineContentFromHook) { pieces.push(lineContentFromHook, ''); } else { pieces.push(lineContent, '<br>'); } } } for (var k = lists.length - 1; k >= 0; k--) { if(lists[k][1] == "number") { pieces.push('</li></ol>'); } else { pieces.push('</li></ul>'); } } return pieces.join(''); } exports.getPadHTMLDocument = function (padId, revNum, callback) { padManager.getPad(padId, function (err, pad) { if(ERR(err, callback)) return; var stylesForExportCSS = ""; // Include some Styles into the Head for Export hooks.aCallAll("stylesForExport", padId, function(err, stylesForExport){ stylesForExport.forEach(function(css){ stylesForExportCSS += css; }); getPadHTML(pad, revNum, function (err, html) { if(ERR(err, callback)) return; var exportedDoc = eejs.require("ep_etherpad-lite/templates/export_html.html", { body: html, padId: Security.escapeHTML(padId), extraCSS: stylesForExportCSS }); callback(null, exportedDoc); }); }); }); }; // copied from ACE var _REGEX_WORDCHAR = /[\u0030-\u0039\u0041-\u005A\u0061-\u007A\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0100-\u1FFF\u3040-\u9FFF\uF900-\uFDFF\uFE70-\uFEFE\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFDC]/; var _REGEX_SPACE = /\s/; var _REGEX_URLCHAR = new RegExp('(' + /[-:@a-zA-Z0-9_.,~%+\/\\?=&#;()$]/.source + '|' + _REGEX_WORDCHAR.source + ')'); var _REGEX_URL = new RegExp(/(?:(?:https?|s?ftp|ftps|file|smb|afp|nfs|(x-)?man|gopher|txmt):\/\/|mailto:)/.source + _REGEX_URLCHAR.source + '*(?![:.,;])' + _REGEX_URLCHAR.source, 'g'); // returns null if no URLs, or [[startIndex1, url1], [startIndex2, url2], ...] function _findURLs(text) { _REGEX_URL.lastIndex = 0; var urls = null; var execResult; while ((execResult = _REGEX_URL.exec(text))) { urls = (urls || []); var startIndex = execResult.index; var url = execResult[0]; urls.push([startIndex, url]); } return urls; } // copied from ACE function _processSpaces(s){ var doesWrap = true; if (s.indexOf("<") < 0 && !doesWrap){ // short-cut return s.replace(/ /g, '&nbsp;'); } var parts = []; s.replace(/<[^>]*>?| |[^ <]+/g, function (m){ parts.push(m); }); if (doesWrap){ var endOfLine = true; var beforeSpace = false; // last space in a run is normal, others are nbsp, // end of line is nbsp for (var i = parts.length - 1; i >= 0; i--){ var p = parts[i]; if (p == " "){ if (endOfLine || beforeSpace) parts[i] = '&nbsp;'; endOfLine = false; beforeSpace = true; } else if (p.charAt(0) != "<"){ endOfLine = false; beforeSpace = false; } } // beginning of line is nbsp for (i = 0; i < parts.length; i++){ p = parts[i]; if (p == " "){ parts[i] = '&nbsp;'; break; } else if (p.charAt(0) != "<"){ break; } } } else { for (i = 0; i < parts.length; i++){ p = parts[i]; if (p == " "){ parts[i] = '&nbsp;'; } } } return parts.join(''); }
JavaScript
CL
38b0087394e599fcbc2e53350a5820bc8448e2070f2c912bc56ceec7a5404ebb
const { BotFrameworkAdapter, MemoryStorage, ConversationState, MessageFactory, ActionTypes, CardFactory, ActivityTypes } = require('botbuilder') const restify = require('restify') const botbuilder_dialogs = require('botbuilder-dialogs') const dialogs = new botbuilder_dialogs.DialogSet() let infoCard = require('./cards/infoCard') const getpokeinfo = require('./database/getpokeinfo') const utility = require('./utils/utility') const Pokedex = require('pokedex-promise-v2') const P = new Pokedex() require('dotenv-extended').load() // Create server let server = restify.createServer() server.listen(process.env.port || process.env.PORT || 3978, function () { console.log(`${server.name} listening to ${server.url}`) }) // Create adapter const adapter = new BotFrameworkAdapter({ appId: process.env.MICROSOFT_APP_ID, appPassword: process.env.MICROSOFT_APP_PASSWORD }) // Add conversation state middleware const conversationState = new ConversationState(new MemoryStorage()) adapter.use(conversationState) // Listen for incoming requests server.post('/api/messages', (req, res) => { // Route received request to adapter for processing adapter.processActivity(req, res, async (context) => { const isMessage = (context.activity.type === 'message') // State will store all of your information const convo = conversationState.get(context) const dc = dialogs.createContext(context, convo) if (context.activity.type === 'conversationUpdate' && context.activity.membersAdded[0].name !== 'Bot' && (context.activity.channelId !== 'directline')) { await context.sendActivity(`안녕하세요! Pokemon 정보를 조회할 수 있는 봇 입니다. 원하는 서비스를 선택하세요! 1. 포켓몬 검색 2. 포켓몬 진화단계 조회 예를들어 '1'입력 시 검색서비스가 제공됩니다`) } else if (context.activity.type === 'message') { if (context.activity.text.match(/안녕/ig)) { await dc.begin('greetings') } else if ((convo.dialogStack.length == '0' && context.activity.text === '1') || context.activity.text.match(/검색/ig)) { // need to check dialogStack.length - if it is not, it conflicts with searchPokemon input id == 1 await dc.begin('searchPokemon') } else if ((convo.dialogStack.length == '0' && context.activity.text === '2') || context.activity.text.match(/진화/ig)) { await dc.begin('evolutionStage') } } if (!context.responded) { // Continue executing the "current" dialog, if any. await dc.continue() if (!context.responded && isMessage) { // Default message await context.sendActivity(`원하는 서비스를 선택하세요! 1. 포켓몬 검색 2. 포켓몬 진화단계 조회 예를들어 '1'입력 시 검색서비스가 제공됩니다`) } } }) }) // Define prompts // Generic prompts dialogs.add('textPrompt', new botbuilder_dialogs.TextPrompt()) dialogs.add('dateTimePrompt', new botbuilder_dialogs.DatetimePrompt()) dialogs.add('partySizePrompt', new botbuilder_dialogs.NumberPrompt()) // Greet user: // Ask for the user name and then greet them by name. dialogs.add('greetings', [ async function (dc) { await dc.prompt('textPrompt', '안녕하세요! 이름이 뭐에요?') }, async function (dc, results) { var userName = results await dc.context.sendActivity(`${userName}님, 만나서 반갑습니다!`) await dc.end() // Ends the dialog } ]) var pokemonInfo = {} dialogs.add('searchPokemon', [ async function (dc, args, next) { // need to check if this is second round pokemonInfo = {} if (typeof args !== 'undefined' && args) { await next(args) } else { await dc.context.sendActivity('포켓몬 검색 서비스입니다.') await dc.prompt('textPrompt', `포켓몬 id 혹은 이름을 입력해주세요! id의 경우 1~807 사이의 숫자를 입력해주세요!`) } }, async function (dc, result) { await getpokeinfo(result).then((pokemonInfo) => { const message = CardFactory.adaptiveCard(infoCard(pokemonInfo.imgUrl_large, pokemonInfo.name_kor, pokemonInfo.id, pokemonInfo.name_eng, pokemonInfo.genra, pokemonInfo.color)) dc.context.sendActivity({type: ActivityTypes.Typing}) return dc.context.sendActivity({ attachments: [message] }) }) await dc.prompt('textPrompt', `검색하고 싶은 포켓몬 id 혹은 이름을 입력해주세요! 처음으로 돌아가시려면 '그만'을 입력해주세요`) }, async function (dc, result) { if (result == '그만') { return dc.end() } return dc.replace('searchPokemon', result) } ]) var evolutionInfo = {} dialogs.add('evolutionStage', [ async function (dc, args, next) { evolutionInfo = {} if (typeof args !== 'undefined' && args) { await next(args) } else { await dc.context.sendActivity('포켓몬의 진화 과정을 안내해드립니다.') await dc.prompt('textPrompt', '진화 단계가 궁금한 포켓몬의 id 혹은 이름을 입력해주세요!') } }, async function (dc, result, evolutionId) { let messageWithCarouselOfCards await P.getPokemonSpeciesByName(result.toLowerCase()) .then(function (result) { evolutionInfo.is_baby = result.is_baby var evolutionChainUrl = result.evolution_chain.url var evolutionId = evolutionChainUrl.replace('https://pokeapi.co/api/v2/evolution-chain/', '').replace('/', '') return P.getEvolutionChainById(evolutionId) }).then(function (result2) { var evolutionStage = [] function evolutionTree (obj) { if (typeof obj === 'undefined') { console.log('end of tree') } else { var pokemonInfo = new Object() pokemonInfo.name = obj.species.name pokemonInfo.id = obj.species.url.replace('https://pokeapi.co/api/v2/pokemon-species/', '').replace('/', '') pokemonInfo.url = utility.getLargeImgUrl(pokemonInfo.id) evolutionStage.push(pokemonInfo) evolutionTree(obj.evolves_to[0]) } } evolutionTree(result2.chain) var attachments = [] evolutionStage.forEach(function (data) { var card = CardFactory.heroCard(data.id, [data.url], [data.name]) attachments.push(card) }, this) var msg = '' evolutionStage.forEach(function (data) { msg += data.name + ' ' }, this) if (dc.context.activity.channelId == 'directline') { dc.context.sendActivity({type: ActivityTypes.Typing}) return dc.context.sendActivity(msg) } else { messageWithCarouselOfCards = MessageFactory.carousel(attachments) dc.context.sendActivity({type: ActivityTypes.Typing}) return dc.context.sendActivity(messageWithCarouselOfCards) } }).catch(function (error) { console.log('There was an ERROR: ', error) }) await dc.prompt('textPrompt', `진화과정이 궁금한 포켓몬 id를 입력해주세요! 처음으로 돌아가시려면 '그만'을 입력해주세요`) }, async function (dc, result) { if (result == '그만') { return dc.end() } return dc.replace('evolutionStage', result) } ])
JavaScript
CL
c8c92d9be70a3d11a90958bd88f34ede2ef3bde0175080087208c08afd335142
const doctrine = require('doctrine'); function getType(tag) { if (!tag.type) { return null; } if (tag.type.type === 'UnionType') { return { name: 'union', value: tag.type.elements.map(element => element.name) }; } if (tag.type.type === 'AllLiteral') { return { name: 'mixed' }; } return { name: tag.type.name ? tag.type.name : tag.type.expression.name }; } function getReturnsJsDoc(jsDoc) { const returnTag = jsDoc.tags.find(tag => tag.title === 'return' || tag.title === 'returns'); if (returnTag) { return { description: returnTag.description, type: getType(returnTag) }; } return null; } function getDefaultJsDoc(jsDoc) { const defaultTag = jsDoc.tags.find(tag => tag.title === 'default'); if (defaultTag) { return { value: defaultTag.description, computed: false }; } return null; } function getEnumdescJsDoc(jsDoc) { const enumdescTag = jsDoc.tags.find(tag => tag.title === 'enumdesc'); if (enumdescTag) { return enumdescTag.description.split(/,\s*/); } return null; } function getSpecialTagJsDoc(jsDoc, tagTitle) { return jsDoc.tags .filter(tag => tag.title === tagTitle) .map(tag => { return { name: tag.name, description: tag.description, type: getType(tag) }; }); } function getDeviceJsDoc(jsDoc) { const deviceTag = jsDoc.tags.find(tag => tag.title === 'device'); if (deviceTag) { // computed 为react-docgen协议要求 // 标注value是需要运行计算的表达式,还是非计算的常量 return { value: deviceTag.description, computed: false }; } } function getVersionJsDoc(jsDoc) { const versionTag = jsDoc.tags.find(tag => tag.title === 'version'); if (versionTag) { return { value: versionTag.description, computed: false }; } } module.exports = function parseJsDoc(docblock, type) { const jsDoc = doctrine.parse(docblock); const result = { description: jsDoc.description || null, docblock: docblock }; if (type.name === 'func') { result.params = getSpecialTagJsDoc(jsDoc, 'param'); result.returns = getReturnsJsDoc(jsDoc); } else if (['object', 'objectOf', 'shape'].indexOf(type.name) > -1) { result.properties = getSpecialTagJsDoc(jsDoc, 'property'); } else if (type.name === 'enum') { const enumdesc = getEnumdescJsDoc(jsDoc); if (enumdesc) { result.value = type.value.map((v, i) => { v.description = enumdesc[i]; return v; }); } } const defaultValue = getDefaultJsDoc(jsDoc); if (defaultValue && defaultValue.value) { result.defaultValue = defaultValue; } const deviceValue = getDeviceJsDoc(jsDoc); if (deviceValue && deviceValue.value) { result.device = deviceValue; } const versionValue = getVersionJsDoc(jsDoc); if (versionValue && versionValue.value) { result.version = versionValue; } return result; };
JavaScript
CL
4caa688311f643089cdea2b32b8e9eb6e78868ce4183cb152d53c5ccb1b8859a
'use strict'; import bcrypt from 'bcryptjs'; import {newMessage} from '../actions/message-actions.js'; import {createNew, setFirstPassword, incrementCreationStep, setUsername, setCreationStep} from '../actions/login-actions.js'; export default function loginHandler(command, args, props) { // props.creatingNew checks if the user is currently in the process of making a new character. if (props.creatingNew) { if (command === 'new') return {funcsToCall: [newMessage], feedback: 'You\'re already in the process of making a character.'}; // Step 0: The user has been asked to enter a name for their character. // Upon entering it, the server will check if the username exists. // If it doesn't, they get the feedback to enter a password from a // socket listener. // Step 1: Entering the password the first time. It sets it as firstPassword, // then preps the user for step 2, which is confirming the password. // Step 2: Compares the password from step 1. If a match, have the server make // a new character. If not, take them back to step 1. if (props.creationStep === 0) return {emitType: 'checkUsername', newUsername: command}; if (props.creationStep === 1) return {funcsToCall: [newMessage, incrementCreationStep, setFirstPassword], firstPassword: command, feedback: 'Confirm password.'}; if (props.creationStep === 2) { if (!bcrypt.compareSync(command, props.firstPassword)) return {funcsToCall: [newMessage, setCreationStep], step: 1, feedback: 'Passwords don\'t match. Please enter a new password.'}; return {emitType: 'createCharacter', newUsername: props.newUsername, password: command}; } // This should never happen, but if for some reason they escape the creationStep process, take them back to step 0. return {funcsToCall: [newMessage, setCreationStep], step: 0, feedback: 'Encountered an unknown error. Starting over. Enter "new" or an existing character name.'}; } // If the user has not already started making a new character, enters the word "new", // but is not on the step of entering a password, then prompt the user to get ready for // step 0 in the creatingNew section. if (command === 'new' && props.creationStep === 0) { return { funcsToCall: [newMessage, createNew], feedback: 'Please enter a name for your character.' }; } // If this section is reached, it means the user has entered a character's name of some sort for step 0. // Step 1: Send the entered username and the entered password to the server for validation. If it fails, // a socket listener sets creationStep back to 0. if (props.creationStep === 0) return {funcsToCall: [newMessage, incrementCreationStep, setUsername], newUsername: command, feedback: 'Enter the password for that character.'}; if (props.creationStep === 1) { return { emitType: 'login', username: props.newUsername, password: command }; } // This should never happen, but if for some reason they escape the creation process, take them back to step 0. return {funcsToCall: [newMessage, setCreationStep], step: 0, feedback: 'Encountered an unknown error. Starting over. Enter "new" or an existing character name.'}; }
JavaScript
CL
d8afe12696c2918d2ea39bbc9b28f13909fa1648fcb20459a865ac4a12f022ee
// this is just a testing room, which creates a text channel UI to test the functions of the server side rooms thing const html = require('nanohtml') const nanocomponent = require('nanocomponent') const TextComposer = require('./component-text-composer') const VideoCrossbar = require('./component-video-crossbar') const LayerMap = require('../map2/map') const ChatLog = require('./component-chat-log') const RoomClient = require('../client-data/room') const HueRing = require('./widget-hue-ring') const AvatarCapture = require('./widget-avatar-capture') const bathtub = require('../../package.json').bathtub class RoomView extends nanocomponent { constructor(options) { super() this.options = options this.room = new RoomClient(options.roomStateData) this.crossbar = new VideoCrossbar({ }) this.messages = new ChatLog({ expires: '30s' }) this.map = new LayerMap({ }) this.composer = new TextComposer({ }) } get title() { return `${this.room.humanName} — ${bathtub.siteName}` } createElement() { return html`<body class="bathtub-room"> <div class="vertical-flex"> <div class="expand stack"> ${this.crossbar.render()} ${this.map.render()} ${this.messages.render()} </div> ${this.composer.render()} </div> </body>` } // on load async load() { // hookup event handlers and other stuff that shouldn't happen server side // handle clicks on text chat bubbles this.messages.onClick = (mouseEvent, type, chatBubble) => { // if it's one of your own bubbles: if (this.room.identity.equals(chatBubble.person.identity)) { // generate a HueRing widget to pick a different identity color new HueRing({ hue: chatBubble.person.attributes.hue, position: mouseEvent, onChoice: (newHue)=> { this.room.updateAttributes({ hue: newHue }) } }) } } // when a user submits a text message in the text composer, send it to the room this.composer.onMessage = (text)=> { this.room.text(text) } // hook up the layer map this.map.room = this.room this.room.on('roomChange', async ()=> { document.title = this.title await this.map.loadArchitecture(this.room.architectureName, this.room.architecture) this.map.render() }) // when people change their attributes, update anything that depends on that data this.room.on('peopleChange', ()=> { this.messages.render() }) this.room.on('personJoin', person => this.map.render() ) this.room.on('personLeave', person => this.map.render() ) this.room.on('personChange', (person, changes) => this.map.handlePersonChange(person, changes) ) // when text messages come in from the server, append them and trigger rendering of Chat Log Component this.room.on('text', ({identity, message}) => { let person = this.room.getPerson(identity) if (!person) return console.error("Person doesn't exist with ID", identity) this.messages.appendText(person, `${message}`) this.messages.render() }) // when user closes window or navigates away, attempt to notify server they left window.addEventListener("beforeunload", ()=> { this.room.leave() }) if (this.map.loadArchitecture) { await this.map.loadArchitecture(this.room.architectureName, this.room.architecture) this.map.render() } this.map.onMoveTo = (position)=> { this.room.updateAttributes({ x: position.x, y: position.y }) } // join room this.room.join({ hue: Math.round(Math.random() * 360), ... this.room.architecture.spawn, }) // ask for webcam feed (depends on user permission) // this.webcam = await navigator.mediaDevices.getUserMedia({ // video: { // width: 640, // height: 480, // frameRate: { ideal: 60, min: 10 }, // facingMode: "user", // front facing camera please // }, // audio: false // }) // // send video feed to a hidden video tag // // todo: refactor this in to something nice // if (this.webcam) { // this.handMirror = html`<video muted playsinline></video>` // this.handMirror.srcObject = this.webcam // this.handMirror.play() // // setup filmstrip builder, which watches webcam handmirror and saves frames in to the strip // // and uploads each strip to the server when they're done // this.avatar = new AvatarCapture({ // source: this.handMirror, // onAvatar: (buffer) => { // this.room.uploadAvatar(buffer) // } // }) // this.avatar.enable() // } else { // console.log("no webcam??") // } } update() { return true } } module.exports = RoomView
JavaScript
CL
a79525b58ec664eeb1c858e29cac2f817b6197d56711a40f2b74a7467fdac4af
/** Messaging gateways and service base classes, which form a network of gateways for messages to propogate across. This module has two main types of classes: A. Gateways: These relay messages to their connected services (children) and also to other gateways that will also relay the message. Gateways exist to abstract away the network and iframe topology. Gateways send messages to their parent gateway and can also distribute messages downstream to child gateways and services. B. Services: Services that receive messages and may (or may not) respond. Services exist to process and transmit messages, while doing meaningful things to parts of systems that they control. Services only send and receive message with their parent gateway. As a general rule, every service should be able to act reasonably and sensibly, regardless of what messages it receives. In short, no service should hard fail. There may be conditions there the system as a whole may not be able to function, but all attempts should be made to soft-fail. Likewise, all services should be prepared to ignore any messages that it does not want to respond to, without any ill effects on the service (e.g., silently ignore) or, alternatively, to send back a message indicating that the message was not understood. Typically, silently ignoring is usually best. Package: SuperGLU (Generalized Learning Utilities) Author: Benjamin Nye License: APL 2.0 Requires: - Zet.js - Serializable.js - Messaging.js **/ const Zet = require('../util/zet'), Serialization = require('../util/serialization'), Messaging = require('./messaging'), version = require('../reference-data').version, UUID = require('../util/uuid'), Message = require('../core/message'); //async = require('asyncawait/async'); var namespace = {} var CATCH_BAD_MESSAGES = false, SESSION_ID_KEY = 'sessionId', SEND_MSG_SLEEP_TIME = 5000, PROPOSAL_ATTEMPT_COUNT = 'noOfAttemptsForProposal', FAIL_SOFT_STRATEGY= 'failSoftStrategyForProposedMsg', QUIT_IN_TIME= 'quitInTime' var Proposal = Zet.declare('Proposal', { CLASS_ID: 'Proposal', defineBody: function (self) { // Private Properties // Public Properties /** * Create a Proposal * @param proposedMessage: The Main Proposed Message. * @param numberOfRetries: Number of Tries to be attempted to send the Proposed Message. * @param lastTimeSent: Time in Milliseconds when the Proposed Message was Last Attempted to Send. */ self.construct = function construct(id, proposal, proposalProcessed, acknowledgementReceived, retryParams, policyType, failSoftStrategyForProposedMsg, proposedMessages, proposedTime) { if (typeof id === "undefined") { id = UUID.genV4().toString() } if (typeof proposal === "undefined") { proposal = null } if (typeof proposalProcessed === "undefined") { proposalProcessed = false } if (typeof acknowledgementReceived === "undefined") { acknowledgementReceived = false } if (typeof retryParams === "undefined") { retryParams = {} } if (typeof policyType === "undefined") { policyType = ALL_TIME_ACCEPT_PROPOSAL_ACK } if (typeof failSoftStrategyForProposedMsg === "undefined") { failSoftStrategyForProposedMsg = 'noOfAttempts' } if (typeof proposedMessages === "undefined") { proposedMessages = {} } if (typeof proposedTime === "undefined") { proposedTime = new Date().getTime(); } self._id = id self._proposal = proposal self._proposalProcessed = proposalProcessed self._acknowledgementReceived = acknowledgementReceived self._retryParams = retryParams self._policyType = policyType self._failSoftStrategyForProposedMsg = failSoftStrategyForProposedMsg self._proposedMessages = proposedMessages self._proposedTime = proposedTime } /** Get the Proposal ID * */ self.getId = function getId() { return self._id } /** Set the Proposal ID * */ self.getId = function getId() { return self._id } /** Set the Proposal Request * */ self.setProposal = function setProposal(proposal) { self._proposal = proposal } /** Get the Proposal Request * */ self.getProposal = function getProposal() { return self._proposal } /** Get the whether the Proposal is Processed or not * */ self.getProposalProcessed = function getProposalProcessed() { return self._proposalProcessed } /** Set the whether the Proposal is Processed or not * */ self.setProposalProcessed = function setProposalProcessed(proposalProcessed) { self._proposalProcessed = proposalProcessed } /** Get the Whether Acknowledgement for Proposal Request is received or not. * */ self.getAcknowledgementReceived = function getAcknowledgementReceived() { return self._acknowledgementReceived } /** Set the Whether Acknowledgement for Proposal Request is received or not. * */ self.setAcknowledgementReceived = function setAcknowledgementReceived(acknowledgementReceived) { self._acknowledgementReceived = acknowledgementReceived } /** Get the Retry Parameters for the Proposal * */ self.getRetryParams = function getRetryParams() { return self._retryParams } /** Set the Retry Parameters for the Proposal * */ self.setRetryParams = function setRetryParams(retryParams) { self._retryParams = retryParams } /** Get the Policy Type for the Proposal Request * */ self.getPolicyType = function getPolicyType() { return self._policyType } /** Set the Policy Type for the Proposal Request * */ self.setPolicyType = function setPolicyType(policyType) { self._policyType = policyType } /** Get the FailSoftStrategyForProposedMsg for the Proposal Request * */ self.getFailSoftStrategyForProposedMsg = function getFailSoftStrategyForProposedMsg() { return self._failSoftStrategyForProposedMsg } /** Set the FailSoftStrategyForProposedMsg for the Proposal Request * */ self.setFailSoftStrategyForProposedMsg = function setFailSoftStrategyForProposedMsg(failSoftStrategyForProposedMsg) { self._failSoftStrategyForProposedMsg = failSoftStrategyForProposedMsg } /** Get the Proposed Messages for the Proposal * */ self.getProposedMessages = function getProposedMessages() { return self._proposedMessages } /** Set the Proposed Messages for the Proposal * */ self.setProposedMessages = function setProposedMessages(proposedMessages) { self._proposedMessages = proposedMessages } /** Get the Proposed Time for the Last Proposal Request Message. * */ self.getProposedTime = function getProposedTime() { return self._proposedTime } /** Set the Proposed Time for the Last Proposal Request Message. * */ self.setProposedTime = function setProposedTime(proposedTime) { self._proposedTime = proposedTime } /** Save the Proposed Message to a storage token * */ self.saveToToken = function saveToToken() { var key, token, newContext, hadKey token = self.inherited(saveToToken) if (self._id != null) { token.setitem(PROPOSAL_ID, tokenizeObject(self._id)) } if (self._proposal != null) { token.setitem(PROPOSAL, tokenizeObject(self._proposal)) } if (self._proposalProcessed != null) { token.setitem(PROPOSAL_PROCESSED, tokenizeObject(self._proposalProcessed)) } if (self._acknowledgementReceived != null) { token.setitem(PROPOSAL_ACK, tokenizeObject(self._acknowledgementReceived)) } if (self._retryParams != null) { token.setitem(RETRY_PARAMS, tokenizeObject(self._retryParams)) } if (self._policyType != null) { token.setitem(POLICY_TYPE, tokenizeObject(self._policyType)) } if (self._failSoftStrategyForProposedMsg != null) { token.setitem(FAIL_SOFT_STRATEGY, tokenizeObject(self._failSoftStrategyForProposedMsg)) } if (self._proposedMessages != null) { token.setitem(PROPOSED_MESSAGES, tokenizeObject(self._proposedMessages)) } if (self._proposedTime != null) { token.setitem(LAST_TIME_SENT, tokenizeObject(self._proposedTime)) } return token } /** * Initialize the message from a storage token and some * additional context (e.g., local objects) * */ self.initializeFromToken = function initializeFromToken(token, context) { self.inherited(initializeFromToken, [token, context]) self._id = untokenizeObject(token.getitem(PROPOSAL_ID, true, null), context) self._proposal = untokenizeObject(token.getitem(PROPOSAL, true, null), context) self._proposalProcessed = untokenizeObject(token.getitem(PROPOSAL_PROCESSED, true, null), context) self._acknowledgementReceived = untokenizeObject(token.getitem(PROPOSAL_ACK, true, null), context) self._retryParams = untokenizeObject(token.getitem(RETRY_PARAMS, true, null), context) self._policyType = untokenizeObject(token.getitem(POLICY_TYPE, true, null), context) self._failSoftStrategyForProposedMsg = untokenizeObject(token.getitem(FAIL_SOFT_STRATEGY, true, null), context) self._proposedMessages = untokenizeObject(token.getitem(PROPOSED_MESSAGES, true, null), context) self._proposedTime = untokenizeObject(token.getitem(LAST_TIME_SENT, true, null), context) } } }) var ProposedMessage = Zet.declare({ CLASS_ID: 'ProposedMessage', defineBody: function (self) { // Private Properties // Public Properties /** Create a ProposedMessage @param proposedMessage: The Main Proposed Message. @param numberOfRetries: Number of Tries to be attempted to send the Proposed Message. @param lastTimeSent: Time in Milliseconds when the Proposed Message was Last Attempted to Send. **/ self.construct = function construct( msgId, proposedMessage, numberOfRetries, lastTimeSent) { if (typeof msgId === "undefined") { msgId = UUID.genV4().toString() } if (typeof proposedMessage === "undefined") { proposedMessage = null } if (typeof numberOfRetries === "undefined") { numberOfRetries = 0 } if (typeof lastTimeSent === "undefined") { lastTimeSent = new Date().getTime(); } self._msgId = msgId self._proposedMessage = proposedMessage self._numberOfRetries = numberOfRetries self._lastTimeSent = lastTimeSent } /** Get the ProposedMessage ID **/ self.getMsgId = function getMsgId() { return self._msgId } /** Set the ProposedMessage ID **/ self.setMsgId = function setMsgId(msgId) { self._msgId = msgId } /** Get the ProposedMessage **/ self.getProposedMessage = function getProposedMessage() { return self._proposedMessage } /** Set the ProposedMessage **/ self.setProposedMessage = function setProposedMessage(proposedMessage) { self._proposedMessage = proposedMessage } /** Get the NumberOfRetries for the Proposed Message **/ self.getNumberOfRetries = function getNumberOfRetries() { return self._numberOfRetries } /** Set the Last Time Sent for the Proposed Message **/ self.setLastTimeSent = function setLastTimeSent(lastTimeSent) { self._lastTimeSent = lastTimeSent } /** Get the NumberOfRetries for the Proposed Message **/ self.getLastTimeSent = function getLastTimeSent() { return self._lastTimeSent } /** Set the NumberOfRetries for the Proposed Message **/ self.setNumberOfRetries = function setNumberOfRetries(numberOfRetries) { self._numberOfRetries = numberOfRetries } /** Save the Proposed Message to a storage token **/ self.saveToToken = function saveToToken() { var key, token, newContext, hadKey token = self.inherited(saveToToken) if (self._proposedMessage != null) { token.setitem(PROPOSED_MESSAGE, tokenizeObject(self._proposedMessage)) } if (self._numberOfRetries != null) { token.setitem(NUMBER_OF_RETRIES, tokenizeObject(self._numberOfRetries)) } if (self._lastTimeSent != null) { token.setitem(LAST_TIME_SENT, tokenizeObject(self._lastTimeSent)) } return token } /** Initialize the message from a storage token and some additional context (e.g., local objects) **/ self.initializeFromToken = function initializeFromToken(token, context) { self.inherited(initializeFromToken, [token, context]) self._msgId= untokenizeObject(token.getitem(PROPOSED_MESSAGE_ID, true, null), context) self._proposedMessage = untokenizeObject(token.getitem(PROPOSED_MESSAGE, true, null), context) self._numberOfRetries = untokenizeObject(token.getitem(NUMBER_OF_RETRIES, true, null), context) self._lastTimeSent = untokenizeObject(token.getitem(LAST_TIME_SENT, true, null), context) } } }) /** The base class for a messaging node (either a Gateway or a Service) **/ var BaseMessagingNode = Zet.declare({ CLASS_ID: 'BaseMessagingNode', // Base class for messaging gateways superclass: Serialization.Serializable, defineBody: function (self) { // Public Properties /** Initialize a messaging node. Should have a unique ID and (optionally) also have one or more gateways connected. @param id: A unique ID for the node. If none given, a random UUID will be used. @type id: str @param gateways: Gateway objects, which this node will register with. @type gateways: list of MessagingGateway object **/ self.construct = function construct(id, nodes) { self.inherited(construct, [id]) if (nodes == null) { nodes = [] } self._nodes = {} self._requests = {} self._uuid = UUID.genV4() self.addNodes(nodes) self.proposals = {} self.prioritizedAcceptedServiceIds = {} self.demotedAcceptedServiceIds = [] } /** Receive a message. When a message is received, two things should occur: 1. Any service-specific processing 2. A check for callbacks that should be triggered by receiving this message The callback check is done here, and can be used as inherited behavior. **/ self.receiveMessage = function receiveMessage(msg) { // Processing to handle a received message //console.log(self._id + " received MSG: "+ self.messageToString(msg)); self._triggerRequests(msg) } /** Send a message to connected nodes, which will dispatch it (if any gateways exist). **/ self.sendMessage = function sendMessage(msg) { //console.log(self._id + " sent MSG: "+ self.messageToString(msg)); self._distributeMessage(self._nodes, msg) } /** Handle an arriving message from some source. Services other than gateways should generally not need to change this. @param msg: The message arriving @param senderId: The id string for the sender of this message. **/ self.handleMessage = function handleMessage(msg, senderId) { self.receiveMessage(msg) } /** Sends a message each of 'nodes', except excluded nodes (e.g., original sender) **/ self._distributeMessage = function _distributeMessage(nodes, msg, excludeIds) { var nodeId, node, condition if (excludeIds == null) { excludeIds = [] } for (nodeId in nodes) { condition = nodes[nodeId].condition node = nodes[nodeId].node if ((excludeIds.indexOf(nodeId) < 0) && (condition == null || condition(msg))) { self._transmitMessage(node, msg, self.getId()) } } } /** Transmit the message to another node **/ self._transmitMessage = function _transmitMessage(node, msg, senderId) { node.handleMessage(msg, senderId) } // Manage Connected Nodes /** Get all connected nodes for the gateway **/ self.getNodes = function getNodes() { return Object.keys(self._nodes).map(function (key) { return self._nodes[key].node }) } /** Connect nodes to this node **/ self.addNodes = function addNodes(nodes) { var i if (nodes == null) { nodes = [] } for (i = 0; i < nodes.length; i++) { nodes[i].onBindToNode(self) self.onBindToNode(nodes[i]) } } /** Remove the given connected nodes. If nodes=null, remove all. **/ self.removeNodes = function removeNodes(nodes) { var i if (nodes == null) { nodes = self.getNodes() } for (i = 0; i < nodes.length; i++) { nodes[i].onUnbindToNode(self) self.onUnbindToNode(nodes[i]) } } /** Register the node and signatures of messages that the node is interested in **/ self.onBindToNode = function onBindToNode(node) { if (!(node.getId() in self._nodes)) { self._nodes[node.getId()] = { 'node': node, 'conditions': node.getMessageConditions() } } } /** This removes this node from a connected node (if any) **/ self.onUnbindToNode = function onUnbindToNode(node) { if (node.getId() in self._nodes) { delete self._nodes[node.getId()] } } /** Get a list of conditions functions that determine if a gateway should relay a message to this node (can be propagated across gateways to filter messages from reaching unnecessary parts of the gateway network). **/ self.getMessageConditions = function getMessageConditions() { /** Function to check if this node is interested in this message type */ return function () { return true } } /** Get the conditions for sending a message to a node **/ self.getNodeMessageConditions = function getNodeMessageConditions(nodeId) { if (nodeId in self._nodes) { return self._nodes[nodeId].conditions } else { return function () { return true } } } /** Update the conditions for sending a message to a node **/ self.updateNodeMessageConditions = function updateNodeMessageConditions(nodeId, conditions) { if (nodeId in self._nodes) { self._nodes[nodeId] = [self._nodes[nodeId].node, conditions] } } // Request Management /** Internal function to get all pending request messages **/ self._getRequests = function _getRequests() { var key, reqs reqs = [] for (key in self._requests) { reqs.push(self._requests[key][0]) } return reqs } /** Add a request to the queue, to respond to at some point @param msg: The message that was sent that needs a reply. @param callback: A function to call when the message is received, as f(newMsg, requestMsg) @TODO: Add a timeout for requests, with a timeout callback (maxWait, timeoutCallback) **/ self._addRequest = function _addRequest(msg, callback) { if (callback != null) { self._requests[msg.getId()] = [msg.clone(), callback] } } /** Make a request, which is added to the queue and then sent off to connected services @param msg: The message that was sent that needs a reply. @param callback: A function to call when the message is received, as f(newMsg, requestMsg) **/ self._makeRequest = function _makeRequest(msg, callback) { self._addRequest(msg, callback) self.sendMessage(msg) //console.log("SENT REQUEST:" + Serialization.makeSerialized(Serialization.tokenizeObject(msg))); } /** Trigger any requests that are waiting for a given message. A request is filled when the conversation ID on the message matches the one for the original request. When a request is filled, it is removed, unless the speech act was request whenever (e.g., always) @param msg: Received message to compare against requests. **/ self._triggerRequests = function _triggerRequests(msg) { var key, convoId, oldMsg, callback //console.log("Heard REPLY:" + Serialization.makeSerialized(Serialization.tokenizeObject(msg))); convoId = msg.getContextValue(Messaging.CONTEXT_CONVERSATION_ID_KEY, null) //console.log("CONVO ID: " + convoId); //console.log(self._requests); if (convoId != null) { // @TODO: This is a dict, so can check directly? for (key in self._requests) { if (key === convoId) { oldMsg = self._requests[key][0] callback = self._requests[key][1] callback(msg, oldMsg) // Remove from the requests, unless asked for a permanent feed if (oldMsg.getSpeechAct() !== Messaging.REQUEST_WHENEVER_ACT) { delete self._requests[key] } } } } } // Pack/Unpack Messages /** Convenience function to serialize a message **/ self.messageToString = function messageToString(msg) { return Serialization.makeSerialized(Serialization.tokenizeObject(msg)) } /** Convenience function to turn a serialized JSON message into a message If the message is invalid when unpacked, it is ignored. **/ self.stringToMessage = function stringToMessage(msg) { if (CATCH_BAD_MESSAGES) { try { msg = Serialization.untokenizeObject(Serialization.makeNative(msg)) } catch (err) { // console.log("ERROR: Could not process message data received. Received:"); // console.log(msg); msg = undefined } } else { msg = Serialization.untokenizeObject(Serialization.makeNative(msg)) } return msg } self.makeProposal = function makeProposal(msg, successCallback, retryParams, policyType) { var proposalId = null; console.log('Context Keys : ' + msg.getContextKeys()) if(msg.getContextKeys()['proposalId'] == undefined) { console.log('Setting ID for PROpOSAL KEY') proposalId = UUID.genV4().toString(); msg.setContextValue('proposalId', proposalId); } msg.setContextValue('conversation-id', proposalId); var makePropsalPckt = new Proposal(proposalId, msg, false, successCallback, retryParams, policyType, new Date().getTime()); makePropsalPckt.setRetryParams(retryParams); makePropsalPckt.setPolicyType('Accept at all times'); makePropsalPckt.setAcknowledgementReceived(false); //Checking if the retryParams are set. If set, then calls functions accordingly. if(retryParams != null) { if(retryParams['noOfAttemptsForProposal'] != null ) { var proposalNoOfAttempts = retryParams['noOfAttemptsForProposal']; if(retryParams['failSoftStrategyForProposedMsg'] != null) { var failSoftStrategy = retryParams['failSoftStrategyForProposedMsg']; makePropsalPckt.setFailSoftStrategyForProposedMsg(failSoftStrategy); if(failSoftStrategy == "RESEND_MSG_WITH_ATTEMPT_COUNTS") { makePropsalPckt.getRetryParams()['noOfAttemptsForProposedMsg'] = retryParams['noOfAttemptsForProposedMsg']; } else if(failSoftStrategy == "QUIT_IN_X_TIME") { makePropsalPckt.getRetryParams()['quitInTime'] = retryParams['quitInTime']; } } self.proposals[proposalId] = makePropsalPckt; self.sendProposal(msg, proposalNoOfAttempts); } else { self.proposals[proposalId] = makePropsalPckt; self.sendMessage(msg); } } else { self.proposals[proposalId] = makePropsalPckt; self.sendMessage(msg); } } self.sendProposal = function sendProposal(msg, noOfAttempts) { console.log('Sending Proposal'); var count = 1 var proposalId = msg.getContextValue('proposalId', null) var proposal = self.proposals[proposalId] while(count <= noOfAttempts && proposal.getAcknowledgementReceived() == false) { count += 1 self.sendMessage(msg); async => { self.sendProposal(msg, noOfAttempts-count); //await(5000); } if (self.proposals[proposalId].getAcknowledgementReceived() == false) { console.log("Timeout. Trying Again") } } if(count > noOfAttempts && self.proposals[proposalId].getAcknowledgementReceived() == false) { console.log("No Respose Received.") } } self.retryProposal = function retryProposal(proposalId) { var proposal = self.proposals[proposalId]; self.sendProposal(proposal.getProposal(), proposal.getRetryParams()['PROPOSAL_ATTEMPT_COUNT']); } self.sendNewProposedMessage = function sendNewProposedMessage(msg, proposalId) { console.log('Starting to Send Proposed Message') self.sendMessage(msg) if(msg.getId() in self.proposals[proposalId].getProposedMessages()) { console.log("Seems Proposed Message Hasn't been Processed"); self.proposals[proposalId].setAcknowledgementReceived(false); self.retryProposal(proposalId) } else { console.log("Proposed Message Sent Successfully") } } // Fail Soft Strategy 1 - Send Proposed Message With Attempt Count. self.sendProposedMsgWithAttemptCnt = function sendProposedMsgWithAttemptCnt(proposal) { console.log('Fail Soft Strategy : Sending With Attempt Count') var attemptCount = proposal.getRetryParams()['noOfAttemptsForProposedMsg'] for (var key in proposal.getProposedMessages()) { console.log( proposal.getProposedMessages()) var proposedMessage = proposal.getProposedMessages()[key]; console.log('HOOOLA' + proposedMessage); if(proposedMessage.getNumberOfRetries() < attemptCount) { proposedMessage.setNumberOfRetries(proposedMessage.getNumberOfRetries() + 1) console.log("Send Proposed Message - Attempt " + proposedMessage.getNumberOfRetries()) self.sendNewProposedMessage(proposedMessage.getProposedMessage(), proposal.getId()) } } } // Decides Proposed Message Strategy and delegates messages accordingly // to sendProposedMessage(BaseMessage msg, String proposalId). self.sendProposedMessage = function sendProposedMessage(proposalId) { var proposal = self.proposals[proposalId] if(!proposal.getProposalProcessed()) { var failSoftStrategy = proposal.getRetryParams()['failSoftStrategyForProposedMsg'] != null ? proposal.getRetryParams()['failSoftStrategyForProposedMsg'] : null; console.log('BOOOOOOLA ' + failSoftStrategy); if(failSoftStrategy != null) { if(failSoftStrategy == 'RESEND_MSG_WITH_ATTEMPT_COUNTS') { self.sendProposedMsgWithAttemptCnt(proposal) } else if(failSoftStrategy == 'QUIT_IN_X_TIME') { self.sendProposedMsgWithQuitXTime(proposal) } else if(failSoftStrategy == 'RESEND_MSG_WITH_DEPRIORITZATION') { self.sendProposedMsgWithPrioritization(proposal) } } else { //No Strategy. for(const [key, value] in proposal.getProposedMessages()) { if(value.getNumberOfRetries() < 2) { value.setNumberOfRetries(value.getNumberOfRetries() + 1) console.log('Send Proposed Message - Attempt ' + value.getNumberOfRetries()) self.sendNewProposedMessage(value.getProposedMessage(), proposalId); } } } } } //Fail Soft Strategy 2 - Send Proposed Message With Quit in X Time. self.sendProposedMsgWithQuitXTimedef = function sendProposedMsgWithQuitXTimedef(proposal) { duration = proposal.getRetryParams().get(QUIT_IN_TIME) for(const [key, value] in proposal.getProposedMessages()){ if(time.time() - value.getLastTimeSent() < duration ){ value.setNumberOfRetries(value.getNumberOfRetries() + 1) console.log('Send Proposed Message') self.sendProposedMessage(value.getMsg(), proposal.getId()) } else { console.log("Cannot Send Message. Attempt to Send Quit After " + str(duration) + " seconds.") } } } } }) var MessagingGateway = Zet.declare({ CLASS_ID: 'MessagingGateway', // Base class for messaging gateways superclass: BaseMessagingNode, defineBody: function (self) { // Public Properties /** Initialize a Messaging Gateway. @param id: Unique ID for the gateway @param nodes: Connected nodes for this gateway @param scope: Extra context data to add to messages sent to this gateway, if those keys missing **/ self.construct = function construct(id, nodes, scope) { // Should check for cycles at some point if (scope == null) { scope = {} } self.inherited(construct, [id, nodes]) self._scope = scope } // Handle Incoming Messages /** Receive a message from a connected node and propogate it. **/ self.handleMessage = function handleMessage(msg, senderId) { self.receiveMessage(msg) self._distributeMessage(self._nodes, msg, [senderId]) } // Relay Messages /** Distribute the message, after adding some gateway context data. **/ self._distributeMessage = function _distributeMessage(nodes, msg, excludeIds) { msg = self.addContextDataToMsg(msg) self.inherited(_distributeMessage, [nodes, msg, excludeIds]) } /** Add the additional context data in the Gateway scope, unless those keys already exist in the message's context object. **/ self.addContextDataToMsg = function addContextDataToMsg(msg) { var key for (key in self._scope) { if (!(msg.hasContextValue(key))) { msg.setContextValue(key, self._scope[key]) } } return msg } } }) /** Messaging Gateway Node Stub for Cross-Domain Page Communication A stub gateway that is a placeholder for a PostMessage gateway in another frame. This should only be a child or parent of a PostMessageGateway, because other nodes will not know to send messages via HTML5 postMessage to the actual frame that this stub represents. **/ var PostMessageGatewayStub = Zet.declare({ CLASS_ID: 'PostMessageGatewayStub', superclass: BaseMessagingNode, defineBody: function (self) { // Private Properties var ANY_ORIGIN = '*' // Public Properties /** Initialize a PostMessageGatewayStub @param id: Unique id for the gateway @param gateway: The parent gateway for this stub @param origin: The base URL expected for messages from this frame. @param element: The HTML element (e.g., frame/iframe) that the stub represents. By default parent window. **/ self.construct = function construct(id, gateway, origin, element) { var nodes = null if (gateway != null) { nodes = [gateway] } self.inherited(construct, [id, nodes]) if (origin == null) { origin = ANY_ORIGIN } if (element == null) { element = parent } if (element === window) { element = null } self._origin = origin self._element = element self._queue = [] } /** Get the origin, which is the frame location that is expected **/ self.getOrigin = function getOrigin() { return self._origin } /** Get the HTML element where messages would be sent **/ self.getElement = function getElement() { return self._element } self.getQueue = function getQueue() { return self._queue } } }) /** Messaging Gateway for Cross-Domain Page Communication Note: This should not directly take other PostMessageGateways as nodes. PostMessageGatewayStub objects must be used instead. Only use ONE PostMessageGateway per frame. **/ var PostMessageGateway = Zet.declare({ superclass: MessagingGateway, CLASS_ID: 'PostMessageGateway', defineBody: function (self) { // Private Properties var ANY_ORIGIN = '*' // Public Properties /** Initialize a PostMessageGateway @param id: The unique ID for this gateway. @param nodes: Child nodes for the gateway @param origin: The origin URL for the current window @param scope: Additional context parameters to add to messages sent by children. **/ self.construct = function construct(id, nodes, origin, scope) { if (origin == null) { origin = ANY_ORIGIN } self._origin = origin // Get these ready before adding nodes in base constructor self._postNodes = {} self._validOrigins = {} self._anyOriginValid = true self._registrationInterval = 0 self._registry = {} // Construct self.inherited(construct, [id, nodes, scope]) self.validatePostingHierarchy() if (window) { self.bindToWindow(window) } if (nodes && nodes.length) { nodes.forEach(function (t) { if (PostMessageGatewayStub.isInstance(t) && t.getElement() === window.parent) { self.startRegistration(t) t._isActive = false //stub is inactive unless registered } }) } } self.startRegistration = function (node) { var senderId = self.getId() var msg = Message(senderId, 'REGISTER', null, true) var interval = setInterval(function () { self._transmitPostMessage(node, msg, senderId) }, 2000) self._registrationInterval = interval } self.stopRegistration = function () { clearInterval(self._registrationInterval) } /** Get the origin for this window **/ self.getOrigin = function getOrigin() { return self._origin } /** Get a stub that is the equivalent to this gateway **/ self.getStub = function getStub() { return PostMessageGatewayStub(self._id, self._gateway, self._origin) } /** Validates that no additional PostMessageGateway nodes are connected and in the same frame. Valid neighbors can have no PostMessageGateway nodes, and only the parent OR the children can be of the PostMessageGatewayStub class **/ self.validatePostingHierarchy = function validatePostingHierarchy() { var key for (key in self._nodes) { if (PostMessageGateway.isInstance(self._nodes[key])) { throw TypeError("Error: Cannot directly connect PostMessageGateways") } } // @TODO: Check for cycles in the posting hierarchy } /** Register the node and signatures of messages that the node is interested in **/ self.onBindToNode = function onBindToNode(node) { self.inherited(onBindToNode, [node]) self._onAttachNode(node) } /** This removes this node from a connected node (if any) **/ self.onUnbindToNode = function onUnbindToNode(node) { self._onDetachNode(node) self.inherited(onUnbindToNode, [node]) } /** When attaching nodes, adds any origins of PostMessageGatewayStubs to an allowed list of valid origins for HTML5 postMessages. @param node: A child node to attach. @type node: BaseMessagingNode **/ self._onAttachNode = function _onAttachNode(node) { // @TODO: Should check if already attached and raise error if (PostMessageGatewayStub.isInstance(node) && (!(node.getId() in self._postNodes))) { if (self._validOrigins[node.getOrigin()] == null) { self._validOrigins[node.getOrigin()] = 1 } else { self._validOrigins[node.getOrigin()] += 1 } if (node.getOrigin() === ANY_ORIGIN) { self._anyOriginValid = true } self._postNodes[node.getId()] = node } } /** When detaching nodes, clears any origins of PostMessageGatewayStubs from an allowed list of valid origins for HTML5 postMessages. @param node: A child node to attach. @type node: BaseMessagingNode **/ self._onDetachNode = function _onDetachNode(node) { if (PostMessageGatewayStub.isInstance(node) && (node.getId() in self._postNodes)) { self._validOrigins[node.getOrigin()] += -1 if (self._validOrigins[node.getOrigin()] === 0) { delete self._validOrigins[node.getOrigin()] if (!(ANY_ORIGIN in self._validOrigins)) { self._anyOriginValid = false } } delete self._postNodes[node.getId()] } } /** Bind the HTML5 event listener for HTML5 postMessage **/ self.bindToWindow = function bindToWindow(aWindow) { var eventMethod, eventer, messageEvent eventMethod = aWindow.addEventListener ? "addEventListener" : "attachEvent" eventer = aWindow[eventMethod] messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message" eventer(messageEvent, function (event) { self._receivePostMessage(event) }) } // Messaging /** Send a message to parent. Send as normal, but send using sendPostMessage if sending to a PostMessage stub. **/ /** Transmit the message to another node **/ self._transmitMessage = function _transmitMessage(node, msg, senderId) { if (PostMessageGatewayStub.isInstance(node)) { if (node._isActive) { self._processPostMessageQueue(node) self._transmitPostMessage(node, msg, senderId) } else { node.getQueue().push({ msg: msg, senderId: senderId }) } } else { node.handleMessage(msg, senderId) } } self._processPostMessageQueue = function (stub) { stub.getQueue().forEach(function (o) { self._transmitPostMessage(stub, o.msg, o.senderId) }) stub.getQueue().splice(0, stub.getQueue().length) } // HTML5 PostMessage Commands self._transmitPostMessage = function _transmitPostMessage(node, msg, senderId) { if (node._stubId) { msg.setObject(msg.getObject() == null ? {} : msg.getObject()) msg.getObject()["stubId"] = node._stubId } var postMsg, element postMsg = JSON.stringify({ 'SuperGLU': true, 'msgType': 'SuperGLU', 'version': version, 'senderId': senderId, 'targetId': node.getId(), 'msg': self.messageToString(msg) }) element = node.getElement() if (element != null) { // console.log(JSON.parse(postMsg).senderId + " POSTED UP " + self.messageToString(msg)); element.postMessage(postMsg, node.getOrigin()) } } self._receivePostMessage = function _receivePostMessage(event) { var senderId, message, targetId //console.log(self._id + " RECEIVED POST " + JSON.parse(event.data)); if (self.isValidOrigin(event.origin)) { try { message = JSON.parse(event.data) } catch (err) { // console.log("Post Message Gateway did not understand: " + event.data); return } senderId = message.senderId targetId = message.targetId message = self.stringToMessage(message.msg) // console.log(message); if (Message.isInstance(message) & (targetId === self.getId()) && message.getVerb() === 'REGISTER' ) { var obj = message.getObject() || {} var node = null var verb = 'REGISTERED' var stubId = UUID.genV4().toString() if (obj.stubId) { stubId = obj.stubId node = self._registry[stubId] } else { node = PostMessageGatewayStub(senderId, null, null, event.source) self._registry[stubId] = node self.addNodes([node]) } var msg = Message(self.getId(), verb, {stubId: stubId}, true) self._transmitPostMessage(node, msg, self.getId()) } else if (Message.isInstance(message) & (targetId === self.getId()) && message.getVerb() === 'REGISTERED' ) { var nodes = self.getNodes() nodes.forEach(function (node) { if (PostMessageGatewayStub.isInstance(node) && node.getElement() === window.parent) { self.stopRegistration() node._isActive = true //stub is inactive unless registered self._stubId = message.getObject().stubId self._processPostMessageQueue(node) } }) } else if (Message.isInstance(message) & (targetId === self.getId()) && (senderId in self._postNodes)) { if (PostMessageGatewayStub.isInstance(self._postNodes[senderId])) { self._postNodes[senderId]._isActive = true } self.handleMessage(message, senderId) } } } self.isValidOrigin = function isValidOrigin(url) { if (self._anyOriginValid) { return true } else { return url in self._validOrigins } } } }) var HTTPMessagingGateway = Zet.declare({ // Base class for messaging gateways // This uses socket.io.js and uuid.js superclass: MessagingGateway, CLASS_ID: 'HTTPMessagingGateway', defineBody: function (self) { // Public Properties // Events: connecting, connect, disconnect, connect_failed, error, // message, anything, reconnecting, reconnect, reconnect_failed // Listed At: github.com/LearnBoost/socket.io/wiki/Exposed-events var MESSAGING_NAMESPACE = '/messaging', TRANSPORT_SET = ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling'] // Set Socket.IO Allowed Transports self.construct = function construct(id, nodes, url, sessionId, scope) { self.inherited(construct, [id, nodes, scope]) // Classifier not used here, as messages are exact responses. if (url == null) { url = null } if (sessionId == null) { sessionId = UUID.genV4().toString() } self._url = url self._socket = io.connect(self._url + MESSAGING_NAMESPACE) self._isConnected = false self._sessionId = sessionId self._socket.on('message', self.receiveWebsocketMessage) } self.bindToConnectEvent = function bindToConnectEvent(funct) { self._socket.on('connect', funct) } self.bindToCloseEvent = function bindToCloseEvent(funct) { self._socket.on('disconnect', funct) } self.addSessionData = function addSessionData(msg) { msg.setContextValue(SESSION_ID_KEY, self._sessionId) return msg } /** Distribute the message, after adding some gateway context data. **/ self._distributeMessage = function _distributeMessage(nodes, msg, excludeIds, noSocket) { msg = self.addContextDataToMsg(msg) if (noSocket !== true && self._url != null) { msg = self.addSessionData(msg) self.sendWebsocketMessage(msg) } self.inherited(_distributeMessage, [nodes, msg, excludeIds]) } self.sendWebsocketMessage = function sendWebsocketMessage(msg) { msg = self.messageToString(msg) self._socket.emit('message', {data: msg, sessionId: self._sessionId}) } self.receiveWebsocketMessage = function receiveWebsocketMessage(msg) { var sessionId sessionId = msg.sessionId msg = msg.data msg = self.stringToMessage(msg) // console.log("GOT THIS:" + sessionId); // console.log("Real Sess: " + self._sessionId); if (Message.isInstance(msg) && (sessionId == null || sessionId == self._sessionId)) { self._distributeMessage(self._nodes, msg, [], true) } } } }) var BaseService = Zet.declare({ // Base class for messaging gateways superclass: BaseMessagingNode, CLASS_ID: 'BaseService', defineBody: function (self) { // Public Properties self.construct = function construct(id, gateway) { var nodes = null if (gateway != null) { nodes = [gateway] } self.inherited(construct, [id, nodes]) } /** Connect nodes to this node. Only one node (a gateway) should be connected to a service. **/ self.addNodes = function addNodes(nodes) { //if (nodes.length + self.getNodes().length <= 1) { self.inherited(addNodes, [nodes]) //} else { // console.log("Error: Attempted to add more than one node to a service. Service must only take a single gateway node. Service was: " + self.getId()) //} } /** Bind nodes to this node. Only one node (a gateway) should be connected to a service. **/ self.onBindToNode = function onBindToNode(node) { if (self.getNodes().length === 0) { self.inherited(onBindToNode, [node]) } else { console.log("Error: Attempted to bind more than one node to a service. Service must only take a single gateway node.") } } } }) var TestService = Zet.declare({ // Base class for messaging gateways superclass: BaseService, CLASS_ID: 'TestService', defineBody: function (self) { // Public Properties self.receiveMessage = function receiveMessage(msg) { console.log("TEST SERVICE " + self.getId() + " GOT: \n" + self.messageToString(msg)) self.inherited(receiveMessage, [msg]) } self.sendTestString = function sendTestString(aStr) { console.log("Test Service is Sending: " + aStr) self.sendMessage(Message("TestService", "Sent Test", "To Server", aStr)) } self.sendTestMessage = function sendTestMessage(actor, verb, object, result, speechAct, context, addGatewayContext) { var msg if (context == null) { context = {} } if (addGatewayContext == null) { addGatewayContext = true } msg = Message(actor, verb, object, result, speechAct, context) if ((self._gateway != null) && (addGatewayContext)) { msg = self._gateway.addContextDataToMsg(msg) } self.sendMessage(msg) } self.sendTestRequest = function sendTestRequest(callback, actor, verb, object, result, speechAct, context, addGatewayContext) { var msg if (context == null) { context = {} } if (addGatewayContext == null) { addGatewayContext = true } msg = Message(actor, verb, object, result, speechAct, context) if ((self._gateway != null) && (addGatewayContext)) { msg = self._gateway.addContextDataToMsg(msg) } self._makeRequest(msg, callback) } } }) namespace.SESSION_ID_KEY = SESSION_ID_KEY namespace.BaseService = BaseService namespace.MessagingGateway = MessagingGateway namespace.PostMessageGatewayStub = PostMessageGatewayStub namespace.PostMessageGateway = PostMessageGateway namespace.HTTPMessagingGateway = HTTPMessagingGateway namespace.TestService = TestService namespace.Proposal = Proposal namespace.ProposedMessage = ProposedMessage module.exports = namespace
JavaScript
CL
2fa9f8dee17295e7aa3302d824e2b05ea317fd1032b5c3a0de0cf450602164e0
"use strict"; var thingsToLoad = ["images/alien.png", "images/monsterNormal.png", "images/monsterAngry.png"]; //Create a new Hexi instance, and start it. var g = hexi(704, 512, setup, thingsToLoad); //Set the background color and scale the canvas //g.backgroundColor = "black"; g.scaleToWindow(); //Start Hexi g.start(); //Game variables var alien = undefined, monster = undefined, boxes = undefined, line = undefined; //The `setup` function to initialize your application function setup() { //Create the alien using the `alienFrames` alien = g.sprite("images/alien.png"); //Center the alien on the left side of the canvas g.stage.putCenter(alien, -g.canvas.width / 4); //Create the monster sprite using the `monsterFrames` monster = g.sprite(["images/monsterNormal.png", "images/monsterAngry.png"]); //Define the monster's two states: `normal` and `scared` //`0` and `1` refer to the monster's two animation frames monster.states = { normal: 0, angry: 1 }; //Center the monster on the right side of the canvas g.stage.putCenter(monster, g.canvas.width / 4); //Create the boxes boxes = []; var numberOfboxes = 4; for (var i = 0; i < numberOfboxes; i++) { boxes.push(g.sprite("images/box.png")); } //Position the boxes in a square shape around the //center of the canvas g.stage.putCenter(boxes[0], -32, -64); g.stage.putCenter(boxes[1], 32, -64); g.stage.putCenter(boxes[2], -32); g.stage.putCenter(boxes[3], 32); //Switch on drag-and-drop for all the sprites alien.draggable = true; monster.draggable = true; boxes.forEach(function (wall) { return wall.draggable = true; }); //Create a `line` sprite. //`line` arguments: //strokeStyle, lineWidth, ax, ay, bx, by //`ax` and `ay` define the line's start x/y point, //`bx`, `by` define the line's end x/y point. line = g.line("red", 4, monster.centerX, monster.centerY, alien.centerX, alien.centerY); //Set the line's alpha to 0.3 line.alpha = 0.3; var message = g.text("Drag and drop the sprites", "16px Futura", "black"); message.x = 30; message.y = 10; //Change the game state to `play` g.state = play; } //The `play` function contains all the game logic and runs in a loop function play() { //Update the position of the line line.ax = monster.centerX; line.ay = monster.centerY; line.bx = alien.centerX; line.by = alien.centerY; //Check whether the monster can see the alien by setting its //`lineOfSight` property. `lineOfSight` will be `true` if there //are no boxes obscuring the view, and `false` if there are monster.lineOfSight = lineOfSight(monster, //Sprite one alien, //Sprite two boxes, //An array of obstacle sprites 16 //The distance between each collision point ); //If the monster has line of sight, set its state to "angry" and if (monster.lineOfSight) { monster.show(monster.states.angry); line.alpha = 1; } else { monster.show(monster.states.normal); line.alpha = 0.3; } } //Helper functions function lineOfSight(spriteOne, //The first sprite, with `centerX` and `centerY` properties spriteTwo, //The second sprite, with `centerX` and `centerY` properties obstacles) //The distance between collision points { var segment = arguments.length <= 3 || arguments[3] === undefined ? 32 : arguments[3]; //Plot a vector between spriteTwo and spriteOne var vx = spriteTwo.centerX - spriteOne.centerX, vy = spriteTwo.centerY - spriteOne.centerY; //Find the vector's magnitude (its length in pixels) var magnitude = Math.sqrt(vx * vx + vy * vy); //How many points will we need to test? var numberOfPoints = magnitude / segment; //Create an array of x/y points, separated by 64 pixels, that //extends from `spriteOne` to `spriteTwo` var points = function points() { //Initialize an array that is going to store all our points //along the vector var arrayOfPoints = []; //Create a point object for each segment of the vector and //store its x/y position as well as its index number on //the map array for (var i = 1; i <= numberOfPoints; i++) { //Calculate the new magnitude for this iteration of the loop var newMagnitude = segment * i; //Find the unit vector. This is a small, scaled down version of //the vector between the sprites that's less than one pixel long. //It points in the same direction as the main vector, but because it's //the smallest size that the vector can be, we can use it to create //new vectors of varying length var dx = vx / magnitude, dy = vy / magnitude; //Use the unit vector and newMagnitude to figure out the x/y //position of the next point in this loop iteration var x = spriteOne.centerX + dx * newMagnitude, y = spriteOne.centerY + dy * newMagnitude; //Push a point object with x and y properties into the `arrayOfPoints` arrayOfPoints.push({ x: x, y: y }); } //Return the array of point objects return arrayOfPoints; }; //Test for a collision between a point and a sprite var hitTestPoint = function hitTestPoint(point, sprite) { //Find out if the point's position is inside the area defined //by the sprite's left, right, top and bottom sides var left = point.x > sprite.x, right = point.x < sprite.x + sprite.width, top = point.y > sprite.y, bottom = point.y < sprite.y + sprite.height; //If all the collision conditions are met, you know the //point is intersecting the sprite return left && right && top && bottom; }; //The `noObstacles` function will return `true` if all the tile //index numbers along the vector are `0`, which means they contain //no obstacles. If any of them aren't 0, then the function returns //`false` which means there's an obstacle in the way var noObstacles = points().every(function (point) { return obstacles.every(function (obstacle) { return !hitTestPoint(point, obstacle); }); }); //Return the true/false value of the collision test return noObstacles; } //# sourceMappingURL=lineOfSight.js.map
JavaScript
CL
51e72c38bf902090bcf12234e622220fe0482d954c03fc6b0608d3cf5b525217
import * as constants from 'modules/Lectures/UpdateRate/constants'; import * as actions from 'modules/Lectures/UpdateRate/actions'; import reducers from 'modules/Lectures/UpdateRate/reducers'; import * as selectors from 'modules/Lectures/UpdateRate/selectors'; import sagas from 'modules/Lectures/UpdateRate/sagas'; const moduleName = 'Lectures/UpdateRate'; export { constants, reducers, moduleName, actions, sagas, selectors, };
JavaScript
CL
498db0b97fdff9b3c33fedb73961d827da1cf852bec7a0278f1312b2a6e05539
app /** * Controller per la visualizzazione delle informazioni del progetto corrente * @module infoProject * @param {Object} $scope L'oggetto {@link https://docs.angularjs.org/guide/scope|$scope} indica il contesto in cui sono * salvati i dati e valutate le espressioni * @param {Object} $http Il servizio AngularJS {@link https://docs.angularjs.org/api/ng/service/$http|$http} per la * comunicazione con i server HTTP * @param {Object} $mdDialog Il servizio di AngularJS Material * {@link https://material.angularjs.org/1.1.6/api/service/$mdDialog|$mdDialog} permette di gestire una finestra di * dialogo con l'utente * @param {Object} Labels Il servizio {@link Labels} contiene i dati del grafo utente */ .controller("infoProject", function($scope, $http, $mdDialog, Labels){ $scope.labels = Labels; $scope.nomeProgetto = Labels.nomeProgetto; /** * Mostra la finestra modale per la visualizzione delle informazioni del * progetto corrente * @function showInfoProject * @param {event} $event Click dell'utente sul bottone dell'interfaccia */ $scope.showInfoProject = function($event) { $mdDialog.show({ targetEvent: $event, templateUrl: 'static/source/templates/infoProjectModal.html', windowClass: 'modal-content', controller: projectInfoCtrl, clickOutsideToClose: true }); }; function projectInfoCtrl($scope, $mdDialog, Labels) { $scope.nomeProgetto = Labels.nomeProgetto; console.log($scope.nomeProgetto); $scope.nomeDB = Labels.nomeDB; $scope.descrizioneProgetto = Labels.descrizioneProgetto; $scope.supportedDB = Labels.supportedDB; $scope.dbms = Labels.dbms; /** * Modifica delle informazioni del progetto corrente, * invia i dati alla view change_project_data * @function modifica */ $scope.modifica = function () { info = { nome: $scope.nomeProgetto, nomeDB: $scope.nomeDB, dbms: $scope.dbms, descrizione: $scope.descrizioneProgetto}; $http.post("../change_project_data/", JSON.stringify(info)) .then(function successCallback(response){ Labels.nomeProgetto = $scope.nomeProgetto; Labels.nomeDB = $scope.nomeDB; Labels.descrizioneProgetto = $scope.descrizioneProgetto; Labels.dbms = $scope.dbms; console.log("Successfully POST-ed data"); }, function errorCallback(response){ console.log("POST-ing of data failed"); }); }; /** * Nasconde la finestra modale * @function closeDialog */ $scope.closeDialog = function () { $mdDialog.hide(); }; } });
JavaScript
CL
f7f09424107d9548ffcdef84b069b99e3fe51adb4c1b78dbfabaf0469e5aa37b
/* * Copyright © 2018 Lisk Foundation * * See the LICENSE file at the top-level directory of this distribution * for licensing information. * * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation, * no part of this software, including this file, may be copied, modified, * propagated, or distributed except according to the terms contained in the * LICENSE file. * * Removal or modification of this copyright notice is prohibited. */ 'use strict'; const path = require('path'); const assert = require('assert'); const { entities: { BaseEntity }, utils: { filterTypes: { BOOLEAN }, }, } = require('../../../components/storage'); const sqlFiles = { upsert: 'chain_state/upsert.sql', get: 'chain_state/get.sql', delete: 'chain_state/delete.sql', }; class ChainState extends BaseEntity { constructor(adapter, defaultFilters = {}) { super(adapter, defaultFilters); this.addField('key', 'string', { filter: BOOLEAN }); this.addField('value', 'string'); this.sqlDirectory = path.join(path.dirname(__filename), '../sql'); this.SQLs = this.loadSQLFiles('chain_state', sqlFiles, this.sqlDirectory); } get(filters = {}, options = {}, tx = null) { return this._getResults(filters, options, tx); } getOne(filters = {}, options = {}, tx = null) { const expectedResultCount = 1; return this._getResults(filters, options, tx, expectedResultCount); } async getKey(key, tx) { assert(key, 'Must provide the key to get'); return this.get({ key }, {}, tx).then(data => { if (data.length === 0) { return null; } return data[0].value; }); } async setKey(key, value, tx) { assert(key, 'Must provide the key to set'); assert( value !== null && value !== undefined, 'Must provide the value to set', ); const expectedResultCount = 0; return this.adapter.executeFile( this.SQLs.upsert, { key, value }, { expectedResultCount }, tx, ); } delete(filters, _options, tx = null) { this.validateFilters(filters); const mergedFilters = this.mergeFilters(filters); const parsedFilters = this.parseFilters(mergedFilters); return this.adapter .executeFile( this.SQLs.delete, { parsedFilters }, { expectedResultCount: 0 }, tx, ) .then(result => result); } _getResults(filters, options, tx, expectedResultCount = undefined) { this.validateFilters(filters); this.validateOptions(options); const mergedFilters = this.mergeFilters(filters); const parsedFilters = this.parseFilters(mergedFilters); const { limit, offset, sort } = { ...this.defaultOptions, ...options, }; const parsedSort = this.parseSort(sort); const params = { limit, offset, parsedSort, parsedFilters, }; return this.adapter.executeFile( this.SQLs.get, params, { expectedResultCount }, tx, ); } } module.exports = ChainState;
JavaScript
CL
1eb96f1685d69970b91c4c1f8b66452015aa5b1ec8dc3d4693fa430d483177ba
// Copyright 2020 The OpenZipkin Authors; licensed to You under the Apache License, Version 2.0. const path = require('path'); const testMiddleware = require('./test/middleware'); module.exports = function(config) { if (process.env.TEST_SUITE === 'nodejs') { /* eslint-disable no-console */ console.log('WARN: Skipping browser tests because TEST_SUITE is \'nodejs\'.'); /* eslint-enable no-console */ process.exit(0); } config.set({ // resolve to the package not the location of this file basePath: path.resolve('.'), failOnEmptyTestSuite: true, middleware: ['custom'], plugins: [ { // This allows http client tests that execute in the browser to be able to hit // endpoint needed for functional testing such as status code parsing. // // Technically, this adds extra endpoints to the karma server (which serves the // unit tests themselves). Http client tests call relative paths to access these // endpoints. This is needed because unlike normal node.js tests, we can't start // a server listener for test endpoints inside the web browser. 'middleware:custom': ['factory', testMiddleware] }, 'karma-mocha', 'karma-browserify', 'karma-chai', 'karma-source-map-support', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-mocha-reporter', ], frameworks: ['mocha', 'browserify', 'chai', 'source-map-support'], preprocessors: { 'test/**/*.js': ['browserify'] }, browserify: { debug: true, }, files: ['test/**/*.js'], // unless you use the mocha reporter, you won't see test failure details. reporters: ['mocha'], mochaReporter: { // unless showDiff, you won't see which properties were unexpected showDiff: true, }, port: 9876, colors: true, logLevel: config.LOG_INFO, // see https://github.com/karma-runner/karma-firefox-launcher/issues/76 customLaunchers: { FirefoxHeadless: { base: 'Firefox', flags: ['-headless'], }, }, browsers: ['ChromeHeadless', 'FirefoxHeadless'], autoWatch: false, concurrency: Infinity }); };
JavaScript
CL
42da1ffec09f3f052fe2decec559029e3b7747f35f325822195447cfbd9f88d7
import React from 'react'; import ReactDOM from 'react-dom'; import { expect } from 'chai'; import { spy } from 'sinon'; import { mount } from 'enzyme'; import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import App from './App'; // MOCKS // have to mock local storage because it's not available in jest class LocalStorageMock { constructor() { this.store = {} } clear() { this.store = {} } getItem(key) { return this.store[key] || null } setItem(key, value) { this.store[key] = value } removeItem(key) { delete this.store[key] } } global.localStorage = new LocalStorageMock // TESTS const mock = new MockAdapter(axios); it('renders without an error', () => { mock.onGet('http://localhost:8000/session').reply(200, { sessionId: "randomSessionId" }); spy(App.prototype, 'componentDidMount'); const wrapper = mount(<App />); expect(App.prototype.componentDidMount.calledOnce).to.equal(true); App.prototype.componentDidMount.restore(); //cleaning the spy }); // more of a behavioural test, checking that the session is set corectly and then poking the state with a proverbial stick // to see if everything is set correctly it('successfully sets the session id', async () => { mock.onGet('http://localhost:8000/session').reply(200, { sessionId: "randomSessionId" }); spy(App.prototype, 'componentWillMount'); spy(App.prototype, 'updateSessionId'); spy(localStorage, 'setItem'); const wrapper = mount(<App />); localStorage.clear(); // we have no way to wait for the componentWillMount func but we can wait for our helper function await wrapper.instance().updateSessionId(); expect(App.prototype.componentWillMount.calledOnce).to.equal(true); // because we manually call it again, there should be 2 calls to update session id expect(App.prototype.updateSessionId.callCount).to.equal(2); // but because state is changed from the first async call, the second call does not set the session id anymore expect(localStorage.setItem.callCount).to.equal(1); expect(wrapper.state().sessionId).to.equal('randomSessionId'); // sinon spy cleanup App.prototype.componentWillMount.restore(); App.prototype.updateSessionId.restore(); localStorage.setItem.restore(); }); describe('changing inputs', () => { it('does allow the values to be changed', async () => { const wrapper = mount(<App />); const email = wrapper.find('[name="email"]'); email.simulate('change', { target: { value: 'mail@random.com' }}); expect(wrapper.state().email).to.equal('mail@random.com'); }); });
JavaScript
CL
282d41a32b6b42571273e0604c18c35db5ef2848588565648deeec9c9a307c4c
/* eslint-disable import/order */ import { applyMiddleware, compose, createStore } from 'redux'; import { routerMiddleware as createRouterMiddleware } from 'connected-react-router'; import createSagaMiddleware from 'redux-saga'; import { createRootReducer, sagas } from './'; /* connected-react-router */ import { createBrowserHistory } from 'history'; /* redux-logger */ import { createLogger } from 'redux-logger'; /* redux-persist */ import { persistReducer, persistStore } from 'redux-persist'; import storage from 'redux-persist/lib/storage'; export const history = createBrowserHistory(); export default function configureStore(preloadedState) { /* middleware */ const sagaMiddleware = createSagaMiddleware(); const loggerMiddleware = createLogger({ collapsed: true }); const routerMiddleware = createRouterMiddleware(history); /* persist state */ const persistConfig = { blacklist: [ 'router', 'session', 'loader', 'user', 'autocompleter', 'validation', 'instagram', 'spotify', 'autocompleter', 'events' ], key: 'root', storage }; const rootReducer = createRootReducer(history); const persistedReducer = persistReducer(persistConfig, rootReducer); /* store */ const store = createStore( persistedReducer, preloadedState, compose( applyMiddleware( sagaMiddleware, loggerMiddleware, routerMiddleware ) ) ); const persistor = persistStore(store); sagaMiddleware.run(sagas); return { persistor, store }; }
JavaScript
CL
47bb39ec175d4c679de5c02282052c6b4761c99c000865e55760e8769f6aac0c
import { createMemoryHistory } from 'history'; import i18n from 'i18next'; import React from 'react'; import { useIdentityContext } from 'react-netlify-identity'; import { ENABLED_LANGUAGES } from '../../constants/env'; import { render } from '../../utils/testUtils'; import LanguageRoute from '.'; jest.mock('react-netlify-identity'); beforeEach(() => { useIdentityContext.mockReturnValue({ isLoggedIn: false, }); }); describe('<LanguageRoute />', () => { it('should render without crashing && do nothing on "/"', () => { render(<LanguageRoute />); }); ENABLED_LANGUAGES.forEach(language => { const history = createMemoryHistory({ initialEntries: [`/${language}`], }); it(`should render without crashing on a matching route (${language}) and change the language`, () => { expect(i18n.language).not.toBe(language); render(<LanguageRoute />, { history }); expect(i18n.language).toBe(language); }); }); });
JavaScript
CL
b42cee0f5ac140c064cd33612b8891d0de2816a8840ce7789588b11177c49fdd
import React from "react"; import { Timeline } from "antd"; export default function Experience() { const windowsize = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; if (windowsize > 780) { return ( <Timeline mode="alternate"> <Timeline.Item label="June 2018 - Present"> <h3>Freelance Front-end Developer</h3> <p> I work primarily as a Front-end developer to develop and launch multiple projects from scratch, carrying the development of its' front-end and back-end codebases. </p> <p> In front-end development, my current toolset includes React, Redux, ES6 and the other various frameworks, libraries and technologies related to them. I also care about UI design, providing elegant UI and graphic design for my clients. </p> <p> In back-end development, my current stack involves NodeJS, MongoDB, REST API, and GraphQL. </p> </Timeline.Item> <Timeline.Item label="October 2014 - July 2019"> <h3>Frontend Web Developer in Globex People LLC </h3> <p> Created multiple web applications, participating in the whole process of their development: UI/UX design, code development, testing, deployment and maintenance. </p> <p> I also had to care about things like good planning of UI, consistency in design, typography, accessbility and responsive design. </p> <p> Main stack: JavaScript, JQuery, HTML, CSS3, Bootstrap, Wordpress, PHP and React. </p> <p>Design tools: Adobe Creative Suite, Balsamiq Mockups, Sketch</p> </Timeline.Item> <Timeline.Item label="Feb 2014 - Sep 2014"> <h3>UI/UX Developer Intern in Accenture </h3> <p> Worked with a lead designer to provide UI/UX solutions, including wireframes, flowcharts, and prototypes. </p> <p> Focused on UI design to bring forth a compelling experience that coincides with their desired branding. Created and maintain websites. </p> </Timeline.Item> </Timeline> ); } else { return ( <Timeline> <Timeline.Item> <h3>Freelance Front-end Developer</h3> <p> I work primarily as a Front-end developer to develop and launch multiple projects from scratch, carrying the development of its' front-end and back-end codebases. </p> <p> In front-end development, my current toolset includes React, Redux, ES6 and the other various frameworks, libraries and technologies related to them. I also care about UI design, providing elegant UI and graphic design for my clients. </p> <p> In back-end development, my current stack involves NodeJS, MongoDB, REST API, and GraphQL. </p> </Timeline.Item> <Timeline.Item> <h3>Frontend Web Developer in Globex People LLC </h3> <p> Created multiple web applications, participating in the whole process of their development: UI/UX design, code development, testing, deployment and maintenance. </p> <p> I also had to care about things like good planning of UI, consistency in design, typography, accessbility and responsive design. </p> <p> Main stack: JavaScript, JQuery, HTML, CSS3, Bootstrap, Wordpress, PHP and React. </p> <p>Design tools: Adobe Creative Suite, Balsamiq Mockups, Sketch</p> </Timeline.Item> <Timeline.Item> <h3>UI/UX Developer Intern in Accenture </h3> <p> Worked with a lead designer to provide UI/UX solutions, including wireframes, flowcharts, and prototypes. </p> <p> Focused on UI design to bring forth a compelling experience that coincides with their desired branding. Created and maintain websites. </p> </Timeline.Item> </Timeline> ); } }
JavaScript
CL
99e41e86c254c3628a864b254569895c04eb1a6db61731e70b675aa30247cbb2
const { handleResponse, successResponse, errorResponseBadRequest, errorResponseServerError } = require('../apiHelpers') const txRelay = require('../txRelay') module.exports = function (app) { // TODO(roneilr): authenticate that user controls senderAddress somehow, potentially validate that // method sig has come from sender address as well app.post('/relay', handleResponse(async (req, res, next) => { let body = req.body if (body && body.contractRegistryKey && body.contractAddress && body.senderAddress && body.encodedABI) { // send tx let receipt try { receipt = await txRelay.sendTransaction( body.contractRegistryKey, body.contractAddress, body.encodedABI, body.senderAddress, false, body.gasLimit || null) } catch (e) { if (e.message.includes('nonce')) { req.logger.warn('Nonce got out of sync, resetting. Original error message: ', e.message) // this is a retry in case we get an error about the nonce being out of sync // the last parameter is an optional bool that forces a nonce reset receipt = await txRelay.sendTransaction( body.contractRegistryKey, body.contractAddress, body.encodedABI, body.senderAddress, true, body.gasLimit || null) // no need to return success response here, regular code execution will continue after catch() } else if (e.message.includes('already been submitted')) { return errorResponseBadRequest(e.message) } else { req.logger.error('Error in transaction:', e.message) return errorResponseServerError('Something caused the transaction to fail') } } return successResponse({ receipt: receipt }) } else return errorResponseBadRequest('Missing one of the required fields: contractRegistryKey, contractAddress, senderAddress, encodedABI') })) }
JavaScript
CL
9f36c4bab9ea73fb7278aa65364b79751fa50be4e9761dd2e987ebc970772008
// LICENSE : MIT "use strict"; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var RuleHelper = require("textlint-rule-helper").RuleHelper; var japaneseRegExp = /(?:[々〇〻\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF]|[\uD840-\uD87F][\uDC00-\uDFFF]|[ぁ-んァ-ヶ])/; /*** * 典型的な句点のパターン * これは`periodMark`と交換しても違和感がないものを登録 * @type {RegExp} */ var classicPeriodMarkPattern = /[。\.]/; var checkEndsWithPeriod = require("check-ends-with-period"); var defaultOptions = { // 優先する句点文字 periodMark: "。", // 句点文字として許可する文字列の配列 // 例外として許可したい文字列を設定する // `periodMark`に指定したものは自動的に許可リストに加わる allowPeriodMarks: [], // 末尾に絵文字を置くことを許可するか allowEmojiAtEnd: false, // 句点で終わって無い場合に`periodMark`を--fix時に追加するかどうか // デフォルトでは自動的に追加しない forceAppendPeriod: false }; var reporter = function reporter(context) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var Syntax = context.Syntax, RuleError = context.RuleError, report = context.report, fixer = context.fixer, getSource = context.getSource; var helper = new RuleHelper(context); // 優先する句点記号 var preferPeriodMark = options.periodMark || defaultOptions.periodMark; // 優先する句点記号は常に句点として許可される var allowPeriodMarks = (options.allowPeriodMarks || defaultOptions.allowPeriodMarks).concat(preferPeriodMark); var allowEmojiAtEnd = options.allowEmojiAtEnd !== undefined ? options.allowEmojiAtEnd : defaultOptions.allowEmojiAtEnd; var forceAppendPeriod = options.forceAppendPeriod !== undefined ? options.forceAppendPeriod : defaultOptions.forceAppendPeriod; var ignoredNodeTypes = [Syntax.ListItem, Syntax.Link, Syntax.Code, Syntax.Image, Syntax.BlockQuote, Syntax.Emphasis]; return _defineProperty({}, Syntax.Paragraph, function (node) { if (helper.isChildNode(node, ignoredNodeTypes)) { return; } var lastNode = node.children[node.children.length - 1]; if (lastNode === undefined || lastNode.type !== Syntax.Str) { return; } var lastStrText = getSource(lastNode); if (lastStrText.length === 0) { return; } // 日本語が含まれていない文章は無視する if (!japaneseRegExp.test(lastStrText)) { return; } var _checkEndsWithPeriod = checkEndsWithPeriod(lastStrText, { periodMarks: allowPeriodMarks, allowEmoji: allowEmojiAtEnd }), valid = _checkEndsWithPeriod.valid, periodMark = _checkEndsWithPeriod.periodMark, index = _checkEndsWithPeriod.index; // 問題が無い場合は何もしない if (valid) { return; } // 文末がスペースである場合はスペースを削除する if (/\s/.test(periodMark)) { report(lastNode, new RuleError("\u6587\u672B\u304C\"" + preferPeriodMark + "\"\u3067\u7D42\u308F\u3063\u3066\u3044\u307E\u305B\u3093\u3002\u672B\u5C3E\u306B\u4E0D\u8981\u306A\u30B9\u30DA\u30FC\u30B9\u304C\u3042\u308A\u307E\u3059\u3002", { index: index, fix: fixer.replaceTextRange([index, index + periodMark.length], "") })); return; } // 典型的なパターンは自動的に`preferPeriodMark`に置き換える // 例) "." であるなら "。"に変換 if (classicPeriodMarkPattern.test(periodMark)) { report(lastNode, new RuleError("\u6587\u672B\u304C\"" + preferPeriodMark + "\"\u3067\u7D42\u308F\u3063\u3066\u3044\u307E\u305B\u3093\u3002", { index: index, fix: fixer.replaceTextRange([index, index + preferPeriodMark.length], preferPeriodMark) })); } else { // 句点を忘れているパターン if (forceAppendPeriod) { // `forceAppendPeriod`のオプションがtrueならば、自動で句点を追加する。 report(lastNode, new RuleError("\u6587\u672B\u304C\"" + preferPeriodMark + "\"\u3067\u7D42\u308F\u3063\u3066\u3044\u307E\u305B\u3093\u3002", { index: index, fix: fixer.replaceTextRange([index + 1, index + 1], preferPeriodMark) })); } else { report(lastNode, new RuleError("\u6587\u672B\u304C\"" + preferPeriodMark + "\"\u3067\u7D42\u308F\u3063\u3066\u3044\u307E\u305B\u3093\u3002", { index: index })); } } }); }; module.exports = { linter: reporter, fixer: reporter }; //# sourceMappingURL=textlint-rule-ja-no-mixed-period.js.map
JavaScript
CL
c82b1c7cf0b3a4e2bdfabe287800957b671a74823426ac0dca497f5dd2743563
// Copyright 2011-2016 Global Software Innovation Pty Ltd /*global angular, _, console, sp, Showdown, spResource, spEntity */ (function () { 'use strict'; /** * AngularJS controller function for the entity explorer. * * note - if you change the parameters here then ensure you change the controller registration to match. */ function entityExplorerController($scope, $stateParams, $timeout, $q, spEntityService, spNavService, spResource) { function renderDoc(value) { return value; //We don't include Showdown as not using anywhere else. //return new Showdown.converter().makeHtml(value); } function receivedEntityAsType(entity) { var inherited, derived; if (!entity || !$scope.entity || entity.id() !== $scope.entity.id()) { return; } inherited = spResource.getAncestorsAndSelf(entity); derived = spResource.getDerivedTypesAndSelf(entity); $scope.entityMeta = { inherited: _.without(inherited, entity), derived: _.without(derived, entity), fields: _.flatten(_.invokeMap(inherited, 'getRelationship', 'fields')), relationships: _.flatten(_.invokeMap(inherited, 'getRelationship', 'relationships')), revRelationships: _.flatten(_.invokeMap(inherited, 'getRelationship', 'reverseRelationships')) }; } function receivedEntity(entity) { var desc; if (!entity) { return; } if (entity.id() === $scope.rootEid) { $scope.rootEntityName = entity.getName(); } $scope.entity = entity; $scope.entityJson = spEntity.toJSON(entity); desc = entity.field('description') || '_no description_'; $scope.entity.docHtml = renderDoc(desc); // request type info in case the entity itself is a "type" spEntityService.getEntity(entity.id(), 'alias,name,description,' + '{fields,relationships}.{alias,name,*,{fromType,toType}.{alias,name,isOfType.{alias,name}},cardinality.{alias,name}},' + 'inherits*.{alias,name,description,{fields,relationships}.{alias,name,*,' + ' {fromType,toType}.{alias,name,isOfType.{alias,name}},cardinality.{alias,name}}},' + 'derivedTypes.{alias,name,description}') .then(receivedEntityAsType); // request instances in case the entity itself is a "type" spEntityService.getEntitiesOfType(entity.id(), 'alias,name').then(function (entities) { $scope.instances = _.take(entities, 500); }); } function receivedTypeEntity(entity) { var desc, typeEntity, inherited, derived, rels; if (!entity) { return; } //only grabbing the first at the moment $scope.typeEntity = _.first(entity.getIsOfType()); if (!$scope.typeEntity) { return; } typeEntity = $scope.typeEntity; desc = typeEntity.field('description') || '_no description_'; typeEntity.docHtml = renderDoc(desc); inherited = spResource.getAncestorsAndSelf(typeEntity); derived = spResource.getDerivedTypesAndSelf(typeEntity); $scope.typeEntityMeta = { inherited: _.without(inherited, typeEntity), derived: _.without(derived, typeEntity), fields: _.flatten(_.invokeMap(inherited, 'getFields')), relationships: [].concat( _.map(_.flatten(_.invokeMap(inherited, 'getRelationships')), function (r) { return { rel: r, id: r.id(), reverse: false, name: r.getToName() || r.getName() || r.alias() || r.id() }; }), _.map(_.flatten(_.invokeMap(inherited, 'getRelationship', 'reverseRelationships')), function (r) { return { rel: r, id: r.id(), reverse: true, name: r.getFromName() || r.getName() || r.getField('reverseAlias') || r.id() }; })) }; entity = $scope.entity; if ($scope.typeEntityMeta.fields && entity) { $scope.fields = _.chain($scope.typeEntityMeta.fields) .map(function (f) { return { id: f.id(), alias: f.alias(), name: f.name, value: entity.getField(f.id())}; }) .filter(function (f) { return !_.isUndefined(f.value) && !_.isNull(f.value); }) .value(); } _.each($scope.typeEntityMeta.relationships, function (relWrapper) { function ensureRelationshipAliases(rel) { var id = rel.id(), alias = rel.getField('alias'), reverseAlias = rel.getField('reverseAlias'), relEntity = spEntity.fromId(id); if (!alias || !reverseAlias) { if (!alias) { relEntity.setField('alias', alias = 'relAlias' + id, 'String'); rel.setField('alias', alias, 'String'); } if (!reverseAlias) { relEntity.setField('reverseAlias', reverseAlias = 'relReverseAlias' + id, 'String'); rel.setField('reverseAlias', reverseAlias, 'String'); } console.log('Updating missing alias for rel', rel.id(), alias, reverseAlias, relEntity); spEntityService.putEntity(relEntity); } } var rel = relWrapper.rel; //console.log('rel', _.map(_.map(rel._fields, 'id'), '_alias')); if (!rel.getField('alias') || !rel.getField('reverseAlias')) { ensureRelationshipAliases(rel); } }); } $scope.go = function (eid) { if (eid && $scope.eid !== eid) { if ($scope.eid) { $scope.eidStack.push($scope.eid); } $scope.eid = eid; } }; $scope.home = function () { $scope.eid = $scope.rootEid; $scope.eidStack = []; }; $scope.back = function () { $scope.eid = $scope.eidStack.pop() || $scope.rootEid; }; $scope.getRelated = function (rel) { if (rel && $scope.eid) { //... ugly ... its past midnight.... rel.alias = rel.alias || (rel.reverse ? rel.rel.getField('reverseAlias') : rel.rel.getField('alias')); $scope.currentRel = rel; $scope.related = []; return spEntityService.getEntity(sp.coerseToNumberOrLeaveAlone($scope.eid), rel.alias + '.name').then(function (entity) { $scope.related = entity.getRelationship(rel.id); $scope.currentRel.instanceCount = $scope.related.length; return $scope.related.length; }); } }; function getNextRelated() { $scope.autoGetRelatedRunning = false; if ($scope.autoGetRelated) { if ($scope.typeEntityMeta && $scope.typeEntityMeta.relationships) { $scope.currentRelIndex = (($scope.currentRelIndex || 0) + 1) % $scope.typeEntityMeta.relationships.length; $q.when($scope.getRelated($scope.typeEntityMeta.relationships[$scope.currentRelIndex])).then(function (n) { // if we got related instances then pause a bit longer $timeout(getNextRelated, n > 0 ? 3000 : 500); $scope.autoGetRelatedRunning = true; }).catch(function () { console.error('getRelated failed', arguments); }); } else { // waiting for type entity... $timeout(getNextRelated, 500); $scope.autoGetRelatedRunning = true; } } } $scope.$watch('autoGetRelated', function () { if ($scope.autoGetRelated && !$scope.autoGetRelatedRunning) { $timeout(getNextRelated, 0); $scope.autoGetRelatedRunning = true; } }); $scope.filteredRelationships = function () { if (!$scope.typeEntityMeta || !$scope.typeEntityMeta.relationships) return []; return !$scope.withInstancesFilter ? $scope.typeEntityMeta.relationships : _.filter($scope.typeEntityMeta.relationships, 'instanceCount'); }; $scope.toOneRelationships = function () { if (!$scope.entityMeta || !$scope.entityMeta.relationships) return []; return _.filter($scope.entityMeta.relationships, function (r) { return r.cardinality.eid().getNsAlias() === 'core:oneToOne' || r.cardinality.eid().getNsAlias() === 'core:manyToOne'; }); }; $scope.toManyRelationships = function () { if (!$scope.entityMeta || !$scope.entityMeta.relationships) return []; return _.filter($scope.entityMeta.relationships, function (r) { return !(r.cardinality.eid().getNsAlias() === 'core:oneToOne' || r.cardinality.eid().getNsAlias() === 'core:manyToOne'); }); }; $scope.choiceRelationships = function () { if (!$scope.entityMeta || !$scope.entityMeta.relationships) return []; return _.filter($scope.entityMeta.relationships, function (r) { return sp.result(r, 'toType.isOfType.0.eid.getNsAlias') === 'core:enumType'; }); }; $scope.onEntityIdEntered = function () { $scope.go($scope.aliasOrId); }; $scope.$on('explore-entity', function (e, eid) { console.log('on explore-entity', eid); $scope.rootEid = eid; $scope.go(eid); }); $scope.$watch('eid', function (eid) { if (eid) { console.log('getting eid ', eid); eid = sp.coerseToNumberOrLeaveAlone(eid); $scope.entity = {}; $scope.entityMeta = {}; $scope.typeEntity = {}; $scope.typeEntityMeta = {}; $scope.fields = []; $scope.instances = []; $scope.related = []; $scope.currentRel = {}; $scope.currentRelIndex = 0; // request basic stuff for the entity spEntityService.getEntity(eid, '*,isOfType.{alias,name}').then(receivedEntity); // request information from its type so we know what fields and relationships are possible spEntityService.getEntity(eid, 'isOfType.{alias,name,description,' + '{fields,relationships,reverseRelationships}.{alias,name,*,{fromType,toType}.{alias,name}},' + 'inherits*.{alias,name,description,{fields,relationships,reverseRelationships}.{alias,name,*,{fromType,toType}.{alias,name}}},' + 'derivedTypes.{alias,name,description}}') .then(receivedTypeEntity); } }); $scope.$watch('selectedRelId', function (selectedRelId) { //todo do the forward and reverse rel thing $scope.getRelated(selectedRelId); }); $scope.rootEid = sp.coerseToNumberOrLeaveAlone($stateParams.eid || 0); $scope.eidStack = []; $scope.eid = $scope.rootEid; $scope.entity = {}; $scope.typeEntity = {}; ////////////////////////////////////////////////////// // Hook up to the nav system $scope.item = spNavService.getCurrentItem(); if (!$scope.item) { console.error('explorerController: no current nav item'); } else { if (!$scope.item.data) { $scope.item.data = {}; $scope.item.isDirty = false; } $scope.parentItem = spNavService.getParentItem(); if ($scope.parentItem && $scope.parentItem.data) { $scope.parentResources = $scope.parentItem.data.resources; if ($scope.parentItem.data.setSelected) { $scope.parentItem.data.setSelected($scope.item); } } // for our test UI $scope.hasDirty = true; // to light up the 'toggle dirty' button $scope.toggleDirty = function () { $scope.item.isDirty = !$scope.item.isDirty; }; } // End of nav system hookup ////////////////////////////////////////////////////// } entityExplorerController.$inject = ['$scope', '$stateParams', '$timeout', '$q', 'spEntityService', 'spNavService', 'spResource']; angular.module('app.entityExplorer', ['ui.router', 'mod.common.spEntityService', 'mod.common.spResource', 'sp.navService']) .config(function ($stateProvider) { $stateProvider.state('explorer', { url: '/{tenant}/{eid}/explorer?path', templateUrl: 'devViews/explorer/entityExplorer.tpl.html' }); // register a nav item for this page (most fields are defaulted, but you can provide your own viewType, iconUrl, href and order) window.testNavItems = window.testNavItems || {}; window.testNavItems.explorer = { name: 'Entity Explorer' }; }) .controller('EntityExplorerController', entityExplorerController); }());
JavaScript
CL
0a16f7d784b9e2e2a321df7d9ef0189c48320a583679ec717977d76652671b93
/** * This module will contain everything related to preloading. * * @module preloader */ var Class = require('js-oop'); var LoaderBase = require('./LoaderBase'); var UtilArrayBuffer = require('./util/UtilArrayBuffer'); var UtilHTTP = require('./util/UtilHTTP'); var FileMeta = require('./FileMeta'); /** * LoaderImage will load in images. If XHR exists in the browser attempting to load image * then XHR will be used otherwise LoaderImage will use Image instead to load the Image. * * @class LoaderImage * @constructor * @extends {LoaderBase} */ var LoaderImage = new Class( { Extends: LoaderBase, initialize: function() { this._imageLoaded = false; this.parent(); this.loadType = LoaderBase.typeArraybuffer; }, load: function( url, cacheID ) { this._createAndLoadImage( url ); return; //first we check if we can load with XHR period //second check that we can load using the method we'd like to which is ArrayBuffer //third we check that we have all the functions to turn an ArrayBuffer to a DataURI if( this.canLoadUsingXHR() && this.canLoadType( this.loadType ) && ArrayBuffer && ( window.URL || window.webkitURL || FileReader ) ) { this.parent( url, cacheID ); //if the above checks dont validate we'll fall back and just use the Image object to preload } else { this._createAndLoadImage( url ); } }, _dispatchProgress: function( progress ) { if( this._imageLoaded ) this.onProgress.dispatch( progress ); else this.onProgress.dispatch( progress * 0.9999 ); }, _dispatchComplete: function() { if( this._imageLoaded ) this.onComplete.dispatch(); }, _onImageLoadComplete: function() { this._imageLoaded = true; this._dispatchProgress( 1 ); this._dispatchComplete(); }, _onImageLoadFail: function() { this._dispatchError( 'Image failed to load' ); }, _parseContent: function() { var arrayBuffer = null; var blobData = null; if( !this.fileMeta ) { this.fileMeta = new FileMeta(); } //if the loadType was not set then the meta will be incorrect possibly //so we'll read it from the url if( !this.loadTypeSet || this.fileMeta.mime === null ) { this.fileMeta.mime = UtilHTTP.getMimeFromURL( this.url ); } //get the ArrayBuffer if( this.xhr.response instanceof ArrayBuffer ) { arrayBuffer = this.xhr.response; //if theres a property mozResponseArrayBuffer use that } else if( this.xhr.mozResponseArrayBuffer ) { arrayBuffer = this.xhr.mozResponseArrayBuffer; //otherwise try converting the string to an ArrayBuffer } else { throw new Error( 'Return type for image load unsupported' ); } blobData = new Blob( [ arrayBuffer ], { type: this.fileMeta.mime } ); //We'll convert the blob to an Image using FileReader if it exists if( window.URL || window.webkitURL ) { this._createAndLoadImage( ( window.URL || window.webkitURL ).createObjectURL( blobData ) ); } else if( FileReader ) { var reader = new FileReader(); reader.onloadend = function() { if( window.URL || window.webkitURL ) { ( window.URL || window.webkitURL ).revokeObjectURL( blobData ); } this._createAndLoadImage( reader.result ); }.bind( this ); reader.readAsDataURL( blobData ); } }, _createAndLoadImage: function( src ) { this.content = new Image(); this.content.onload = this._onImageLoadComplete.bind( this ); this.content.onerror = this._onImageLoadFail.bind( this ); this.content.src = src; } }); module.exports = LoaderImage;
JavaScript
CL
e53d8131f9b7dcd5ee09b7dc1653e9c9572ed8eace09a1b3309feca5bcdfc168
import {AppRegistry} from 'react-native'; import checkForUpdates from '../libs/checkForUpdates'; import Config from '../CONFIG'; import HttpUtils from '../libs/HttpUtils'; import DateUtils from '../libs/DateUtils'; import {version as currentVersion} from '../../package.json'; import Visibility from '../libs/Visibility'; /** * Download the latest app version from the server, and if it is different than the current one, * then refresh. If the page is visibile, prompt the user to refresh. * */ function webUpdate() { HttpUtils.download('version.json') .then(({version}) => { if (version !== currentVersion) { if (!Visibility.isVisible()) { // Page is hidden, refresh immediately window.location.reload(true); return; } // Prompt user to refresh the page if (window.confirm('Refresh the page to get the latest updates!')) { window.location.reload(true); } } }); } /** * Create an object whose shape reflects the callbacks used in checkForUpdates. * * @returns {Object} */ const webUpdater = () => ({ init: () => { // We want to check for updates and refresh the page if necessary when the app is backgrounded. // That way, it will auto-update silently when they minimize the page, // and we don't bug the user any more than necessary :) window.addEventListener('visibilitychange', () => { if (!Visibility.isVisible()) { webUpdate(); } }); }, update: () => webUpdate(), }); export default function () { AppRegistry.runApplication(Config.APP_NAME, { rootTag: document.getElementById('root'), }); // When app loads, get current version (production only) if (Config.IS_IN_PRODUCTION) { checkForUpdates(webUpdater()); } // Start current date updater DateUtils.startCurrentDateUpdater(); }
JavaScript
CL
a7a2ee15e444c8e7cec9e8c2ff3f3b684b7e1738db12f9ea173ec4228e905cd4
'use strict'; let fs = require('fs'); let path = require('path'); let fse = require('fs-extra'); let moment = require('moment'); let webpack = require('webpack'); let autoprefixer = require('autoprefixer'); let CopyWebpackPlugin = require('copy-webpack-plugin'); let HtmlWebpackPlugin = require('html-webpack-plugin'); let CleanWebpackPlugin = require('clean-webpack-plugin'); let ExtractTextWebpackPlugin = require('extract-text-webpack-plugin'); let HtmlInlineSourceWebpackPlugin = require('html-inline-source-webpack-plugin'); const entry = require('./webpack.entry.json'); const packageJson = require('../package.json'); const alias = {}; const imageSize = 10240 * 2; const sourcePath = path.join(__dirname, '../src'); const constant = { NODE_ENV : 'production', NAME : packageJson.name, VERSION : packageJson.version, MANIFEST : 'manifest.appcache', TIMESTAMP : moment().format('YYYY-MM-DD h:mm:ss a'), }; const banner = `@ProjectName ${ packageJson.name } @Version ${ packageJson.version } @Author ${ packageJson.author.name }(${ packageJson.author.url }) @Update ${ moment().format('YYYY-MM-DD h:mm:ss a') }`; process.argv.forEach(( param ) => { if (/^--/.test(param)) { let temp = param.slice(2).split('='); let key = temp[0]; let value = temp[1] || true; process.argv[key] = value; } }); let version = ['x', 'x', 'x']; const regexp = /^((^|\.)(0|([1-9](\d+)?))){1,3}$/; if (process.argv.version && regexp.test(process.argv.version)) { process.argv.version.split('.').forEach(( value, index ) => { version[index] = value; }); } let config = { entry, output : (() => { if (process.argv.build == 'js') { return { path : './dist/', filename : `[name]${ process.argv.uglify ? '.min' : '' }.js`, library : process.argv.library, libraryTarget : process.argv.libraryTarget, }; } else { return { path : './dist/', filename : 'js/[name].js', publicPath : '', }; } })(), extensions : ['.vue', '.js', '.coffee', '.json', '.scss'], resolve : { alias, }, module : { loaders : [ { test : /\.vue$/, loader : 'vue', }, { test : /\.(png|jpg|gif|svg)$/, loader : `url?limit=${ imageSize }&name=${ process.argv.build == 'js' ? '../' : '' }img/[name].[ext]?[hash]`, }, { test : /\.css$/, loader : process.argv.build == 'js' ? 'css!postcss' : ExtractTextWebpackPlugin.extract('style', 'css!postcss'), }, { test : /\.scss$/, loader : process.argv.build == 'js' ? 'css!postcss!sass' : ExtractTextWebpackPlugin.extract('style', 'css!postcss!sass'), }, { test : /\.js$/, exclude : path.join(__dirname, '../node_modules/'), loader : 'babel', query : { presets : ['es2015', 'stage-0'], // plugins : ['transform-remove-strict-mode'], // plugins: ['transform-runtime'], }, }, { test : /\.coffee/, loader : 'coffee', }, { test : /\.(coffee\.md|litcoffee)$/, loader : 'coffee?literate', }, ], }, plugins : [ new webpack.DefinePlugin((() => { let result = {}; Object.keys(constant).forEach(( key ) => { result[key] = JSON.stringify(constant[key]); }); return { 'process.env' : result, }; })()), new webpack.BannerPlugin(banner), ], vue : { loaders : { sass : ExtractTextWebpackPlugin.extract('style', 'css!postcss!sass'), scss : ExtractTextWebpackPlugin.extract('style', 'css!postcss!sass'), }, }, postcss () { return [autoprefixer({ browsers : ['last 2 versions'] })]; }, }; let plugins = config.plugins; if (process.argv.build == 'js') { if (process.argv.uglify) { plugins.unshift(new webpack.optimize.UglifyJsPlugin({ compress : { warnings : false, }, output : { comments : false, }, })); } else { plugins.unshift(new CleanWebpackPlugin(['dist'], { root : path.join(__dirname, '..'), })); } } else { plugins.unshift(new webpack.optimize.UglifyJsPlugin({ compress : { warnings : false, }, output : { comments : false, }, })); plugins.unshift(new CopyWebpackPlugin((() => { let result = []; fs.readdirSync(sourcePath).forEach(( filename ) => { let file = path.join(sourcePath, filename); if (filename[0] === '.') { return; } let stats = fs.statSync(file); if (stats.isDirectory()) { if (filename == 'entry') { return; } if (filename == 'package') { return; } } if (stats.isFile()) { if (path.extname(file) == '.html') { return; } if (path.extname(file) == '.appcache') { return; } } result.push({ from : file, to : filename, }); }); return result; })())); plugins.unshift(new CleanWebpackPlugin(['dist'], { root : path.join(__dirname, '..'), })); plugins.push(new ExtractTextWebpackPlugin('css/[name].css')); fs.readdirSync(sourcePath).forEach(( filename ) => { let template = path.join(sourcePath, filename); if (/\.(appcache|html)$/.test(filename)) { plugins.push(new HtmlWebpackPlugin({ minify : false, inject : false, filename, template, })); } }); plugins.push(new HtmlInlineSourceWebpackPlugin(() => { let distPath = path.join(sourcePath, '../dist'); fse.writeJsonSync(path.join(distPath, 'package.json'), getPackageJson()); fs.readdirSync(path.join(distPath, 'js', 'package')).forEach(( filename ) => { let jsPath = path.join(distPath, 'js', 'package', filename); let cssPath = path.join(distPath, 'css', 'package', `${ path.basename(filename, '.js') }.css`); fse.copySync(jsPath, path.join(distPath, 'package', filename)); fse.copySync(cssPath, path.join(distPath, 'package', `${ path.basename(filename, '.js') }.css`)); // let js = fs.readFileSync(jsPath, 'utf8'); // let css = fs.readFileSync(cssPath, 'utf8'); // fs.writeFileSync(path.join(distPath, 'package', filename), js, 'utf8'); // fs.writeFileSync(path.join(distPath, 'package', `${ path.basename(filename, '.js') }.css`), css, 'utf8'); }); fse.remove(path.join(distPath, 'js')); fse.remove(path.join(distPath, 'css')); })); } function getPackageJson () { if (getPackageJson.result) { return getPackageJson.result; } let result = {}; let version = ['x', 'x', 'x']; const regexp = /^((^|\.)(0|([1-9](\d+)?))){1,3}$/; if (process.argv.version && regexp.test(process.argv.version)) { process.argv.version.split('.').forEach(( value, index ) => { version[index] = value; }); } let versionRegexp = version.slice(); versionRegexp.forEach(( value, index ) => { if (value === 'x') { versionRegexp[index] = '(0|[1-9](\\d+)?)'; } }); versionRegexp = new RegExp('^' + versionRegexp.join('\\.') + '$'); let packagePath = path.join(sourcePath, 'package'); fs.readdirSync(packagePath).forEach(( packageVersion ) => { let packageVersionJs = path.join(packagePath, packageVersion, 'index.js'); let packageVersionJson = path.join(packagePath, packageVersion, 'package.json'); if (fs.existsSync(packageVersionJson) && fs.statSync(packageVersionJson).isFile()) { if (versionRegexp.test(packageVersion)) { result[packageVersion] = fse.readJsonSync(packageVersionJson); if (!result[packageVersion]['timestamp']) { result[packageVersion]['timestamp'] = +new Date; fse.writeJsonSync(packageVersionJson, result[packageVersion]); } } else { let json = fse.readJsonSync(packageVersionJson); if (json['timestamp']) { result[packageVersion] = json; } } } }); return getPackageJson.result = result; } module.exports = config;
JavaScript
CL
f27d1c524408cd79d54a6d48f321fd429383b25012bbe9ef7461b6e2132ca857
const path = require('path') module.exports = api => { const { setSharedData, removeSharedData } = api.namespace('vue-apollo-') api.onProjectOpen(() => { setSharedData('urls', null) }) function onGraphqlServerMessage ({ data }) { if (data.vueApollo) { setSharedData('urls', data.vueApollo.urls) } } const common = { link: 'https://github.com/Akryum/vue-cli-plugin-apollo#injected-commands', views: [ { id: 'run-graphlq-api.playground', label: 'Playground', icon: 'gamepad', component: 'vue-apollo-playground', }, ], defaultView: 'run-graphlq-api.playground', onRun: () => { api.ipcOn(onGraphqlServerMessage) }, onExit: () => { api.ipcOff(onGraphqlServerMessage) removeSharedData('urls') }, } api.describeTask({ match: /vue-cli-service graphql-api/, description: 'Run and watch the GraphQL server', ...common, }) api.describeTask({ match: /vue-cli-service run-graphql-api/, description: 'Run the GraphQL server', ...common, }) api.addClientAddon({ id: 'vue-apollo', path: path.resolve(__dirname, './client-addon-dist'), }) }
JavaScript
CL
8995ce3054a671dbf690c08ff661559280bb56dba1f99d0e346dc0d8bf018c3a
import React from "react"; function MainContent() { return ( <main> <h3>From this h3 element down to the footer is MainContent.js </h3> <p>Breaking out each section into <em>components</em> (aka separate JS files)</p> <ul> <li>It makes our code less verbose and more easily read.</li> <li>Makes our code more flexable and easier to reuse.</li> <li> All you need to do to reuse: <ol> <li> Import the component. Just like Nav.js is imported to App.js </li> <li>Then make the call to it in the App function.</li> </ol> </li> </ul> </main> ); } export default MainContent;
JavaScript
CL
6b4090ac2763f2ff16aa96d119e554af20fa8a5280e6cc6fcb6294dba275428e
import React, { Component } from "react"; import { Segment, Header, Input, Button, Form } from "semantic-ui-react"; import web3 from "../ethereum/web3"; import ipfs from "../utils/ipfs"; import FileInstance from "../ethereum/fileInstance"; import { getMultihashFromBytes32 } from "../utils/multihash"; import EthCrypto from "eth-crypto"; import { decrypt } from "../utils/crypto"; import { toast } from "react-toastify"; const FileSaver = require("file-saver"); /** * This component enables the user to download a file by providing their private key, * which is used to decrypt the file's key */ class FileDownload extends Component { state = { userPrivateKey: "", loading: false, fileIpfsPath: "", keyIpfsPath: "", fileName: "", encryptedKey: {} }; /** Retrives the file's IPFS hash and key */ componentDidMount = async () => { const accounts = await web3.eth.getAccounts(); const fileInstance = FileInstance(this.props.address); let returnedHash; let fileHash; let keyHash; /** Depending on whether the viewed file is a uploaded or shared one, * call the respective function from file contract to retrieve file details */ if (!this.props.shared) { returnedHash = await fileInstance.methods.getFileDetail().call({ from: accounts[0] }); /** Convert the retrived hash to multihash format */ fileHash = getMultihashFromBytes32({ digest: returnedHash[0], hashFunction: returnedHash[1], size: returnedHash[2] }); this.setState({ fileIpfsPath: fileHash, keyIpfsPath: `${fileHash}/${accounts[0]}` }); } else { returnedHash = await fileInstance.methods.getSharedFileDetail().call({ from: accounts[0] }); /** IPFS hash of the file */ fileHash = getMultihashFromBytes32({ digest: returnedHash[0], hashFunction: returnedHash[1], size: returnedHash[2] }); /** IPFS hash of the respective key */ keyHash = getMultihashFromBytes32({ digest: returnedHash[3], hashFunction: returnedHash[4], size: returnedHash[5] }); this.setState({ fileIpfsPath: fileHash, keyIpfsPath: keyHash }); } this.setState({ account: accounts[0] }); /** Retrieve the File Name */ await ipfs.files.get(this.state.fileIpfsPath, (err, files) => { if (err) { throw err; } this.setState({ fileName: files[2].path.split("/").pop(), fileContent: files[2].content }); }); /** Retrive the encrypted key */ await ipfs.files.cat(this.state.keyIpfsPath, (err, file) => { if (err) { throw err; } this.setState({ encryptedKey: JSON.parse(file.toString("utf8")) }); }); }; /** * It decrypts the key which is used to decrypt the file and downloads it */ onSubmit = async event => { event.preventDefault(); this.setState({ loading: true }); /** Decrypt the key using user's private key */ let decryptedKey; try { decryptedKey = await EthCrypto.decryptWithPrivateKey( this.state.userPrivateKey, this.state.encryptedKey ); } catch (error) { toast.error("Invalid Private Key"); this.setState({ loading: false }); return; } /** Convert key into valid jwk format */ const key = await window.crypto.subtle.importKey( "jwk", JSON.parse(decryptedKey), "AES-GCM", true, ["encrypt", "decrypt"] ); const fileContent = this.state.fileContent; // Retrieve the original file Content const fileBuffer = fileContent.slice(0, fileContent.length - 12); // Retrive the original random nonce used for encrypting const iv = fileContent.slice(fileContent.length - 12); // Decrypt the file const decryptedFile = await decrypt(fileBuffer, key, iv); // Contruct the file const file = new File([decryptedFile], this.state.fileName); FileSaver.saveAs(file); this.setState({ loading: false }); }; render() { return ( <Segment> <Header size="tiny">Download File</Header> <Form onSubmit={this.onSubmit}> <Form.Field> <Input placeholder="Your Private key" value={this.state.userPrivateKey} onChange={event => this.setState({ userPrivateKey: event.target.value }) } required /> </Form.Field> <Button primary loading={this.state.loading} type="submit"> Download </Button> </Form> </Segment> ); } } export default FileDownload;
JavaScript
CL
ffe75fbd86250f4de4ae6dfc3aa0ee4a300530b0c8c50d8b30af46da0c764538
#if UNITY_EDITOR #pragma strict @script ExecuteInEditMode var myID : int = 0; var isActive : boolean = false; var isSelected : boolean = false; var myMesh : Mesh; var tileUVs : boolean = true; var UVW_TopBottom : boolean = false; var UVW_LeftRight : boolean = false; var UVW_FrontBack : boolean = false; var textureOffset : Vector3; var textureRotation : float = 0; var textureScale = Vector3(1.0,1.0,1.0); var myVertHandles = new GameObject[4]; var myFillUVs = new Vector2[4]; var holdPosition : Vector3; var uvSettings : UVSettings = new UVSettings(); private var pivot_savedUVs = new Vector2[4]; function Activate() { //dev //transform.rotation = Quaternion.identity; /* if(showVerts) { for(theVertHandle in myVertHandles) { theVertHandle.GetComponent(builder_VertHandle).UpdateAttachedVerts(); } } */ //myMesh.RecalculateNormals(); // //for click-painting: must also enable a collider! if(!gameObject.GetComponent(MeshCollider)) gameObject.AddComponent(MeshCollider); holdPosition = transform.position; isActive = true; gameObject.hideFlags = 0; } function DeActivate() { //GenerateLightMapUVs(); isActive = false; //set hide flags var baseHideFlags = HideFlags.NotEditable | HideFlags.HideInInspector; gameObject.hideFlags = baseHideFlags; //remove the collider added on activate if(gameObject.GetComponent(MeshCollider)) DestroyImmediate(gameObject.GetComponent(MeshCollider)); } function Setup() { myMesh = gameObject.GetComponent(MeshFilter).sharedMesh; // Debug.Log(gameObject.name+": Mesh Assigned. (Please ignore the above mesh error)"); isActive = false; isSelected = false; //set hide flags var baseHideFlags = HideFlags.NotEditable | HideFlags.HideInInspector; gameObject.hideFlags = baseHideFlags; //set static flags var matName = gameObject.renderer.sharedMaterial.name; gameObject.isStatic = false; var baseFlags = StaticEditorFlags.BatchingStatic | StaticEditorFlags.LightmapStatic | StaticEditorFlags.OccludeeStatic; GameObjectUtility.SetStaticEditorFlags(gameObject, baseFlags); if(matName == "Collider" || matName == "NoDraw" || matName == "Trigger") { gameObject.isStatic = false; } else if(matName == "Occluder") { gameObject.isStatic = false; var newFlags = StaticEditorFlags.OccluderStatic; GameObjectUtility.SetStaticEditorFlags(gameObject, newFlags); } myID = gameObject.GetInstanceID(); UVW_Flatten(); } function ActivateColliderMode() { renderer.material = Resources.LoadAssetAtPath("Assets/6by7/ProBuilder/Materials/Collider.mat", typeof(Material)) as Material; } function UpdateUVPosition(newtextureOffset : Vector3) { textureOffset = newtextureOffset; UVW_Flatten(); } function UpdateUVScale(newTextureScale : Vector3) { textureScale = newTextureScale; UVW_Flatten(); } function UpdateUVRotation(newTextureRotation : float) { textureRotation = newTextureRotation; UVW_Flatten(); } function UVW_Flatten() { // use only UV class calls UV.UpdateUVs(gameObject, uvSettings); return; /* var meshVerts = myMesh.vertices; var width : float; var length : float; if(UVW_TopBottom) { //calc texture fill stretching if(!tileUVs) { // maybe useful in future, not working as needed for now // width = (meshVerts[0]-meshVerts[1]).magnitude; // length = (meshVerts[0]-meshVerts[2]).magnitude; // textureScale.x = 1f/width; // textureScale.z = 1f/length; var stretchedUVs_TB : Vector2[] = new Vector2[4]; for(var tb=0;tb<4;tb++) { stretchedUVs_TB[tb] = Vector2(myFillUVs[tb].x+textureOffset.x, myFillUVs[tb].y+textureOffset.z); stretchedUVs_TB[tb] = UV.RotateUVs(stretchedUVs_TB[tb], textureRotation); } myMesh.uv = stretchedUVs_TB; } else { //flatten top-bottom uvs var uvs_TopAndBottom : Vector2[] = new Vector2[4]; for (var i = 0 ; i < 4; i++) { uvs_TopAndBottom[i] = Vector2 ((meshVerts[i].x+textureOffset.x+.5)*textureScale.x, (meshVerts[i].z+textureOffset.z+.5)*textureScale.z); uvs_TopAndBottom[i] = UV.RotateUVs(uvs_TopAndBottom[i], textureRotation); } myMesh.uv = uvs_TopAndBottom; // } } else if(UVW_LeftRight) { //calc texture fill stretching if(!tileUVs) { // maybe useful in future, not working as needed for now // width = (meshVerts[3]-meshVerts[2]).magnitude; // length = (meshVerts[0]-meshVerts[2]).magnitude; // textureScale.z = 1f/width; // textureScale.y = 1f/length; var stretchedUVs_LR : Vector2[] = new Vector2[4]; for(var lr=0;lr<4;lr++) { stretchedUVs_LR[lr] = Vector2(myFillUVs[lr].x+textureOffset.x, myFillUVs[lr].y+textureOffset.y); stretchedUVs_LR[lr] = UV.RotateUVs(stretchedUVs_LR[lr], textureRotation); } myMesh.uv = stretchedUVs_LR; } else { //flatten left-right uvs var uvs_LeftAndRight : Vector2[] = new Vector2[4]; for (var o = 0 ; o < 4; o++) { uvs_LeftAndRight[o] = Vector2 ((meshVerts[o].y+textureOffset.y+.5)*textureScale.y, (meshVerts[o].z+textureOffset.z+.5)*textureScale.z); uvs_LeftAndRight[o] = UV.RotateUVs(uvs_LeftAndRight[o], textureRotation); } myMesh.uv = uvs_LeftAndRight; // } } else { //calc texture fill stretching if(!tileUVs) { // maybe useful in future, not working as needed for now // width = (meshVerts[0]-meshVerts[1]).magnitude; // length = (meshVerts[0]-meshVerts[2]).magnitude; // textureScale.x = 1f/width; // textureScale.y = 1f/length; var stretchedUVs_FB : Vector2[] = new Vector2[4]; for(var fb=0;fb<4;fb++) { stretchedUVs_FB[fb] = Vector2(myFillUVs[fb].x+textureOffset.x, myFillUVs[fb].y+textureOffset.y); stretchedUVs_FB[fb] = UV.RotateUVs(stretchedUVs_FB[fb], textureRotation); } myMesh.uv = stretchedUVs_FB; } else { //flatten front-back uvs var uvs_FrontAndBack : Vector2[] = new Vector2[4]; for (var p = 0 ; p < 4; p++) { uvs_FrontAndBack[p] = Vector2 ((meshVerts[p].y+textureOffset.y+.5)*textureScale.y, (meshVerts[p].x+textureOffset.x+.5)*textureScale.x); uvs_FrontAndBack[p] = UV.RotateUVs(uvs_FrontAndBack[p], textureRotation); } myMesh.uv = uvs_FrontAndBack; // } } myMesh.RecalculateNormals(); */ } // function RotateUVs(originalUVRotation : Vector2, angleChange : float) // { // var c : float = Mathf.Cos(angleChange*Mathf.Deg2Rad); // var s : float = Mathf.Sin(angleChange*Mathf.Deg2Rad); // var finalUVRotation : Vector2 = Vector2(originalUVRotation.x*c - originalUVRotation.y*s, originalUVRotation.x*s + originalUVRotation.y*c); // return(finalUVRotation); // } function ApplymyFillUVs() { myMesh.uv = myFillUVs; } // function GenerateLightMapUVs() // { // var vertices : Vector3[] = myMesh.vertices; // var uvs : Vector2[] = new Vector2[vertices.Length]; // //calculate the lightmapped uvs // if(UVW_TopBottom) // { // for (var i = 0 ; i < uvs.Length; i++) // uvs[i] = Vector2 (vertices[i].x, vertices[i].z); // } // else if(UVW_LeftRight) // { // for (var o = 0 ; o < uvs.Length; o++) // uvs[o] = Vector2 (vertices[o].y, vertices[o].z); // } // else // { // for (var p = 0 ; p < uvs.Length; p++) // uvs[p] = Vector2 (vertices[p].x, vertices[p].y); // } // //set the lightmapped uvs // myMesh.uv2 = uvs; // } function VisToggle(bitBoolean : int) { var newHideFlags = 0; if(bitBoolean == 0) { //set hide flags newHideFlags = HideFlags.NotEditable | HideFlags.HideInInspector | HideFlags.HideInHierarchy; gameObject.hideFlags = newHideFlags; gameObject.active = false; } else { //set hide flags newHideFlags = HideFlags.NotEditable | HideFlags.HideInInspector; gameObject.hideFlags = newHideFlags; gameObject.active = true; } } function SaveUVState() { pivot_savedUVs = myMesh.uv; } function ReloadUVState() { myMesh.uv = pivot_savedUVs; }
JavaScript
CL
7e4400c81d64d9391760532353fa8ad7b42bf30ab7f2fbc88659e0e8a773fb16
import {Link} from "./link.js"; import marked from "../node_modules/marked/marked.min.js" export class MarkedConverter { /** * Creates an instance of MarkedConfig. * @param {(Link) => void} linkFoundCallback * * @memberof MarkedConfig */ constructor(linkFoundCallback) { this.linkFoundCallback = linkFoundCallback; } /** * Get configuration for the markdown conversion. * * @param {string} contextUrl * @returns * * @memberof MarkedConfig */ getConfig(contextUrl) { //TODO: Don't recreate the config each time this is called, but still keep url context. let renderer = this.getRenderer(contextUrl); return { renderer: renderer, gfm: true, tables: true, breaks: true, pedantic: false, sanitize: false, smartLists: true, smartypants: true }; } /**"" * * * @param {string} contextUrl * @returns * * @memberof MarkedConfig */ getRenderer(contextUrl) { let renderer = new marked.Renderer(); renderer.link = this.getLinkFunction(contextUrl); return renderer; } getLinkFunction(contextUrl) { return (href, title, text) => { let link = Link.buildLink(href, contextUrl, text); this.onLinkFound(link); return link.getMarkup(false); } } /** * Converts the input markdown document to html. * * @param {string} mdDocument - string Markdown document * @param {string} contextUrl - The Parent url context needed for resolving relative paths. * @returns * * @memberof MarkedConverter */ convert(mdDocument, contextUrl) { return marked(mdDocument, this.getConfig(contextUrl)); } /** * Propogates the link found event. * * @param {Link} link * * @memberof MarkedConfig */ onLinkFound(link) { if (this.linkFoundCallback) { this.linkFoundCallback(link); } } }
JavaScript
CL
eb0ed688554d80cccbe2a3cfeac4cef55a0ba3bd6b0d72f666cc6e71cc4b7f70
import {useContentEditorContext} from '~/contexts/ContentEditor'; import {useFormikContext} from 'formik'; import {Constants} from '~/ContentEditor.constants'; import React from 'react'; import styles from './PublishMenu.scss'; import {DisplayAction} from '@jahia/ui-extender'; import {getButtonRenderer, isDirty} from '~/utils'; import {ChevronDown} from '@jahia/moonstone'; const ButtonRenderer = getButtonRenderer({ labelStyle: 'none', defaultButtonProps: { size: 'big', color: 'accent', className: styles.menu, 'data-sel-role': 'ContentEditorHeaderMenu' } }); export const PublishMenu = () => { const {nodeData, lang, i18nContext} = useContentEditorContext(); const formik = useFormikContext(); const wipInfo = formik.values[Constants.wip.fieldName]; const isWip = wipInfo.status === Constants.wip.status.ALL_CONTENT || (wipInfo.status === Constants.wip.status.LANGUAGES && wipInfo.languages.includes(lang)); const dirty = isDirty(formik, i18nContext); let isDisabled = dirty || nodeData.lockedAndCannotBeEdited || isWip; return ( <DisplayAction menuUseElementAnchor disabled={isDisabled} actionKey="publishMenu" language={lang} path={nodeData.path} render={ButtonRenderer} buttonProps={{icon: <ChevronDown/>}} /> ); };
JavaScript
CL
04a34d49220974bb4e56677fb5cbeeaa375a5c80527b24cf6f758b7e94975133
/*jshint -W106 */ (function() { 'use strict'; angular .module('googlePlus') .provider('googlePlusService', GooglePlus); function GooglePlus (CONFIG) { var clientid; var scope; var auth2; this.setConfig = function (params){ clientid = params.clientid; scope = params.scope; }; this.$get = ['$q', 'psafLogger', '$http', function ($q, psafLogger, $http) { var logger = psafLogger.getInstance('hoursappsprout.login.GooglePlus'); return { login: function () { var deferred = $q.defer(); console.log('calling from googlePlus.service'); // Flow modified from ngCordova to match our needs // ngCordova was not setup to get a code. It only supported access token response_type if (window.cordova) { var browserRef = window.open('https://accounts.google.com/o/oauth2/auth?access_type=online&' + 'client_id=' + clientid + '&redirect_uri=http://localhost/callback&scope=' + scope + '&approval_prompt=force&response_type=code', '_blank', 'location=no,clearsessioncache=yes,'+ 'clearcache=yes'); browserRef.addEventListener('loadstart', function (event) { if ((event.url).indexOf('http://localhost/callback') === 0) { var callbackResponse = (event.url).split('?')[1]; var responseParameters = (callbackResponse).split('&'); var parameterMap = []; for (var i = 0; i < responseParameters.length; i++) { var key = responseParameters[i].split('=')[0]; parameterMap[key] = responseParameters[i].split('=')[1]; } if (parameterMap['code'] !== undefined && parameterMap['code'] !== null) { deferred.resolve(parameterMap['code']); } else { deferred.reject('Unable to load google code'); } browserRef.close(); } }); } else { gapi.auth.signIn({ clientid: clientid, scope: scope, immediate: false, cookiepolicy: 'single_host_origin', approvalprompt: 'force', accesstype: 'offline', redirecturi: CONFIG.redirect_uri, callback: function (authResult) { if (authResult && !authResult.error) { // The redirect URI does not come back in this request and is required // on the server authResult['redirect_uri'] = CONFIG.redirect_uri; deferred.resolve(authResult); } else { deferred.reject('auth error'); } } }); } return deferred.promise; } }; }]; }})();
JavaScript
CL
189cfff17d57c0d2b65d2c948d68f1165ba2bfe6161b523af9e9b59766ff76b8
setup.createAdventure = (town, base) => { // Tables used later const adventure = { location: setup.adventure.location.random(), introduction: setup.adventure.introduction.random(), climax: setup.adventure.climax.random(), otherGoal: setup.adventure.otherGoal.random(), backdrop: setup.adventure.backdrop.random(), quandary: setup.adventure.quandary.random(), twist: setup.adventure.twist.random(), sidequest: setup.adventure.sidequest.random(), patron: setup.adventure.patron.random(), villain: setup.adventure.villain.random(), villainActions: setup.adventure.villainActions.random(), allyDescription: setup.adventure.allyDescription.random(), ...base } const SV = State.variables let adventureGoalNPC let adventureVillain let adventureAlly let adventurePatron switch (adventure.location) { case 'dungeon': adventure.goal = adventure.goal || ["stop the dungeon's monstrous inhabitants from raiding the surface world.", "foil a villain's evil scheme.", 'destroy a magical threat inside the dungeon.', 'acquire treasure.', 'find a particular item for a specific purpose.', 'retrieve a stolen item hidden in the dungeon.', 'find information needed for a special purpose.', 'rescue a captive.', 'discover the fate of a previous adventuring party.', 'find an npc who disappeared in the area.', 'slay a dragon or some other challenging monster.', 'discover the nature and origin of a strange location or phenomenon.', 'pursue fleeing foes taking refuge in the dungeon.', 'escape from captivity in the dungeon.', 'clear a ruin so it can be rebuilt and reoccupied.', 'discover why a villain is interested in the dungeon.', 'win a bet or complete a rite of passage by surviving in the dungeon for a certain amount of time.', 'parley with a villain in the dungeon.', 'hide from a threat outside the dungeon.'].random() break case 'wilderness': adventure.goal = adventure.goal || ['assess the scope of a natural or unnatural disaster.', 'escort an npc to a destination.', "arrive at a destination without being seen by the villain's forces.", 'stop monsters from raiding caravans and farms.', 'establish trade with a distant town.', 'protect a caravan traveling to a distant town.', 'map a new land.', 'find a place to establish a colony.', 'find a natural resource.', 'hunt a specific monster.', 'return home from a distant place.', 'obtain information from a reclusive hermit.', 'find an object that was lost in the wilds.', 'discover the fate of a missing group of explorers.', 'pursue fleeing foes.', 'assess the size of an approaching army.', 'escape the reign of a tyrant.', 'protect a wilderness site from attackers.'].random() break case 'other': adventure.goal = adventure.goal || ['seize control of a fortified location such as a fortress, town, or ship.', 'defend a location from attackers.', 'retrieve an object from inside a secure location in a settlement.', 'retrieve an object from a caravan.', 'salvage an object or goods from a lost vessel or caravan.', 'break a prisoner out of a jail or prison camp.', 'escape from a jail or prison camp.', 'successfully travel through an obstacle course to gain recognition or reward.', 'infiltrate a fortified location.', 'find the source of strange occurrences in a haunted house or other location.', 'interfere with the operation of a business.', 'rescue a character, monster, or object from a natural or unnatural disaster.'].random() } switch (adventure.goal) { case 'rescue a captive.': adventureGoalNPC = setup.createNPC(town) SV.adventureGoalNPC = adventureGoalNPC Object.assign(adventure, { adventureGoalNPC, goal: `rescue ${adventureGoalNPC.name}, ${lib.articles.output(adventureGoalNPC.raceNote)} who was captured and taken prisoner.` }) break case 'discover the fate of a previous adventuring party.': adventureGoalNPC = setup.createNPC(town) SV.adventureGoalNPC = adventureGoalNPC Object.assign(adventure, { adventureGoalNPC, goal: `rescue ${adventureGoalNPC.name}, ${lib.articles.output(adventureGoalNPC.raceNote)} who was captured and taken prisoner.` }) break case 'find an npc who disappeared in the area.': adventureGoalNPC = setup.createNPC(town) SV.adventureGoalNPC = adventureGoalNPC Object.assign(adventure, { adventureGoalNPC, goal: `find ${adventureGoalNPC.name}, ${lib.articles.output(adventureGoalNPC.raceNote)} who disappeared in the area.` }) break case 'escort an npc to a destination.': adventureGoalNPC = setup.createNPC(town) SV.adventureGoalNPC = adventureGoalNPC Object.assign(adventure, { adventureGoalNPC, goal: `escort ${adventureGoalNPC.name}, ${lib.articles.output(adventureGoalNPC.raceNote)} who needs protection on the way to another place.` }) break case 'discover the fate of a missing group of explorers.': adventureGoalNPC = setup.createNPC(town) SV.adventureGoalNPC = adventureGoalNPC Object.assign(adventure, { adventureGoalNPC, goal: `discover the fate of ${adventureGoalNPC.name} and ${adventureGoalNPC.hisher} exploring party, who disappeared in the area.` }) break case 'break a prisoner out of a jail or prison camp.': adventureGoalNPC = setup.createNPC(town) SV.adventureGoalNPC = adventureGoalNPC Object.assign(adventure, { adventureGoalNPC, goal: `rescue ${adventureGoalNPC.name}, ${lib.articles.output(adventureGoalNPC.raceNote)} who was captured and taken prisoner.` }) break case 'rescue a character, monster, or object from a natural or unnatural disaster.': adventureGoalNPC = setup.createNPC(town) SV.adventureGoalNPC = adventureGoalNPC Object.assign(adventure, { adventureGoalNPC, goal: `rescue ${adventureGoalNPC.name}, ${lib.articles.output(adventureGoalNPC.raceNote)} who was caught in a natural disaster.` }) switch (adventure.villain) { case 'giant bent on plunder': adventureVillain = setup.createNPC(town, { height: 'huge', race: 'giant' }) SV.adventureVillain = adventureVillain Object.assign(adventure, { adventureVillain }) break case 'fey with a mysterious goal': adventureVillain = setup.createNPC(town, { race: 'fey' }) SV.adventureVillain = adventureVillain Object.assign(adventure, { adventureVillain }) break case 'humanoid cultist': adventureVillain = setup.createNPC(town, { profession: ['cleric', 'sorcerer', 'wizard'].random() }) SV.adventureVillain = adventureVillain Object.assign(adventure, { adventureVillain, villain: `cultist called ${adventureVillain.name}` }) break case 'humanoid conqueror': adventureVillain = setup.createNPC(town, { profession: ['barbarian', 'fighter', 'paladin'].random() }) SV.adventureVillain = adventureVillain Object.assign(adventure, { adventureVillain, villain: `fearsome conqueror called ${adventureVillain.name}` }) break case 'humanoid seeking revenge': adventureVillain = setup.createNPC(town) SV.adventureVillain = adventureVillain Object.assign(adventure, { adventureVillain, villain: `${adventureVillain.raceNote} called ${adventureVillain.name} hellbent on revenge.` }) break case 'humanoid schemer seeking to rule': adventureVillain = setup.createNPC(town, { profession: ['sorcerer', 'rogue'].random() }) SV.adventureVillain = adventureVillain Object.assign(adventure, { adventureVillain, villain: `conniving${adventureVillain.raceNote}called ${adventureVillain.name} who seeks power` }) break case 'humanoid criminal mastermind': adventureVillain = setup.createNPC(town, { profession: ['sorcerer', 'rogue'].random() }) SV.adventureVillain = adventureVillain Object.assign(adventure, { adventureVillain, villain: `conniving${adventureVillain.raceNote}called ${adventureVillain.name} who seeks to build a criminal empire` }) break case 'humanoid raider or ravager': adventureVillain = setup.createNPC(town, { profession: ['barbarian', 'fighter'].random() }) SV.adventureVillain = adventureVillain Object.assign(adventure, { adventureVillain, villain: `fearsome raider called ${adventureVillain.name}` }) break case 'humanoid under a curse': adventureVillain = setup.createNPC(town) SV.adventureVillain = adventureVillain Object.assign(adventure, { adventureVillain, villain: `${adventureVillain.raceNote} called ${adventureVillain.name} who was placed under a curse` }) break case 'misguided humanoid zealot': adventureVillain = setup.createNPC(town, { profession: 'cleric' }) SV.adventureVillain = adventureVillain Object.assign(adventure, { adventureVillain, villain: `misguided${adventureVillain.raceNote}zealot called ${adventureVillain.name}` }) break default: adventureVillain = setup.createNPC(town) SV.adventureVillain = adventureVillain Object.assign(adventure, { adventureVillain }) switch (adventure.ally) { case 'young adventurer': adventureAlly = setup.createNPC(town, { age: 'relatively young' }) SV.adventureAlly = adventureAlly Object.assign(adventure, { adventureAlly }) break case 'enthusiastic commoner': adventureAlly = setup.createNPC(town, { profession: 'peasant' }) SV.adventureAlly = adventureAlly Object.assign(adventure, { adventureAlly }) break case 'soldier': adventureAlly = setup.createNPC(town, { profession: 'fighter', background: 'soldier' }) SV.adventureAlly = adventureAlly Object.assign(adventure, { adventureAlly }) break case 'priest': adventureAlly = setup.createNPC(town, { profession: 'cleric' }) SV.adventureAlly = adventureAlly Object.assign(adventure, { adventureAlly }) break case 'sage': adventureAlly = setup.createNPC(town, { profession: ['cleric', 'monk', 'druid', 'wizard'].random(), background: 'sage' }) SV.adventureAlly = adventureAlly Object.assign(adventure, { adventureAlly }) break case 'celestial ally': adventureAlly = setup.createNPC(town, { race: 'celestial being' }) SV.adventureAlly = adventureAlly Object.assign(adventure, { adventureAlly }) break case 'fey ally': adventureAlly = setup.createNPC(town, { race: 'fey' }) SV.adventureAlly = adventureAlly Object.assign(adventure, { adventureAlly }) break default: adventureAlly = setup.createNPC(town) SV.adventureAlly = adventureAlly Object.assign(adventure, { adventureAlly }) break } switch (adventure.patron) { case 'retired adventurer': adventurePatron = setup.createNPC(town, { adventure: 'retired' }) SV.adventurePatron = adventurePatron Object.assign(adventure, { adventurePatron }) break case 'local ruler': adventurePatron = setup.createNPC(town, { profession: 'lord' }) SV.adventurePatron = adventurePatron Object.assign(adventure, { adventurePatron }) break case 'military officer': adventurePatron = setup.createNPC(town, { profession: ['fighter', 'paladin'].random(), background: 'soldier' }) SV.adventurePatron = adventurePatron Object.assign(adventure, { adventurePatron }) break case 'temple official': adventurePatron = setup.createNPC(town, { profession: ['cleric', 'cleric', 'cleric', 'paladin'].random(), background: 'sage' }) SV.adventurePatron = adventurePatron Object.assign(adventure, { adventurePatron }) break case 'sage': adventurePatron = setup.createNPC(town, { profession: ['cleric', 'cleric', 'cleric', 'paladin'].random(), background: 'sage' }) SV.adventurePatron = adventurePatron Object.assign(adventure, { adventurePatron }) break case 'respected elder': adventurePatron = setup.createNPC(town, { age: 'venerable' }) SV.adventurePatron = adventurePatron Object.assign(adventure, { adventurePatron }) break case 'deity or celestial': adventurePatron = setup.createNPC(town, { race: 'celestial being' }) SV.adventurePatron = adventurePatron Object.assign(adventure, { adventurePatron }) break case 'mysterious fey': adventurePatron = setup.createNPC(town, { race: 'fey' }) SV.adventurePatron = adventurePatron Object.assign(adventure, { adventurePatron }) break case 'former teacher': adventurePatron = setup.createNPC(town, { age: 'venerable' }) SV.adventurePatron = adventurePatron Object.assign(adventure, { adventurePatron }) break default: adventurePatron = setup.createNPC(town) SV.adventurePatron = adventurePatron Object.assign(adventure, { adventurePatron }) } return adventure } } }
JavaScript
CL
39117a0d7f7d72c2de684d617ccda436543cf28c47772905699e2a04c8989005
/* jshint browser: true */ var isElement = require( "lodash/lang/isElement" ); var clone = require( "lodash/lang/clone" ); var defaultsDeep = require( "lodash/object/defaultsDeep" ); var Jed = require( "jed" ); var imageDisplayMode = require( "./helpers/imageDisplayMode" ); var renderDescription = require( "./helpers/renderDescription" ); var imagePlaceholder = require( "./element/imagePlaceholder" ); var bemAddModifier = require( "./helpers/bem/addModifier" ); var bemRemoveModifier = require( "./helpers/bem/removeModifier" ); var TextField = require( "./inputs/textInput" ); var TextArea = require( "./inputs/textarea" ); var InputElement = require( "./element/input" ); var PreviewEvents = require( "./preview/events" ); var templates = require( "./templates.js" ); var facebookEditorTemplate = templates.facebookPreview; var facebookAuthorTemplate = templates.facebookAuthor; var facebookDefaults = { data: { title: "", description: "", imageUrl: "", }, defaultValue: { title: "", description: "", imageUrl: "", }, baseURL: "example.com", callbacks: { updateSocialPreview: function() {}, modifyTitle: function( title ) { return title; }, modifyDescription: function( description ) { return description; }, modifyImageUrl: function( imageUrl ) { return imageUrl; }, }, }; var inputFacebookPreviewBindings = [ { preview: "editable-preview__title--facebook", inputField: "title", }, { preview: "editable-preview__image--facebook", inputField: "imageUrl", }, { preview: "editable-preview__description--facebook", inputField: "description", }, ]; var WIDTH_FACEBOOK_IMAGE_SMALL = 158; var WIDTH_FACEBOOK_IMAGE_LARGE = 470; var FACEBOOK_IMAGE_TOO_SMALL_WIDTH = 200; var FACEBOOK_IMAGE_TOO_SMALL_HEIGHT = 200; var FACEBOOK_IMAGE_THRESHOLD_WIDTH = 600; var FACEBOOK_IMAGE_THRESHOLD_HEIGHT = 315; /** * @module snippetPreview */ /** * Defines the config and outputTarget for the SnippetPreview. * * @param {Object} opts - Snippet preview options. * @param {Object} opts.placeholder - The placeholder values for the fields, will be shown as * actual placeholders in the inputs and as a fallback for the preview. * @param {string} opts.placeholder.title - Placeholder for the title field. * @param {string} opts.placeholder.description - Placeholder for the description field. * @param {string} opts.placeholder.imageUrl - Placeholder for the image url field. * * @param {Object} opts.defaultValue - The default value for the fields, if the user has not * changed a field, this value will be used for the analyzer, * preview and the progress bars. * @param {string} opts.defaultValue.title - Default title. * @param {string} opts.defaultValue.description - Default description. * @param {string} opts.defaultValue.imageUrl - Default image url. * * @param {string} opts.baseURL - The basic URL as it will be displayed in Facebook. * @param {HTMLElement} opts.targetElement - The target element that contains this snippet editor. * * @param {Object} opts.callbacks - Functions that are called on specific instances. * @param {Function} opts.callbacks.updateSocialPreview - Function called when the social preview is updated. * * @param {Object} i18n - The i18n object. * * @property {Object} i18n - The translation object. * * @property {HTMLElement} targetElement - The target element that contains this snippet editor. * * @property {Object} element - The elements for this snippet editor. * @property {Object} element.rendered - The rendered elements. * @property {HTMLElement} element.rendered.title - The rendered title element. * @property {HTMLElement} element.rendered.imageUrl - The rendered url path element. * @property {HTMLElement} element.rendered.description - The rendered Facebook description element. * * @property {Object} element.input - The input elements. * @property {HTMLElement} element.input.title - The title input element. * @property {HTMLElement} element.input.imageUrl - The url path input element. * @property {HTMLElement} element.input.description - The meta description input element. * * @property {HTMLElement} element.container - The main container element. * @property {HTMLElement} element.formContainer - The form container element. * @property {HTMLElement} element.editToggle - The button that toggles the editor form. * * @property {Object} data - The data for this snippet editor. * @property {string} data.title - The title. * @property {string} data.imageUrl - The url path. * @property {string} data.description - The meta description. * * @property {string} baseURL - The basic URL as it will be displayed in google. * * @constructor */ var FacebookPreview = function( opts, i18n ) { this.i18n = i18n || this.constructI18n(); facebookDefaults.placeholder = { title: this.i18n.dgettext( "yoast-social-previews", "This is an example title - edit by clicking here" ), description: this.i18n.sprintf( /** translators: %1$s expands to Facebook */ this.i18n.dgettext( "yoast-social-previews", "Modify your %1$s description by editing it right here" ), "Facebook" ), imageUrl: "", }; defaultsDeep( opts, facebookDefaults ); if ( ! isElement( opts.targetElement ) ) { throw new Error( "The Facebook preview requires a valid target element" ); } this.data = opts.data; this.opts = opts; this._currentFocus = null; this._currentHover = null; }; /** * Initializes i18n object based on passed configuration * * @param {Object} translations - The values to translate. * * @returns {Jed} - The Jed translation object. */ FacebookPreview.prototype.constructI18n = function( translations ) { var defaultTranslations = { domain: "yoast-social-previews", /* eslint-disable camelcase */ locale_data: { /* eslint-enable camelcase */ "yoast-social-previews": { "": {}, }, }, }; translations = translations || {}; defaultsDeep( translations, defaultTranslations ); return new Jed( translations ); }; /** * Renders the template and bind the events. * * @returns {void} */ FacebookPreview.prototype.init = function() { this.renderTemplate(); this.bindEvents(); this.updatePreview(); }; /** * Renders snippet editor and adds it to the targetElement. * * @returns {void} */ FacebookPreview.prototype.renderTemplate = function() { var targetElement = this.opts.targetElement; targetElement.innerHTML = facebookEditorTemplate( { rendered: { title: "", description: "", imageUrl: "", baseUrl: this.opts.baseURL, }, placeholder: this.opts.placeholder, i18n: { /** translators: %1$s expands to Facebook */ edit: this.i18n.sprintf( this.i18n.dgettext( "yoast-social-previews", "Edit %1$s preview" ), "Facebook" ), /** translators: %1$s expands to Facebook */ snippetPreview: this.i18n.sprintf( this.i18n.dgettext( "yoast-social-previews", "%1$s preview" ), "Facebook" ), /** translators: %1$s expands to Facebook */ snippetEditor: this.i18n.sprintf( this.i18n.dgettext( "yoast-social-previews", "%1$s editor" ), "Facebook" ), }, } ); this.element = { rendered: { title: targetElement.getElementsByClassName( "editable-preview__value--facebook-title" )[ 0 ], description: targetElement.getElementsByClassName( "editable-preview__value--facebook-description" )[ 0 ], }, fields: this.getFields(), container: targetElement.getElementsByClassName( "editable-preview--facebook" )[ 0 ], formContainer: targetElement.getElementsByClassName( "snippet-editor__form" )[ 0 ], editToggle: targetElement.getElementsByClassName( "snippet-editor__edit-button" )[ 0 ], formFields: targetElement.getElementsByClassName( "snippet-editor__form-field" ), headingEditor: targetElement.getElementsByClassName( "snippet-editor__heading-editor" )[ 0 ], authorContainer: targetElement.getElementsByClassName( "editable-preview__value--facebook-author" )[ 0 ], }; this.element.formContainer.innerHTML = this.element.fields.imageUrl.render() + this.element.fields.title.render() + this.element.fields.description.render(); this.element.input = { title: targetElement.getElementsByClassName( "js-snippet-editor-title" )[ 0 ], imageUrl: targetElement.getElementsByClassName( "js-snippet-editor-imageUrl" )[ 0 ], description: targetElement.getElementsByClassName( "js-snippet-editor-description" )[ 0 ], }; this.element.fieldElements = this.getFieldElements(); this.element.closeEditor = targetElement.getElementsByClassName( "snippet-editor__submit" )[ 0 ]; this.element.caretHooks = { title: this.element.input.title.previousSibling, imageUrl: this.element.input.imageUrl.previousSibling, description: this.element.input.description.previousSibling, }; this.element.preview = { title: this.element.rendered.title.parentNode, imageUrl: targetElement.getElementsByClassName( "editable-preview__image--facebook" )[ 0 ], description: this.element.rendered.description.parentNode, }; }; /** * Returns the form fields. * * @returns {{title: *, description: *, imageUrl: *, button: Button}} Object with the fields. */ FacebookPreview.prototype.getFields = function() { return { title: new TextField( { className: "snippet-editor__input snippet-editor__title js-snippet-editor-title", id: "facebook-editor-title", value: this.data.title, placeholder: this.opts.placeholder.title, /** translators: %1$s expands to Facebook */ title: this.i18n.sprintf( this.i18n.dgettext( "yoast-social-previews", "%1$s title" ), "Facebook" ), labelClassName: "snippet-editor__label", } ), description: new TextArea( { className: "snippet-editor__input snippet-editor__description js-snippet-editor-description", id: "facebook-editor-description", value: this.data.description, placeholder: this.opts.placeholder.description, /** translators: %1$s expands to Facebook */ title: this.i18n.sprintf( this.i18n.dgettext( "yoast-social-previews", "%1$s description" ), "Facebook" ), labelClassName: "snippet-editor__label", } ), imageUrl: new TextField( { className: "snippet-editor__input snippet-editor__imageUrl js-snippet-editor-imageUrl", id: "facebook-editor-imageUrl", value: this.data.imageUrl, placeholder: this.opts.placeholder.imageUrl, /** translators: %1$s expands to Facebook */ title: this.i18n.sprintf( this.i18n.dgettext( "yoast-social-previews", "%1$s image" ), "Facebook" ), labelClassName: "snippet-editor__label", } ), }; }; /** * Returns all field elements. * * @returns {{title: InputElement, description: InputElement, imageUrl: InputElement}} The field elements. */ FacebookPreview.prototype.getFieldElements = function() { var targetElement = this.opts.targetElement; return { title: new InputElement( targetElement.getElementsByClassName( "js-snippet-editor-title" )[ 0 ], { currentValue: this.data.title, defaultValue: this.opts.defaultValue.title, placeholder: this.opts.placeholder.title, fallback: this.i18n.sprintf( /** translators: %1$s expands to Facebook */ this.i18n.dgettext( "yoast-social-previews", "Please provide a %1$s title by editing the snippet below." ), "Facebook" ), }, this.updatePreview.bind( this ) ), description: new InputElement( targetElement.getElementsByClassName( "js-snippet-editor-description" )[ 0 ], { currentValue: this.data.description, defaultValue: this.opts.defaultValue.description, placeholder: this.opts.placeholder.description, fallback: this.i18n.sprintf( /** translators: %1$s expands to Facebook */ this.i18n.dgettext( "yoast-social-previews", "Please provide a %1$s description by editing the snippet below." ), "Facebook" ), }, this.updatePreview.bind( this ) ), imageUrl: new InputElement( targetElement.getElementsByClassName( "js-snippet-editor-imageUrl" )[ 0 ], { currentValue: this.data.imageUrl, defaultValue: this.opts.defaultValue.imageUrl, placeholder: this.opts.placeholder.imageUrl, fallback: "", }, this.updatePreview.bind( this ) ), }; }; /** * Updates the Facebook preview. * * @returns {void} */ FacebookPreview.prototype.updatePreview = function() { // Update the data. this.data.title = this.element.fieldElements.title.getInputValue(); this.data.description = this.element.fieldElements.description.getInputValue(); this.data.imageUrl = this.element.fieldElements.imageUrl.getInputValue(); // Sets the title field this.setTitle( this.element.fieldElements.title.getValue() ); this.setTitle( this.element.fieldElements.title.getValue() ); // Set the description field and parse the styling of it. this.setDescription( this.element.fieldElements.description.getValue() ); // Sets the Image this.setImage( this.data.imageUrl ); // Clone so the data isn't changeable. this.opts.callbacks.updateSocialPreview( clone( this.data ) ); }; /** * Sets the preview title. * * @param {string} title The title to set. * * @returns {void} */ FacebookPreview.prototype.setTitle = function( title ) { title = this.opts.callbacks.modifyTitle( title ); this.element.rendered.title.innerHTML = title; }; /** * Sets the preview description. * * @param {string} description The description to set. * * @returns {void} */ FacebookPreview.prototype.setDescription = function( description ) { description = this.opts.callbacks.modifyDescription( description ); this.element.rendered.description.innerHTML = description; renderDescription( this.element.rendered.description, this.element.fieldElements.description.getInputValue() ); }; /** * Gets the image container. * * @returns {string} The container that will hold the image. */ FacebookPreview.prototype.getImageContainer = function() { return this.element.preview.imageUrl; }; /** * Updates the image object with the new URL. * * @param {string} imageUrl The image path. * * @returns {void} */ FacebookPreview.prototype.setImage = function( imageUrl ) { imageUrl = this.opts.callbacks.modifyImageUrl( imageUrl ); if ( imageUrl === "" && this.data.imageUrl === "" ) { this.removeImageFromContainer(); return this.noUrlSet(); } var img = new Image(); img.onload = function() { if ( this.isTooSmallImage( img ) ) { this.removeImageFromContainer(); return this.imageTooSmall(); } this.setSizingClass( img ); this.addImageToContainer( imageUrl ); }.bind( this ); img.onerror = function() { this.removeImageFromContainer(); return this.imageError(); }.bind( this ); // Load image to trigger load or error event. img.src = imageUrl; }; /** * Displays the No URL Set warning. * * @returns {void} */ FacebookPreview.prototype.noUrlSet = function() { this.removeImageClasses(); imagePlaceholder( this.getImageContainer(), this.i18n.dgettext( "yoast-social-previews", "Please select an image by clicking here" ), false, "facebook" ); return; }; /** * Displays the Image Too Small error. * * @returns {void} */ FacebookPreview.prototype.imageTooSmall = function() { var message; this.removeImageClasses(); if ( this.data.imageUrl === "" ) { message = this.i18n.sprintf( /* translators: %1$s expands to Facebook */ this.i18n.dgettext( "yoast-social-previews", "We are unable to detect an image " + "in your post that is large enough to be displayed on Facebook. We advise you " + "to select a %1$s image that fits the recommended image size." ), "Facebook" ); } else { message = this.i18n.sprintf( /* translators: %1$s expands to Facebook */ this.i18n.dgettext( "yoast-social-previews", "The image you selected is too small for %1$s" ), "Facebook" ); } imagePlaceholder( this.getImageContainer(), message, true, "facebook" ); return; }; /** * Displays the Url Cannot Be Loaded error. * * @returns {void} */ FacebookPreview.prototype.imageError = function() { this.removeImageClasses(); imagePlaceholder( this.getImageContainer(), this.i18n.dgettext( "yoast-social-previews", "The given image url cannot be loaded" ), true, "facebook" ); }; /** * Sets the image of the image container. * * @param {string} image The image to use. * * @returns {void} */ FacebookPreview.prototype.addImageToContainer = function( image ) { var container = this.getImageContainer(); container.innerHTML = ""; container.style.backgroundImage = "url(" + image + ")"; }; /** * Removes the image from the container. * * @returns {void} */ FacebookPreview.prototype.removeImageFromContainer = function() { var container = this.getImageContainer(); container.style.backgroundImage = ""; }; /** * Sets the proper CSS class for the current image. * * @param {Image} img The image to base the sizing class on. * * @returns {void} */ FacebookPreview.prototype.setSizingClass = function( img ) { this.removeImageClasses(); if ( imageDisplayMode( img ) === "portrait" ) { this.setPortraitImageClasses(); return; } if ( this.isSmallImage( img ) ) { this.setSmallImageClasses(); return; } this.setLargeImageClasses(); return; }; /** * Returns the max image width. * * @param {Image} img The image object to use. * * @returns {int} The calculated maxwidth. */ FacebookPreview.prototype.getMaxImageWidth = function( img ) { if ( this.isSmallImage( img ) ) { return WIDTH_FACEBOOK_IMAGE_SMALL; } return WIDTH_FACEBOOK_IMAGE_LARGE; }; /** * Detects if the Facebook preview should switch to small image mode. * * @param {HTMLImageElement} image The image in question. * * @returns {boolean} Whether the image is small. */ FacebookPreview.prototype.isSmallImage = function( image ) { return ( image.width < FACEBOOK_IMAGE_THRESHOLD_WIDTH || image.height < FACEBOOK_IMAGE_THRESHOLD_HEIGHT ); }; /** * Detects if the Facebook preview image is too small. * * @param {HTMLImageElement} image The image in question. * * @returns {boolean} Whether the image is too small. */ FacebookPreview.prototype.isTooSmallImage = function( image ) { return ( image.width < FACEBOOK_IMAGE_TOO_SMALL_WIDTH || image.height < FACEBOOK_IMAGE_TOO_SMALL_HEIGHT ); }; /** * Sets the classes on the Facebook preview so that it will display a small Facebook image preview. * * @returns {void} */ FacebookPreview.prototype.setSmallImageClasses = function() { var targetElement = this.opts.targetElement; bemAddModifier( "facebook-small", "social-preview__inner", targetElement ); bemAddModifier( "facebook-small", "editable-preview__image--facebook", targetElement ); bemAddModifier( "facebook-small", "editable-preview__text-keeper--facebook", targetElement ); }; /** * Removes the small image classes. * * @returns {void} */ FacebookPreview.prototype.removeSmallImageClasses = function() { var targetElement = this.opts.targetElement; bemRemoveModifier( "facebook-small", "social-preview__inner", targetElement ); bemRemoveModifier( "facebook-small", "editable-preview__image--facebook", targetElement ); bemRemoveModifier( "facebook-small", "editable-preview__text-keeper--facebook", targetElement ); }; /** * Sets the classes on the facebook preview so that it will display a large facebook image preview. * * @returns {void} */ FacebookPreview.prototype.setLargeImageClasses = function() { var targetElement = this.opts.targetElement; bemAddModifier( "facebook-large", "social-preview__inner", targetElement ); bemAddModifier( "facebook-large", "editable-preview__image--facebook", targetElement ); bemAddModifier( "facebook-large", "editable-preview__text-keeper--facebook", targetElement ); }; /** * Removes the large image classes. * * @returns {void} */ FacebookPreview.prototype.removeLargeImageClasses = function() { var targetElement = this.opts.targetElement; bemRemoveModifier( "facebook-large", "social-preview__inner", targetElement ); bemRemoveModifier( "facebook-large", "editable-preview__image--facebook", targetElement ); bemRemoveModifier( "facebook-large", "editable-preview__text-keeper--facebook", targetElement ); }; /** * Sets the classes on the Facebook preview so that it will display a portrait Facebook image preview. * * @returns {void} */ FacebookPreview.prototype.setPortraitImageClasses = function() { var targetElement = this.opts.targetElement; bemAddModifier( "facebook-portrait", "social-preview__inner", targetElement ); bemAddModifier( "facebook-portrait", "editable-preview__image--facebook", targetElement ); bemAddModifier( "facebook-portrait", "editable-preview__text-keeper--facebook", targetElement ); bemAddModifier( "facebook-bottom", "editable-preview__website--facebook", targetElement ); }; /** * Removes the portrait image classes. * * @returns {void} */ FacebookPreview.prototype.removePortraitImageClasses = function() { var targetElement = this.opts.targetElement; bemRemoveModifier( "facebook-portrait", "social-preview__inner", targetElement ); bemRemoveModifier( "facebook-portrait", "editable-preview__image--facebook", targetElement ); bemRemoveModifier( "facebook-portrait", "editable-preview__text-keeper--facebook", targetElement ); bemRemoveModifier( "facebook-bottom", "editable-preview__website--facebook", targetElement ); }; /** * Removes all image classes. * * @returns {void} */ FacebookPreview.prototype.removeImageClasses = function() { this.removeSmallImageClasses(); this.removeLargeImageClasses(); this.removePortraitImageClasses(); }; /** * Binds the reloadSnippetText function to the blur of the snippet inputs. * * @returns {void} */ FacebookPreview.prototype.bindEvents = function() { var previewEvents = new PreviewEvents( inputFacebookPreviewBindings, this.element, true ); previewEvents.bindEvents( this.element.editToggle, this.element.closeEditor ); }; /** * Sets the value of the Facebook author name. * * @param {string} authorName The name of the author to show. * * @returns {void} */ FacebookPreview.prototype.setAuthor = function( authorName ) { var authorHtml = ""; if ( authorName !== "" ) { authorHtml = facebookAuthorTemplate( { authorName: authorName, authorBy: this.i18n.dgettext( "yoast-social-previews", "By" ), } ); } this.element.authorContainer.innerHTML = authorHtml; }; module.exports = FacebookPreview;
JavaScript
CL
2243f85de2447eb66be724333cfaa403c91ddfeb57c0cdf13d85095855b728bb
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Route, Redirect } from "react-router-dom"; import './index.css'; // Project Component and containers import Layout from './Layout/Layout'; import Main from './Layout/Main/Main'; import Sidebar from './Layout/Aux/Sidebar'; import GlobalState from './context/GlobalState'; import About from './Pages/About'; import drawerContext from './context/drawer-context'; import Work from './Pages/Work'; import ScrollToTop from './Helpers/ScrollToTop'; import Experiences from './Pages/Experiences'; import Skills from './Pages/Skills'; import Footer from './Helpers/Footer'; // Font Awesome icons const data = [ { iconClass: 'fas fa-user-circle', text: 'About', }, { iconClass: 'fas fa-code', text: 'Work', }, { iconClass: 'fas fa-id-badge', text: 'Experiences', }, { iconClass: 'fas fa-tools', text: 'Skills', } ] class Application extends React.Component { static contextType = drawerContext; render() { const iconStyle = { fontSize: '32px', padding: '5px 15px', } const imageStyle = { padding: "5px", width: '150px', height: 'auto' } const textStyle = { margin: '0.15rem auto', color: 'white', fontFamily: "'Kosugi Maru', sans-serif", letterSpacing: '2px', fontSize: '2.2rem', fontWeight: 'bold' } // const arrow = this.state.o return ( <GlobalState> <Router> <Layout data={data}> <Sidebar> <i style={iconStyle}></i> <img style={imageStyle} className="ui small centered circular image" src="me.jpeg" alt="" data-tooltip="Add users to your feed" /> <p style={textStyle} >ATUL BISHT</p> <img src="right-point.png" alt="" className={"rightPoint "} /> </Sidebar> <Main> <ScrollToTop> <Route exact path="/" render={() => (<Redirect to="/about" />)} /> <Route exact path="/about" render={() => (<About />)}></Route> <Route exact path="/work" render={() => (<Work />)}></Route> <Route exact path="/experiences" render={() => (<Experiences />)} ></Route> <Route exact path="/skills" render={() => (<Skills />)}></Route> </ScrollToTop> <Footer /> </Main> </Layout> </Router> </GlobalState> ); } } ReactDOM.render(<Application />, document.getElementById('root'));
JavaScript
CL
5d62a353ff7eaa23f857424350ace39032afcc516cafda7669ab5042ce9ae76b
import React, { useState } from 'react'; import styled from 'styled-components'; import axios from 'axios'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; // import { fab } from '@fortawesome/free-brands-svg-icons'; import { faInstagram, faFacebook, faPinterest, faTwitter } from '@fortawesome/free-brands-svg-icons'; // //////////////// ASSIGNED GRID AREA //////////////// // const AddToCartArea = styled.div` grid-area: AddToCart; `; // //////////////// STYLED COMPONENTS //////////////// // const DropdownWrapper = styled.div` display: flex; .empty-div { margin: 10px; } `; const StyledDropdown = styled.select` width: 100%; height: 70%; padding: 0.5rem; margin-bottom: 15px; cursor: pointer; `; const Button = styled.button` width: 100%; height: 30%; display: flex; justify-content: center; padding: 0.5rem; font-size: 15px; align-items: center; color: white; background-color: #FF5A5F; border: 2px solid #FF5A5F; border-radius: 1.5em; cursor: pointer; transition-duration: 0.3s; &:hover { box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); } `; const SocialMediaShare = styled.div` display: flex; justify-content: space-around; margin-top: 20px; .fa-icon { cursor: pointer; } `; const Dropdown = (props) => ( <StyledDropdown className={props.className} onChange={props.onChange} disabled={props.disabled}> {props.children} </StyledDropdown> ); // //////////////// HELPER FUNCTIONS //////////////// // // input: skus <- an object with sku id as it's key and a nested object containing size and quantity // as it's value // output: sizes <- an array of all available sizes (quantity has to be greater than 0) const getAvailableSizes = (skus) => { const sizes = Object.values(skus).filter((sku) => sku.quantity > 0).map((sku) => sku.size); return sizes; }; // input: skus, size // output: max quantity is either the remaining quantity of the selected size or 15 const getMaxQuantity = (skus, size) => { const maxQuantity = Object.values(skus).filter((sku) => sku.size === size)[0].quantity; return (maxQuantity > 15) ? 15 : maxQuantity; }; // input: N <- maximum number // output: an array containing 1, 2, ..., N const getArrayOneToN = (n) => [...Array(n).keys()].map((num) => num + 1); // input: style, size // output: sku id const getSkuId = (skus, size) => Object.keys(skus).find((key) => skus[key].size === size); // //////////////// MAIN COMPONENT //////////////// // const AddToCart = (props) => { const { style } = props; const { skus } = style; const [size, setSize] = useState('SELECT SIZE'); const [quantity, setQuantity] = useState(1); const sizes = getAvailableSizes(skus); const handleSizeSelect = (event) => { setSize(event.target.value); }; const handleQuantitySelect = (event) => { setQuantity(event.target.value); }; const handleSubmit = (event) => { event.preventDefault(); axios.post('/cart', { skuId: getSkuId(skus, size), quantity, }) .catch((err) => { console.log(err); }); }; return ( <AddToCartArea> <DropdownWrapper> <Dropdown className="size-selector" onChange={handleSizeSelect} > <option>SELECT SIZE</option> {sizes.map((size, index) => (<option key={index}>{size}</option>))} </Dropdown> <div className="empty-div" /> {(size === 'SELECT SIZE') ? ( <Dropdown className="qty-selector" onChange={handleQuantitySelect} disabled > <option>1</option> </Dropdown> ) : ( <Dropdown className="qty-selector" onChange={handleQuantitySelect} action="/" > {getArrayOneToN(getMaxQuantity(skus, size)).map((quantity, index) => (<option key={index}>{quantity}</option>))} </Dropdown> )} </DropdownWrapper> <Button onClick={handleSubmit}>ADD TO BAG</Button> <SocialMediaShare> <FontAwesomeIcon className="fa-icon" icon={faInstagram} size="2x" color="#FF5A5F" onClick={() => window.open('http://www.instagram.com/')} /> <FontAwesomeIcon className="fa-icon" icon={faFacebook} size="2x" color="#FF5A5F" onClick={() => window.open('http://www.facebook.com/')} /> <FontAwesomeIcon className="fa-icon" icon={faPinterest} size="2x" color="#FF5A5F" onClick={() => window.open('http://www.pinterest.com/')} /> <FontAwesomeIcon className="fa-icon" icon={faTwitter} size="2x" color="#FF5A5F" onClick={() => window.open('http://www.twitter.com/')} /> </SocialMediaShare> </AddToCartArea> ); }; export default AddToCart;
JavaScript
CL
6ac8238f428c1b673ef4d11e61e409aab6fc8bfa158e70eccb4a62004ce39909
var quotes = [ "I think success has no rules, but you can learn a lot from failure.(Jean Kerr)", "Do you love life ? Then do not squander time for that's the stuff5 life is made of .(Benjamin Franklin , American president )", "To choose time is to save time .( Francis Bacon , British philosopher )", "A man can fail many times, but he isn't a failure until he begins to blame somebody else.(J. Burroughs)", "An aim in life is the only fortune worth finding.(Robert Louis Stevenson)", "Genius only means hard-working all one's life. (Mendeleyev Russian chemist)", "There is no such thing as a great talent without great will - power. (Balzac)", "Cease to struggle and you cease to live.(Thomas Carlyle)", "A strong man will struggle with the storms of fate.(Thomas Addison)", "Living without an aim is like sailing without a compass.(John Ruskin)" ] function newQuote(){ var randomNumber = Math.floor(Math.random()*(quotes.length)); document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber]; }
JavaScript
CL
941ca2c034bbc6909aa5f64ede0213fdcf98bfeaa82a00d3db11d5c6312b6e68